libcli/smb: add smb2cli_tcon_{should_sign,is_signing_on}()
[bbaumbach/samba-autobuild/.git] / libcli / smb / smbXcli_base.c
1 /*
2    Unix SMB/CIFS implementation.
3    Infrastructure for async SMB client requests
4    Copyright (C) Volker Lendecke 2008
5    Copyright (C) Stefan Metzmacher 2011
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "includes.h"
22 #include "system/network.h"
23 #include "../lib/async_req/async_sock.h"
24 #include "../lib/util/tevent_ntstatus.h"
25 #include "../lib/util/tevent_unix.h"
26 #include "lib/util/util_net.h"
27 #include "lib/util/dlinklist.h"
28 #include "../libcli/smb/smb_common.h"
29 #include "../libcli/smb/smb_seal.h"
30 #include "../libcli/smb/smb_signing.h"
31 #include "../libcli/smb/read_smb.h"
32 #include "smbXcli_base.h"
33 #include "librpc/ndr/libndr.h"
34
35 struct smbXcli_conn;
36 struct smbXcli_req;
37 struct smbXcli_session;
38 struct smbXcli_tcon;
39
40 struct smbXcli_conn {
41         int read_fd;
42         int write_fd;
43         struct sockaddr_storage local_ss;
44         struct sockaddr_storage remote_ss;
45         const char *remote_name;
46
47         struct tevent_queue *outgoing;
48         struct tevent_req **pending;
49         struct tevent_req *read_smb_req;
50
51         enum protocol_types protocol;
52         bool allow_signing;
53         bool desire_signing;
54         bool mandatory_signing;
55
56         /*
57          * The incoming dispatch function should return:
58          * - NT_STATUS_RETRY, if more incoming PDUs are expected.
59          * - NT_STATUS_OK, if no more processing is desired, e.g.
60          *                 the dispatch function called
61          *                 tevent_req_done().
62          * - All other return values disconnect the connection.
63          */
64         NTSTATUS (*dispatch_incoming)(struct smbXcli_conn *conn,
65                                       TALLOC_CTX *tmp_mem,
66                                       uint8_t *inbuf);
67
68         struct {
69                 struct {
70                         uint32_t capabilities;
71                         uint32_t max_xmit;
72                 } client;
73
74                 struct {
75                         uint32_t capabilities;
76                         uint32_t max_xmit;
77                         uint16_t max_mux;
78                         uint16_t security_mode;
79                         bool readbraw;
80                         bool writebraw;
81                         bool lockread;
82                         bool writeunlock;
83                         uint32_t session_key;
84                         struct GUID guid;
85                         DATA_BLOB gss_blob;
86                         uint8_t challenge[8];
87                         const char *workgroup;
88                         const char *name;
89                         int time_zone;
90                         NTTIME system_time;
91                 } server;
92
93                 uint32_t capabilities;
94                 uint32_t max_xmit;
95
96                 uint16_t mid;
97
98                 struct smb_signing_state *signing;
99                 struct smb_trans_enc_state *trans_enc;
100
101                 struct tevent_req *read_braw_req;
102         } smb1;
103
104         struct {
105                 struct {
106                         uint32_t capabilities;
107                         uint16_t security_mode;
108                         struct GUID guid;
109                 } client;
110
111                 struct {
112                         uint32_t capabilities;
113                         uint16_t security_mode;
114                         struct GUID guid;
115                         uint32_t max_trans_size;
116                         uint32_t max_read_size;
117                         uint32_t max_write_size;
118                         NTTIME system_time;
119                         NTTIME start_time;
120                         DATA_BLOB gss_blob;
121                 } server;
122
123                 uint64_t mid;
124                 uint16_t cur_credits;
125                 uint16_t max_credits;
126         } smb2;
127
128         struct smbXcli_session *sessions;
129 };
130
131 struct smb2cli_session {
132         uint64_t session_id;
133         uint16_t session_flags;
134         DATA_BLOB application_key;
135         DATA_BLOB signing_key;
136         bool should_sign;
137         bool should_encrypt;
138         DATA_BLOB encryption_key;
139         DATA_BLOB decryption_key;
140         uint64_t nonce_high;
141         uint64_t nonce_low;
142         uint16_t channel_sequence;
143         bool replay_active;
144 };
145
146 struct smbXcli_session {
147         struct smbXcli_session *prev, *next;
148         struct smbXcli_conn *conn;
149
150         struct {
151                 uint16_t session_id;
152                 DATA_BLOB application_key;
153                 bool protected_key;
154         } smb1;
155
156         struct smb2cli_session *smb2;
157
158         struct {
159                 DATA_BLOB signing_key;
160         } smb2_channel;
161
162         /*
163          * this should be a short term hack
164          * until the upper layers have implemented
165          * re-authentication.
166          */
167         bool disconnect_expired;
168 };
169
170 struct smbXcli_tcon {
171         bool is_smb1;
172         uint32_t fs_attributes;
173
174         struct {
175                 uint16_t tcon_id;
176                 uint16_t optional_support;
177                 uint32_t maximal_access;
178                 uint32_t guest_maximal_access;
179                 char *service;
180                 char *fs_type;
181         } smb1;
182
183         struct {
184                 uint32_t tcon_id;
185                 uint8_t type;
186                 uint32_t flags;
187                 uint32_t capabilities;
188                 uint32_t maximal_access;
189                 bool should_sign;
190                 bool should_encrypt;
191         } smb2;
192 };
193
194 struct smbXcli_req_state {
195         struct tevent_context *ev;
196         struct smbXcli_conn *conn;
197         struct smbXcli_session *session; /* maybe NULL */
198         struct smbXcli_tcon *tcon; /* maybe NULL */
199
200         uint8_t length_hdr[4];
201
202         bool one_way;
203
204         uint8_t *inbuf;
205
206         struct {
207                 /* Space for the header including the wct */
208                 uint8_t hdr[HDR_VWV];
209
210                 /*
211                  * For normal requests, smb1cli_req_send chooses a mid.
212                  * SecondaryV trans requests need to use the mid of the primary
213                  * request, so we need a place to store it.
214                  * Assume it is set if != 0.
215                  */
216                 uint16_t mid;
217
218                 uint16_t *vwv;
219                 uint8_t bytecount_buf[2];
220
221 #define MAX_SMB_IOV 10
222                 /* length_hdr, hdr, words, byte_count, buffers */
223                 struct iovec iov[1 + 3 + MAX_SMB_IOV];
224                 int iov_count;
225
226                 bool one_way_seqnum;
227                 uint32_t seqnum;
228                 struct tevent_req **chained_requests;
229
230                 uint8_t recv_cmd;
231                 NTSTATUS recv_status;
232                 /* always an array of 3 talloc elements */
233                 struct iovec *recv_iov;
234         } smb1;
235
236         struct {
237                 const uint8_t *fixed;
238                 uint16_t fixed_len;
239                 const uint8_t *dyn;
240                 uint32_t dyn_len;
241
242                 uint8_t transform[SMB2_TF_HDR_SIZE];
243                 uint8_t hdr[SMB2_HDR_BODY];
244                 uint8_t pad[7]; /* padding space for compounding */
245
246                 /*
247                  * always an array of 3 talloc elements
248                  * (without a SMB2_TRANSFORM header!)
249                  *
250                  * HDR, BODY, DYN
251                  */
252                 struct iovec *recv_iov;
253
254                 /*
255                  * the expected max for the response dyn_len
256                  */
257                 uint32_t max_dyn_len;
258
259                 uint16_t credit_charge;
260
261                 bool should_sign;
262                 bool should_encrypt;
263                 uint64_t encryption_session_id;
264
265                 bool signing_skipped;
266                 bool notify_async;
267                 bool got_async;
268         } smb2;
269 };
270
271 static int smbXcli_conn_destructor(struct smbXcli_conn *conn)
272 {
273         /*
274          * NT_STATUS_OK, means we do not notify the callers
275          */
276         smbXcli_conn_disconnect(conn, NT_STATUS_OK);
277
278         while (conn->sessions) {
279                 conn->sessions->conn = NULL;
280                 DLIST_REMOVE(conn->sessions, conn->sessions);
281         }
282
283         if (conn->smb1.trans_enc) {
284                 TALLOC_FREE(conn->smb1.trans_enc);
285         }
286
287         return 0;
288 }
289
290 struct smbXcli_conn *smbXcli_conn_create(TALLOC_CTX *mem_ctx,
291                                          int fd,
292                                          const char *remote_name,
293                                          enum smb_signing_setting signing_state,
294                                          uint32_t smb1_capabilities,
295                                          struct GUID *client_guid,
296                                          uint32_t smb2_capabilities)
297 {
298         struct smbXcli_conn *conn = NULL;
299         void *ss = NULL;
300         struct sockaddr *sa = NULL;
301         socklen_t sa_length;
302         int ret;
303
304         conn = talloc_zero(mem_ctx, struct smbXcli_conn);
305         if (!conn) {
306                 return NULL;
307         }
308
309         conn->read_fd = fd;
310         conn->write_fd = dup(fd);
311         if (conn->write_fd == -1) {
312                 goto error;
313         }
314
315         conn->remote_name = talloc_strdup(conn, remote_name);
316         if (conn->remote_name == NULL) {
317                 goto error;
318         }
319
320
321         ss = (void *)&conn->local_ss;
322         sa = (struct sockaddr *)ss;
323         sa_length = sizeof(conn->local_ss);
324         ret = getsockname(fd, sa, &sa_length);
325         if (ret == -1) {
326                 goto error;
327         }
328         ss = (void *)&conn->remote_ss;
329         sa = (struct sockaddr *)ss;
330         sa_length = sizeof(conn->remote_ss);
331         ret = getpeername(fd, sa, &sa_length);
332         if (ret == -1) {
333                 goto error;
334         }
335
336         conn->outgoing = tevent_queue_create(conn, "smbXcli_outgoing");
337         if (conn->outgoing == NULL) {
338                 goto error;
339         }
340         conn->pending = NULL;
341
342         conn->protocol = PROTOCOL_NONE;
343
344         switch (signing_state) {
345         case SMB_SIGNING_OFF:
346                 /* never */
347                 conn->allow_signing = false;
348                 conn->desire_signing = false;
349                 conn->mandatory_signing = false;
350                 break;
351         case SMB_SIGNING_DEFAULT:
352         case SMB_SIGNING_IF_REQUIRED:
353                 /* if the server requires it */
354                 conn->allow_signing = true;
355                 conn->desire_signing = false;
356                 conn->mandatory_signing = false;
357                 break;
358         case SMB_SIGNING_REQUIRED:
359                 /* always */
360                 conn->allow_signing = true;
361                 conn->desire_signing = true;
362                 conn->mandatory_signing = true;
363                 break;
364         }
365
366         conn->smb1.client.capabilities = smb1_capabilities;
367         conn->smb1.client.max_xmit = UINT16_MAX;
368
369         conn->smb1.capabilities = conn->smb1.client.capabilities;
370         conn->smb1.max_xmit = 1024;
371
372         conn->smb1.mid = 1;
373
374         /* initialise signing */
375         conn->smb1.signing = smb_signing_init(conn,
376                                               conn->allow_signing,
377                                               conn->desire_signing,
378                                               conn->mandatory_signing);
379         if (!conn->smb1.signing) {
380                 goto error;
381         }
382
383         conn->smb2.client.security_mode = SMB2_NEGOTIATE_SIGNING_ENABLED;
384         if (conn->mandatory_signing) {
385                 conn->smb2.client.security_mode |= SMB2_NEGOTIATE_SIGNING_REQUIRED;
386         }
387         if (client_guid) {
388                 conn->smb2.client.guid = *client_guid;
389         }
390         conn->smb2.client.capabilities = smb2_capabilities;
391
392         conn->smb2.cur_credits = 1;
393         conn->smb2.max_credits = 0;
394
395         talloc_set_destructor(conn, smbXcli_conn_destructor);
396         return conn;
397
398  error:
399         if (conn->write_fd != -1) {
400                 close(conn->write_fd);
401         }
402         TALLOC_FREE(conn);
403         return NULL;
404 }
405
406 bool smbXcli_conn_is_connected(struct smbXcli_conn *conn)
407 {
408         if (conn == NULL) {
409                 return false;
410         }
411
412         if (conn->read_fd == -1) {
413                 return false;
414         }
415
416         return true;
417 }
418
419 enum protocol_types smbXcli_conn_protocol(struct smbXcli_conn *conn)
420 {
421         return conn->protocol;
422 }
423
424 bool smbXcli_conn_use_unicode(struct smbXcli_conn *conn)
425 {
426         if (conn->protocol >= PROTOCOL_SMB2_02) {
427                 return true;
428         }
429
430         if (conn->smb1.capabilities & CAP_UNICODE) {
431                 return true;
432         }
433
434         return false;
435 }
436
437 void smbXcli_conn_set_sockopt(struct smbXcli_conn *conn, const char *options)
438 {
439         set_socket_options(conn->read_fd, options);
440 }
441
442 const struct sockaddr_storage *smbXcli_conn_local_sockaddr(struct smbXcli_conn *conn)
443 {
444         return &conn->local_ss;
445 }
446
447 const struct sockaddr_storage *smbXcli_conn_remote_sockaddr(struct smbXcli_conn *conn)
448 {
449         return &conn->remote_ss;
450 }
451
452 const char *smbXcli_conn_remote_name(struct smbXcli_conn *conn)
453 {
454         return conn->remote_name;
455 }
456
457 uint16_t smbXcli_conn_max_requests(struct smbXcli_conn *conn)
458 {
459         if (conn->protocol >= PROTOCOL_SMB2_02) {
460                 /*
461                  * TODO...
462                  */
463                 return 1;
464         }
465
466         return conn->smb1.server.max_mux;
467 }
468
469 NTTIME smbXcli_conn_server_system_time(struct smbXcli_conn *conn)
470 {
471         if (conn->protocol >= PROTOCOL_SMB2_02) {
472                 return conn->smb2.server.system_time;
473         }
474
475         return conn->smb1.server.system_time;
476 }
477
478 const DATA_BLOB *smbXcli_conn_server_gss_blob(struct smbXcli_conn *conn)
479 {
480         if (conn->protocol >= PROTOCOL_SMB2_02) {
481                 return &conn->smb2.server.gss_blob;
482         }
483
484         return &conn->smb1.server.gss_blob;
485 }
486
487 const struct GUID *smbXcli_conn_server_guid(struct smbXcli_conn *conn)
488 {
489         if (conn->protocol >= PROTOCOL_SMB2_02) {
490                 return &conn->smb2.server.guid;
491         }
492
493         return &conn->smb1.server.guid;
494 }
495
496 struct smbXcli_conn_samba_suicide_state {
497         struct smbXcli_conn *conn;
498         struct iovec iov;
499         uint8_t buf[9];
500 };
501
502 static void smbXcli_conn_samba_suicide_done(struct tevent_req *subreq);
503
504 struct tevent_req *smbXcli_conn_samba_suicide_send(TALLOC_CTX *mem_ctx,
505                                                    struct tevent_context *ev,
506                                                    struct smbXcli_conn *conn,
507                                                    uint8_t exitcode)
508 {
509         struct tevent_req *req, *subreq;
510         struct smbXcli_conn_samba_suicide_state *state;
511
512         req = tevent_req_create(mem_ctx, &state,
513                                 struct smbXcli_conn_samba_suicide_state);
514         if (req == NULL) {
515                 return NULL;
516         }
517         state->conn = conn;
518         SIVAL(state->buf, 4, 0x74697865);
519         SCVAL(state->buf, 8, exitcode);
520         _smb_setlen_nbt(state->buf, sizeof(state->buf)-4);
521
522         state->iov.iov_base = state->buf;
523         state->iov.iov_len = sizeof(state->buf);
524
525         subreq = writev_send(state, ev, conn->outgoing, conn->write_fd,
526                              false, &state->iov, 1);
527         if (tevent_req_nomem(subreq, req)) {
528                 return tevent_req_post(req, ev);
529         }
530         tevent_req_set_callback(subreq, smbXcli_conn_samba_suicide_done, req);
531         return req;
532 }
533
534 static void smbXcli_conn_samba_suicide_done(struct tevent_req *subreq)
535 {
536         struct tevent_req *req = tevent_req_callback_data(
537                 subreq, struct tevent_req);
538         struct smbXcli_conn_samba_suicide_state *state = tevent_req_data(
539                 req, struct smbXcli_conn_samba_suicide_state);
540         ssize_t nwritten;
541         int err;
542
543         nwritten = writev_recv(subreq, &err);
544         TALLOC_FREE(subreq);
545         if (nwritten == -1) {
546                 NTSTATUS status = map_nt_error_from_unix_common(err);
547                 smbXcli_conn_disconnect(state->conn, status);
548                 return;
549         }
550         tevent_req_done(req);
551 }
552
553 NTSTATUS smbXcli_conn_samba_suicide_recv(struct tevent_req *req)
554 {
555         return tevent_req_simple_recv_ntstatus(req);
556 }
557
558 NTSTATUS smbXcli_conn_samba_suicide(struct smbXcli_conn *conn,
559                                     uint8_t exitcode)
560 {
561         TALLOC_CTX *frame = talloc_stackframe();
562         struct tevent_context *ev;
563         struct tevent_req *req;
564         NTSTATUS status = NT_STATUS_NO_MEMORY;
565         bool ok;
566
567         if (smbXcli_conn_has_async_calls(conn)) {
568                 /*
569                  * Can't use sync call while an async call is in flight
570                  */
571                 status = NT_STATUS_INVALID_PARAMETER_MIX;
572                 goto fail;
573         }
574         ev = samba_tevent_context_init(frame);
575         if (ev == NULL) {
576                 goto fail;
577         }
578         req = smbXcli_conn_samba_suicide_send(frame, ev, conn, exitcode);
579         if (req == NULL) {
580                 goto fail;
581         }
582         ok = tevent_req_poll(req, ev);
583         if (!ok) {
584                 status = map_nt_error_from_unix_common(errno);
585                 goto fail;
586         }
587         status = smbXcli_conn_samba_suicide_recv(req);
588  fail:
589         TALLOC_FREE(frame);
590         return status;
591 }
592
593 uint32_t smb1cli_conn_capabilities(struct smbXcli_conn *conn)
594 {
595         return conn->smb1.capabilities;
596 }
597
598 uint32_t smb1cli_conn_max_xmit(struct smbXcli_conn *conn)
599 {
600         return conn->smb1.max_xmit;
601 }
602
603 bool smb1cli_conn_req_possible(struct smbXcli_conn *conn)
604 {
605         size_t pending;
606         uint16_t possible = conn->smb1.server.max_mux;
607
608         pending = tevent_queue_length(conn->outgoing);
609         if (pending >= possible) {
610                 return false;
611         }
612         pending += talloc_array_length(conn->pending);
613         if (pending >= possible) {
614                 return false;
615         }
616
617         return true;
618 }
619
620 uint32_t smb1cli_conn_server_session_key(struct smbXcli_conn *conn)
621 {
622         return conn->smb1.server.session_key;
623 }
624
625 const uint8_t *smb1cli_conn_server_challenge(struct smbXcli_conn *conn)
626 {
627         return conn->smb1.server.challenge;
628 }
629
630 uint16_t smb1cli_conn_server_security_mode(struct smbXcli_conn *conn)
631 {
632         return conn->smb1.server.security_mode;
633 }
634
635 bool smb1cli_conn_server_readbraw(struct smbXcli_conn *conn)
636 {
637         return conn->smb1.server.readbraw;
638 }
639
640 bool smb1cli_conn_server_writebraw(struct smbXcli_conn *conn)
641 {
642         return conn->smb1.server.writebraw;
643 }
644
645 bool smb1cli_conn_server_lockread(struct smbXcli_conn *conn)
646 {
647         return conn->smb1.server.lockread;
648 }
649
650 bool smb1cli_conn_server_writeunlock(struct smbXcli_conn *conn)
651 {
652         return conn->smb1.server.writeunlock;
653 }
654
655 int smb1cli_conn_server_time_zone(struct smbXcli_conn *conn)
656 {
657         return conn->smb1.server.time_zone;
658 }
659
660 bool smb1cli_conn_activate_signing(struct smbXcli_conn *conn,
661                                    const DATA_BLOB user_session_key,
662                                    const DATA_BLOB response)
663 {
664         return smb_signing_activate(conn->smb1.signing,
665                                     user_session_key,
666                                     response);
667 }
668
669 bool smb1cli_conn_check_signing(struct smbXcli_conn *conn,
670                                 const uint8_t *buf, uint32_t seqnum)
671 {
672         const uint8_t *hdr = buf + NBT_HDR_SIZE;
673         size_t len = smb_len_nbt(buf);
674
675         return smb_signing_check_pdu(conn->smb1.signing, hdr, len, seqnum);
676 }
677
678 bool smb1cli_conn_signing_is_active(struct smbXcli_conn *conn)
679 {
680         return smb_signing_is_active(conn->smb1.signing);
681 }
682
683 void smb1cli_conn_set_encryption(struct smbXcli_conn *conn,
684                                  struct smb_trans_enc_state *es)
685 {
686         /* Replace the old state, if any. */
687         if (conn->smb1.trans_enc) {
688                 TALLOC_FREE(conn->smb1.trans_enc);
689         }
690         conn->smb1.trans_enc = es;
691 }
692
693 bool smb1cli_conn_encryption_on(struct smbXcli_conn *conn)
694 {
695         return common_encryption_on(conn->smb1.trans_enc);
696 }
697
698
699 static NTSTATUS smb1cli_pull_raw_error(const uint8_t *hdr)
700 {
701         uint32_t flags2 = SVAL(hdr, HDR_FLG2);
702         NTSTATUS status = NT_STATUS(IVAL(hdr, HDR_RCLS));
703
704         if (NT_STATUS_IS_OK(status)) {
705                 return NT_STATUS_OK;
706         }
707
708         if (flags2 & FLAGS2_32_BIT_ERROR_CODES) {
709                 return status;
710         }
711
712         return NT_STATUS_DOS(CVAL(hdr, HDR_RCLS), SVAL(hdr, HDR_ERR));
713 }
714
715 /**
716  * Is the SMB command able to hold an AND_X successor
717  * @param[in] cmd       The SMB command in question
718  * @retval Can we add a chained request after "cmd"?
719  */
720 bool smb1cli_is_andx_req(uint8_t cmd)
721 {
722         switch (cmd) {
723         case SMBtconX:
724         case SMBlockingX:
725         case SMBopenX:
726         case SMBreadX:
727         case SMBwriteX:
728         case SMBsesssetupX:
729         case SMBulogoffX:
730         case SMBntcreateX:
731                 return true;
732                 break;
733         default:
734                 break;
735         }
736
737         return false;
738 }
739
740 static uint16_t smb1cli_alloc_mid(struct smbXcli_conn *conn)
741 {
742         size_t num_pending = talloc_array_length(conn->pending);
743         uint16_t result;
744
745         if (conn->protocol == PROTOCOL_NONE) {
746                 /*
747                  * This is what windows sends on the SMB1 Negprot request
748                  * and some vendors reuse the SMB1 MID as SMB2 sequence number.
749                  */
750                 return 0;
751         }
752
753         while (true) {
754                 size_t i;
755
756                 result = conn->smb1.mid++;
757                 if ((result == 0) || (result == 0xffff)) {
758                         continue;
759                 }
760
761                 for (i=0; i<num_pending; i++) {
762                         if (result == smb1cli_req_mid(conn->pending[i])) {
763                                 break;
764                         }
765                 }
766
767                 if (i == num_pending) {
768                         return result;
769                 }
770         }
771 }
772
773 void smbXcli_req_unset_pending(struct tevent_req *req)
774 {
775         struct smbXcli_req_state *state =
776                 tevent_req_data(req,
777                 struct smbXcli_req_state);
778         struct smbXcli_conn *conn = state->conn;
779         size_t num_pending = talloc_array_length(conn->pending);
780         size_t i;
781
782         if (state->smb1.mid != 0) {
783                 /*
784                  * This is a [nt]trans[2] request which waits
785                  * for more than one reply.
786                  */
787                 return;
788         }
789
790         tevent_req_set_cleanup_fn(req, NULL);
791
792         if (num_pending == 1) {
793                 /*
794                  * The pending read_smb tevent_req is a child of
795                  * conn->pending. So if nothing is pending anymore, we need to
796                  * delete the socket read fde.
797                  */
798                 TALLOC_FREE(conn->pending);
799                 conn->read_smb_req = NULL;
800                 return;
801         }
802
803         for (i=0; i<num_pending; i++) {
804                 if (req == conn->pending[i]) {
805                         break;
806                 }
807         }
808         if (i == num_pending) {
809                 /*
810                  * Something's seriously broken. Just returning here is the
811                  * right thing nevertheless, the point of this routine is to
812                  * remove ourselves from conn->pending.
813                  */
814                 return;
815         }
816
817         /*
818          * Remove ourselves from the conn->pending array
819          */
820         for (; i < (num_pending - 1); i++) {
821                 conn->pending[i] = conn->pending[i+1];
822         }
823
824         /*
825          * No NULL check here, we're shrinking by sizeof(void *), and
826          * talloc_realloc just adjusts the size for this.
827          */
828         conn->pending = talloc_realloc(NULL, conn->pending, struct tevent_req *,
829                                        num_pending - 1);
830         return;
831 }
832
833 static void smbXcli_req_cleanup(struct tevent_req *req,
834                                 enum tevent_req_state req_state)
835 {
836         struct smbXcli_req_state *state =
837                 tevent_req_data(req,
838                 struct smbXcli_req_state);
839
840         switch (req_state) {
841         case TEVENT_REQ_RECEIVED:
842                 /*
843                  * Make sure we really remove it from
844                  * the pending array on destruction.
845                  */
846                 state->smb1.mid = 0;
847                 smbXcli_req_unset_pending(req);
848                 return;
849         default:
850                 return;
851         }
852 }
853
854 static bool smb1cli_req_cancel(struct tevent_req *req);
855 static bool smb2cli_req_cancel(struct tevent_req *req);
856
857 static bool smbXcli_req_cancel(struct tevent_req *req)
858 {
859         struct smbXcli_req_state *state =
860                 tevent_req_data(req,
861                 struct smbXcli_req_state);
862
863         if (!smbXcli_conn_is_connected(state->conn)) {
864                 return false;
865         }
866
867         if (state->conn->protocol == PROTOCOL_NONE) {
868                 return false;
869         }
870
871         if (state->conn->protocol >= PROTOCOL_SMB2_02) {
872                 return smb2cli_req_cancel(req);
873         }
874
875         return smb1cli_req_cancel(req);
876 }
877
878 static bool smbXcli_conn_receive_next(struct smbXcli_conn *conn);
879
880 bool smbXcli_req_set_pending(struct tevent_req *req)
881 {
882         struct smbXcli_req_state *state =
883                 tevent_req_data(req,
884                 struct smbXcli_req_state);
885         struct smbXcli_conn *conn;
886         struct tevent_req **pending;
887         size_t num_pending;
888
889         conn = state->conn;
890
891         if (!smbXcli_conn_is_connected(conn)) {
892                 return false;
893         }
894
895         num_pending = talloc_array_length(conn->pending);
896
897         pending = talloc_realloc(conn, conn->pending, struct tevent_req *,
898                                  num_pending+1);
899         if (pending == NULL) {
900                 return false;
901         }
902         pending[num_pending] = req;
903         conn->pending = pending;
904         tevent_req_set_cleanup_fn(req, smbXcli_req_cleanup);
905         tevent_req_set_cancel_fn(req, smbXcli_req_cancel);
906
907         if (!smbXcli_conn_receive_next(conn)) {
908                 /*
909                  * the caller should notify the current request
910                  *
911                  * And all other pending requests get notified
912                  * by smbXcli_conn_disconnect().
913                  */
914                 smbXcli_req_unset_pending(req);
915                 smbXcli_conn_disconnect(conn, NT_STATUS_NO_MEMORY);
916                 return false;
917         }
918
919         return true;
920 }
921
922 static void smbXcli_conn_received(struct tevent_req *subreq);
923
924 static bool smbXcli_conn_receive_next(struct smbXcli_conn *conn)
925 {
926         size_t num_pending = talloc_array_length(conn->pending);
927         struct tevent_req *req;
928         struct smbXcli_req_state *state;
929
930         if (conn->read_smb_req != NULL) {
931                 return true;
932         }
933
934         if (num_pending == 0) {
935                 if (conn->smb2.mid < UINT64_MAX) {
936                         /* no more pending requests, so we are done for now */
937                         return true;
938                 }
939
940                 /*
941                  * If there are no more SMB2 requests possible,
942                  * because we are out of message ids,
943                  * we need to disconnect.
944                  */
945                 smbXcli_conn_disconnect(conn, NT_STATUS_CONNECTION_ABORTED);
946                 return true;
947         }
948
949         req = conn->pending[0];
950         state = tevent_req_data(req, struct smbXcli_req_state);
951
952         /*
953          * We're the first ones, add the read_smb request that waits for the
954          * answer from the server
955          */
956         conn->read_smb_req = read_smb_send(conn->pending,
957                                            state->ev,
958                                            conn->read_fd);
959         if (conn->read_smb_req == NULL) {
960                 return false;
961         }
962         tevent_req_set_callback(conn->read_smb_req, smbXcli_conn_received, conn);
963         return true;
964 }
965
966 void smbXcli_conn_disconnect(struct smbXcli_conn *conn, NTSTATUS status)
967 {
968         struct smbXcli_session *session;
969
970         tevent_queue_stop(conn->outgoing);
971
972         if (conn->read_fd != -1) {
973                 close(conn->read_fd);
974         }
975         if (conn->write_fd != -1) {
976                 close(conn->write_fd);
977         }
978         conn->read_fd = -1;
979         conn->write_fd = -1;
980
981         session = conn->sessions;
982         if (talloc_array_length(conn->pending) == 0) {
983                 /*
984                  * if we do not have pending requests
985                  * there is no need to update the channel_sequence
986                  */
987                 session = NULL;
988         }
989         for (; session; session = session->next) {
990                 smb2cli_session_increment_channel_sequence(session);
991         }
992
993         /*
994          * Cancel all pending requests. We do not do a for-loop walking
995          * conn->pending because that array changes in
996          * smbXcli_req_unset_pending.
997          */
998         while (talloc_array_length(conn->pending) > 0) {
999                 struct tevent_req *req;
1000                 struct smbXcli_req_state *state;
1001                 struct tevent_req **chain;
1002                 size_t num_chained;
1003                 size_t i;
1004
1005                 req = conn->pending[0];
1006                 state = tevent_req_data(req, struct smbXcli_req_state);
1007
1008                 if (state->smb1.chained_requests == NULL) {
1009                         /*
1010                          * We're dead. No point waiting for trans2
1011                          * replies.
1012                          */
1013                         state->smb1.mid = 0;
1014
1015                         smbXcli_req_unset_pending(req);
1016
1017                         if (NT_STATUS_IS_OK(status)) {
1018                                 /* do not notify the callers */
1019                                 continue;
1020                         }
1021
1022                         /*
1023                          * we need to defer the callback, because we may notify
1024                          * more then one caller.
1025                          */
1026                         tevent_req_defer_callback(req, state->ev);
1027                         tevent_req_nterror(req, status);
1028                         continue;
1029                 }
1030
1031                 chain = talloc_move(conn, &state->smb1.chained_requests);
1032                 num_chained = talloc_array_length(chain);
1033
1034                 for (i=0; i<num_chained; i++) {
1035                         req = chain[i];
1036                         state = tevent_req_data(req, struct smbXcli_req_state);
1037
1038                         /*
1039                          * We're dead. No point waiting for trans2
1040                          * replies.
1041                          */
1042                         state->smb1.mid = 0;
1043
1044                         smbXcli_req_unset_pending(req);
1045
1046                         if (NT_STATUS_IS_OK(status)) {
1047                                 /* do not notify the callers */
1048                                 continue;
1049                         }
1050
1051                         /*
1052                          * we need to defer the callback, because we may notify
1053                          * more than one caller.
1054                          */
1055                         tevent_req_defer_callback(req, state->ev);
1056                         tevent_req_nterror(req, status);
1057                 }
1058                 TALLOC_FREE(chain);
1059         }
1060 }
1061
1062 /*
1063  * Fetch a smb request's mid. Only valid after the request has been sent by
1064  * smb1cli_req_send().
1065  */
1066 uint16_t smb1cli_req_mid(struct tevent_req *req)
1067 {
1068         struct smbXcli_req_state *state =
1069                 tevent_req_data(req,
1070                 struct smbXcli_req_state);
1071
1072         if (state->smb1.mid != 0) {
1073                 return state->smb1.mid;
1074         }
1075
1076         return SVAL(state->smb1.hdr, HDR_MID);
1077 }
1078
1079 void smb1cli_req_set_mid(struct tevent_req *req, uint16_t mid)
1080 {
1081         struct smbXcli_req_state *state =
1082                 tevent_req_data(req,
1083                 struct smbXcli_req_state);
1084
1085         state->smb1.mid = mid;
1086 }
1087
1088 uint32_t smb1cli_req_seqnum(struct tevent_req *req)
1089 {
1090         struct smbXcli_req_state *state =
1091                 tevent_req_data(req,
1092                 struct smbXcli_req_state);
1093
1094         return state->smb1.seqnum;
1095 }
1096
1097 void smb1cli_req_set_seqnum(struct tevent_req *req, uint32_t seqnum)
1098 {
1099         struct smbXcli_req_state *state =
1100                 tevent_req_data(req,
1101                 struct smbXcli_req_state);
1102
1103         state->smb1.seqnum = seqnum;
1104 }
1105
1106 static size_t smbXcli_iov_len(const struct iovec *iov, int count)
1107 {
1108         size_t result = 0;
1109         int i;
1110         for (i=0; i<count; i++) {
1111                 result += iov[i].iov_len;
1112         }
1113         return result;
1114 }
1115
1116 static uint8_t *smbXcli_iov_concat(TALLOC_CTX *mem_ctx,
1117                                    const struct iovec *iov,
1118                                    int count)
1119 {
1120         size_t len = smbXcli_iov_len(iov, count);
1121         size_t copied;
1122         uint8_t *buf;
1123         int i;
1124
1125         buf = talloc_array(mem_ctx, uint8_t, len);
1126         if (buf == NULL) {
1127                 return NULL;
1128         }
1129         copied = 0;
1130         for (i=0; i<count; i++) {
1131                 memcpy(buf+copied, iov[i].iov_base, iov[i].iov_len);
1132                 copied += iov[i].iov_len;
1133         }
1134         return buf;
1135 }
1136
1137 static void smb1cli_req_flags(enum protocol_types protocol,
1138                               uint32_t smb1_capabilities,
1139                               uint8_t smb_command,
1140                               uint8_t additional_flags,
1141                               uint8_t clear_flags,
1142                               uint8_t *_flags,
1143                               uint16_t additional_flags2,
1144                               uint16_t clear_flags2,
1145                               uint16_t *_flags2)
1146 {
1147         uint8_t flags = 0;
1148         uint16_t flags2 = 0;
1149
1150         if (protocol >= PROTOCOL_LANMAN1) {
1151                 flags |= FLAG_CASELESS_PATHNAMES;
1152                 flags |= FLAG_CANONICAL_PATHNAMES;
1153         }
1154
1155         if (protocol >= PROTOCOL_LANMAN2) {
1156                 flags2 |= FLAGS2_LONG_PATH_COMPONENTS;
1157                 flags2 |= FLAGS2_EXTENDED_ATTRIBUTES;
1158         }
1159
1160         if (protocol >= PROTOCOL_NT1) {
1161                 flags2 |= FLAGS2_IS_LONG_NAME;
1162
1163                 if (smb1_capabilities & CAP_UNICODE) {
1164                         flags2 |= FLAGS2_UNICODE_STRINGS;
1165                 }
1166                 if (smb1_capabilities & CAP_STATUS32) {
1167                         flags2 |= FLAGS2_32_BIT_ERROR_CODES;
1168                 }
1169                 if (smb1_capabilities & CAP_EXTENDED_SECURITY) {
1170                         flags2 |= FLAGS2_EXTENDED_SECURITY;
1171                 }
1172         }
1173
1174         flags |= additional_flags;
1175         flags &= ~clear_flags;
1176         flags2 |= additional_flags2;
1177         flags2 &= ~clear_flags2;
1178
1179         *_flags = flags;
1180         *_flags2 = flags2;
1181 }
1182
1183 static void smb1cli_req_cancel_done(struct tevent_req *subreq);
1184
1185 static bool smb1cli_req_cancel(struct tevent_req *req)
1186 {
1187         struct smbXcli_req_state *state =
1188                 tevent_req_data(req,
1189                 struct smbXcli_req_state);
1190         uint8_t flags;
1191         uint16_t flags2;
1192         uint32_t pid;
1193         uint16_t mid;
1194         struct tevent_req *subreq;
1195         NTSTATUS status;
1196
1197         flags = CVAL(state->smb1.hdr, HDR_FLG);
1198         flags2 = SVAL(state->smb1.hdr, HDR_FLG2);
1199         pid  = SVAL(state->smb1.hdr, HDR_PID);
1200         pid |= SVAL(state->smb1.hdr, HDR_PIDHIGH)<<16;
1201         mid = SVAL(state->smb1.hdr, HDR_MID);
1202
1203         subreq = smb1cli_req_create(state, state->ev,
1204                                     state->conn,
1205                                     SMBntcancel,
1206                                     flags, 0,
1207                                     flags2, 0,
1208                                     0, /* timeout */
1209                                     pid,
1210                                     state->tcon,
1211                                     state->session,
1212                                     0, NULL, /* vwv */
1213                                     0, NULL); /* bytes */
1214         if (subreq == NULL) {
1215                 return false;
1216         }
1217         smb1cli_req_set_mid(subreq, mid);
1218
1219         status = smb1cli_req_chain_submit(&subreq, 1);
1220         if (!NT_STATUS_IS_OK(status)) {
1221                 TALLOC_FREE(subreq);
1222                 return false;
1223         }
1224         smb1cli_req_set_mid(subreq, 0);
1225
1226         tevent_req_set_callback(subreq, smb1cli_req_cancel_done, NULL);
1227
1228         return true;
1229 }
1230
1231 static void smb1cli_req_cancel_done(struct tevent_req *subreq)
1232 {
1233         /* we do not care about the result */
1234         TALLOC_FREE(subreq);
1235 }
1236
1237 struct tevent_req *smb1cli_req_create(TALLOC_CTX *mem_ctx,
1238                                       struct tevent_context *ev,
1239                                       struct smbXcli_conn *conn,
1240                                       uint8_t smb_command,
1241                                       uint8_t additional_flags,
1242                                       uint8_t clear_flags,
1243                                       uint16_t additional_flags2,
1244                                       uint16_t clear_flags2,
1245                                       uint32_t timeout_msec,
1246                                       uint32_t pid,
1247                                       struct smbXcli_tcon *tcon,
1248                                       struct smbXcli_session *session,
1249                                       uint8_t wct, uint16_t *vwv,
1250                                       int iov_count,
1251                                       struct iovec *bytes_iov)
1252 {
1253         struct tevent_req *req;
1254         struct smbXcli_req_state *state;
1255         uint8_t flags = 0;
1256         uint16_t flags2 = 0;
1257         uint16_t uid = 0;
1258         uint16_t tid = 0;
1259
1260         if (iov_count > MAX_SMB_IOV) {
1261                 /*
1262                  * Should not happen :-)
1263                  */
1264                 return NULL;
1265         }
1266
1267         req = tevent_req_create(mem_ctx, &state,
1268                                 struct smbXcli_req_state);
1269         if (req == NULL) {
1270                 return NULL;
1271         }
1272         state->ev = ev;
1273         state->conn = conn;
1274         state->session = session;
1275         state->tcon = tcon;
1276
1277         if (session) {
1278                 uid = session->smb1.session_id;
1279         }
1280
1281         if (tcon) {
1282                 tid = tcon->smb1.tcon_id;
1283
1284                 if (tcon->fs_attributes & FILE_CASE_SENSITIVE_SEARCH) {
1285                         clear_flags |= FLAG_CASELESS_PATHNAMES;
1286                 } else {
1287                         /* Default setting, case insensitive. */
1288                         additional_flags |= FLAG_CASELESS_PATHNAMES;
1289                 }
1290
1291                 if (smbXcli_conn_dfs_supported(conn) &&
1292                     smbXcli_tcon_is_dfs_share(tcon))
1293                 {
1294                         additional_flags2 |= FLAGS2_DFS_PATHNAMES;
1295                 }
1296         }
1297
1298         state->smb1.recv_cmd = 0xFF;
1299         state->smb1.recv_status = NT_STATUS_INTERNAL_ERROR;
1300         state->smb1.recv_iov = talloc_zero_array(state, struct iovec, 3);
1301         if (state->smb1.recv_iov == NULL) {
1302                 TALLOC_FREE(req);
1303                 return NULL;
1304         }
1305
1306         smb1cli_req_flags(conn->protocol,
1307                           conn->smb1.capabilities,
1308                           smb_command,
1309                           additional_flags,
1310                           clear_flags,
1311                           &flags,
1312                           additional_flags2,
1313                           clear_flags2,
1314                           &flags2);
1315
1316         SIVAL(state->smb1.hdr, 0,           SMB_MAGIC);
1317         SCVAL(state->smb1.hdr, HDR_COM,     smb_command);
1318         SIVAL(state->smb1.hdr, HDR_RCLS,    NT_STATUS_V(NT_STATUS_OK));
1319         SCVAL(state->smb1.hdr, HDR_FLG,     flags);
1320         SSVAL(state->smb1.hdr, HDR_FLG2,    flags2);
1321         SSVAL(state->smb1.hdr, HDR_PIDHIGH, pid >> 16);
1322         SSVAL(state->smb1.hdr, HDR_TID,     tid);
1323         SSVAL(state->smb1.hdr, HDR_PID,     pid);
1324         SSVAL(state->smb1.hdr, HDR_UID,     uid);
1325         SSVAL(state->smb1.hdr, HDR_MID,     0); /* this comes later */
1326         SCVAL(state->smb1.hdr, HDR_WCT,     wct);
1327
1328         state->smb1.vwv = vwv;
1329
1330         SSVAL(state->smb1.bytecount_buf, 0, smbXcli_iov_len(bytes_iov, iov_count));
1331
1332         state->smb1.iov[0].iov_base = (void *)state->length_hdr;
1333         state->smb1.iov[0].iov_len  = sizeof(state->length_hdr);
1334         state->smb1.iov[1].iov_base = (void *)state->smb1.hdr;
1335         state->smb1.iov[1].iov_len  = sizeof(state->smb1.hdr);
1336         state->smb1.iov[2].iov_base = (void *)state->smb1.vwv;
1337         state->smb1.iov[2].iov_len  = wct * sizeof(uint16_t);
1338         state->smb1.iov[3].iov_base = (void *)state->smb1.bytecount_buf;
1339         state->smb1.iov[3].iov_len  = sizeof(uint16_t);
1340
1341         if (iov_count != 0) {
1342                 memcpy(&state->smb1.iov[4], bytes_iov,
1343                        iov_count * sizeof(*bytes_iov));
1344         }
1345         state->smb1.iov_count = iov_count + 4;
1346
1347         if (timeout_msec > 0) {
1348                 struct timeval endtime;
1349
1350                 endtime = timeval_current_ofs_msec(timeout_msec);
1351                 if (!tevent_req_set_endtime(req, ev, endtime)) {
1352                         return req;
1353                 }
1354         }
1355
1356         switch (smb_command) {
1357         case SMBtranss:
1358         case SMBtranss2:
1359         case SMBnttranss:
1360                 state->one_way = true;
1361                 break;
1362         case SMBntcancel:
1363                 state->one_way = true;
1364                 state->smb1.one_way_seqnum = true;
1365                 break;
1366         case SMBlockingX:
1367                 if ((wct == 8) &&
1368                     (CVAL(vwv+3, 0) == LOCKING_ANDX_OPLOCK_RELEASE)) {
1369                         state->one_way = true;
1370                 }
1371                 break;
1372         }
1373
1374         return req;
1375 }
1376
1377 static NTSTATUS smb1cli_conn_signv(struct smbXcli_conn *conn,
1378                                    struct iovec *iov, int iov_count,
1379                                    uint32_t *seqnum,
1380                                    bool one_way_seqnum)
1381 {
1382         TALLOC_CTX *frame = NULL;
1383         uint8_t *buf;
1384
1385         /*
1386          * Obvious optimization: Make cli_calculate_sign_mac work with struct
1387          * iovec directly. MD5Update would do that just fine.
1388          */
1389
1390         if (iov_count < 4) {
1391                 return NT_STATUS_INVALID_PARAMETER_MIX;
1392         }
1393         if (iov[0].iov_len != NBT_HDR_SIZE) {
1394                 return NT_STATUS_INVALID_PARAMETER_MIX;
1395         }
1396         if (iov[1].iov_len != (MIN_SMB_SIZE-sizeof(uint16_t))) {
1397                 return NT_STATUS_INVALID_PARAMETER_MIX;
1398         }
1399         if (iov[2].iov_len > (0xFF * sizeof(uint16_t))) {
1400                 return NT_STATUS_INVALID_PARAMETER_MIX;
1401         }
1402         if (iov[3].iov_len != sizeof(uint16_t)) {
1403                 return NT_STATUS_INVALID_PARAMETER_MIX;
1404         }
1405
1406         frame = talloc_stackframe();
1407
1408         buf = smbXcli_iov_concat(frame, &iov[1], iov_count - 1);
1409         if (buf == NULL) {
1410                 return NT_STATUS_NO_MEMORY;
1411         }
1412
1413         *seqnum = smb_signing_next_seqnum(conn->smb1.signing,
1414                                           one_way_seqnum);
1415         smb_signing_sign_pdu(conn->smb1.signing,
1416                              buf, talloc_get_size(buf),
1417                              *seqnum);
1418         memcpy(iov[1].iov_base, buf, iov[1].iov_len);
1419
1420         TALLOC_FREE(frame);
1421         return NT_STATUS_OK;
1422 }
1423
1424 static void smb1cli_req_writev_done(struct tevent_req *subreq);
1425 static NTSTATUS smb1cli_conn_dispatch_incoming(struct smbXcli_conn *conn,
1426                                                TALLOC_CTX *tmp_mem,
1427                                                uint8_t *inbuf);
1428
1429 static NTSTATUS smb1cli_req_writev_submit(struct tevent_req *req,
1430                                           struct smbXcli_req_state *state,
1431                                           struct iovec *iov, int iov_count)
1432 {
1433         struct tevent_req *subreq;
1434         NTSTATUS status;
1435         uint8_t cmd;
1436         uint16_t mid;
1437
1438         if (!smbXcli_conn_is_connected(state->conn)) {
1439                 return NT_STATUS_CONNECTION_DISCONNECTED;
1440         }
1441
1442         if (state->conn->protocol > PROTOCOL_NT1) {
1443                 return NT_STATUS_REVISION_MISMATCH;
1444         }
1445
1446         if (iov_count < 4) {
1447                 return NT_STATUS_INVALID_PARAMETER_MIX;
1448         }
1449         if (iov[0].iov_len != NBT_HDR_SIZE) {
1450                 return NT_STATUS_INVALID_PARAMETER_MIX;
1451         }
1452         if (iov[1].iov_len != (MIN_SMB_SIZE-sizeof(uint16_t))) {
1453                 return NT_STATUS_INVALID_PARAMETER_MIX;
1454         }
1455         if (iov[2].iov_len > (0xFF * sizeof(uint16_t))) {
1456                 return NT_STATUS_INVALID_PARAMETER_MIX;
1457         }
1458         if (iov[3].iov_len != sizeof(uint16_t)) {
1459                 return NT_STATUS_INVALID_PARAMETER_MIX;
1460         }
1461
1462         cmd = CVAL(iov[1].iov_base, HDR_COM);
1463         if (cmd == SMBreadBraw) {
1464                 if (smbXcli_conn_has_async_calls(state->conn)) {
1465                         return NT_STATUS_INVALID_PARAMETER_MIX;
1466                 }
1467                 state->conn->smb1.read_braw_req = req;
1468         }
1469
1470         if (state->smb1.mid != 0) {
1471                 mid = state->smb1.mid;
1472         } else {
1473                 mid = smb1cli_alloc_mid(state->conn);
1474         }
1475         SSVAL(iov[1].iov_base, HDR_MID, mid);
1476
1477         _smb_setlen_nbt(iov[0].iov_base, smbXcli_iov_len(&iov[1], iov_count-1));
1478
1479         status = smb1cli_conn_signv(state->conn, iov, iov_count,
1480                                     &state->smb1.seqnum,
1481                                     state->smb1.one_way_seqnum);
1482
1483         if (!NT_STATUS_IS_OK(status)) {
1484                 return status;
1485         }
1486
1487         /*
1488          * If we supported multiple encrytion contexts
1489          * here we'd look up based on tid.
1490          */
1491         if (common_encryption_on(state->conn->smb1.trans_enc)) {
1492                 char *buf, *enc_buf;
1493
1494                 buf = (char *)smbXcli_iov_concat(talloc_tos(), iov, iov_count);
1495                 if (buf == NULL) {
1496                         return NT_STATUS_NO_MEMORY;
1497                 }
1498                 status = common_encrypt_buffer(state->conn->smb1.trans_enc,
1499                                                (char *)buf, &enc_buf);
1500                 TALLOC_FREE(buf);
1501                 if (!NT_STATUS_IS_OK(status)) {
1502                         DEBUG(0, ("Error in encrypting client message: %s\n",
1503                                   nt_errstr(status)));
1504                         return status;
1505                 }
1506                 buf = (char *)talloc_memdup(state, enc_buf,
1507                                             smb_len_nbt(enc_buf)+4);
1508                 SAFE_FREE(enc_buf);
1509                 if (buf == NULL) {
1510                         return NT_STATUS_NO_MEMORY;
1511                 }
1512                 iov[0].iov_base = (void *)buf;
1513                 iov[0].iov_len = talloc_get_size(buf);
1514                 iov_count = 1;
1515         }
1516
1517         if (state->conn->dispatch_incoming == NULL) {
1518                 state->conn->dispatch_incoming = smb1cli_conn_dispatch_incoming;
1519         }
1520
1521         tevent_req_set_cancel_fn(req, smbXcli_req_cancel);
1522
1523         subreq = writev_send(state, state->ev, state->conn->outgoing,
1524                              state->conn->write_fd, false, iov, iov_count);
1525         if (subreq == NULL) {
1526                 return NT_STATUS_NO_MEMORY;
1527         }
1528         tevent_req_set_callback(subreq, smb1cli_req_writev_done, req);
1529         return NT_STATUS_OK;
1530 }
1531
1532 struct tevent_req *smb1cli_req_send(TALLOC_CTX *mem_ctx,
1533                                     struct tevent_context *ev,
1534                                     struct smbXcli_conn *conn,
1535                                     uint8_t smb_command,
1536                                     uint8_t additional_flags,
1537                                     uint8_t clear_flags,
1538                                     uint16_t additional_flags2,
1539                                     uint16_t clear_flags2,
1540                                     uint32_t timeout_msec,
1541                                     uint32_t pid,
1542                                     struct smbXcli_tcon *tcon,
1543                                     struct smbXcli_session *session,
1544                                     uint8_t wct, uint16_t *vwv,
1545                                     uint32_t num_bytes,
1546                                     const uint8_t *bytes)
1547 {
1548         struct tevent_req *req;
1549         struct iovec iov;
1550         NTSTATUS status;
1551
1552         iov.iov_base = discard_const_p(void, bytes);
1553         iov.iov_len = num_bytes;
1554
1555         req = smb1cli_req_create(mem_ctx, ev, conn, smb_command,
1556                                  additional_flags, clear_flags,
1557                                  additional_flags2, clear_flags2,
1558                                  timeout_msec,
1559                                  pid, tcon, session,
1560                                  wct, vwv, 1, &iov);
1561         if (req == NULL) {
1562                 return NULL;
1563         }
1564         if (!tevent_req_is_in_progress(req)) {
1565                 return tevent_req_post(req, ev);
1566         }
1567         status = smb1cli_req_chain_submit(&req, 1);
1568         if (tevent_req_nterror(req, status)) {
1569                 return tevent_req_post(req, ev);
1570         }
1571         return req;
1572 }
1573
1574 static void smb1cli_req_writev_done(struct tevent_req *subreq)
1575 {
1576         struct tevent_req *req =
1577                 tevent_req_callback_data(subreq,
1578                 struct tevent_req);
1579         struct smbXcli_req_state *state =
1580                 tevent_req_data(req,
1581                 struct smbXcli_req_state);
1582         ssize_t nwritten;
1583         int err;
1584
1585         nwritten = writev_recv(subreq, &err);
1586         TALLOC_FREE(subreq);
1587         if (nwritten == -1) {
1588                 NTSTATUS status = map_nt_error_from_unix_common(err);
1589                 smbXcli_conn_disconnect(state->conn, status);
1590                 return;
1591         }
1592
1593         if (state->one_way) {
1594                 state->inbuf = NULL;
1595                 tevent_req_done(req);
1596                 return;
1597         }
1598
1599         if (!smbXcli_req_set_pending(req)) {
1600                 tevent_req_nterror(req, NT_STATUS_NO_MEMORY);
1601                 return;
1602         }
1603 }
1604
1605 static void smbXcli_conn_received(struct tevent_req *subreq)
1606 {
1607         struct smbXcli_conn *conn =
1608                 tevent_req_callback_data(subreq,
1609                 struct smbXcli_conn);
1610         TALLOC_CTX *frame = talloc_stackframe();
1611         NTSTATUS status;
1612         uint8_t *inbuf;
1613         ssize_t received;
1614         int err;
1615
1616         if (subreq != conn->read_smb_req) {
1617                 DEBUG(1, ("Internal error: cli_smb_received called with "
1618                           "unexpected subreq\n"));
1619                 smbXcli_conn_disconnect(conn, NT_STATUS_INTERNAL_ERROR);
1620                 TALLOC_FREE(frame);
1621                 return;
1622         }
1623         conn->read_smb_req = NULL;
1624
1625         received = read_smb_recv(subreq, frame, &inbuf, &err);
1626         TALLOC_FREE(subreq);
1627         if (received == -1) {
1628                 status = map_nt_error_from_unix_common(err);
1629                 smbXcli_conn_disconnect(conn, status);
1630                 TALLOC_FREE(frame);
1631                 return;
1632         }
1633
1634         status = conn->dispatch_incoming(conn, frame, inbuf);
1635         TALLOC_FREE(frame);
1636         if (NT_STATUS_IS_OK(status)) {
1637                 /*
1638                  * We should not do any more processing
1639                  * as the dispatch function called
1640                  * tevent_req_done().
1641                  */
1642                 return;
1643         }
1644
1645         if (!NT_STATUS_EQUAL(status, NT_STATUS_RETRY)) {
1646                 /*
1647                  * We got an error, so notify all pending requests
1648                  */
1649                 smbXcli_conn_disconnect(conn, status);
1650                 return;
1651         }
1652
1653         /*
1654          * We got NT_STATUS_RETRY, so we may ask for a
1655          * next incoming pdu.
1656          */
1657         if (!smbXcli_conn_receive_next(conn)) {
1658                 smbXcli_conn_disconnect(conn, NT_STATUS_NO_MEMORY);
1659         }
1660 }
1661
1662 static NTSTATUS smb1cli_inbuf_parse_chain(uint8_t *buf, TALLOC_CTX *mem_ctx,
1663                                           struct iovec **piov, int *pnum_iov)
1664 {
1665         struct iovec *iov;
1666         int num_iov;
1667         size_t buflen;
1668         size_t taken;
1669         size_t remaining;
1670         uint8_t *hdr;
1671         uint8_t cmd;
1672         uint32_t wct_ofs;
1673         NTSTATUS status;
1674         size_t min_size = MIN_SMB_SIZE;
1675
1676         buflen = smb_len_tcp(buf);
1677         taken = 0;
1678
1679         hdr = buf + NBT_HDR_SIZE;
1680
1681         status = smb1cli_pull_raw_error(hdr);
1682         if (NT_STATUS_IS_ERR(status)) {
1683                 /*
1684                  * This is an ugly hack to support OS/2
1685                  * which skips the byte_count in the DATA block
1686                  * on some error responses.
1687                  *
1688                  * See bug #9096
1689                  */
1690                 min_size -= sizeof(uint16_t);
1691         }
1692
1693         if (buflen < min_size) {
1694                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
1695         }
1696
1697         /*
1698          * This returns iovec elements in the following order:
1699          *
1700          * - SMB header
1701          *
1702          * - Parameter Block
1703          * - Data Block
1704          *
1705          * - Parameter Block
1706          * - Data Block
1707          *
1708          * - Parameter Block
1709          * - Data Block
1710          */
1711         num_iov = 1;
1712
1713         iov = talloc_array(mem_ctx, struct iovec, num_iov);
1714         if (iov == NULL) {
1715                 return NT_STATUS_NO_MEMORY;
1716         }
1717         iov[0].iov_base = hdr;
1718         iov[0].iov_len = HDR_WCT;
1719         taken += HDR_WCT;
1720
1721         cmd = CVAL(hdr, HDR_COM);
1722         wct_ofs = HDR_WCT;
1723
1724         while (true) {
1725                 size_t len = buflen - taken;
1726                 struct iovec *cur;
1727                 struct iovec *iov_tmp;
1728                 uint8_t wct;
1729                 uint32_t bcc_ofs;
1730                 uint16_t bcc;
1731                 size_t needed;
1732
1733                 /*
1734                  * we need at least WCT
1735                  */
1736                 needed = sizeof(uint8_t);
1737                 if (len < needed) {
1738                         DEBUG(10, ("%s: %d bytes left, expected at least %d\n",
1739                                    __location__, (int)len, (int)needed));
1740                         goto inval;
1741                 }
1742
1743                 /*
1744                  * Now we check if the specified words are there
1745                  */
1746                 wct = CVAL(hdr, wct_ofs);
1747                 needed += wct * sizeof(uint16_t);
1748                 if (len < needed) {
1749                         DEBUG(10, ("%s: %d bytes left, expected at least %d\n",
1750                                    __location__, (int)len, (int)needed));
1751                         goto inval;
1752                 }
1753
1754                 if ((num_iov == 1) &&
1755                     (len == needed) &&
1756                     NT_STATUS_IS_ERR(status))
1757                 {
1758                         /*
1759                          * This is an ugly hack to support OS/2
1760                          * which skips the byte_count in the DATA block
1761                          * on some error responses.
1762                          *
1763                          * See bug #9096
1764                          */
1765                         iov_tmp = talloc_realloc(mem_ctx, iov, struct iovec,
1766                                                  num_iov + 2);
1767                         if (iov_tmp == NULL) {
1768                                 TALLOC_FREE(iov);
1769                                 return NT_STATUS_NO_MEMORY;
1770                         }
1771                         iov = iov_tmp;
1772                         cur = &iov[num_iov];
1773                         num_iov += 2;
1774
1775                         cur[0].iov_len = 0;
1776                         cur[0].iov_base = hdr + (wct_ofs + sizeof(uint8_t));
1777                         cur[1].iov_len = 0;
1778                         cur[1].iov_base = cur[0].iov_base;
1779
1780                         taken += needed;
1781                         break;
1782                 }
1783
1784                 /*
1785                  * we need at least BCC
1786                  */
1787                 needed += sizeof(uint16_t);
1788                 if (len < needed) {
1789                         DEBUG(10, ("%s: %d bytes left, expected at least %d\n",
1790                                    __location__, (int)len, (int)needed));
1791                         goto inval;
1792                 }
1793
1794                 /*
1795                  * Now we check if the specified bytes are there
1796                  */
1797                 bcc_ofs = wct_ofs + sizeof(uint8_t) + wct * sizeof(uint16_t);
1798                 bcc = SVAL(hdr, bcc_ofs);
1799                 needed += bcc * sizeof(uint8_t);
1800                 if (len < needed) {
1801                         DEBUG(10, ("%s: %d bytes left, expected at least %d\n",
1802                                    __location__, (int)len, (int)needed));
1803                         goto inval;
1804                 }
1805
1806                 /*
1807                  * we allocate 2 iovec structures for words and bytes
1808                  */
1809                 iov_tmp = talloc_realloc(mem_ctx, iov, struct iovec,
1810                                          num_iov + 2);
1811                 if (iov_tmp == NULL) {
1812                         TALLOC_FREE(iov);
1813                         return NT_STATUS_NO_MEMORY;
1814                 }
1815                 iov = iov_tmp;
1816                 cur = &iov[num_iov];
1817                 num_iov += 2;
1818
1819                 cur[0].iov_len = wct * sizeof(uint16_t);
1820                 cur[0].iov_base = hdr + (wct_ofs + sizeof(uint8_t));
1821                 cur[1].iov_len = bcc * sizeof(uint8_t);
1822                 cur[1].iov_base = hdr + (bcc_ofs + sizeof(uint16_t));
1823
1824                 taken += needed;
1825
1826                 if (!smb1cli_is_andx_req(cmd)) {
1827                         /*
1828                          * If the current command does not have AndX chanining
1829                          * we are done.
1830                          */
1831                         break;
1832                 }
1833
1834                 if (wct == 0 && bcc == 0) {
1835                         /*
1836                          * An empty response also ends the chain,
1837                          * most likely with an error.
1838                          */
1839                         break;
1840                 }
1841
1842                 if (wct < 2) {
1843                         DEBUG(10, ("%s: wct[%d] < 2 for cmd[0x%02X]\n",
1844                                    __location__, (int)wct, (int)cmd));
1845                         goto inval;
1846                 }
1847                 cmd = CVAL(cur[0].iov_base, 0);
1848                 if (cmd == 0xFF) {
1849                         /*
1850                          * If it is the end of the chain we are also done.
1851                          */
1852                         break;
1853                 }
1854                 wct_ofs = SVAL(cur[0].iov_base, 2);
1855
1856                 if (wct_ofs < taken) {
1857                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
1858                 }
1859                 if (wct_ofs > buflen) {
1860                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
1861                 }
1862
1863                 /*
1864                  * we consumed everything up to the start of the next
1865                  * parameter block.
1866                  */
1867                 taken = wct_ofs;
1868         }
1869
1870         remaining = buflen - taken;
1871
1872         if (remaining > 0 && num_iov >= 3) {
1873                 /*
1874                  * The last DATA block gets the remaining
1875                  * bytes, this is needed to support
1876                  * CAP_LARGE_WRITEX and CAP_LARGE_READX.
1877                  */
1878                 iov[num_iov-1].iov_len += remaining;
1879         }
1880
1881         *piov = iov;
1882         *pnum_iov = num_iov;
1883         return NT_STATUS_OK;
1884
1885 inval:
1886         TALLOC_FREE(iov);
1887         return NT_STATUS_INVALID_NETWORK_RESPONSE;
1888 }
1889
1890 static NTSTATUS smb1cli_conn_dispatch_incoming(struct smbXcli_conn *conn,
1891                                                TALLOC_CTX *tmp_mem,
1892                                                uint8_t *inbuf)
1893 {
1894         struct tevent_req *req;
1895         struct smbXcli_req_state *state;
1896         NTSTATUS status;
1897         size_t num_pending;
1898         size_t i;
1899         uint8_t cmd;
1900         uint16_t mid;
1901         bool oplock_break;
1902         uint8_t *inhdr = inbuf + NBT_HDR_SIZE;
1903         size_t len = smb_len_tcp(inbuf);
1904         struct iovec *iov = NULL;
1905         int num_iov = 0;
1906         struct tevent_req **chain = NULL;
1907         size_t num_chained = 0;
1908         size_t num_responses = 0;
1909
1910         if (conn->smb1.read_braw_req != NULL) {
1911                 req = conn->smb1.read_braw_req;
1912                 conn->smb1.read_braw_req = NULL;
1913                 state = tevent_req_data(req, struct smbXcli_req_state);
1914
1915                 smbXcli_req_unset_pending(req);
1916
1917                 if (state->smb1.recv_iov == NULL) {
1918                         /*
1919                          * For requests with more than
1920                          * one response, we have to readd the
1921                          * recv_iov array.
1922                          */
1923                         state->smb1.recv_iov = talloc_zero_array(state,
1924                                                                  struct iovec,
1925                                                                  3);
1926                         if (tevent_req_nomem(state->smb1.recv_iov, req)) {
1927                                 return NT_STATUS_OK;
1928                         }
1929                 }
1930
1931                 state->smb1.recv_iov[0].iov_base = (void *)(inhdr);
1932                 state->smb1.recv_iov[0].iov_len = len;
1933                 ZERO_STRUCT(state->smb1.recv_iov[1]);
1934                 ZERO_STRUCT(state->smb1.recv_iov[2]);
1935
1936                 state->smb1.recv_cmd = SMBreadBraw;
1937                 state->smb1.recv_status = NT_STATUS_OK;
1938                 state->inbuf = talloc_move(state->smb1.recv_iov, &inbuf);
1939
1940                 tevent_req_done(req);
1941                 return NT_STATUS_OK;
1942         }
1943
1944         if ((IVAL(inhdr, 0) != SMB_MAGIC) /* 0xFF"SMB" */
1945             && (SVAL(inhdr, 0) != 0x45ff)) /* 0xFF"E" */ {
1946                 DEBUG(10, ("Got non-SMB PDU\n"));
1947                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
1948         }
1949
1950         /*
1951          * If we supported multiple encrytion contexts
1952          * here we'd look up based on tid.
1953          */
1954         if (common_encryption_on(conn->smb1.trans_enc)
1955             && (CVAL(inbuf, 0) == 0)) {
1956                 uint16_t enc_ctx_num;
1957
1958                 status = get_enc_ctx_num(inbuf, &enc_ctx_num);
1959                 if (!NT_STATUS_IS_OK(status)) {
1960                         DEBUG(10, ("get_enc_ctx_num returned %s\n",
1961                                    nt_errstr(status)));
1962                         return status;
1963                 }
1964
1965                 if (enc_ctx_num != conn->smb1.trans_enc->enc_ctx_num) {
1966                         DEBUG(10, ("wrong enc_ctx %d, expected %d\n",
1967                                    enc_ctx_num,
1968                                    conn->smb1.trans_enc->enc_ctx_num));
1969                         return NT_STATUS_INVALID_HANDLE;
1970                 }
1971
1972                 status = common_decrypt_buffer(conn->smb1.trans_enc,
1973                                                (char *)inbuf);
1974                 if (!NT_STATUS_IS_OK(status)) {
1975                         DEBUG(10, ("common_decrypt_buffer returned %s\n",
1976                                    nt_errstr(status)));
1977                         return status;
1978                 }
1979                 inhdr = inbuf + NBT_HDR_SIZE;
1980                 len = smb_len_nbt(inbuf);
1981         }
1982
1983         mid = SVAL(inhdr, HDR_MID);
1984         num_pending = talloc_array_length(conn->pending);
1985
1986         for (i=0; i<num_pending; i++) {
1987                 if (mid == smb1cli_req_mid(conn->pending[i])) {
1988                         break;
1989                 }
1990         }
1991         if (i == num_pending) {
1992                 /* Dump unexpected reply */
1993                 return NT_STATUS_RETRY;
1994         }
1995
1996         oplock_break = false;
1997
1998         if (mid == 0xffff) {
1999                 /*
2000                  * Paranoia checks that this is really an oplock break request.
2001                  */
2002                 oplock_break = (len == 51); /* hdr + 8 words */
2003                 oplock_break &= ((CVAL(inhdr, HDR_FLG) & FLAG_REPLY) == 0);
2004                 oplock_break &= (CVAL(inhdr, HDR_COM) == SMBlockingX);
2005                 oplock_break &= (SVAL(inhdr, HDR_VWV+VWV(6)) == 0);
2006                 oplock_break &= (SVAL(inhdr, HDR_VWV+VWV(7)) == 0);
2007
2008                 if (!oplock_break) {
2009                         /* Dump unexpected reply */
2010                         return NT_STATUS_RETRY;
2011                 }
2012         }
2013
2014         req = conn->pending[i];
2015         state = tevent_req_data(req, struct smbXcli_req_state);
2016
2017         if (!oplock_break /* oplock breaks are not signed */
2018             && !smb_signing_check_pdu(conn->smb1.signing,
2019                                       inhdr, len, state->smb1.seqnum+1)) {
2020                 DEBUG(10, ("cli_check_sign_mac failed\n"));
2021                 return NT_STATUS_ACCESS_DENIED;
2022         }
2023
2024         status = smb1cli_inbuf_parse_chain(inbuf, tmp_mem,
2025                                            &iov, &num_iov);
2026         if (!NT_STATUS_IS_OK(status)) {
2027                 DEBUG(10,("smb1cli_inbuf_parse_chain - %s\n",
2028                           nt_errstr(status)));
2029                 return status;
2030         }
2031
2032         cmd = CVAL(inhdr, HDR_COM);
2033         status = smb1cli_pull_raw_error(inhdr);
2034
2035         if (NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_SESSION_EXPIRED) &&
2036             (state->session != NULL) && state->session->disconnect_expired)
2037         {
2038                 /*
2039                  * this should be a short term hack
2040                  * until the upper layers have implemented
2041                  * re-authentication.
2042                  */
2043                 return status;
2044         }
2045
2046         if (state->smb1.chained_requests == NULL) {
2047                 if (num_iov != 3) {
2048                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
2049                 }
2050
2051                 smbXcli_req_unset_pending(req);
2052
2053                 if (state->smb1.recv_iov == NULL) {
2054                         /*
2055                          * For requests with more than
2056                          * one response, we have to readd the
2057                          * recv_iov array.
2058                          */
2059                         state->smb1.recv_iov = talloc_zero_array(state,
2060                                                                  struct iovec,
2061                                                                  3);
2062                         if (tevent_req_nomem(state->smb1.recv_iov, req)) {
2063                                 return NT_STATUS_OK;
2064                         }
2065                 }
2066
2067                 state->smb1.recv_cmd = cmd;
2068                 state->smb1.recv_status = status;
2069                 state->inbuf = talloc_move(state->smb1.recv_iov, &inbuf);
2070
2071                 state->smb1.recv_iov[0] = iov[0];
2072                 state->smb1.recv_iov[1] = iov[1];
2073                 state->smb1.recv_iov[2] = iov[2];
2074
2075                 if (talloc_array_length(conn->pending) == 0) {
2076                         tevent_req_done(req);
2077                         return NT_STATUS_OK;
2078                 }
2079
2080                 tevent_req_defer_callback(req, state->ev);
2081                 tevent_req_done(req);
2082                 return NT_STATUS_RETRY;
2083         }
2084
2085         chain = talloc_move(tmp_mem, &state->smb1.chained_requests);
2086         num_chained = talloc_array_length(chain);
2087         num_responses = (num_iov - 1)/2;
2088
2089         if (num_responses > num_chained) {
2090                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
2091         }
2092
2093         for (i=0; i<num_chained; i++) {
2094                 size_t iov_idx = 1 + (i*2);
2095                 struct iovec *cur = &iov[iov_idx];
2096                 uint8_t *inbuf_ref;
2097
2098                 req = chain[i];
2099                 state = tevent_req_data(req, struct smbXcli_req_state);
2100
2101                 smbXcli_req_unset_pending(req);
2102
2103                 /*
2104                  * as we finish multiple requests here
2105                  * we need to defer the callbacks as
2106                  * they could destroy our current stack state.
2107                  */
2108                 tevent_req_defer_callback(req, state->ev);
2109
2110                 if (i >= num_responses) {
2111                         tevent_req_nterror(req, NT_STATUS_REQUEST_ABORTED);
2112                         continue;
2113                 }
2114
2115                 if (state->smb1.recv_iov == NULL) {
2116                         /*
2117                          * For requests with more than
2118                          * one response, we have to readd the
2119                          * recv_iov array.
2120                          */
2121                         state->smb1.recv_iov = talloc_zero_array(state,
2122                                                                  struct iovec,
2123                                                                  3);
2124                         if (tevent_req_nomem(state->smb1.recv_iov, req)) {
2125                                 continue;
2126                         }
2127                 }
2128
2129                 state->smb1.recv_cmd = cmd;
2130
2131                 if (i == (num_responses - 1)) {
2132                         /*
2133                          * The last request in the chain gets the status
2134                          */
2135                         state->smb1.recv_status = status;
2136                 } else {
2137                         cmd = CVAL(cur[0].iov_base, 0);
2138                         state->smb1.recv_status = NT_STATUS_OK;
2139                 }
2140
2141                 state->inbuf = inbuf;
2142
2143                 /*
2144                  * Note: here we use talloc_reference() in a way
2145                  *       that does not expose it to the caller.
2146                  */
2147                 inbuf_ref = talloc_reference(state->smb1.recv_iov, inbuf);
2148                 if (tevent_req_nomem(inbuf_ref, req)) {
2149                         continue;
2150                 }
2151
2152                 /* copy the related buffers */
2153                 state->smb1.recv_iov[0] = iov[0];
2154                 state->smb1.recv_iov[1] = cur[0];
2155                 state->smb1.recv_iov[2] = cur[1];
2156
2157                 tevent_req_done(req);
2158         }
2159
2160         return NT_STATUS_RETRY;
2161 }
2162
2163 NTSTATUS smb1cli_req_recv(struct tevent_req *req,
2164                           TALLOC_CTX *mem_ctx,
2165                           struct iovec **piov,
2166                           uint8_t **phdr,
2167                           uint8_t *pwct,
2168                           uint16_t **pvwv,
2169                           uint32_t *pvwv_offset,
2170                           uint32_t *pnum_bytes,
2171                           uint8_t **pbytes,
2172                           uint32_t *pbytes_offset,
2173                           uint8_t **pinbuf,
2174                           const struct smb1cli_req_expected_response *expected,
2175                           size_t num_expected)
2176 {
2177         struct smbXcli_req_state *state =
2178                 tevent_req_data(req,
2179                 struct smbXcli_req_state);
2180         NTSTATUS status = NT_STATUS_OK;
2181         struct iovec *recv_iov = NULL;
2182         uint8_t *hdr = NULL;
2183         uint8_t wct = 0;
2184         uint32_t vwv_offset = 0;
2185         uint16_t *vwv = NULL;
2186         uint32_t num_bytes = 0;
2187         uint32_t bytes_offset = 0;
2188         uint8_t *bytes = NULL;
2189         size_t i;
2190         bool found_status = false;
2191         bool found_size = false;
2192
2193         if (piov != NULL) {
2194                 *piov = NULL;
2195         }
2196         if (phdr != NULL) {
2197                 *phdr = 0;
2198         }
2199         if (pwct != NULL) {
2200                 *pwct = 0;
2201         }
2202         if (pvwv != NULL) {
2203                 *pvwv = NULL;
2204         }
2205         if (pvwv_offset != NULL) {
2206                 *pvwv_offset = 0;
2207         }
2208         if (pnum_bytes != NULL) {
2209                 *pnum_bytes = 0;
2210         }
2211         if (pbytes != NULL) {
2212                 *pbytes = NULL;
2213         }
2214         if (pbytes_offset != NULL) {
2215                 *pbytes_offset = 0;
2216         }
2217         if (pinbuf != NULL) {
2218                 *pinbuf = NULL;
2219         }
2220
2221         if (state->inbuf != NULL) {
2222                 recv_iov = state->smb1.recv_iov;
2223                 state->smb1.recv_iov = NULL;
2224                 if (state->smb1.recv_cmd != SMBreadBraw) {
2225                         hdr = (uint8_t *)recv_iov[0].iov_base;
2226                         wct = recv_iov[1].iov_len/2;
2227                         vwv = (uint16_t *)recv_iov[1].iov_base;
2228                         vwv_offset = PTR_DIFF(vwv, hdr);
2229                         num_bytes = recv_iov[2].iov_len;
2230                         bytes = (uint8_t *)recv_iov[2].iov_base;
2231                         bytes_offset = PTR_DIFF(bytes, hdr);
2232                 }
2233         }
2234
2235         if (tevent_req_is_nterror(req, &status)) {
2236                 for (i=0; i < num_expected; i++) {
2237                         if (NT_STATUS_EQUAL(status, expected[i].status)) {
2238                                 found_status = true;
2239                                 break;
2240                         }
2241                 }
2242
2243                 if (found_status) {
2244                         return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
2245                 }
2246
2247                 return status;
2248         }
2249
2250         if (num_expected == 0) {
2251                 found_status = true;
2252                 found_size = true;
2253         }
2254
2255         status = state->smb1.recv_status;
2256
2257         for (i=0; i < num_expected; i++) {
2258                 if (!NT_STATUS_EQUAL(status, expected[i].status)) {
2259                         continue;
2260                 }
2261
2262                 found_status = true;
2263                 if (expected[i].wct == 0) {
2264                         found_size = true;
2265                         break;
2266                 }
2267
2268                 if (expected[i].wct == wct) {
2269                         found_size = true;
2270                         break;
2271                 }
2272         }
2273
2274         if (!found_status) {
2275                 return status;
2276         }
2277
2278         if (!found_size) {
2279                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
2280         }
2281
2282         if (piov != NULL) {
2283                 *piov = talloc_move(mem_ctx, &recv_iov);
2284         }
2285
2286         if (phdr != NULL) {
2287                 *phdr = hdr;
2288         }
2289         if (pwct != NULL) {
2290                 *pwct = wct;
2291         }
2292         if (pvwv != NULL) {
2293                 *pvwv = vwv;
2294         }
2295         if (pvwv_offset != NULL) {
2296                 *pvwv_offset = vwv_offset;
2297         }
2298         if (pnum_bytes != NULL) {
2299                 *pnum_bytes = num_bytes;
2300         }
2301         if (pbytes != NULL) {
2302                 *pbytes = bytes;
2303         }
2304         if (pbytes_offset != NULL) {
2305                 *pbytes_offset = bytes_offset;
2306         }
2307         if (pinbuf != NULL) {
2308                 *pinbuf = state->inbuf;
2309         }
2310
2311         return status;
2312 }
2313
2314 size_t smb1cli_req_wct_ofs(struct tevent_req **reqs, int num_reqs)
2315 {
2316         size_t wct_ofs;
2317         int i;
2318
2319         wct_ofs = HDR_WCT;
2320
2321         for (i=0; i<num_reqs; i++) {
2322                 struct smbXcli_req_state *state;
2323                 state = tevent_req_data(reqs[i], struct smbXcli_req_state);
2324                 wct_ofs += smbXcli_iov_len(state->smb1.iov+2,
2325                                            state->smb1.iov_count-2);
2326                 wct_ofs = (wct_ofs + 3) & ~3;
2327         }
2328         return wct_ofs;
2329 }
2330
2331 NTSTATUS smb1cli_req_chain_submit(struct tevent_req **reqs, int num_reqs)
2332 {
2333         struct smbXcli_req_state *first_state =
2334                 tevent_req_data(reqs[0],
2335                 struct smbXcli_req_state);
2336         struct smbXcli_req_state *state;
2337         size_t wct_offset;
2338         size_t chain_padding = 0;
2339         int i, iovlen;
2340         struct iovec *iov = NULL;
2341         struct iovec *this_iov;
2342         NTSTATUS status;
2343         size_t nbt_len;
2344
2345         if (num_reqs == 1) {
2346                 return smb1cli_req_writev_submit(reqs[0], first_state,
2347                                                  first_state->smb1.iov,
2348                                                  first_state->smb1.iov_count);
2349         }
2350
2351         iovlen = 0;
2352         for (i=0; i<num_reqs; i++) {
2353                 if (!tevent_req_is_in_progress(reqs[i])) {
2354                         return NT_STATUS_INTERNAL_ERROR;
2355                 }
2356
2357                 state = tevent_req_data(reqs[i], struct smbXcli_req_state);
2358
2359                 if (state->smb1.iov_count < 4) {
2360                         return NT_STATUS_INVALID_PARAMETER_MIX;
2361                 }
2362
2363                 if (i == 0) {
2364                         /*
2365                          * The NBT and SMB header
2366                          */
2367                         iovlen += 2;
2368                 } else {
2369                         /*
2370                          * Chain padding
2371                          */
2372                         iovlen += 1;
2373                 }
2374
2375                 /*
2376                  * words and bytes
2377                  */
2378                 iovlen += state->smb1.iov_count - 2;
2379         }
2380
2381         iov = talloc_zero_array(first_state, struct iovec, iovlen);
2382         if (iov == NULL) {
2383                 return NT_STATUS_NO_MEMORY;
2384         }
2385
2386         first_state->smb1.chained_requests = (struct tevent_req **)talloc_memdup(
2387                 first_state, reqs, sizeof(*reqs) * num_reqs);
2388         if (first_state->smb1.chained_requests == NULL) {
2389                 TALLOC_FREE(iov);
2390                 return NT_STATUS_NO_MEMORY;
2391         }
2392
2393         wct_offset = HDR_WCT;
2394         this_iov = iov;
2395
2396         for (i=0; i<num_reqs; i++) {
2397                 size_t next_padding = 0;
2398                 uint16_t *vwv;
2399
2400                 state = tevent_req_data(reqs[i], struct smbXcli_req_state);
2401
2402                 if (i < num_reqs-1) {
2403                         if (!smb1cli_is_andx_req(CVAL(state->smb1.hdr, HDR_COM))
2404                             || CVAL(state->smb1.hdr, HDR_WCT) < 2) {
2405                                 TALLOC_FREE(iov);
2406                                 TALLOC_FREE(first_state->smb1.chained_requests);
2407                                 return NT_STATUS_INVALID_PARAMETER_MIX;
2408                         }
2409                 }
2410
2411                 wct_offset += smbXcli_iov_len(state->smb1.iov+2,
2412                                               state->smb1.iov_count-2) + 1;
2413                 if ((wct_offset % 4) != 0) {
2414                         next_padding = 4 - (wct_offset % 4);
2415                 }
2416                 wct_offset += next_padding;
2417                 vwv = state->smb1.vwv;
2418
2419                 if (i < num_reqs-1) {
2420                         struct smbXcli_req_state *next_state =
2421                                 tevent_req_data(reqs[i+1],
2422                                 struct smbXcli_req_state);
2423                         SCVAL(vwv+0, 0, CVAL(next_state->smb1.hdr, HDR_COM));
2424                         SCVAL(vwv+0, 1, 0);
2425                         SSVAL(vwv+1, 0, wct_offset);
2426                 } else if (smb1cli_is_andx_req(CVAL(state->smb1.hdr, HDR_COM))) {
2427                         /* properly end the chain */
2428                         SCVAL(vwv+0, 0, 0xff);
2429                         SCVAL(vwv+0, 1, 0xff);
2430                         SSVAL(vwv+1, 0, 0);
2431                 }
2432
2433                 if (i == 0) {
2434                         /*
2435                          * The NBT and SMB header
2436                          */
2437                         this_iov[0] = state->smb1.iov[0];
2438                         this_iov[1] = state->smb1.iov[1];
2439                         this_iov += 2;
2440                 } else {
2441                         /*
2442                          * This one is a bit subtle. We have to add
2443                          * chain_padding bytes between the requests, and we
2444                          * have to also include the wct field of the
2445                          * subsequent requests. We use the subsequent header
2446                          * for the padding, it contains the wct field in its
2447                          * last byte.
2448                          */
2449                         this_iov[0].iov_len = chain_padding+1;
2450                         this_iov[0].iov_base = (void *)&state->smb1.hdr[
2451                                 sizeof(state->smb1.hdr) - this_iov[0].iov_len];
2452                         memset(this_iov[0].iov_base, 0, this_iov[0].iov_len-1);
2453                         this_iov += 1;
2454                 }
2455
2456                 /*
2457                  * copy the words and bytes
2458                  */
2459                 memcpy(this_iov, state->smb1.iov+2,
2460                        sizeof(struct iovec) * (state->smb1.iov_count-2));
2461                 this_iov += state->smb1.iov_count - 2;
2462                 chain_padding = next_padding;
2463         }
2464
2465         nbt_len = smbXcli_iov_len(&iov[1], iovlen-1);
2466         if (nbt_len > first_state->conn->smb1.max_xmit) {
2467                 TALLOC_FREE(iov);
2468                 TALLOC_FREE(first_state->smb1.chained_requests);
2469                 return NT_STATUS_INVALID_PARAMETER_MIX;
2470         }
2471
2472         status = smb1cli_req_writev_submit(reqs[0], first_state, iov, iovlen);
2473         if (!NT_STATUS_IS_OK(status)) {
2474                 TALLOC_FREE(iov);
2475                 TALLOC_FREE(first_state->smb1.chained_requests);
2476                 return status;
2477         }
2478
2479         return NT_STATUS_OK;
2480 }
2481
2482 bool smbXcli_conn_has_async_calls(struct smbXcli_conn *conn)
2483 {
2484         return ((tevent_queue_length(conn->outgoing) != 0)
2485                 || (talloc_array_length(conn->pending) != 0));
2486 }
2487
2488 bool smbXcli_conn_dfs_supported(struct smbXcli_conn *conn)
2489 {
2490         if (conn->protocol >= PROTOCOL_SMB2_02) {
2491                 return (smb2cli_conn_server_capabilities(conn) & SMB2_CAP_DFS);
2492         }
2493
2494         return (smb1cli_conn_capabilities(conn) & CAP_DFS);
2495 }
2496
2497 bool smb2cli_conn_req_possible(struct smbXcli_conn *conn, uint32_t *max_dyn_len)
2498 {
2499         uint16_t credits = 1;
2500
2501         if (conn->smb2.cur_credits == 0) {
2502                 if (max_dyn_len != NULL) {
2503                         *max_dyn_len = 0;
2504                 }
2505                 return false;
2506         }
2507
2508         if (conn->smb2.server.capabilities & SMB2_CAP_LARGE_MTU) {
2509                 credits = conn->smb2.cur_credits;
2510         }
2511
2512         if (max_dyn_len != NULL) {
2513                 *max_dyn_len = credits * 65536;
2514         }
2515
2516         return true;
2517 }
2518
2519 uint32_t smb2cli_conn_server_capabilities(struct smbXcli_conn *conn)
2520 {
2521         return conn->smb2.server.capabilities;
2522 }
2523
2524 uint16_t smb2cli_conn_server_security_mode(struct smbXcli_conn *conn)
2525 {
2526         return conn->smb2.server.security_mode;
2527 }
2528
2529 uint32_t smb2cli_conn_max_trans_size(struct smbXcli_conn *conn)
2530 {
2531         return conn->smb2.server.max_trans_size;
2532 }
2533
2534 uint32_t smb2cli_conn_max_read_size(struct smbXcli_conn *conn)
2535 {
2536         return conn->smb2.server.max_read_size;
2537 }
2538
2539 uint32_t smb2cli_conn_max_write_size(struct smbXcli_conn *conn)
2540 {
2541         return conn->smb2.server.max_write_size;
2542 }
2543
2544 void smb2cli_conn_set_max_credits(struct smbXcli_conn *conn,
2545                                   uint16_t max_credits)
2546 {
2547         conn->smb2.max_credits = max_credits;
2548 }
2549
2550 static void smb2cli_req_cancel_done(struct tevent_req *subreq);
2551
2552 static bool smb2cli_req_cancel(struct tevent_req *req)
2553 {
2554         struct smbXcli_req_state *state =
2555                 tevent_req_data(req,
2556                 struct smbXcli_req_state);
2557         uint32_t flags = IVAL(state->smb2.hdr, SMB2_HDR_FLAGS);
2558         uint64_t mid = BVAL(state->smb2.hdr, SMB2_HDR_MESSAGE_ID);
2559         uint64_t aid = BVAL(state->smb2.hdr, SMB2_HDR_ASYNC_ID);
2560         struct smbXcli_tcon *tcon = state->tcon;
2561         struct smbXcli_session *session = state->session;
2562         uint8_t *fixed = state->smb2.pad;
2563         uint16_t fixed_len = 4;
2564         struct tevent_req *subreq;
2565         struct smbXcli_req_state *substate;
2566         NTSTATUS status;
2567
2568         SSVAL(fixed, 0, 0x04);
2569         SSVAL(fixed, 2, 0);
2570
2571         subreq = smb2cli_req_create(state, state->ev,
2572                                     state->conn,
2573                                     SMB2_OP_CANCEL,
2574                                     flags, 0,
2575                                     0, /* timeout */
2576                                     tcon, session,
2577                                     fixed, fixed_len,
2578                                     NULL, 0, 0);
2579         if (subreq == NULL) {
2580                 return false;
2581         }
2582         substate = tevent_req_data(subreq, struct smbXcli_req_state);
2583
2584         /*
2585          * clear everything but the SMB2_HDR_FLAG_ASYNC flag
2586          * e.g. if SMB2_HDR_FLAG_CHAINED is set we get INVALID_PARAMETER back
2587          */
2588         flags &= SMB2_HDR_FLAG_ASYNC;
2589
2590         if (flags & SMB2_HDR_FLAG_ASYNC) {
2591                 mid = 0;
2592         }
2593
2594         SIVAL(substate->smb2.hdr, SMB2_HDR_FLAGS, flags);
2595         SBVAL(substate->smb2.hdr, SMB2_HDR_MESSAGE_ID, mid);
2596         SBVAL(substate->smb2.hdr, SMB2_HDR_ASYNC_ID, aid);
2597
2598         status = smb2cli_req_compound_submit(&subreq, 1);
2599         if (!NT_STATUS_IS_OK(status)) {
2600                 TALLOC_FREE(subreq);
2601                 return false;
2602         }
2603
2604         tevent_req_set_callback(subreq, smb2cli_req_cancel_done, NULL);
2605
2606         return true;
2607 }
2608
2609 static void smb2cli_req_cancel_done(struct tevent_req *subreq)
2610 {
2611         /* we do not care about the result */
2612         TALLOC_FREE(subreq);
2613 }
2614
2615 struct tevent_req *smb2cli_req_create(TALLOC_CTX *mem_ctx,
2616                                       struct tevent_context *ev,
2617                                       struct smbXcli_conn *conn,
2618                                       uint16_t cmd,
2619                                       uint32_t additional_flags,
2620                                       uint32_t clear_flags,
2621                                       uint32_t timeout_msec,
2622                                       struct smbXcli_tcon *tcon,
2623                                       struct smbXcli_session *session,
2624                                       const uint8_t *fixed,
2625                                       uint16_t fixed_len,
2626                                       const uint8_t *dyn,
2627                                       uint32_t dyn_len,
2628                                       uint32_t max_dyn_len)
2629 {
2630         struct tevent_req *req;
2631         struct smbXcli_req_state *state;
2632         uint32_t flags = 0;
2633         uint32_t tid = 0;
2634         uint64_t uid = 0;
2635         bool use_channel_sequence = false;
2636         uint16_t channel_sequence = 0;
2637         bool use_replay_flag = false;
2638
2639         req = tevent_req_create(mem_ctx, &state,
2640                                 struct smbXcli_req_state);
2641         if (req == NULL) {
2642                 return NULL;
2643         }
2644
2645         state->ev = ev;
2646         state->conn = conn;
2647         state->session = session;
2648         state->tcon = tcon;
2649
2650         if (conn->smb2.server.capabilities & SMB2_CAP_PERSISTENT_HANDLES) {
2651                 use_channel_sequence = true;
2652         } else if (conn->smb2.server.capabilities & SMB2_CAP_MULTI_CHANNEL) {
2653                 use_channel_sequence = true;
2654         }
2655
2656         if (smbXcli_conn_protocol(conn) >= PROTOCOL_SMB3_00) {
2657                 use_replay_flag = true;
2658         }
2659
2660         if (session) {
2661                 uid = session->smb2->session_id;
2662
2663                 if (use_channel_sequence) {
2664                         channel_sequence = session->smb2->channel_sequence;
2665                 }
2666
2667                 if (use_replay_flag && session->smb2->replay_active) {
2668                         additional_flags |= SMB2_HDR_FLAG_REPLAY_OPERATION;
2669                 }
2670
2671                 state->smb2.should_sign = session->smb2->should_sign;
2672                 state->smb2.should_encrypt = session->smb2->should_encrypt;
2673
2674                 if (cmd == SMB2_OP_SESSSETUP &&
2675                     session->smb2->signing_key.length != 0) {
2676                         state->smb2.should_sign = true;
2677                 }
2678
2679                 if (cmd == SMB2_OP_SESSSETUP &&
2680                     session->smb2_channel.signing_key.length == 0) {
2681                         state->smb2.should_encrypt = false;
2682                 }
2683
2684                 if (additional_flags & SMB2_HDR_FLAG_SIGNED) {
2685                         if (session->smb2_channel.signing_key.length == 0) {
2686                                 tevent_req_nterror(req, NT_STATUS_NO_USER_SESSION_KEY);
2687                                 return req;
2688                         }
2689
2690                         additional_flags &= ~SMB2_HDR_FLAG_SIGNED;
2691                         state->smb2.should_sign = true;
2692                 }
2693         }
2694
2695         if (tcon) {
2696                 tid = tcon->smb2.tcon_id;
2697
2698                 if (tcon->smb2.should_sign) {
2699                         state->smb2.should_sign = true;
2700                 }
2701                 if (tcon->smb2.should_encrypt) {
2702                         state->smb2.should_encrypt = true;
2703                 }
2704         }
2705
2706         if (state->smb2.should_encrypt) {
2707                 state->smb2.should_sign = false;
2708         }
2709
2710         state->smb2.recv_iov = talloc_zero_array(state, struct iovec, 3);
2711         if (state->smb2.recv_iov == NULL) {
2712                 TALLOC_FREE(req);
2713                 return NULL;
2714         }
2715
2716         flags |= additional_flags;
2717         flags &= ~clear_flags;
2718
2719         state->smb2.fixed = fixed;
2720         state->smb2.fixed_len = fixed_len;
2721         state->smb2.dyn = dyn;
2722         state->smb2.dyn_len = dyn_len;
2723         state->smb2.max_dyn_len = max_dyn_len;
2724
2725         if (state->smb2.should_encrypt) {
2726                 SIVAL(state->smb2.transform, SMB2_TF_PROTOCOL_ID, SMB2_TF_MAGIC);
2727                 SBVAL(state->smb2.transform, SMB2_TF_SESSION_ID, uid);
2728         }
2729
2730         SIVAL(state->smb2.hdr, SMB2_HDR_PROTOCOL_ID,    SMB2_MAGIC);
2731         SSVAL(state->smb2.hdr, SMB2_HDR_LENGTH,         SMB2_HDR_BODY);
2732         SSVAL(state->smb2.hdr, SMB2_HDR_OPCODE,         cmd);
2733         SSVAL(state->smb2.hdr, SMB2_HDR_CHANNEL_SEQUENCE, channel_sequence);
2734         SIVAL(state->smb2.hdr, SMB2_HDR_FLAGS,          flags);
2735         SIVAL(state->smb2.hdr, SMB2_HDR_PID,            0); /* reserved */
2736         SIVAL(state->smb2.hdr, SMB2_HDR_TID,            tid);
2737         SBVAL(state->smb2.hdr, SMB2_HDR_SESSION_ID,     uid);
2738
2739         switch (cmd) {
2740         case SMB2_OP_CANCEL:
2741                 state->one_way = true;
2742                 break;
2743         case SMB2_OP_BREAK:
2744                 /*
2745                  * If this is a dummy request, it will have
2746                  * UINT64_MAX as message id.
2747                  * If we send on break acknowledgement,
2748                  * this gets overwritten later.
2749                  */
2750                 SBVAL(state->smb2.hdr, SMB2_HDR_MESSAGE_ID, UINT64_MAX);
2751                 break;
2752         }
2753
2754         if (timeout_msec > 0) {
2755                 struct timeval endtime;
2756
2757                 endtime = timeval_current_ofs_msec(timeout_msec);
2758                 if (!tevent_req_set_endtime(req, ev, endtime)) {
2759                         return req;
2760                 }
2761         }
2762
2763         return req;
2764 }
2765
2766 void smb2cli_req_set_notify_async(struct tevent_req *req)
2767 {
2768         struct smbXcli_req_state *state =
2769                 tevent_req_data(req,
2770                 struct smbXcli_req_state);
2771
2772         state->smb2.notify_async = true;
2773 }
2774
2775 static void smb2cli_req_writev_done(struct tevent_req *subreq);
2776 static NTSTATUS smb2cli_conn_dispatch_incoming(struct smbXcli_conn *conn,
2777                                                TALLOC_CTX *tmp_mem,
2778                                                uint8_t *inbuf);
2779
2780 NTSTATUS smb2cli_req_compound_submit(struct tevent_req **reqs,
2781                                      int num_reqs)
2782 {
2783         struct smbXcli_req_state *state;
2784         struct tevent_req *subreq;
2785         struct iovec *iov;
2786         int i, num_iov, nbt_len;
2787         int tf_iov = -1;
2788         const DATA_BLOB *encryption_key = NULL;
2789         uint64_t encryption_session_id = 0;
2790
2791         /*
2792          * 1 for the nbt length, optional TRANSFORM
2793          * per request: HDR, fixed, dyn, padding
2794          * -1 because the last one does not need padding
2795          */
2796
2797         iov = talloc_array(reqs[0], struct iovec, 1 + 1 + 4*num_reqs - 1);
2798         if (iov == NULL) {
2799                 return NT_STATUS_NO_MEMORY;
2800         }
2801
2802         num_iov = 1;
2803         nbt_len = 0;
2804
2805         /*
2806          * the session of the first request that requires encryption
2807          * specifies the encryption key.
2808          */
2809         for (i=0; i<num_reqs; i++) {
2810                 if (!tevent_req_is_in_progress(reqs[i])) {
2811                         return NT_STATUS_INTERNAL_ERROR;
2812                 }
2813
2814                 state = tevent_req_data(reqs[i], struct smbXcli_req_state);
2815
2816                 if (!smbXcli_conn_is_connected(state->conn)) {
2817                         return NT_STATUS_CONNECTION_DISCONNECTED;
2818                 }
2819
2820                 if ((state->conn->protocol != PROTOCOL_NONE) &&
2821                     (state->conn->protocol < PROTOCOL_SMB2_02)) {
2822                         return NT_STATUS_REVISION_MISMATCH;
2823                 }
2824
2825                 if (state->session == NULL) {
2826                         continue;
2827                 }
2828
2829                 if (!state->smb2.should_encrypt) {
2830                         continue;
2831                 }
2832
2833                 encryption_key = &state->session->smb2->encryption_key;
2834                 if (encryption_key->length == 0) {
2835                         return NT_STATUS_INVALID_PARAMETER_MIX;
2836                 }
2837
2838                 encryption_session_id = state->session->smb2->session_id;
2839
2840                 tf_iov = num_iov;
2841                 iov[num_iov].iov_base = state->smb2.transform;
2842                 iov[num_iov].iov_len  = sizeof(state->smb2.transform);
2843                 num_iov += 1;
2844
2845                 SBVAL(state->smb2.transform, SMB2_TF_PROTOCOL_ID, SMB2_TF_MAGIC);
2846                 SBVAL(state->smb2.transform, SMB2_TF_NONCE,
2847                       state->session->smb2->nonce_low);
2848                 SBVAL(state->smb2.transform, SMB2_TF_NONCE+8,
2849                       state->session->smb2->nonce_high);
2850                 SBVAL(state->smb2.transform, SMB2_TF_SESSION_ID,
2851                       encryption_session_id);
2852
2853                 state->session->smb2->nonce_low += 1;
2854                 if (state->session->smb2->nonce_low == 0) {
2855                         state->session->smb2->nonce_high += 1;
2856                         state->session->smb2->nonce_low += 1;
2857                 }
2858
2859                 nbt_len += SMB2_TF_HDR_SIZE;
2860                 break;
2861         }
2862
2863         for (i=0; i<num_reqs; i++) {
2864                 int hdr_iov;
2865                 size_t reqlen;
2866                 bool ret;
2867                 uint16_t opcode;
2868                 uint64_t avail;
2869                 uint16_t charge;
2870                 uint16_t credits;
2871                 uint64_t mid;
2872                 const DATA_BLOB *signing_key = NULL;
2873
2874                 if (!tevent_req_is_in_progress(reqs[i])) {
2875                         return NT_STATUS_INTERNAL_ERROR;
2876                 }
2877
2878                 state = tevent_req_data(reqs[i], struct smbXcli_req_state);
2879
2880                 if (!smbXcli_conn_is_connected(state->conn)) {
2881                         return NT_STATUS_CONNECTION_DISCONNECTED;
2882                 }
2883
2884                 if ((state->conn->protocol != PROTOCOL_NONE) &&
2885                     (state->conn->protocol < PROTOCOL_SMB2_02)) {
2886                         return NT_STATUS_REVISION_MISMATCH;
2887                 }
2888
2889                 opcode = SVAL(state->smb2.hdr, SMB2_HDR_OPCODE);
2890                 if (opcode == SMB2_OP_CANCEL) {
2891                         goto skip_credits;
2892                 }
2893
2894                 avail = UINT64_MAX - state->conn->smb2.mid;
2895                 if (avail < 1) {
2896                         return NT_STATUS_CONNECTION_ABORTED;
2897                 }
2898
2899                 if (state->conn->smb2.server.capabilities & SMB2_CAP_LARGE_MTU) {
2900                         uint32_t max_dyn_len = 1;
2901
2902                         max_dyn_len = MAX(max_dyn_len, state->smb2.dyn_len);
2903                         max_dyn_len = MAX(max_dyn_len, state->smb2.max_dyn_len);
2904
2905                         charge = (max_dyn_len - 1)/ 65536 + 1;
2906                 } else {
2907                         charge = 1;
2908                 }
2909
2910                 charge = MAX(state->smb2.credit_charge, charge);
2911
2912                 avail = MIN(avail, state->conn->smb2.cur_credits);
2913                 if (avail < charge) {
2914                         return NT_STATUS_INTERNAL_ERROR;
2915                 }
2916
2917                 credits = 0;
2918                 if (state->conn->smb2.max_credits > state->conn->smb2.cur_credits) {
2919                         credits = state->conn->smb2.max_credits -
2920                                   state->conn->smb2.cur_credits;
2921                 }
2922                 if (state->conn->smb2.max_credits >= state->conn->smb2.cur_credits) {
2923                         credits += 1;
2924                 }
2925
2926                 mid = state->conn->smb2.mid;
2927                 state->conn->smb2.mid += charge;
2928                 state->conn->smb2.cur_credits -= charge;
2929
2930                 if (state->conn->smb2.server.capabilities & SMB2_CAP_LARGE_MTU) {
2931                         SSVAL(state->smb2.hdr, SMB2_HDR_CREDIT_CHARGE, charge);
2932                 }
2933                 SSVAL(state->smb2.hdr, SMB2_HDR_CREDIT, credits);
2934                 SBVAL(state->smb2.hdr, SMB2_HDR_MESSAGE_ID, mid);
2935
2936 skip_credits:
2937                 if (state->session && encryption_key == NULL) {
2938                         /*
2939                          * We prefer the channel signing key if it is
2940                          * already there.
2941                          */
2942                         if (state->smb2.should_sign) {
2943                                 signing_key = &state->session->smb2_channel.signing_key;
2944                         }
2945
2946                         /*
2947                          * If it is a channel binding, we already have the main
2948                          * signing key and try that one.
2949                          */
2950                         if (signing_key && signing_key->length == 0) {
2951                                 signing_key = &state->session->smb2->signing_key;
2952                         }
2953
2954                         /*
2955                          * If we do not have any session key yet, we skip the
2956                          * signing of SMB2_OP_SESSSETUP requests.
2957                          */
2958                         if (signing_key && signing_key->length == 0) {
2959                                 signing_key = NULL;
2960                         }
2961                 }
2962
2963                 hdr_iov = num_iov;
2964                 iov[num_iov].iov_base = state->smb2.hdr;
2965                 iov[num_iov].iov_len  = sizeof(state->smb2.hdr);
2966                 num_iov += 1;
2967
2968                 iov[num_iov].iov_base = discard_const(state->smb2.fixed);
2969                 iov[num_iov].iov_len  = state->smb2.fixed_len;
2970                 num_iov += 1;
2971
2972                 if (state->smb2.dyn != NULL) {
2973                         iov[num_iov].iov_base = discard_const(state->smb2.dyn);
2974                         iov[num_iov].iov_len  = state->smb2.dyn_len;
2975                         num_iov += 1;
2976                 }
2977
2978                 reqlen  = sizeof(state->smb2.hdr);
2979                 reqlen += state->smb2.fixed_len;
2980                 reqlen += state->smb2.dyn_len;
2981
2982                 if (i < num_reqs-1) {
2983                         if ((reqlen % 8) > 0) {
2984                                 uint8_t pad = 8 - (reqlen % 8);
2985                                 iov[num_iov].iov_base = state->smb2.pad;
2986                                 iov[num_iov].iov_len = pad;
2987                                 num_iov += 1;
2988                                 reqlen += pad;
2989                         }
2990                         SIVAL(state->smb2.hdr, SMB2_HDR_NEXT_COMMAND, reqlen);
2991                 }
2992
2993                 state->smb2.encryption_session_id = encryption_session_id;
2994
2995                 if (signing_key != NULL) {
2996                         NTSTATUS status;
2997
2998                         status = smb2_signing_sign_pdu(*signing_key,
2999                                                        state->session->conn->protocol,
3000                                                        &iov[hdr_iov], num_iov - hdr_iov);
3001                         if (!NT_STATUS_IS_OK(status)) {
3002                                 return status;
3003                         }
3004                 }
3005
3006                 nbt_len += reqlen;
3007
3008                 ret = smbXcli_req_set_pending(reqs[i]);
3009                 if (!ret) {
3010                         return NT_STATUS_NO_MEMORY;
3011                 }
3012         }
3013
3014         state = tevent_req_data(reqs[0], struct smbXcli_req_state);
3015         _smb_setlen_tcp(state->length_hdr, nbt_len);
3016         iov[0].iov_base = state->length_hdr;
3017         iov[0].iov_len  = sizeof(state->length_hdr);
3018
3019         if (encryption_key != NULL) {
3020                 NTSTATUS status;
3021                 size_t buflen = nbt_len - SMB2_TF_HDR_SIZE;
3022                 uint8_t *buf;
3023                 int vi;
3024
3025                 buf = talloc_array(iov, uint8_t, buflen);
3026                 if (buf == NULL) {
3027                         return NT_STATUS_NO_MEMORY;
3028                 }
3029
3030                 /*
3031                  * We copy the buffers before encrypting them,
3032                  * this is at least currently needed for the
3033                  * to keep state->smb2.hdr.
3034                  *
3035                  * Also the callers may expect there buffers
3036                  * to be const.
3037                  */
3038                 for (vi = tf_iov + 1; vi < num_iov; vi++) {
3039                         struct iovec *v = &iov[vi];
3040                         const uint8_t *o = (const uint8_t *)v->iov_base;
3041
3042                         memcpy(buf, o, v->iov_len);
3043                         v->iov_base = (void *)buf;
3044                         buf += v->iov_len;
3045                 }
3046
3047                 status = smb2_signing_encrypt_pdu(*encryption_key,
3048                                         state->conn->protocol,
3049                                         &iov[tf_iov], num_iov - tf_iov);
3050                 if (!NT_STATUS_IS_OK(status)) {
3051                         return status;
3052                 }
3053         }
3054
3055         if (state->conn->dispatch_incoming == NULL) {
3056                 state->conn->dispatch_incoming = smb2cli_conn_dispatch_incoming;
3057         }
3058
3059         subreq = writev_send(state, state->ev, state->conn->outgoing,
3060                              state->conn->write_fd, false, iov, num_iov);
3061         if (subreq == NULL) {
3062                 return NT_STATUS_NO_MEMORY;
3063         }
3064         tevent_req_set_callback(subreq, smb2cli_req_writev_done, reqs[0]);
3065         return NT_STATUS_OK;
3066 }
3067
3068 void smb2cli_req_set_credit_charge(struct tevent_req *req, uint16_t charge)
3069 {
3070         struct smbXcli_req_state *state =
3071                 tevent_req_data(req,
3072                 struct smbXcli_req_state);
3073
3074         state->smb2.credit_charge = charge;
3075 }
3076
3077 struct tevent_req *smb2cli_req_send(TALLOC_CTX *mem_ctx,
3078                                     struct tevent_context *ev,
3079                                     struct smbXcli_conn *conn,
3080                                     uint16_t cmd,
3081                                     uint32_t additional_flags,
3082                                     uint32_t clear_flags,
3083                                     uint32_t timeout_msec,
3084                                     struct smbXcli_tcon *tcon,
3085                                     struct smbXcli_session *session,
3086                                     const uint8_t *fixed,
3087                                     uint16_t fixed_len,
3088                                     const uint8_t *dyn,
3089                                     uint32_t dyn_len,
3090                                     uint32_t max_dyn_len)
3091 {
3092         struct tevent_req *req;
3093         NTSTATUS status;
3094
3095         req = smb2cli_req_create(mem_ctx, ev, conn, cmd,
3096                                  additional_flags, clear_flags,
3097                                  timeout_msec,
3098                                  tcon, session,
3099                                  fixed, fixed_len,
3100                                  dyn, dyn_len,
3101                                  max_dyn_len);
3102         if (req == NULL) {
3103                 return NULL;
3104         }
3105         if (!tevent_req_is_in_progress(req)) {
3106                 return tevent_req_post(req, ev);
3107         }
3108         status = smb2cli_req_compound_submit(&req, 1);
3109         if (tevent_req_nterror(req, status)) {
3110                 return tevent_req_post(req, ev);
3111         }
3112         return req;
3113 }
3114
3115 static void smb2cli_req_writev_done(struct tevent_req *subreq)
3116 {
3117         struct tevent_req *req =
3118                 tevent_req_callback_data(subreq,
3119                 struct tevent_req);
3120         struct smbXcli_req_state *state =
3121                 tevent_req_data(req,
3122                 struct smbXcli_req_state);
3123         ssize_t nwritten;
3124         int err;
3125
3126         nwritten = writev_recv(subreq, &err);
3127         TALLOC_FREE(subreq);
3128         if (nwritten == -1) {
3129                 /* here, we need to notify all pending requests */
3130                 NTSTATUS status = map_nt_error_from_unix_common(err);
3131                 smbXcli_conn_disconnect(state->conn, status);
3132                 return;
3133         }
3134 }
3135
3136 static NTSTATUS smb2cli_inbuf_parse_compound(struct smbXcli_conn *conn,
3137                                              uint8_t *buf,
3138                                              size_t buflen,
3139                                              TALLOC_CTX *mem_ctx,
3140                                              struct iovec **piov, int *pnum_iov)
3141 {
3142         struct iovec *iov;
3143         int num_iov = 0;
3144         size_t taken = 0;
3145         uint8_t *first_hdr = buf;
3146         size_t verified_buflen = 0;
3147         uint8_t *tf = NULL;
3148         size_t tf_len = 0;
3149
3150         iov = talloc_array(mem_ctx, struct iovec, num_iov);
3151         if (iov == NULL) {
3152                 return NT_STATUS_NO_MEMORY;
3153         }
3154
3155         while (taken < buflen) {
3156                 size_t len = buflen - taken;
3157                 uint8_t *hdr = first_hdr + taken;
3158                 struct iovec *cur;
3159                 size_t full_size;
3160                 size_t next_command_ofs;
3161                 uint16_t body_size;
3162                 struct iovec *iov_tmp;
3163
3164                 if (verified_buflen > taken) {
3165                         len = verified_buflen - taken;
3166                 } else {
3167                         tf = NULL;
3168                         tf_len = 0;
3169                 }
3170
3171                 if (len < 4) {
3172                         DEBUG(10, ("%d bytes left, expected at least %d\n",
3173                                    (int)len, 4));
3174                         goto inval;
3175                 }
3176                 if (IVAL(hdr, 0) == SMB2_TF_MAGIC) {
3177                         struct smbXcli_session *s;
3178                         uint64_t uid;
3179                         struct iovec tf_iov[2];
3180                         size_t enc_len;
3181                         NTSTATUS status;
3182
3183                         if (len < SMB2_TF_HDR_SIZE) {
3184                                 DEBUG(10, ("%d bytes left, expected at least %d\n",
3185                                            (int)len, SMB2_TF_HDR_SIZE));
3186                                 goto inval;
3187                         }
3188                         tf = hdr;
3189                         tf_len = SMB2_TF_HDR_SIZE;
3190                         taken += tf_len;
3191
3192                         hdr = first_hdr + taken;
3193                         enc_len = IVAL(tf, SMB2_TF_MSG_SIZE);
3194                         uid = BVAL(tf, SMB2_TF_SESSION_ID);
3195
3196                         if (len < SMB2_TF_HDR_SIZE + enc_len) {
3197                                 DEBUG(10, ("%d bytes left, expected at least %d\n",
3198                                            (int)len,
3199                                            (int)(SMB2_TF_HDR_SIZE + enc_len)));
3200                                 goto inval;
3201                         }
3202
3203                         s = conn->sessions;
3204                         for (; s; s = s->next) {
3205                                 if (s->smb2->session_id != uid) {
3206                                         continue;
3207                                 }
3208                                 break;
3209                         }
3210
3211                         if (s == NULL) {
3212                                 DEBUG(10, ("unknown session_id %llu\n",
3213                                            (unsigned long long)uid));
3214                                 goto inval;
3215                         }
3216
3217                         tf_iov[0].iov_base = (void *)tf;
3218                         tf_iov[0].iov_len = tf_len;
3219                         tf_iov[1].iov_base = (void *)hdr;
3220                         tf_iov[1].iov_len = enc_len;
3221
3222                         status = smb2_signing_decrypt_pdu(s->smb2->decryption_key,
3223                                                           conn->protocol,
3224                                                           tf_iov, 2);
3225                         if (!NT_STATUS_IS_OK(status)) {
3226                                 TALLOC_FREE(iov);
3227                                 return status;
3228                         }
3229
3230                         verified_buflen = taken + enc_len;
3231                         len = enc_len;
3232                 }
3233
3234                 /*
3235                  * We need the header plus the body length field
3236                  */
3237
3238                 if (len < SMB2_HDR_BODY + 2) {
3239                         DEBUG(10, ("%d bytes left, expected at least %d\n",
3240                                    (int)len, SMB2_HDR_BODY));
3241                         goto inval;
3242                 }
3243                 if (IVAL(hdr, 0) != SMB2_MAGIC) {
3244                         DEBUG(10, ("Got non-SMB2 PDU: %x\n",
3245                                    IVAL(hdr, 0)));
3246                         goto inval;
3247                 }
3248                 if (SVAL(hdr, 4) != SMB2_HDR_BODY) {
3249                         DEBUG(10, ("Got HDR len %d, expected %d\n",
3250                                    SVAL(hdr, 4), SMB2_HDR_BODY));
3251                         goto inval;
3252                 }
3253
3254                 full_size = len;
3255                 next_command_ofs = IVAL(hdr, SMB2_HDR_NEXT_COMMAND);
3256                 body_size = SVAL(hdr, SMB2_HDR_BODY);
3257
3258                 if (next_command_ofs != 0) {
3259                         if (next_command_ofs < (SMB2_HDR_BODY + 2)) {
3260                                 goto inval;
3261                         }
3262                         if (next_command_ofs > full_size) {
3263                                 goto inval;
3264                         }
3265                         full_size = next_command_ofs;
3266                 }
3267                 if (body_size < 2) {
3268                         goto inval;
3269                 }
3270                 body_size &= 0xfffe;
3271
3272                 if (body_size > (full_size - SMB2_HDR_BODY)) {
3273                         goto inval;
3274                 }
3275
3276                 iov_tmp = talloc_realloc(mem_ctx, iov, struct iovec,
3277                                          num_iov + 4);
3278                 if (iov_tmp == NULL) {
3279                         TALLOC_FREE(iov);
3280                         return NT_STATUS_NO_MEMORY;
3281                 }
3282                 iov = iov_tmp;
3283                 cur = &iov[num_iov];
3284                 num_iov += 4;
3285
3286                 cur[0].iov_base = tf;
3287                 cur[0].iov_len  = tf_len;
3288                 cur[1].iov_base = hdr;
3289                 cur[1].iov_len  = SMB2_HDR_BODY;
3290                 cur[2].iov_base = hdr + SMB2_HDR_BODY;
3291                 cur[2].iov_len  = body_size;
3292                 cur[3].iov_base = hdr + SMB2_HDR_BODY + body_size;
3293                 cur[3].iov_len  = full_size - (SMB2_HDR_BODY + body_size);
3294
3295                 taken += full_size;
3296         }
3297
3298         *piov = iov;
3299         *pnum_iov = num_iov;
3300         return NT_STATUS_OK;
3301
3302 inval:
3303         TALLOC_FREE(iov);
3304         return NT_STATUS_INVALID_NETWORK_RESPONSE;
3305 }
3306
3307 static struct tevent_req *smb2cli_conn_find_pending(struct smbXcli_conn *conn,
3308                                                     uint64_t mid)
3309 {
3310         size_t num_pending = talloc_array_length(conn->pending);
3311         size_t i;
3312
3313         for (i=0; i<num_pending; i++) {
3314                 struct tevent_req *req = conn->pending[i];
3315                 struct smbXcli_req_state *state =
3316                         tevent_req_data(req,
3317                         struct smbXcli_req_state);
3318
3319                 if (mid == BVAL(state->smb2.hdr, SMB2_HDR_MESSAGE_ID)) {
3320                         return req;
3321                 }
3322         }
3323         return NULL;
3324 }
3325
3326 static NTSTATUS smb2cli_conn_dispatch_incoming(struct smbXcli_conn *conn,
3327                                                TALLOC_CTX *tmp_mem,
3328                                                uint8_t *inbuf)
3329 {
3330         struct tevent_req *req;
3331         struct smbXcli_req_state *state = NULL;
3332         struct iovec *iov;
3333         int i, num_iov;
3334         NTSTATUS status;
3335         bool defer = true;
3336         struct smbXcli_session *last_session = NULL;
3337         size_t inbuf_len = smb_len_tcp(inbuf);
3338
3339         status = smb2cli_inbuf_parse_compound(conn,
3340                                               inbuf + NBT_HDR_SIZE,
3341                                               inbuf_len,
3342                                               tmp_mem,
3343                                               &iov, &num_iov);
3344         if (!NT_STATUS_IS_OK(status)) {
3345                 return status;
3346         }
3347
3348         for (i=0; i<num_iov; i+=4) {
3349                 uint8_t *inbuf_ref = NULL;
3350                 struct iovec *cur = &iov[i];
3351                 uint8_t *inhdr = (uint8_t *)cur[1].iov_base;
3352                 uint16_t opcode = SVAL(inhdr, SMB2_HDR_OPCODE);
3353                 uint32_t flags = IVAL(inhdr, SMB2_HDR_FLAGS);
3354                 uint64_t mid = BVAL(inhdr, SMB2_HDR_MESSAGE_ID);
3355                 uint16_t req_opcode;
3356                 uint32_t req_flags;
3357                 uint16_t credits = SVAL(inhdr, SMB2_HDR_CREDIT);
3358                 uint32_t new_credits;
3359                 struct smbXcli_session *session = NULL;
3360                 const DATA_BLOB *signing_key = NULL;
3361                 bool was_encrypted = false;
3362
3363                 new_credits = conn->smb2.cur_credits;
3364                 new_credits += credits;
3365                 if (new_credits > UINT16_MAX) {
3366                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
3367                 }
3368                 conn->smb2.cur_credits += credits;
3369
3370                 req = smb2cli_conn_find_pending(conn, mid);
3371                 if (req == NULL) {
3372                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
3373                 }
3374                 state = tevent_req_data(req, struct smbXcli_req_state);
3375
3376                 req_opcode = SVAL(state->smb2.hdr, SMB2_HDR_OPCODE);
3377                 if (opcode != req_opcode) {
3378                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
3379                 }
3380                 req_flags = SVAL(state->smb2.hdr, SMB2_HDR_FLAGS);
3381
3382                 if (!(flags & SMB2_HDR_FLAG_REDIRECT)) {
3383                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
3384                 }
3385
3386                 status = NT_STATUS(IVAL(inhdr, SMB2_HDR_STATUS));
3387                 if ((flags & SMB2_HDR_FLAG_ASYNC) &&
3388                     NT_STATUS_EQUAL(status, STATUS_PENDING)) {
3389                         uint64_t async_id = BVAL(inhdr, SMB2_HDR_ASYNC_ID);
3390
3391                         if (state->smb2.got_async) {
3392                                 /* We only expect one STATUS_PENDING response */
3393                                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
3394                         }
3395                         state->smb2.got_async = true;
3396
3397                         /*
3398                          * async interim responses are not signed,
3399                          * even if the SMB2_HDR_FLAG_SIGNED flag
3400                          * is set.
3401                          */
3402                         req_flags |= SMB2_HDR_FLAG_ASYNC;
3403                         SBVAL(state->smb2.hdr, SMB2_HDR_FLAGS, req_flags);
3404                         SBVAL(state->smb2.hdr, SMB2_HDR_ASYNC_ID, async_id);
3405
3406                         if (state->smb2.notify_async) {
3407                                 tevent_req_defer_callback(req, state->ev);
3408                                 tevent_req_notify_callback(req);
3409                         }
3410                         continue;
3411                 }
3412
3413                 session = state->session;
3414                 if (req_flags & SMB2_HDR_FLAG_CHAINED) {
3415                         session = last_session;
3416                 }
3417                 last_session = session;
3418
3419                 if (state->smb2.should_sign) {
3420                         if (!(flags & SMB2_HDR_FLAG_SIGNED)) {
3421                                 return NT_STATUS_ACCESS_DENIED;
3422                         }
3423                 }
3424
3425                 if (flags & SMB2_HDR_FLAG_SIGNED) {
3426                         uint64_t uid = BVAL(inhdr, SMB2_HDR_SESSION_ID);
3427
3428                         if (session == NULL) {
3429                                 struct smbXcli_session *s;
3430
3431                                 s = state->conn->sessions;
3432                                 for (; s; s = s->next) {
3433                                         if (s->smb2->session_id != uid) {
3434                                                 continue;
3435                                         }
3436
3437                                         session = s;
3438                                         break;
3439                                 }
3440                         }
3441
3442                         if (session == NULL) {
3443                                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
3444                         }
3445
3446                         last_session = session;
3447                         signing_key = &session->smb2_channel.signing_key;
3448                 }
3449
3450                 if (opcode == SMB2_OP_SESSSETUP) {
3451                         /*
3452                          * We prefer the channel signing key, if it is
3453                          * already there.
3454                          *
3455                          * If we do not have a channel signing key yet,
3456                          * we try the main signing key, if it is not
3457                          * the final response.
3458                          */
3459                         if (signing_key && signing_key->length == 0 &&
3460                             !NT_STATUS_IS_OK(status)) {
3461                                 signing_key = &session->smb2->signing_key;
3462                         }
3463
3464                         if (signing_key && signing_key->length == 0) {
3465                                 /*
3466                                  * If we do not have a session key to
3467                                  * verify the signature, we defer the
3468                                  * signing check to the caller.
3469                                  *
3470                                  * The caller gets NT_STATUS_OK, it
3471                                  * has to call
3472                                  * smb2cli_session_set_session_key()
3473                                  * or
3474                                  * smb2cli_session_set_channel_key()
3475                                  * which will check the signature
3476                                  * with the channel signing key.
3477                                  */
3478                                 signing_key = NULL;
3479                         }
3480                 }
3481
3482                 if (cur[0].iov_len == SMB2_TF_HDR_SIZE) {
3483                         const uint8_t *tf = (const uint8_t *)cur[0].iov_base;
3484                         uint64_t uid = BVAL(tf, SMB2_TF_SESSION_ID);
3485
3486                         /*
3487                          * If the response was encrypted in a SMB2_TRANSFORM
3488                          * pdu, which belongs to the correct session,
3489                          * we do not need to do signing checks
3490                          *
3491                          * It could be the session the response belongs to
3492                          * or the session that was used to encrypt the
3493                          * SMB2_TRANSFORM request.
3494                          */
3495                         if ((session && session->smb2->session_id == uid) ||
3496                             (state->smb2.encryption_session_id == uid)) {
3497                                 signing_key = NULL;
3498                                 was_encrypted = true;
3499                         }
3500                 }
3501
3502                 if (NT_STATUS_EQUAL(status, NT_STATUS_USER_SESSION_DELETED)) {
3503                         /*
3504                          * if the server returns NT_STATUS_USER_SESSION_DELETED
3505                          * the response is not signed and we should
3506                          * propagate the NT_STATUS_USER_SESSION_DELETED
3507                          * status to the caller.
3508                          */
3509                         state->smb2.signing_skipped = true;
3510                         signing_key = NULL;
3511                 }
3512
3513                 if (NT_STATUS_EQUAL(status, NT_STATUS_INVALID_PARAMETER)) {
3514                         /*
3515                          * if the server returns
3516                          * NT_STATUS_INVALID_PARAMETER
3517                          * the response might not be encrypted.
3518                          */
3519                         if (state->smb2.should_encrypt && !was_encrypted) {
3520                                 state->smb2.signing_skipped = true;
3521                                 signing_key = NULL;
3522                         }
3523                 }
3524
3525                 if (state->smb2.should_encrypt && !was_encrypted) {
3526                         if (!state->smb2.signing_skipped) {
3527                                 return NT_STATUS_ACCESS_DENIED;
3528                         }
3529                 }
3530
3531                 if (NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_NAME_DELETED) ||
3532                     NT_STATUS_EQUAL(status, NT_STATUS_FILE_CLOSED) ||
3533                     NT_STATUS_EQUAL(status, NT_STATUS_INVALID_PARAMETER)) {
3534                         /*
3535                          * if the server returns
3536                          * NT_STATUS_NETWORK_NAME_DELETED
3537                          * NT_STATUS_FILE_CLOSED
3538                          * NT_STATUS_INVALID_PARAMETER
3539                          * the response might not be signed
3540                          * as this happens before the signing checks.
3541                          *
3542                          * If server echos the signature (or all zeros)
3543                          * we should report the status from the server
3544                          * to the caller.
3545                          */
3546                         if (signing_key) {
3547                                 int cmp;
3548
3549                                 cmp = memcmp(inhdr+SMB2_HDR_SIGNATURE,
3550                                              state->smb2.hdr+SMB2_HDR_SIGNATURE,
3551                                              16);
3552                                 if (cmp == 0) {
3553                                         state->smb2.signing_skipped = true;
3554                                         signing_key = NULL;
3555                                 }
3556                         }
3557                         if (signing_key) {
3558                                 int cmp;
3559                                 static const uint8_t zeros[16];
3560
3561                                 cmp = memcmp(inhdr+SMB2_HDR_SIGNATURE,
3562                                              zeros,
3563                                              16);
3564                                 if (cmp == 0) {
3565                                         state->smb2.signing_skipped = true;
3566                                         signing_key = NULL;
3567                                 }
3568                         }
3569                 }
3570
3571                 if (signing_key) {
3572                         status = smb2_signing_check_pdu(*signing_key,
3573                                                         state->conn->protocol,
3574                                                         &cur[1], 3);
3575                         if (!NT_STATUS_IS_OK(status)) {
3576                                 /*
3577                                  * If the signing check fails, we disconnect
3578                                  * the connection.
3579                                  */
3580                                 return status;
3581                         }
3582                 }
3583
3584                 if (NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_SESSION_EXPIRED) &&
3585                     (session != NULL) && session->disconnect_expired)
3586                 {
3587                         /*
3588                          * this should be a short term hack
3589                          * until the upper layers have implemented
3590                          * re-authentication.
3591                          */
3592                         return status;
3593                 }
3594
3595                 smbXcli_req_unset_pending(req);
3596
3597                 /*
3598                  * There might be more than one response
3599                  * we need to defer the notifications
3600                  */
3601                 if ((num_iov == 5) && (talloc_array_length(conn->pending) == 0)) {
3602                         defer = false;
3603                 }
3604
3605                 if (defer) {
3606                         tevent_req_defer_callback(req, state->ev);
3607                 }
3608
3609                 /*
3610                  * Note: here we use talloc_reference() in a way
3611                  *       that does not expose it to the caller.
3612                  */
3613                 inbuf_ref = talloc_reference(state->smb2.recv_iov, inbuf);
3614                 if (tevent_req_nomem(inbuf_ref, req)) {
3615                         continue;
3616                 }
3617
3618                 /* copy the related buffers */
3619                 state->smb2.recv_iov[0] = cur[1];
3620                 state->smb2.recv_iov[1] = cur[2];
3621                 state->smb2.recv_iov[2] = cur[3];
3622
3623                 tevent_req_done(req);
3624         }
3625
3626         if (defer) {
3627                 return NT_STATUS_RETRY;
3628         }
3629
3630         return NT_STATUS_OK;
3631 }
3632
3633 NTSTATUS smb2cli_req_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
3634                           struct iovec **piov,
3635                           const struct smb2cli_req_expected_response *expected,
3636                           size_t num_expected)
3637 {
3638         struct smbXcli_req_state *state =
3639                 tevent_req_data(req,
3640                 struct smbXcli_req_state);
3641         NTSTATUS status;
3642         size_t body_size;
3643         bool found_status = false;
3644         bool found_size = false;
3645         size_t i;
3646
3647         if (piov != NULL) {
3648                 *piov = NULL;
3649         }
3650
3651         if (tevent_req_is_in_progress(req) && state->smb2.got_async) {
3652                 return STATUS_PENDING;
3653         }
3654
3655         if (tevent_req_is_nterror(req, &status)) {
3656                 for (i=0; i < num_expected; i++) {
3657                         if (NT_STATUS_EQUAL(status, expected[i].status)) {
3658                                 found_status = true;
3659                                 break;
3660                         }
3661                 }
3662
3663                 if (found_status) {
3664                         return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
3665                 }
3666
3667                 return status;
3668         }
3669
3670         if (num_expected == 0) {
3671                 found_status = true;
3672                 found_size = true;
3673         }
3674
3675         status = NT_STATUS(IVAL(state->smb2.recv_iov[0].iov_base, SMB2_HDR_STATUS));
3676         body_size = SVAL(state->smb2.recv_iov[1].iov_base, 0);
3677
3678         for (i=0; i < num_expected; i++) {
3679                 if (!NT_STATUS_EQUAL(status, expected[i].status)) {
3680                         continue;
3681                 }
3682
3683                 found_status = true;
3684                 if (expected[i].body_size == 0) {
3685                         found_size = true;
3686                         break;
3687                 }
3688
3689                 if (expected[i].body_size == body_size) {
3690                         found_size = true;
3691                         break;
3692                 }
3693         }
3694
3695         if (!found_status) {
3696                 return status;
3697         }
3698
3699         if (state->smb2.signing_skipped) {
3700                 if (num_expected > 0) {
3701                         return NT_STATUS_ACCESS_DENIED;
3702                 }
3703                 if (!NT_STATUS_IS_ERR(status)) {
3704                         return NT_STATUS_ACCESS_DENIED;
3705                 }
3706         }
3707
3708         if (!found_size) {
3709                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
3710         }
3711
3712         if (piov != NULL) {
3713                 *piov = talloc_move(mem_ctx, &state->smb2.recv_iov);
3714         }
3715
3716         return status;
3717 }
3718
3719 static const struct {
3720         enum protocol_types proto;
3721         const char *smb1_name;
3722 } smb1cli_prots[] = {
3723         {PROTOCOL_CORE,         "PC NETWORK PROGRAM 1.0"},
3724         {PROTOCOL_COREPLUS,     "MICROSOFT NETWORKS 1.03"},
3725         {PROTOCOL_LANMAN1,      "MICROSOFT NETWORKS 3.0"},
3726         {PROTOCOL_LANMAN1,      "LANMAN1.0"},
3727         {PROTOCOL_LANMAN2,      "LM1.2X002"},
3728         {PROTOCOL_LANMAN2,      "DOS LANMAN2.1"},
3729         {PROTOCOL_LANMAN2,      "LANMAN2.1"},
3730         {PROTOCOL_LANMAN2,      "Samba"},
3731         {PROTOCOL_NT1,          "NT LANMAN 1.0"},
3732         {PROTOCOL_NT1,          "NT LM 0.12"},
3733         {PROTOCOL_SMB2_02,      "SMB 2.002"},
3734         {PROTOCOL_SMB2_10,      "SMB 2.???"},
3735 };
3736
3737 static const struct {
3738         enum protocol_types proto;
3739         uint16_t smb2_dialect;
3740 } smb2cli_prots[] = {
3741         {PROTOCOL_SMB2_02,      SMB2_DIALECT_REVISION_202},
3742         {PROTOCOL_SMB2_10,      SMB2_DIALECT_REVISION_210},
3743         {PROTOCOL_SMB2_22,      SMB2_DIALECT_REVISION_222},
3744         {PROTOCOL_SMB2_24,      SMB2_DIALECT_REVISION_224},
3745         {PROTOCOL_SMB3_00,      SMB3_DIALECT_REVISION_300},
3746         {PROTOCOL_SMB3_02,      SMB3_DIALECT_REVISION_302},
3747 };
3748
3749 struct smbXcli_negprot_state {
3750         struct smbXcli_conn *conn;
3751         struct tevent_context *ev;
3752         uint32_t timeout_msec;
3753         enum protocol_types min_protocol;
3754         enum protocol_types max_protocol;
3755
3756         struct {
3757                 uint8_t fixed[36];
3758                 uint8_t dyn[ARRAY_SIZE(smb2cli_prots)*2];
3759         } smb2;
3760 };
3761
3762 static void smbXcli_negprot_invalid_done(struct tevent_req *subreq);
3763 static struct tevent_req *smbXcli_negprot_smb1_subreq(struct smbXcli_negprot_state *state);
3764 static void smbXcli_negprot_smb1_done(struct tevent_req *subreq);
3765 static struct tevent_req *smbXcli_negprot_smb2_subreq(struct smbXcli_negprot_state *state);
3766 static void smbXcli_negprot_smb2_done(struct tevent_req *subreq);
3767 static NTSTATUS smbXcli_negprot_dispatch_incoming(struct smbXcli_conn *conn,
3768                                                   TALLOC_CTX *frame,
3769                                                   uint8_t *inbuf);
3770
3771 struct tevent_req *smbXcli_negprot_send(TALLOC_CTX *mem_ctx,
3772                                         struct tevent_context *ev,
3773                                         struct smbXcli_conn *conn,
3774                                         uint32_t timeout_msec,
3775                                         enum protocol_types min_protocol,
3776                                         enum protocol_types max_protocol)
3777 {
3778         struct tevent_req *req, *subreq;
3779         struct smbXcli_negprot_state *state;
3780
3781         req = tevent_req_create(mem_ctx, &state,
3782                                 struct smbXcli_negprot_state);
3783         if (req == NULL) {
3784                 return NULL;
3785         }
3786         state->conn = conn;
3787         state->ev = ev;
3788         state->timeout_msec = timeout_msec;
3789         state->min_protocol = min_protocol;
3790         state->max_protocol = max_protocol;
3791
3792         if (min_protocol == PROTOCOL_NONE) {
3793                 tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER_MIX);
3794                 return tevent_req_post(req, ev);
3795         }
3796
3797         if (max_protocol == PROTOCOL_NONE) {
3798                 tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER_MIX);
3799                 return tevent_req_post(req, ev);
3800         }
3801
3802         if (min_protocol > max_protocol) {
3803                 tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER_MIX);
3804                 return tevent_req_post(req, ev);
3805         }
3806
3807         if ((min_protocol < PROTOCOL_SMB2_02) &&
3808             (max_protocol < PROTOCOL_SMB2_02)) {
3809                 /*
3810                  * SMB1 only...
3811                  */
3812                 conn->dispatch_incoming = smb1cli_conn_dispatch_incoming;
3813
3814                 subreq = smbXcli_negprot_smb1_subreq(state);
3815                 if (tevent_req_nomem(subreq, req)) {
3816                         return tevent_req_post(req, ev);
3817                 }
3818                 tevent_req_set_callback(subreq, smbXcli_negprot_smb1_done, req);
3819                 return req;
3820         }
3821
3822         if ((min_protocol >= PROTOCOL_SMB2_02) &&
3823             (max_protocol >= PROTOCOL_SMB2_02)) {
3824                 /*
3825                  * SMB2 only...
3826                  */
3827                 conn->dispatch_incoming = smb2cli_conn_dispatch_incoming;
3828
3829                 subreq = smbXcli_negprot_smb2_subreq(state);
3830                 if (tevent_req_nomem(subreq, req)) {
3831                         return tevent_req_post(req, ev);
3832                 }
3833                 tevent_req_set_callback(subreq, smbXcli_negprot_smb2_done, req);
3834                 return req;
3835         }
3836
3837         /*
3838          * We send an SMB1 negprot with the SMB2 dialects
3839          * and expect a SMB1 or a SMB2 response.
3840          *
3841          * smbXcli_negprot_dispatch_incoming() will fix the
3842          * callback to match protocol of the response.
3843          */
3844         conn->dispatch_incoming = smbXcli_negprot_dispatch_incoming;
3845
3846         subreq = smbXcli_negprot_smb1_subreq(state);
3847         if (tevent_req_nomem(subreq, req)) {
3848                 return tevent_req_post(req, ev);
3849         }
3850         tevent_req_set_callback(subreq, smbXcli_negprot_invalid_done, req);
3851         return req;
3852 }
3853
3854 static void smbXcli_negprot_invalid_done(struct tevent_req *subreq)
3855 {
3856         struct tevent_req *req =
3857                 tevent_req_callback_data(subreq,
3858                 struct tevent_req);
3859         NTSTATUS status;
3860
3861         /*
3862          * we just want the low level error
3863          */
3864         status = tevent_req_simple_recv_ntstatus(subreq);
3865         TALLOC_FREE(subreq);
3866         if (tevent_req_nterror(req, status)) {
3867                 return;
3868         }
3869
3870         /* this should never happen */
3871         tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
3872 }
3873
3874 static struct tevent_req *smbXcli_negprot_smb1_subreq(struct smbXcli_negprot_state *state)
3875 {
3876         size_t i;
3877         DATA_BLOB bytes = data_blob_null;
3878         uint8_t flags;
3879         uint16_t flags2;
3880
3881         /* setup the protocol strings */
3882         for (i=0; i < ARRAY_SIZE(smb1cli_prots); i++) {
3883                 uint8_t c = 2;
3884                 bool ok;
3885
3886                 if (smb1cli_prots[i].proto < state->min_protocol) {
3887                         continue;
3888                 }
3889
3890                 if (smb1cli_prots[i].proto > state->max_protocol) {
3891                         continue;
3892                 }
3893
3894                 ok = data_blob_append(state, &bytes, &c, sizeof(c));
3895                 if (!ok) {
3896                         return NULL;
3897                 }
3898
3899                 /*
3900                  * We now it is already ascii and
3901                  * we want NULL termination.
3902                  */
3903                 ok = data_blob_append(state, &bytes,
3904                                       smb1cli_prots[i].smb1_name,
3905                                       strlen(smb1cli_prots[i].smb1_name)+1);
3906                 if (!ok) {
3907                         return NULL;
3908                 }
3909         }
3910
3911         smb1cli_req_flags(state->max_protocol,
3912                           state->conn->smb1.client.capabilities,
3913                           SMBnegprot,
3914                           0, 0, &flags,
3915                           0, 0, &flags2);
3916
3917         return smb1cli_req_send(state, state->ev, state->conn,
3918                                 SMBnegprot,
3919                                 flags, ~flags,
3920                                 flags2, ~flags2,
3921                                 state->timeout_msec,
3922                                 0xFFFE, 0, NULL, /* pid, tid, session */
3923                                 0, NULL, /* wct, vwv */
3924                                 bytes.length, bytes.data);
3925 }
3926
3927 static void smbXcli_negprot_smb1_done(struct tevent_req *subreq)
3928 {
3929         struct tevent_req *req =
3930                 tevent_req_callback_data(subreq,
3931                 struct tevent_req);
3932         struct smbXcli_negprot_state *state =
3933                 tevent_req_data(req,
3934                 struct smbXcli_negprot_state);
3935         struct smbXcli_conn *conn = state->conn;
3936         struct iovec *recv_iov = NULL;
3937         uint8_t *inhdr;
3938         uint8_t wct;
3939         uint16_t *vwv;
3940         uint32_t num_bytes;
3941         uint8_t *bytes;
3942         NTSTATUS status;
3943         uint16_t protnum;
3944         size_t i;
3945         size_t num_prots = 0;
3946         uint8_t flags;
3947         uint32_t client_capabilities = conn->smb1.client.capabilities;
3948         uint32_t both_capabilities;
3949         uint32_t server_capabilities = 0;
3950         uint32_t capabilities;
3951         uint32_t client_max_xmit = conn->smb1.client.max_xmit;
3952         uint32_t server_max_xmit = 0;
3953         uint32_t max_xmit;
3954         uint32_t server_max_mux = 0;
3955         uint16_t server_security_mode = 0;
3956         uint32_t server_session_key = 0;
3957         bool server_readbraw = false;
3958         bool server_writebraw = false;
3959         bool server_lockread = false;
3960         bool server_writeunlock = false;
3961         struct GUID server_guid = GUID_zero();
3962         DATA_BLOB server_gss_blob = data_blob_null;
3963         uint8_t server_challenge[8];
3964         char *server_workgroup = NULL;
3965         char *server_name = NULL;
3966         int server_time_zone = 0;
3967         NTTIME server_system_time = 0;
3968         static const struct smb1cli_req_expected_response expected[] = {
3969         {
3970                 .status = NT_STATUS_OK,
3971                 .wct = 0x11, /* NT1 */
3972         },
3973         {
3974                 .status = NT_STATUS_OK,
3975                 .wct = 0x0D, /* LM */
3976         },
3977         {
3978                 .status = NT_STATUS_OK,
3979                 .wct = 0x01, /* CORE */
3980         }
3981         };
3982
3983         ZERO_STRUCT(server_challenge);
3984
3985         status = smb1cli_req_recv(subreq, state,
3986                                   &recv_iov,
3987                                   &inhdr,
3988                                   &wct,
3989                                   &vwv,
3990                                   NULL, /* pvwv_offset */
3991                                   &num_bytes,
3992                                   &bytes,
3993                                   NULL, /* pbytes_offset */
3994                                   NULL, /* pinbuf */
3995                                   expected, ARRAY_SIZE(expected));
3996         TALLOC_FREE(subreq);
3997         if (tevent_req_nterror(req, status)) {
3998                 return;
3999         }
4000
4001         flags = CVAL(inhdr, HDR_FLG);
4002
4003         protnum = SVAL(vwv, 0);
4004
4005         for (i=0; i < ARRAY_SIZE(smb1cli_prots); i++) {
4006                 if (smb1cli_prots[i].proto < state->min_protocol) {
4007                         continue;
4008                 }
4009
4010                 if (smb1cli_prots[i].proto > state->max_protocol) {
4011                         continue;
4012                 }
4013
4014                 if (protnum != num_prots) {
4015                         num_prots++;
4016                         continue;
4017                 }
4018
4019                 conn->protocol = smb1cli_prots[i].proto;
4020                 break;
4021         }
4022
4023         if (conn->protocol == PROTOCOL_NONE) {
4024                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
4025                 return;
4026         }
4027
4028         if ((conn->protocol < PROTOCOL_NT1) && conn->mandatory_signing) {
4029                 DEBUG(0,("smbXcli_negprot: SMB signing is mandatory "
4030                          "and the selected protocol level doesn't support it.\n"));
4031                 tevent_req_nterror(req, NT_STATUS_ACCESS_DENIED);
4032                 return;
4033         }
4034
4035         if (flags & FLAG_SUPPORT_LOCKREAD) {
4036                 server_lockread = true;
4037                 server_writeunlock = true;
4038         }
4039
4040         if (conn->protocol >= PROTOCOL_NT1) {
4041                 const char *client_signing = NULL;
4042                 bool server_mandatory = false;
4043                 bool server_allowed = false;
4044                 const char *server_signing = NULL;
4045                 bool ok;
4046                 uint8_t key_len;
4047
4048                 if (wct != 0x11) {
4049                         tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
4050                         return;
4051                 }
4052
4053                 /* NT protocol */
4054                 server_security_mode = CVAL(vwv + 1, 0);
4055                 server_max_mux = SVAL(vwv + 1, 1);
4056                 server_max_xmit = IVAL(vwv + 3, 1);
4057                 server_session_key = IVAL(vwv + 7, 1);
4058                 server_time_zone = SVALS(vwv + 15, 1);
4059                 server_time_zone *= 60;
4060                 /* this time arrives in real GMT */
4061                 server_system_time = BVAL(vwv + 11, 1);
4062                 server_capabilities = IVAL(vwv + 9, 1);
4063
4064                 key_len = CVAL(vwv + 16, 1);
4065
4066                 if (server_capabilities & CAP_RAW_MODE) {
4067                         server_readbraw = true;
4068                         server_writebraw = true;
4069                 }
4070                 if (server_capabilities & CAP_LOCK_AND_READ) {
4071                         server_lockread = true;
4072                 }
4073
4074                 if (server_capabilities & CAP_EXTENDED_SECURITY) {
4075                         DATA_BLOB blob1, blob2;
4076
4077                         if (num_bytes < 16) {
4078                                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
4079                                 return;
4080                         }
4081
4082                         blob1 = data_blob_const(bytes, 16);
4083                         status = GUID_from_data_blob(&blob1, &server_guid);
4084                         if (tevent_req_nterror(req, status)) {
4085                                 return;
4086                         }
4087
4088                         blob1 = data_blob_const(bytes+16, num_bytes-16);
4089                         blob2 = data_blob_dup_talloc(state, blob1);
4090                         if (blob1.length > 0 &&
4091                             tevent_req_nomem(blob2.data, req)) {
4092                                 return;
4093                         }
4094                         server_gss_blob = blob2;
4095                 } else {
4096                         DATA_BLOB blob1, blob2;
4097
4098                         if (num_bytes < key_len) {
4099                                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
4100                                 return;
4101                         }
4102
4103                         if (key_len != 0 && key_len != 8) {
4104                                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
4105                                 return;
4106                         }
4107
4108                         if (key_len == 8) {
4109                                 memcpy(server_challenge, bytes, 8);
4110                         }
4111
4112                         blob1 = data_blob_const(bytes+key_len, num_bytes-key_len);
4113                         blob2 = data_blob_const(bytes+key_len, num_bytes-key_len);
4114                         if (blob1.length > 0) {
4115                                 size_t len;
4116
4117                                 len = utf16_len_n(blob1.data,
4118                                                   blob1.length);
4119                                 blob1.length = len;
4120
4121                                 ok = convert_string_talloc(state,
4122                                                            CH_UTF16LE,
4123                                                            CH_UNIX,
4124                                                            blob1.data,
4125                                                            blob1.length,
4126                                                            &server_workgroup,
4127                                                            &len);
4128                                 if (!ok) {
4129                                         status = map_nt_error_from_unix_common(errno);
4130                                         tevent_req_nterror(req, status);
4131                                         return;
4132                                 }
4133                         }
4134
4135                         blob2.data += blob1.length;
4136                         blob2.length -= blob1.length;
4137                         if (blob2.length > 0) {
4138                                 size_t len;
4139
4140                                 len = utf16_len_n(blob1.data,
4141                                                   blob1.length);
4142                                 blob1.length = len;
4143
4144                                 ok = convert_string_talloc(state,
4145                                                            CH_UTF16LE,
4146                                                            CH_UNIX,
4147                                                            blob2.data,
4148                                                            blob2.length,
4149                                                            &server_name,
4150                                                            &len);
4151                                 if (!ok) {
4152                                         status = map_nt_error_from_unix_common(errno);
4153                                         tevent_req_nterror(req, status);
4154                                         return;
4155                                 }
4156                         }
4157                 }
4158
4159                 client_signing = "disabled";
4160                 if (conn->allow_signing) {
4161                         client_signing = "allowed";
4162                 }
4163                 if (conn->mandatory_signing) {
4164                         client_signing = "required";
4165                 }
4166
4167                 server_signing = "not supported";
4168                 if (server_security_mode & NEGOTIATE_SECURITY_SIGNATURES_ENABLED) {
4169                         server_signing = "supported";
4170                         server_allowed = true;
4171                 } else if (conn->mandatory_signing) {
4172                         /*
4173                          * We have mandatory signing as client
4174                          * lets assume the server will look at our
4175                          * FLAGS2_SMB_SECURITY_SIGNATURES_REQUIRED
4176                          * flag in the session setup
4177                          */
4178                         server_signing = "not announced";
4179                         server_allowed = true;
4180                 }
4181                 if (server_security_mode & NEGOTIATE_SECURITY_SIGNATURES_REQUIRED) {
4182                         server_signing = "required";
4183                         server_mandatory = true;
4184                 }
4185
4186                 ok = smb_signing_set_negotiated(conn->smb1.signing,
4187                                                 server_allowed,
4188                                                 server_mandatory);
4189                 if (!ok) {
4190                         DEBUG(1,("cli_negprot: SMB signing is required, "
4191                                  "but client[%s] and server[%s] mismatch\n",
4192                                  client_signing, server_signing));
4193                         tevent_req_nterror(req, NT_STATUS_ACCESS_DENIED);
4194                         return;
4195                 }
4196
4197         } else if (conn->protocol >= PROTOCOL_LANMAN1) {
4198                 DATA_BLOB blob1;
4199                 uint8_t key_len;
4200                 time_t t;
4201
4202                 if (wct != 0x0D) {
4203                         tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
4204                         return;
4205                 }
4206
4207                 server_security_mode = SVAL(vwv + 1, 0);
4208                 server_max_xmit = SVAL(vwv + 2, 0);
4209                 server_max_mux = SVAL(vwv + 3, 0);
4210                 server_readbraw = ((SVAL(vwv + 5, 0) & 0x1) != 0);
4211                 server_writebraw = ((SVAL(vwv + 5, 0) & 0x2) != 0);
4212                 server_session_key = IVAL(vwv + 6, 0);
4213                 server_time_zone = SVALS(vwv + 10, 0);
4214                 server_time_zone *= 60;
4215                 /* this time is converted to GMT by make_unix_date */
4216                 t = pull_dos_date((const uint8_t *)(vwv + 8), server_time_zone);
4217                 unix_to_nt_time(&server_system_time, t);
4218                 key_len = SVAL(vwv + 11, 0);
4219
4220                 if (num_bytes < key_len) {
4221                         tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
4222                         return;
4223                 }
4224
4225                 if (key_len != 0 && key_len != 8) {
4226                         tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
4227                         return;
4228                 }
4229
4230                 if (key_len == 8) {
4231                         memcpy(server_challenge, bytes, 8);
4232                 }
4233
4234                 blob1 = data_blob_const(bytes+key_len, num_bytes-key_len);
4235                 if (blob1.length > 0) {
4236                         size_t len;
4237                         bool ok;
4238
4239                         len = utf16_len_n(blob1.data,
4240                                           blob1.length);
4241                         blob1.length = len;
4242
4243                         ok = convert_string_talloc(state,
4244                                                    CH_DOS,
4245                                                    CH_UNIX,
4246                                                    blob1.data,
4247                                                    blob1.length,
4248                                                    &server_workgroup,
4249                                                    &len);
4250                         if (!ok) {
4251                                 status = map_nt_error_from_unix_common(errno);
4252                                 tevent_req_nterror(req, status);
4253                                 return;
4254                         }
4255                 }
4256
4257         } else {
4258                 /* the old core protocol */
4259                 server_time_zone = get_time_zone(time(NULL));
4260                 server_max_xmit = 1024;
4261                 server_max_mux = 1;
4262         }
4263
4264         if (server_max_xmit < 1024) {
4265                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
4266                 return;
4267         }
4268
4269         if (server_max_mux < 1) {
4270                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
4271                 return;
4272         }
4273
4274         /*
4275          * Now calculate the negotiated capabilities
4276          * based on the mask for:
4277          * - client only flags
4278          * - flags used in both directions
4279          * - server only flags
4280          */
4281         both_capabilities = client_capabilities & server_capabilities;
4282         capabilities = client_capabilities & SMB_CAP_CLIENT_MASK;
4283         capabilities |= both_capabilities & SMB_CAP_BOTH_MASK;
4284         capabilities |= server_capabilities & SMB_CAP_SERVER_MASK;
4285
4286         max_xmit = MIN(client_max_xmit, server_max_xmit);
4287
4288         conn->smb1.server.capabilities = server_capabilities;
4289         conn->smb1.capabilities = capabilities;
4290
4291         conn->smb1.server.max_xmit = server_max_xmit;
4292         conn->smb1.max_xmit = max_xmit;
4293
4294         conn->smb1.server.max_mux = server_max_mux;
4295
4296         conn->smb1.server.security_mode = server_security_mode;
4297
4298         conn->smb1.server.readbraw = server_readbraw;
4299         conn->smb1.server.writebraw = server_writebraw;
4300         conn->smb1.server.lockread = server_lockread;
4301         conn->smb1.server.writeunlock = server_writeunlock;
4302
4303         conn->smb1.server.session_key = server_session_key;
4304
4305         talloc_steal(conn, server_gss_blob.data);
4306         conn->smb1.server.gss_blob = server_gss_blob;
4307         conn->smb1.server.guid = server_guid;
4308         memcpy(conn->smb1.server.challenge, server_challenge, 8);
4309         conn->smb1.server.workgroup = talloc_move(conn, &server_workgroup);
4310         conn->smb1.server.name = talloc_move(conn, &server_name);
4311
4312         conn->smb1.server.time_zone = server_time_zone;
4313         conn->smb1.server.system_time = server_system_time;
4314
4315         tevent_req_done(req);
4316 }
4317
4318 static struct tevent_req *smbXcli_negprot_smb2_subreq(struct smbXcli_negprot_state *state)
4319 {
4320         size_t i;
4321         uint8_t *buf;
4322         uint16_t dialect_count = 0;
4323
4324         buf = state->smb2.dyn;
4325         for (i=0; i < ARRAY_SIZE(smb2cli_prots); i++) {
4326                 if (smb2cli_prots[i].proto < state->min_protocol) {
4327                         continue;
4328                 }
4329
4330                 if (smb2cli_prots[i].proto > state->max_protocol) {
4331                         continue;
4332                 }
4333
4334                 SSVAL(buf, dialect_count*2, smb2cli_prots[i].smb2_dialect);
4335                 dialect_count++;
4336         }
4337
4338         buf = state->smb2.fixed;
4339         SSVAL(buf, 0, 36);
4340         SSVAL(buf, 2, dialect_count);
4341         SSVAL(buf, 4, state->conn->smb2.client.security_mode);
4342         SSVAL(buf, 6, 0);       /* Reserved */
4343         if (state->max_protocol >= PROTOCOL_SMB2_22) {
4344                 SIVAL(buf, 8, state->conn->smb2.client.capabilities);
4345         } else {
4346                 SIVAL(buf, 8, 0);       /* Capabilities */
4347         }
4348         if (state->max_protocol >= PROTOCOL_SMB2_10) {
4349                 NTSTATUS status;
4350                 DATA_BLOB blob;
4351
4352                 status = GUID_to_ndr_blob(&state->conn->smb2.client.guid,
4353                                           state, &blob);
4354                 if (!NT_STATUS_IS_OK(status)) {
4355                         return NULL;
4356                 }
4357                 memcpy(buf+12, blob.data, 16); /* ClientGuid */
4358         } else {
4359                 memset(buf+12, 0, 16);  /* ClientGuid */
4360         }
4361         SBVAL(buf, 28, 0);      /* ClientStartTime */
4362
4363         return smb2cli_req_send(state, state->ev,
4364                                 state->conn, SMB2_OP_NEGPROT,
4365                                 0, 0, /* flags */
4366                                 state->timeout_msec,
4367                                 NULL, NULL, /* tcon, session */
4368                                 state->smb2.fixed, sizeof(state->smb2.fixed),
4369                                 state->smb2.dyn, dialect_count*2,
4370                                 UINT16_MAX); /* max_dyn_len */
4371 }
4372
4373 static void smbXcli_negprot_smb2_done(struct tevent_req *subreq)
4374 {
4375         struct tevent_req *req =
4376                 tevent_req_callback_data(subreq,
4377                 struct tevent_req);
4378         struct smbXcli_negprot_state *state =
4379                 tevent_req_data(req,
4380                 struct smbXcli_negprot_state);
4381         struct smbXcli_conn *conn = state->conn;
4382         size_t security_offset, security_length;
4383         DATA_BLOB blob;
4384         NTSTATUS status;
4385         struct iovec *iov;
4386         uint8_t *body;
4387         size_t i;
4388         uint16_t dialect_revision;
4389         static const struct smb2cli_req_expected_response expected[] = {
4390         {
4391                 .status = NT_STATUS_OK,
4392                 .body_size = 0x41
4393         }
4394         };
4395
4396         status = smb2cli_req_recv(subreq, state, &iov,
4397                                   expected, ARRAY_SIZE(expected));
4398         TALLOC_FREE(subreq);
4399         if (tevent_req_nterror(req, status)) {
4400                 return;
4401         }
4402
4403         body = (uint8_t *)iov[1].iov_base;
4404
4405         dialect_revision = SVAL(body, 4);
4406
4407         for (i=0; i < ARRAY_SIZE(smb2cli_prots); i++) {
4408                 if (smb2cli_prots[i].proto < state->min_protocol) {
4409                         continue;
4410                 }
4411
4412                 if (smb2cli_prots[i].proto > state->max_protocol) {
4413                         continue;
4414                 }
4415
4416                 if (smb2cli_prots[i].smb2_dialect != dialect_revision) {
4417                         continue;
4418                 }
4419
4420                 conn->protocol = smb2cli_prots[i].proto;
4421                 break;
4422         }
4423
4424         if (conn->protocol == PROTOCOL_NONE) {
4425                 if (state->min_protocol >= PROTOCOL_SMB2_02) {
4426                         tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
4427                         return;
4428                 }
4429
4430                 if (dialect_revision != SMB2_DIALECT_REVISION_2FF) {
4431                         tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
4432                         return;
4433                 }
4434
4435                 /* make sure we do not loop forever */
4436                 state->min_protocol = PROTOCOL_SMB2_02;
4437
4438                 /*
4439                  * send a SMB2 negprot, in order to negotiate
4440                  * the SMB2 dialect.
4441                  */
4442                 subreq = smbXcli_negprot_smb2_subreq(state);
4443                 if (tevent_req_nomem(subreq, req)) {
4444                         return;
4445                 }
4446                 tevent_req_set_callback(subreq, smbXcli_negprot_smb2_done, req);
4447                 return;
4448         }
4449
4450         conn->smb2.server.security_mode = SVAL(body, 2);
4451
4452         blob = data_blob_const(body + 8, 16);
4453         status = GUID_from_data_blob(&blob, &conn->smb2.server.guid);
4454         if (tevent_req_nterror(req, status)) {
4455                 return;
4456         }
4457
4458         conn->smb2.server.capabilities  = IVAL(body, 24);
4459         conn->smb2.server.max_trans_size= IVAL(body, 28);
4460         conn->smb2.server.max_read_size = IVAL(body, 32);
4461         conn->smb2.server.max_write_size= IVAL(body, 36);
4462         conn->smb2.server.system_time   = BVAL(body, 40);
4463         conn->smb2.server.start_time    = BVAL(body, 48);
4464
4465         security_offset = SVAL(body, 56);
4466         security_length = SVAL(body, 58);
4467
4468         if (security_offset != SMB2_HDR_BODY + iov[1].iov_len) {
4469                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
4470                 return;
4471         }
4472
4473         if (security_length > iov[2].iov_len) {
4474                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
4475                 return;
4476         }
4477
4478         conn->smb2.server.gss_blob = data_blob_talloc(conn,
4479                                                 iov[2].iov_base,
4480                                                 security_length);
4481         if (tevent_req_nomem(conn->smb2.server.gss_blob.data, req)) {
4482                 return;
4483         }
4484
4485         tevent_req_done(req);
4486 }
4487
4488 static NTSTATUS smbXcli_negprot_dispatch_incoming(struct smbXcli_conn *conn,
4489                                                   TALLOC_CTX *tmp_mem,
4490                                                   uint8_t *inbuf)
4491 {
4492         size_t num_pending = talloc_array_length(conn->pending);
4493         struct tevent_req *subreq;
4494         struct smbXcli_req_state *substate;
4495         struct tevent_req *req;
4496         uint32_t protocol_magic;
4497         size_t inbuf_len = smb_len_nbt(inbuf);
4498
4499         if (num_pending != 1) {
4500                 return NT_STATUS_INTERNAL_ERROR;
4501         }
4502
4503         if (inbuf_len < 4) {
4504                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
4505         }
4506
4507         subreq = conn->pending[0];
4508         substate = tevent_req_data(subreq, struct smbXcli_req_state);
4509         req = tevent_req_callback_data(subreq, struct tevent_req);
4510
4511         protocol_magic = IVAL(inbuf, 4);
4512
4513         switch (protocol_magic) {
4514         case SMB_MAGIC:
4515                 tevent_req_set_callback(subreq, smbXcli_negprot_smb1_done, req);
4516                 conn->dispatch_incoming = smb1cli_conn_dispatch_incoming;
4517                 return smb1cli_conn_dispatch_incoming(conn, tmp_mem, inbuf);
4518
4519         case SMB2_MAGIC:
4520                 if (substate->smb2.recv_iov == NULL) {
4521                         /*
4522                          * For the SMB1 negprot we have move it.
4523                          */
4524                         substate->smb2.recv_iov = substate->smb1.recv_iov;
4525                         substate->smb1.recv_iov = NULL;
4526                 }
4527
4528                 /*
4529                  * we got an SMB2 answer, which consumed sequence number 0
4530                  * so we need to use 1 as the next one.
4531                  *
4532                  * we also need to set the current credits to 0
4533                  * as we consumed the initial one. The SMB2 answer
4534                  * hopefully grant us a new credit.
4535                  */
4536                 conn->smb2.mid = 1;
4537                 conn->smb2.cur_credits = 0;
4538                 tevent_req_set_callback(subreq, smbXcli_negprot_smb2_done, req);
4539                 conn->dispatch_incoming = smb2cli_conn_dispatch_incoming;
4540                 return smb2cli_conn_dispatch_incoming(conn, tmp_mem, inbuf);
4541         }
4542
4543         DEBUG(10, ("Got non-SMB PDU\n"));
4544         return NT_STATUS_INVALID_NETWORK_RESPONSE;
4545 }
4546
4547 NTSTATUS smbXcli_negprot_recv(struct tevent_req *req)
4548 {
4549         return tevent_req_simple_recv_ntstatus(req);
4550 }
4551
4552 NTSTATUS smbXcli_negprot(struct smbXcli_conn *conn,
4553                          uint32_t timeout_msec,
4554                          enum protocol_types min_protocol,
4555                          enum protocol_types max_protocol)
4556 {
4557         TALLOC_CTX *frame = talloc_stackframe();
4558         struct tevent_context *ev;
4559         struct tevent_req *req;
4560         NTSTATUS status = NT_STATUS_NO_MEMORY;
4561         bool ok;
4562
4563         if (smbXcli_conn_has_async_calls(conn)) {
4564                 /*
4565                  * Can't use sync call while an async call is in flight
4566                  */
4567                 status = NT_STATUS_INVALID_PARAMETER_MIX;
4568                 goto fail;
4569         }
4570         ev = samba_tevent_context_init(frame);
4571         if (ev == NULL) {
4572                 goto fail;
4573         }
4574         req = smbXcli_negprot_send(frame, ev, conn, timeout_msec,
4575                                    min_protocol, max_protocol);
4576         if (req == NULL) {
4577                 goto fail;
4578         }
4579         ok = tevent_req_poll(req, ev);
4580         if (!ok) {
4581                 status = map_nt_error_from_unix_common(errno);
4582                 goto fail;
4583         }
4584         status = smbXcli_negprot_recv(req);
4585  fail:
4586         TALLOC_FREE(frame);
4587         return status;
4588 }
4589
4590 static int smbXcli_session_destructor(struct smbXcli_session *session)
4591 {
4592         if (session->conn == NULL) {
4593                 return 0;
4594         }
4595
4596         DLIST_REMOVE(session->conn->sessions, session);
4597         return 0;
4598 }
4599
4600 struct smbXcli_session *smbXcli_session_create(TALLOC_CTX *mem_ctx,
4601                                                struct smbXcli_conn *conn)
4602 {
4603         struct smbXcli_session *session;
4604
4605         session = talloc_zero(mem_ctx, struct smbXcli_session);
4606         if (session == NULL) {
4607                 return NULL;
4608         }
4609         session->smb2 = talloc_zero(session, struct smb2cli_session);
4610         if (session->smb2 == NULL) {
4611                 talloc_free(session);
4612                 return NULL;
4613         }
4614         talloc_set_destructor(session, smbXcli_session_destructor);
4615
4616         DLIST_ADD_END(conn->sessions, session, struct smbXcli_session *);
4617         session->conn = conn;
4618
4619         return session;
4620 }
4621
4622 struct smbXcli_session *smbXcli_session_copy(TALLOC_CTX *mem_ctx,
4623                                                 struct smbXcli_session *src)
4624 {
4625         struct smbXcli_session *session;
4626
4627         session = talloc_zero(mem_ctx, struct smbXcli_session);
4628         if (session == NULL) {
4629                 return NULL;
4630         }
4631         session->smb2 = talloc_zero(session, struct smb2cli_session);
4632         if (session->smb2 == NULL) {
4633                 talloc_free(session);
4634                 return NULL;
4635         }
4636
4637         session->conn = src->conn;
4638         *session->smb2 = *src->smb2;
4639         session->smb2_channel = src->smb2_channel;
4640         session->disconnect_expired = src->disconnect_expired;
4641
4642         DLIST_ADD_END(src->conn->sessions, session, struct smbXcli_session *);
4643         talloc_set_destructor(session, smbXcli_session_destructor);
4644
4645         return session;
4646 }
4647
4648 bool smbXcli_session_is_authenticated(struct smbXcli_session *session)
4649 {
4650         const DATA_BLOB *application_key;
4651
4652         if (session->conn == NULL) {
4653                 return false;
4654         }
4655
4656         /*
4657          * If we have an application key we had a session key negotiated
4658          * at auth time.
4659          */
4660         if (session->conn->protocol >= PROTOCOL_SMB2_02) {
4661                 application_key = &session->smb2->application_key;
4662         } else {
4663                 application_key = &session->smb1.application_key;
4664         }
4665
4666         if (application_key->length == 0) {
4667                 return false;
4668         }
4669
4670         return true;
4671 }
4672
4673 NTSTATUS smbXcli_session_application_key(struct smbXcli_session *session,
4674                                          TALLOC_CTX *mem_ctx,
4675                                          DATA_BLOB *key)
4676 {
4677         const DATA_BLOB *application_key;
4678
4679         *key = data_blob_null;
4680
4681         if (session->conn == NULL) {
4682                 return NT_STATUS_NO_USER_SESSION_KEY;
4683         }
4684
4685         if (session->conn->protocol >= PROTOCOL_SMB2_02) {
4686                 application_key = &session->smb2->application_key;
4687         } else {
4688                 application_key = &session->smb1.application_key;
4689         }
4690
4691         if (application_key->length == 0) {
4692                 return NT_STATUS_NO_USER_SESSION_KEY;
4693         }
4694
4695         *key = data_blob_dup_talloc(mem_ctx, *application_key);
4696         if (key->data == NULL) {
4697                 return NT_STATUS_NO_MEMORY;
4698         }
4699
4700         return NT_STATUS_OK;
4701 }
4702
4703 void smbXcli_session_set_disconnect_expired(struct smbXcli_session *session)
4704 {
4705         session->disconnect_expired = true;
4706 }
4707
4708 uint16_t smb1cli_session_current_id(struct smbXcli_session *session)
4709 {
4710         return session->smb1.session_id;
4711 }
4712
4713 void smb1cli_session_set_id(struct smbXcli_session *session,
4714                             uint16_t session_id)
4715 {
4716         session->smb1.session_id = session_id;
4717 }
4718
4719 NTSTATUS smb1cli_session_set_session_key(struct smbXcli_session *session,
4720                                          const DATA_BLOB _session_key)
4721 {
4722         struct smbXcli_conn *conn = session->conn;
4723         uint8_t session_key[16];
4724
4725         if (conn == NULL) {
4726                 return NT_STATUS_INVALID_PARAMETER_MIX;
4727         }
4728
4729         if (session->smb1.application_key.length != 0) {
4730                 /*
4731                  * TODO: do not allow this...
4732                  *
4733                  * return NT_STATUS_INVALID_PARAMETER_MIX;
4734                  */
4735                 data_blob_clear_free(&session->smb1.application_key);
4736                 session->smb1.protected_key = false;
4737         }
4738
4739         if (_session_key.length == 0) {
4740                 return NT_STATUS_OK;
4741         }
4742
4743         ZERO_STRUCT(session_key);
4744         memcpy(session_key, _session_key.data,
4745                MIN(_session_key.length, sizeof(session_key)));
4746
4747         session->smb1.application_key = data_blob_talloc(session,
4748                                                          session_key,
4749                                                          sizeof(session_key));
4750         ZERO_STRUCT(session_key);
4751         if (session->smb1.application_key.data == NULL) {
4752                 return NT_STATUS_NO_MEMORY;
4753         }
4754
4755         session->smb1.protected_key = false;
4756
4757         return NT_STATUS_OK;
4758 }
4759
4760 NTSTATUS smb1cli_session_protect_session_key(struct smbXcli_session *session)
4761 {
4762         if (session->smb1.protected_key) {
4763                 /* already protected */
4764                 return NT_STATUS_OK;
4765         }
4766
4767         if (session->smb1.application_key.length != 16) {
4768                 return NT_STATUS_INVALID_PARAMETER_MIX;
4769         }
4770
4771         smb_key_derivation(session->smb1.application_key.data,
4772                            session->smb1.application_key.length,
4773                            session->smb1.application_key.data);
4774
4775         session->smb1.protected_key = true;
4776
4777         return NT_STATUS_OK;
4778 }
4779
4780 uint8_t smb2cli_session_security_mode(struct smbXcli_session *session)
4781 {
4782         struct smbXcli_conn *conn = session->conn;
4783         uint8_t security_mode = 0;
4784
4785         if (conn == NULL) {
4786                 return security_mode;
4787         }
4788
4789         security_mode = SMB2_NEGOTIATE_SIGNING_ENABLED;
4790         if (conn->mandatory_signing) {
4791                 security_mode |= SMB2_NEGOTIATE_SIGNING_REQUIRED;
4792         }
4793
4794         return security_mode;
4795 }
4796
4797 uint64_t smb2cli_session_current_id(struct smbXcli_session *session)
4798 {
4799         return session->smb2->session_id;
4800 }
4801
4802 uint16_t smb2cli_session_get_flags(struct smbXcli_session *session)
4803 {
4804         return session->smb2->session_flags;
4805 }
4806
4807 void smb2cli_session_set_id_and_flags(struct smbXcli_session *session,
4808                                       uint64_t session_id,
4809                                       uint16_t session_flags)
4810 {
4811         session->smb2->session_id = session_id;
4812         session->smb2->session_flags = session_flags;
4813 }
4814
4815 void smb2cli_session_increment_channel_sequence(struct smbXcli_session *session)
4816 {
4817         session->smb2->channel_sequence += 1;
4818 }
4819
4820 uint16_t smb2cli_session_reset_channel_sequence(struct smbXcli_session *session,
4821                                                 uint16_t channel_sequence)
4822 {
4823         uint16_t prev_cs;
4824
4825         prev_cs = session->smb2->channel_sequence;
4826         session->smb2->channel_sequence = channel_sequence;
4827
4828         return prev_cs;
4829 }
4830
4831 void smb2cli_session_start_replay(struct smbXcli_session *session)
4832 {
4833         session->smb2->replay_active = true;
4834 }
4835
4836 void smb2cli_session_stop_replay(struct smbXcli_session *session)
4837 {
4838         session->smb2->replay_active = false;
4839 }
4840
4841 NTSTATUS smb2cli_session_set_session_key(struct smbXcli_session *session,
4842                                          const DATA_BLOB _session_key,
4843                                          const struct iovec *recv_iov)
4844 {
4845         struct smbXcli_conn *conn = session->conn;
4846         uint16_t no_sign_flags;
4847         uint8_t session_key[16];
4848         bool check_signature = true;
4849         uint32_t hdr_flags;
4850         NTSTATUS status;
4851
4852         if (conn == NULL) {
4853                 return NT_STATUS_INVALID_PARAMETER_MIX;
4854         }
4855
4856         if (recv_iov[0].iov_len != SMB2_HDR_BODY) {
4857                 return NT_STATUS_INVALID_PARAMETER_MIX;
4858         }
4859
4860         no_sign_flags = SMB2_SESSION_FLAG_IS_GUEST | SMB2_SESSION_FLAG_IS_NULL;
4861
4862         if (session->smb2->session_flags & no_sign_flags) {
4863                 session->smb2->should_sign = false;
4864                 return NT_STATUS_OK;
4865         }
4866
4867         if (session->smb2->signing_key.length != 0) {
4868                 return NT_STATUS_INVALID_PARAMETER_MIX;
4869         }
4870
4871         ZERO_STRUCT(session_key);
4872         memcpy(session_key, _session_key.data,
4873                MIN(_session_key.length, sizeof(session_key)));
4874
4875         session->smb2->signing_key = data_blob_talloc(session,
4876                                                      session_key,
4877                                                      sizeof(session_key));
4878         if (session->smb2->signing_key.data == NULL) {
4879                 ZERO_STRUCT(session_key);
4880                 return NT_STATUS_NO_MEMORY;
4881         }
4882
4883         if (conn->protocol >= PROTOCOL_SMB2_24) {
4884                 const DATA_BLOB label = data_blob_string_const_null("SMB2AESCMAC");
4885                 const DATA_BLOB context = data_blob_string_const_null("SmbSign");
4886
4887                 smb2_key_derivation(session_key, sizeof(session_key),
4888                                     label.data, label.length,
4889                                     context.data, context.length,
4890                                     session->smb2->signing_key.data);
4891         }
4892
4893         session->smb2->encryption_key = data_blob_dup_talloc(session,
4894                                                 session->smb2->signing_key);
4895         if (session->smb2->encryption_key.data == NULL) {
4896                 ZERO_STRUCT(session_key);
4897                 return NT_STATUS_NO_MEMORY;
4898         }
4899
4900         if (conn->protocol >= PROTOCOL_SMB2_24) {
4901                 const DATA_BLOB label = data_blob_string_const_null("SMB2AESCCM");
4902                 const DATA_BLOB context = data_blob_string_const_null("ServerIn ");
4903
4904                 smb2_key_derivation(session_key, sizeof(session_key),
4905                                     label.data, label.length,
4906                                     context.data, context.length,
4907                                     session->smb2->encryption_key.data);
4908         }
4909
4910         session->smb2->decryption_key = data_blob_dup_talloc(session,
4911                                                 session->smb2->signing_key);
4912         if (session->smb2->decryption_key.data == NULL) {
4913                 ZERO_STRUCT(session_key);
4914                 return NT_STATUS_NO_MEMORY;
4915         }
4916
4917         if (conn->protocol >= PROTOCOL_SMB2_24) {
4918                 const DATA_BLOB label = data_blob_string_const_null("SMB2AESCCM");
4919                 const DATA_BLOB context = data_blob_string_const_null("ServerOut");
4920
4921                 smb2_key_derivation(session_key, sizeof(session_key),
4922                                     label.data, label.length,
4923                                     context.data, context.length,
4924                                     session->smb2->decryption_key.data);
4925         }
4926
4927         session->smb2->application_key = data_blob_dup_talloc(session,
4928                                                 session->smb2->signing_key);
4929         if (session->smb2->application_key.data == NULL) {
4930                 ZERO_STRUCT(session_key);
4931                 return NT_STATUS_NO_MEMORY;
4932         }
4933
4934         if (conn->protocol >= PROTOCOL_SMB2_24) {
4935                 const DATA_BLOB label = data_blob_string_const_null("SMB2APP");
4936                 const DATA_BLOB context = data_blob_string_const_null("SmbRpc");
4937
4938                 smb2_key_derivation(session_key, sizeof(session_key),
4939                                     label.data, label.length,
4940                                     context.data, context.length,
4941                                     session->smb2->application_key.data);
4942         }
4943         ZERO_STRUCT(session_key);
4944
4945         session->smb2_channel.signing_key = data_blob_dup_talloc(session,
4946                                                 session->smb2->signing_key);
4947         if (session->smb2_channel.signing_key.data == NULL) {
4948                 return NT_STATUS_NO_MEMORY;
4949         }
4950
4951         check_signature = conn->mandatory_signing;
4952
4953         hdr_flags = IVAL(recv_iov[0].iov_base, SMB2_HDR_FLAGS);
4954         if (hdr_flags & SMB2_HDR_FLAG_SIGNED) {
4955                 /*
4956                  * Sadly some vendors don't sign the
4957                  * final SMB2 session setup response
4958                  *
4959                  * At least Windows and Samba are always doing this
4960                  * if there's a session key available.
4961                  *
4962                  * We only check the signature if it's mandatory
4963                  * or SMB2_HDR_FLAG_SIGNED is provided.
4964                  */
4965                 check_signature = true;
4966         }
4967
4968         if (check_signature) {
4969                 status = smb2_signing_check_pdu(session->smb2_channel.signing_key,
4970                                                 session->conn->protocol,
4971                                                 recv_iov, 3);
4972                 if (!NT_STATUS_IS_OK(status)) {
4973                         return status;
4974                 }
4975         }
4976
4977         session->smb2->should_sign = false;
4978         session->smb2->should_encrypt = false;
4979
4980         if (conn->desire_signing) {
4981                 session->smb2->should_sign = true;
4982         }
4983
4984         if (conn->smb2.server.security_mode & SMB2_NEGOTIATE_SIGNING_REQUIRED) {
4985                 session->smb2->should_sign = true;
4986         }
4987
4988         if (session->smb2->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA) {
4989                 session->smb2->should_encrypt = true;
4990         }
4991
4992         if (conn->protocol < PROTOCOL_SMB2_24) {
4993                 session->smb2->should_encrypt = false;
4994         }
4995
4996         if (!(conn->smb2.server.capabilities & SMB2_CAP_ENCRYPTION)) {
4997                 session->smb2->should_encrypt = false;
4998         }
4999
5000         generate_random_buffer((uint8_t *)&session->smb2->nonce_high,
5001                                sizeof(session->smb2->nonce_high));
5002         session->smb2->nonce_low = 1;
5003
5004         return NT_STATUS_OK;
5005 }
5006
5007 NTSTATUS smb2cli_session_create_channel(TALLOC_CTX *mem_ctx,
5008                                         struct smbXcli_session *session1,
5009                                         struct smbXcli_conn *conn,
5010                                         struct smbXcli_session **_session2)
5011 {
5012         struct smbXcli_session *session2;
5013
5014         if (session1->smb2->signing_key.length == 0) {
5015                 return NT_STATUS_INVALID_PARAMETER_MIX;
5016         }
5017
5018         if (conn == NULL) {
5019                 return NT_STATUS_INVALID_PARAMETER_MIX;
5020         }
5021
5022         session2 = talloc_zero(mem_ctx, struct smbXcli_session);
5023         if (session2 == NULL) {
5024                 return NT_STATUS_NO_MEMORY;
5025         }
5026         session2->smb2 = talloc_reference(session2, session1->smb2);
5027         if (session2->smb2 == NULL) {
5028                 talloc_free(session2);
5029                 return NT_STATUS_NO_MEMORY;
5030         }
5031
5032         talloc_set_destructor(session2, smbXcli_session_destructor);
5033         DLIST_ADD_END(conn->sessions, session2, struct smbXcli_session *);
5034         session2->conn = conn;
5035
5036         *_session2 = session2;
5037         return NT_STATUS_OK;
5038 }
5039
5040 NTSTATUS smb2cli_session_set_channel_key(struct smbXcli_session *session,
5041                                          const DATA_BLOB _channel_key,
5042                                          const struct iovec *recv_iov)
5043 {
5044         struct smbXcli_conn *conn = session->conn;
5045         uint8_t channel_key[16];
5046         NTSTATUS status;
5047
5048         if (conn == NULL) {
5049                 return NT_STATUS_INVALID_PARAMETER_MIX;
5050         }
5051
5052         if (session->smb2_channel.signing_key.length != 0) {
5053                 return NT_STATUS_INVALID_PARAMETER_MIX;
5054         }
5055
5056         ZERO_STRUCT(channel_key);
5057         memcpy(channel_key, _channel_key.data,
5058                MIN(_channel_key.length, sizeof(channel_key)));
5059
5060         session->smb2_channel.signing_key = data_blob_talloc(session,
5061                                                 channel_key,
5062                                                 sizeof(channel_key));
5063         if (session->smb2_channel.signing_key.data == NULL) {
5064                 ZERO_STRUCT(channel_key);
5065                 return NT_STATUS_NO_MEMORY;
5066         }
5067
5068         if (conn->protocol >= PROTOCOL_SMB2_24) {
5069                 const DATA_BLOB label = data_blob_string_const_null("SMB2AESCMAC");
5070                 const DATA_BLOB context = data_blob_string_const_null("SmbSign");
5071
5072                 smb2_key_derivation(channel_key, sizeof(channel_key),
5073                                     label.data, label.length,
5074                                     context.data, context.length,
5075                                     session->smb2_channel.signing_key.data);
5076         }
5077         ZERO_STRUCT(channel_key);
5078
5079         status = smb2_signing_check_pdu(session->smb2_channel.signing_key,
5080                                         session->conn->protocol,
5081                                         recv_iov, 3);
5082         if (!NT_STATUS_IS_OK(status)) {
5083                 return status;
5084         }
5085
5086         return NT_STATUS_OK;
5087 }
5088
5089 NTSTATUS smb2cli_session_encryption_on(struct smbXcli_session *session)
5090 {
5091         if (session->smb2->should_encrypt) {
5092                 return NT_STATUS_OK;
5093         }
5094
5095         if (session->conn->protocol < PROTOCOL_SMB2_24) {
5096                 return NT_STATUS_NOT_SUPPORTED;
5097         }
5098
5099         if (!(session->conn->smb2.server.capabilities & SMB2_CAP_ENCRYPTION)) {
5100                 return NT_STATUS_NOT_SUPPORTED;
5101         }
5102
5103         if (session->smb2->signing_key.data == NULL) {
5104                 return NT_STATUS_NOT_SUPPORTED;
5105         }
5106         session->smb2->should_encrypt = true;
5107         return NT_STATUS_OK;
5108 }
5109
5110 struct smbXcli_tcon *smbXcli_tcon_create(TALLOC_CTX *mem_ctx)
5111 {
5112         struct smbXcli_tcon *tcon;
5113
5114         tcon = talloc_zero(mem_ctx, struct smbXcli_tcon);
5115         if (tcon == NULL) {
5116                 return NULL;
5117         }
5118
5119         return tcon;
5120 }
5121
5122 void smbXcli_tcon_set_fs_attributes(struct smbXcli_tcon *tcon,
5123                                     uint32_t fs_attributes)
5124 {
5125         tcon->fs_attributes = fs_attributes;
5126 }
5127
5128 uint32_t smbXcli_tcon_get_fs_attributes(struct smbXcli_tcon *tcon)
5129 {
5130         return tcon->fs_attributes;
5131 }
5132
5133 bool smbXcli_tcon_is_dfs_share(struct smbXcli_tcon *tcon)
5134 {
5135         if (tcon == NULL) {
5136                 return false;
5137         }
5138
5139         if (tcon->is_smb1) {
5140                 if (tcon->smb1.optional_support & SMB_SHARE_IN_DFS) {
5141                         return true;
5142                 }
5143
5144                 return false;
5145         }
5146
5147         if (tcon->smb2.capabilities & SMB2_SHARE_CAP_DFS) {
5148                 return true;
5149         }
5150
5151         return false;
5152 }
5153
5154 uint16_t smb1cli_tcon_current_id(struct smbXcli_tcon *tcon)
5155 {
5156         return tcon->smb1.tcon_id;
5157 }
5158
5159 void smb1cli_tcon_set_id(struct smbXcli_tcon *tcon, uint16_t tcon_id)
5160 {
5161         tcon->is_smb1 = true;
5162         tcon->smb1.tcon_id = tcon_id;
5163 }
5164
5165 bool smb1cli_tcon_set_values(struct smbXcli_tcon *tcon,
5166                              uint16_t tcon_id,
5167                              uint16_t optional_support,
5168                              uint32_t maximal_access,
5169                              uint32_t guest_maximal_access,
5170                              const char *service,
5171                              const char *fs_type)
5172 {
5173         tcon->is_smb1 = true;
5174         tcon->fs_attributes = 0;
5175         tcon->smb1.tcon_id = tcon_id;
5176         tcon->smb1.optional_support = optional_support;
5177         tcon->smb1.maximal_access = maximal_access;
5178         tcon->smb1.guest_maximal_access = guest_maximal_access;
5179
5180         TALLOC_FREE(tcon->smb1.service);
5181         tcon->smb1.service = talloc_strdup(tcon, service);
5182         if (service != NULL && tcon->smb1.service == NULL) {
5183                 return false;
5184         }
5185
5186         TALLOC_FREE(tcon->smb1.fs_type);
5187         tcon->smb1.fs_type = talloc_strdup(tcon, fs_type);
5188         if (fs_type != NULL && tcon->smb1.fs_type == NULL) {
5189                 return false;
5190         }
5191
5192         return true;
5193 }
5194
5195 uint32_t smb2cli_tcon_current_id(struct smbXcli_tcon *tcon)
5196 {
5197         return tcon->smb2.tcon_id;
5198 }
5199
5200 uint32_t smb2cli_tcon_capabilities(struct smbXcli_tcon *tcon)
5201 {
5202         return tcon->smb2.capabilities;
5203 }
5204
5205 void smb2cli_tcon_set_values(struct smbXcli_tcon *tcon,
5206                              struct smbXcli_session *session,
5207                              uint32_t tcon_id,
5208                              uint8_t type,
5209                              uint32_t flags,
5210                              uint32_t capabilities,
5211                              uint32_t maximal_access)
5212 {
5213         tcon->is_smb1 = false;
5214         tcon->fs_attributes = 0;
5215         tcon->smb2.tcon_id = tcon_id;
5216         tcon->smb2.type = type;
5217         tcon->smb2.flags = flags;
5218         tcon->smb2.capabilities = capabilities;
5219         tcon->smb2.maximal_access = maximal_access;
5220
5221         tcon->smb2.should_sign = false;
5222         tcon->smb2.should_encrypt = false;
5223
5224         if (session == NULL) {
5225                 return;
5226         }
5227
5228         tcon->smb2.should_sign = session->smb2->should_sign;
5229         tcon->smb2.should_encrypt = session->smb2->should_encrypt;
5230
5231         if (flags & SMB2_SHAREFLAG_ENCRYPT_DATA) {
5232                 tcon->smb2.should_encrypt = true;
5233         }
5234 }
5235
5236 void smb2cli_tcon_should_sign(struct smbXcli_tcon *tcon,
5237                               bool should_sign)
5238 {
5239         tcon->smb2.should_sign = should_sign;
5240 }
5241
5242 bool smb2cli_tcon_is_signing_on(struct smbXcli_tcon *tcon)
5243 {
5244         if (tcon->smb2.should_encrypt) {
5245                 return true;
5246         }
5247
5248         return tcon->smb2.should_sign;
5249 }
5250
5251 void smb2cli_tcon_should_encrypt(struct smbXcli_tcon *tcon,
5252                                  bool should_encrypt)
5253 {
5254         tcon->smb2.should_encrypt = should_encrypt;
5255 }
5256
5257 bool smb2cli_tcon_is_encryption_on(struct smbXcli_tcon *tcon)
5258 {
5259         return tcon->smb2.should_encrypt;
5260 }