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