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