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