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