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