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