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