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