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