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