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