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