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