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