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