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