smbXcli: fix smb signing for SMBntcancel
[obnox/samba/samba-obnox.git] / libcli / smb / smbXcli_base.c
1 /*
2    Unix SMB/CIFS implementation.
3    Infrastructure for async SMB client requests
4    Copyright (C) Volker Lendecke 2008
5    Copyright (C) Stefan Metzmacher 2011
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "includes.h"
22 #include "system/network.h"
23 #include "../lib/async_req/async_sock.h"
24 #include "../lib/util/tevent_ntstatus.h"
25 #include "../lib/util/tevent_unix.h"
26 #include "lib/util/util_net.h"
27 #include "lib/util/dlinklist.h"
28 #include "../libcli/smb/smb_common.h"
29 #include "../libcli/smb/smb_seal.h"
30 #include "../libcli/smb/smb_signing.h"
31 #include "../libcli/smb/read_smb.h"
32 #include "smbXcli_base.h"
33 #include "librpc/ndr/libndr.h"
34
35 struct smbXcli_conn;
36 struct smbXcli_req;
37 struct smbXcli_session;
38
39 struct smbXcli_conn {
40         int fd;
41         struct sockaddr_storage local_ss;
42         struct sockaddr_storage remote_ss;
43         const char *remote_name;
44
45         struct tevent_queue *outgoing;
46         struct tevent_req **pending;
47         struct tevent_req *read_smb_req;
48
49         enum protocol_types protocol;
50         bool allow_signing;
51         bool desire_signing;
52         bool mandatory_signing;
53
54         /*
55          * The incoming dispatch function should return:
56          * - NT_STATUS_RETRY, if more incoming PDUs are expected.
57          * - NT_STATUS_OK, if no more processing is desired, e.g.
58          *                 the dispatch function called
59          *                 tevent_req_done().
60          * - All other return values disconnect the connection.
61          */
62         NTSTATUS (*dispatch_incoming)(struct smbXcli_conn *conn,
63                                       TALLOC_CTX *tmp_mem,
64                                       uint8_t *inbuf);
65
66         struct {
67                 struct {
68                         uint32_t capabilities;
69                         uint32_t max_xmit;
70                 } client;
71
72                 struct {
73                         uint32_t capabilities;
74                         uint32_t max_xmit;
75                         uint16_t max_mux;
76                         uint16_t security_mode;
77                         bool readbraw;
78                         bool writebraw;
79                         bool lockread;
80                         bool writeunlock;
81                         uint32_t session_key;
82                         struct GUID guid;
83                         DATA_BLOB gss_blob;
84                         uint8_t challenge[8];
85                         const char *workgroup;
86                         const char *name;
87                         int time_zone;
88                         NTTIME system_time;
89                 } server;
90
91                 uint32_t capabilities;
92                 uint32_t max_xmit;
93
94                 uint16_t mid;
95
96                 struct smb_signing_state *signing;
97                 struct smb_trans_enc_state *trans_enc;
98         } smb1;
99
100         struct {
101                 struct {
102                         uint16_t security_mode;
103                         struct GUID guid;
104                 } client;
105
106                 struct {
107                         uint32_t capabilities;
108                         uint16_t security_mode;
109                         struct GUID guid;
110                         uint32_t max_trans_size;
111                         uint32_t max_read_size;
112                         uint32_t max_write_size;
113                         NTTIME system_time;
114                         NTTIME start_time;
115                         DATA_BLOB gss_blob;
116                 } server;
117
118                 uint64_t mid;
119                 uint16_t cur_credits;
120                 uint16_t max_credits;
121         } smb2;
122
123         struct smbXcli_session *sessions;
124 };
125
126 struct smbXcli_session {
127         struct smbXcli_session *prev, *next;
128         struct smbXcli_conn *conn;
129
130         struct {
131                 uint64_t session_id;
132                 uint16_t session_flags;
133                 DATA_BLOB signing_key;
134                 DATA_BLOB session_key;
135                 bool should_sign;
136                 bool channel_setup;
137         } smb2;
138 };
139
140 struct smbXcli_req_state {
141         struct tevent_context *ev;
142         struct smbXcli_conn *conn;
143         struct smbXcli_session *session; /* maybe NULL */
144
145         uint8_t length_hdr[4];
146
147         bool one_way;
148
149         uint8_t *inbuf;
150
151         struct {
152                 /* Space for the header including the wct */
153                 uint8_t hdr[HDR_VWV];
154
155                 /*
156                  * For normal requests, smb1cli_req_send chooses a mid.
157                  * SecondaryV trans requests need to use the mid of the primary
158                  * request, so we need a place to store it.
159                  * Assume it is set if != 0.
160                  */
161                 uint16_t mid;
162
163                 uint16_t *vwv;
164                 uint8_t bytecount_buf[2];
165
166 #define MAX_SMB_IOV 5
167                 /* length_hdr, hdr, words, byte_count, buffers */
168                 struct iovec iov[1 + 3 + MAX_SMB_IOV];
169                 int iov_count;
170
171                 bool one_way_seqnum;
172                 uint32_t seqnum;
173                 struct tevent_req **chained_requests;
174
175                 uint8_t recv_cmd;
176                 NTSTATUS recv_status;
177                 /* always an array of 3 talloc elements */
178                 struct iovec *recv_iov;
179         } smb1;
180
181         struct {
182                 const uint8_t *fixed;
183                 uint16_t fixed_len;
184                 const uint8_t *dyn;
185                 uint32_t dyn_len;
186
187                 uint8_t hdr[64];
188                 uint8_t pad[7]; /* padding space for compounding */
189
190                 /* always an array of 3 talloc elements */
191                 struct iovec *recv_iov;
192
193                 uint16_t credit_charge;
194
195                 bool signing_skipped;
196         } smb2;
197 };
198
199 static int smbXcli_conn_destructor(struct smbXcli_conn *conn)
200 {
201         /*
202          * NT_STATUS_OK, means we do not notify the callers
203          */
204         smbXcli_conn_disconnect(conn, NT_STATUS_OK);
205
206         while (conn->sessions) {
207                 conn->sessions->conn = NULL;
208                 DLIST_REMOVE(conn->sessions, conn->sessions);
209         }
210
211         if (conn->smb1.trans_enc) {
212                 common_free_encryption_state(&conn->smb1.trans_enc);
213         }
214
215         return 0;
216 }
217
218 struct smbXcli_conn *smbXcli_conn_create(TALLOC_CTX *mem_ctx,
219                                          int fd,
220                                          const char *remote_name,
221                                          enum smb_signing_setting signing_state,
222                                          uint32_t smb1_capabilities,
223                                          struct GUID *client_guid)
224 {
225         struct smbXcli_conn *conn = NULL;
226         void *ss = NULL;
227         struct sockaddr *sa = NULL;
228         socklen_t sa_length;
229         int ret;
230
231         conn = talloc_zero(mem_ctx, struct smbXcli_conn);
232         if (!conn) {
233                 return NULL;
234         }
235
236         conn->remote_name = talloc_strdup(conn, remote_name);
237         if (conn->remote_name == NULL) {
238                 goto error;
239         }
240
241         conn->fd = fd;
242
243         ss = (void *)&conn->local_ss;
244         sa = (struct sockaddr *)ss;
245         sa_length = sizeof(conn->local_ss);
246         ret = getsockname(fd, sa, &sa_length);
247         if (ret == -1) {
248                 goto error;
249         }
250         ss = (void *)&conn->remote_ss;
251         sa = (struct sockaddr *)ss;
252         sa_length = sizeof(conn->remote_ss);
253         ret = getpeername(fd, sa, &sa_length);
254         if (ret == -1) {
255                 goto error;
256         }
257
258         conn->outgoing = tevent_queue_create(conn, "smbXcli_outgoing");
259         if (conn->outgoing == NULL) {
260                 goto error;
261         }
262         conn->pending = NULL;
263
264         conn->protocol = PROTOCOL_NONE;
265
266         switch (signing_state) {
267         case SMB_SIGNING_OFF:
268                 /* never */
269                 conn->allow_signing = false;
270                 conn->desire_signing = false;
271                 conn->mandatory_signing = false;
272                 break;
273         case SMB_SIGNING_DEFAULT:
274         case SMB_SIGNING_IF_REQUIRED:
275                 /* if the server requires it */
276                 conn->allow_signing = true;
277                 conn->desire_signing = false;
278                 conn->mandatory_signing = false;
279                 break;
280         case SMB_SIGNING_REQUIRED:
281                 /* always */
282                 conn->allow_signing = true;
283                 conn->desire_signing = true;
284                 conn->mandatory_signing = true;
285                 break;
286         }
287
288         conn->smb1.client.capabilities = smb1_capabilities;
289         conn->smb1.client.max_xmit = UINT16_MAX;
290
291         conn->smb1.capabilities = conn->smb1.client.capabilities;
292         conn->smb1.max_xmit = 1024;
293
294         conn->smb1.mid = 1;
295
296         /* initialise signing */
297         conn->smb1.signing = smb_signing_init(conn,
298                                               conn->allow_signing,
299                                               conn->desire_signing,
300                                               conn->mandatory_signing);
301         if (!conn->smb1.signing) {
302                 goto error;
303         }
304
305         conn->smb2.client.security_mode = SMB2_NEGOTIATE_SIGNING_ENABLED;
306         if (conn->mandatory_signing) {
307                 conn->smb2.client.security_mode |= SMB2_NEGOTIATE_SIGNING_REQUIRED;
308         }
309         if (client_guid) {
310                 conn->smb2.client.guid = *client_guid;
311         }
312
313         conn->smb2.cur_credits = 1;
314         conn->smb2.max_credits = 0;
315
316         talloc_set_destructor(conn, smbXcli_conn_destructor);
317         return conn;
318
319  error:
320         TALLOC_FREE(conn);
321         return NULL;
322 }
323
324 bool smbXcli_conn_is_connected(struct smbXcli_conn *conn)
325 {
326         if (conn == NULL) {
327                 return false;
328         }
329
330         if (conn->fd == -1) {
331                 return false;
332         }
333
334         return true;
335 }
336
337 enum protocol_types smbXcli_conn_protocol(struct smbXcli_conn *conn)
338 {
339         return conn->protocol;
340 }
341
342 bool smbXcli_conn_use_unicode(struct smbXcli_conn *conn)
343 {
344         if (conn->protocol >= PROTOCOL_SMB2_02) {
345                 return true;
346         }
347
348         if (conn->smb1.capabilities & CAP_UNICODE) {
349                 return true;
350         }
351
352         return false;
353 }
354
355 void smbXcli_conn_set_sockopt(struct smbXcli_conn *conn, const char *options)
356 {
357         set_socket_options(conn->fd, options);
358 }
359
360 const struct sockaddr_storage *smbXcli_conn_local_sockaddr(struct smbXcli_conn *conn)
361 {
362         return &conn->local_ss;
363 }
364
365 const struct sockaddr_storage *smbXcli_conn_remote_sockaddr(struct smbXcli_conn *conn)
366 {
367         return &conn->remote_ss;
368 }
369
370 const char *smbXcli_conn_remote_name(struct smbXcli_conn *conn)
371 {
372         return conn->remote_name;
373 }
374
375 uint16_t smbXcli_conn_max_requests(struct smbXcli_conn *conn)
376 {
377         if (conn->protocol >= PROTOCOL_SMB2_02) {
378                 /*
379                  * TODO...
380                  */
381                 return 1;
382         }
383
384         return conn->smb1.server.max_mux;
385 }
386
387 NTTIME smbXcli_conn_server_system_time(struct smbXcli_conn *conn)
388 {
389         if (conn->protocol >= PROTOCOL_SMB2_02) {
390                 return conn->smb2.server.system_time;
391         }
392
393         return conn->smb1.server.system_time;
394 }
395
396 const DATA_BLOB *smbXcli_conn_server_gss_blob(struct smbXcli_conn *conn)
397 {
398         if (conn->protocol >= PROTOCOL_SMB2_02) {
399                 return &conn->smb2.server.gss_blob;
400         }
401
402         return &conn->smb1.server.gss_blob;
403 }
404
405 const struct GUID *smbXcli_conn_server_guid(struct smbXcli_conn *conn)
406 {
407         if (conn->protocol >= PROTOCOL_SMB2_02) {
408                 return &conn->smb2.server.guid;
409         }
410
411         return &conn->smb1.server.guid;
412 }
413
414 uint32_t smb1cli_conn_capabilities(struct smbXcli_conn *conn)
415 {
416         return conn->smb1.capabilities;
417 }
418
419 uint32_t smb1cli_conn_max_xmit(struct smbXcli_conn *conn)
420 {
421         return conn->smb1.max_xmit;
422 }
423
424 uint32_t smb1cli_conn_server_session_key(struct smbXcli_conn *conn)
425 {
426         return conn->smb1.server.session_key;
427 }
428
429 const uint8_t *smb1cli_conn_server_challenge(struct smbXcli_conn *conn)
430 {
431         return conn->smb1.server.challenge;
432 }
433
434 uint16_t smb1cli_conn_server_security_mode(struct smbXcli_conn *conn)
435 {
436         return conn->smb1.server.security_mode;
437 }
438
439 int smb1cli_conn_server_time_zone(struct smbXcli_conn *conn)
440 {
441         return conn->smb1.server.time_zone;
442 }
443
444 bool smb1cli_conn_activate_signing(struct smbXcli_conn *conn,
445                                    const DATA_BLOB user_session_key,
446                                    const DATA_BLOB response)
447 {
448         return smb_signing_activate(conn->smb1.signing,
449                                     user_session_key,
450                                     response);
451 }
452
453 bool smb1cli_conn_check_signing(struct smbXcli_conn *conn,
454                                 const uint8_t *buf, uint32_t seqnum)
455 {
456         return smb_signing_check_pdu(conn->smb1.signing, buf, seqnum);
457 }
458
459 bool smb1cli_conn_signing_is_active(struct smbXcli_conn *conn)
460 {
461         return smb_signing_is_active(conn->smb1.signing);
462 }
463
464 void smb1cli_conn_set_encryption(struct smbXcli_conn *conn,
465                                  struct smb_trans_enc_state *es)
466 {
467         /* Replace the old state, if any. */
468         if (conn->smb1.trans_enc) {
469                 common_free_encryption_state(&conn->smb1.trans_enc);
470         }
471         conn->smb1.trans_enc = es;
472 }
473
474 bool smb1cli_conn_encryption_on(struct smbXcli_conn *conn)
475 {
476         return common_encryption_on(conn->smb1.trans_enc);
477 }
478
479
480 static NTSTATUS smb1cli_pull_raw_error(const uint8_t *hdr)
481 {
482         uint32_t flags2 = SVAL(hdr, HDR_FLG2);
483         NTSTATUS status = NT_STATUS(IVAL(hdr, HDR_RCLS));
484
485         if (NT_STATUS_IS_OK(status)) {
486                 return NT_STATUS_OK;
487         }
488
489         if (flags2 & FLAGS2_32_BIT_ERROR_CODES) {
490                 return status;
491         }
492
493         return NT_STATUS_DOS(CVAL(hdr, HDR_RCLS), SVAL(hdr, HDR_ERR));
494 }
495
496 /**
497  * Is the SMB command able to hold an AND_X successor
498  * @param[in] cmd       The SMB command in question
499  * @retval Can we add a chained request after "cmd"?
500  */
501 bool smb1cli_is_andx_req(uint8_t cmd)
502 {
503         switch (cmd) {
504         case SMBtconX:
505         case SMBlockingX:
506         case SMBopenX:
507         case SMBreadX:
508         case SMBwriteX:
509         case SMBsesssetupX:
510         case SMBulogoffX:
511         case SMBntcreateX:
512                 return true;
513                 break;
514         default:
515                 break;
516         }
517
518         return false;
519 }
520
521 static uint16_t smb1cli_alloc_mid(struct smbXcli_conn *conn)
522 {
523         size_t num_pending = talloc_array_length(conn->pending);
524         uint16_t result;
525
526         while (true) {
527                 size_t i;
528
529                 result = conn->smb1.mid++;
530                 if ((result == 0) || (result == 0xffff)) {
531                         continue;
532                 }
533
534                 for (i=0; i<num_pending; i++) {
535                         if (result == smb1cli_req_mid(conn->pending[i])) {
536                                 break;
537                         }
538                 }
539
540                 if (i == num_pending) {
541                         return result;
542                 }
543         }
544 }
545
546 void smbXcli_req_unset_pending(struct tevent_req *req)
547 {
548         struct smbXcli_req_state *state =
549                 tevent_req_data(req,
550                 struct smbXcli_req_state);
551         struct smbXcli_conn *conn = state->conn;
552         size_t num_pending = talloc_array_length(conn->pending);
553         size_t i;
554
555         if (state->smb1.mid != 0) {
556                 /*
557                  * This is a [nt]trans[2] request which waits
558                  * for more than one reply.
559                  */
560                 return;
561         }
562
563         talloc_set_destructor(req, NULL);
564
565         if (num_pending == 1) {
566                 /*
567                  * The pending read_smb tevent_req is a child of
568                  * conn->pending. So if nothing is pending anymore, we need to
569                  * delete the socket read fde.
570                  */
571                 TALLOC_FREE(conn->pending);
572                 conn->read_smb_req = NULL;
573                 return;
574         }
575
576         for (i=0; i<num_pending; i++) {
577                 if (req == conn->pending[i]) {
578                         break;
579                 }
580         }
581         if (i == num_pending) {
582                 /*
583                  * Something's seriously broken. Just returning here is the
584                  * right thing nevertheless, the point of this routine is to
585                  * remove ourselves from conn->pending.
586                  */
587                 return;
588         }
589
590         /*
591          * Remove ourselves from the conn->pending array
592          */
593         for (; i < (num_pending - 1); i++) {
594                 conn->pending[i] = conn->pending[i+1];
595         }
596
597         /*
598          * No NULL check here, we're shrinking by sizeof(void *), and
599          * talloc_realloc just adjusts the size for this.
600          */
601         conn->pending = talloc_realloc(NULL, conn->pending, struct tevent_req *,
602                                        num_pending - 1);
603         return;
604 }
605
606 static int smbXcli_req_destructor(struct tevent_req *req)
607 {
608         struct smbXcli_req_state *state =
609                 tevent_req_data(req,
610                 struct smbXcli_req_state);
611
612         /*
613          * Make sure we really remove it from
614          * the pending array on destruction.
615          */
616         state->smb1.mid = 0;
617         smbXcli_req_unset_pending(req);
618         return 0;
619 }
620
621 static bool smbXcli_conn_receive_next(struct smbXcli_conn *conn);
622
623 bool smbXcli_req_set_pending(struct tevent_req *req)
624 {
625         struct smbXcli_req_state *state =
626                 tevent_req_data(req,
627                 struct smbXcli_req_state);
628         struct smbXcli_conn *conn;
629         struct tevent_req **pending;
630         size_t num_pending;
631
632         conn = state->conn;
633
634         if (!smbXcli_conn_is_connected(conn)) {
635                 return false;
636         }
637
638         num_pending = talloc_array_length(conn->pending);
639
640         pending = talloc_realloc(conn, conn->pending, struct tevent_req *,
641                                  num_pending+1);
642         if (pending == NULL) {
643                 return false;
644         }
645         pending[num_pending] = req;
646         conn->pending = pending;
647         talloc_set_destructor(req, smbXcli_req_destructor);
648
649         if (!smbXcli_conn_receive_next(conn)) {
650                 /*
651                  * the caller should notify the current request
652                  *
653                  * And all other pending requests get notified
654                  * by smbXcli_conn_disconnect().
655                  */
656                 smbXcli_req_unset_pending(req);
657                 smbXcli_conn_disconnect(conn, NT_STATUS_NO_MEMORY);
658                 return false;
659         }
660
661         return true;
662 }
663
664 static void smbXcli_conn_received(struct tevent_req *subreq);
665
666 static bool smbXcli_conn_receive_next(struct smbXcli_conn *conn)
667 {
668         size_t num_pending = talloc_array_length(conn->pending);
669         struct tevent_req *req;
670         struct smbXcli_req_state *state;
671
672         if (conn->read_smb_req != NULL) {
673                 return true;
674         }
675
676         if (num_pending == 0) {
677                 if (conn->smb2.mid < UINT64_MAX) {
678                         /* no more pending requests, so we are done for now */
679                         return true;
680                 }
681
682                 /*
683                  * If there are no more SMB2 requests possible,
684                  * because we are out of message ids,
685                  * we need to disconnect.
686                  */
687                 smbXcli_conn_disconnect(conn, NT_STATUS_CONNECTION_ABORTED);
688                 return true;
689         }
690
691         req = conn->pending[0];
692         state = tevent_req_data(req, struct smbXcli_req_state);
693
694         /*
695          * We're the first ones, add the read_smb request that waits for the
696          * answer from the server
697          */
698         conn->read_smb_req = read_smb_send(conn->pending, state->ev, conn->fd);
699         if (conn->read_smb_req == NULL) {
700                 return false;
701         }
702         tevent_req_set_callback(conn->read_smb_req, smbXcli_conn_received, conn);
703         return true;
704 }
705
706 void smbXcli_conn_disconnect(struct smbXcli_conn *conn, NTSTATUS status)
707 {
708         if (conn->fd != -1) {
709                 close(conn->fd);
710         }
711         conn->fd = -1;
712
713         /*
714          * Cancel all pending requests. We do not do a for-loop walking
715          * conn->pending because that array changes in
716          * smbXcli_req_unset_pending.
717          */
718         while (talloc_array_length(conn->pending) > 0) {
719                 struct tevent_req *req;
720                 struct smbXcli_req_state *state;
721                 struct tevent_req **chain;
722                 size_t num_chained;
723                 size_t i;
724
725                 req = conn->pending[0];
726                 state = tevent_req_data(req, struct smbXcli_req_state);
727
728                 if (state->smb1.chained_requests == NULL) {
729                         /*
730                          * We're dead. No point waiting for trans2
731                          * replies.
732                          */
733                         state->smb1.mid = 0;
734
735                         smbXcli_req_unset_pending(req);
736
737                         if (NT_STATUS_IS_OK(status)) {
738                                 /* do not notify the callers */
739                                 continue;
740                         }
741
742                         /*
743                          * we need to defer the callback, because we may notify
744                          * more then one caller.
745                          */
746                         tevent_req_defer_callback(req, state->ev);
747                         tevent_req_nterror(req, status);
748                         continue;
749                 }
750
751                 chain = talloc_move(conn, &state->smb1.chained_requests);
752                 num_chained = talloc_array_length(chain);
753
754                 for (i=0; i<num_chained; i++) {
755                         req = chain[i];
756                         state = tevent_req_data(req, struct smbXcli_req_state);
757
758                         /*
759                          * We're dead. No point waiting for trans2
760                          * replies.
761                          */
762                         state->smb1.mid = 0;
763
764                         smbXcli_req_unset_pending(req);
765
766                         if (NT_STATUS_IS_OK(status)) {
767                                 /* do not notify the callers */
768                                 continue;
769                         }
770
771                         /*
772                          * we need to defer the callback, because we may notify
773                          * more then one caller.
774                          */
775                         tevent_req_defer_callback(req, state->ev);
776                         tevent_req_nterror(req, status);
777                 }
778                 TALLOC_FREE(chain);
779         }
780 }
781
782 /*
783  * Fetch a smb request's mid. Only valid after the request has been sent by
784  * smb1cli_req_send().
785  */
786 uint16_t smb1cli_req_mid(struct tevent_req *req)
787 {
788         struct smbXcli_req_state *state =
789                 tevent_req_data(req,
790                 struct smbXcli_req_state);
791
792         if (state->smb1.mid != 0) {
793                 return state->smb1.mid;
794         }
795
796         return SVAL(state->smb1.hdr, HDR_MID);
797 }
798
799 void smb1cli_req_set_mid(struct tevent_req *req, uint16_t mid)
800 {
801         struct smbXcli_req_state *state =
802                 tevent_req_data(req,
803                 struct smbXcli_req_state);
804
805         state->smb1.mid = mid;
806 }
807
808 uint32_t smb1cli_req_seqnum(struct tevent_req *req)
809 {
810         struct smbXcli_req_state *state =
811                 tevent_req_data(req,
812                 struct smbXcli_req_state);
813
814         return state->smb1.seqnum;
815 }
816
817 void smb1cli_req_set_seqnum(struct tevent_req *req, uint32_t seqnum)
818 {
819         struct smbXcli_req_state *state =
820                 tevent_req_data(req,
821                 struct smbXcli_req_state);
822
823         state->smb1.seqnum = seqnum;
824 }
825
826 static size_t smbXcli_iov_len(const struct iovec *iov, int count)
827 {
828         size_t result = 0;
829         int i;
830         for (i=0; i<count; i++) {
831                 result += iov[i].iov_len;
832         }
833         return result;
834 }
835
836 static uint8_t *smbXcli_iov_concat(TALLOC_CTX *mem_ctx,
837                                    const struct iovec *iov,
838                                    int count)
839 {
840         size_t len = smbXcli_iov_len(iov, count);
841         size_t copied;
842         uint8_t *buf;
843         int i;
844
845         buf = talloc_array(mem_ctx, uint8_t, len);
846         if (buf == NULL) {
847                 return NULL;
848         }
849         copied = 0;
850         for (i=0; i<count; i++) {
851                 memcpy(buf+copied, iov[i].iov_base, iov[i].iov_len);
852                 copied += iov[i].iov_len;
853         }
854         return buf;
855 }
856
857 static void smb1cli_req_flags(enum protocol_types protocol,
858                               uint32_t smb1_capabilities,
859                               uint8_t smb_command,
860                               uint8_t additional_flags,
861                               uint8_t clear_flags,
862                               uint8_t *_flags,
863                               uint16_t additional_flags2,
864                               uint16_t clear_flags2,
865                               uint16_t *_flags2)
866 {
867         uint8_t flags = 0;
868         uint16_t flags2 = 0;
869
870         if (protocol >= PROTOCOL_LANMAN1) {
871                 flags |= FLAG_CASELESS_PATHNAMES;
872                 flags |= FLAG_CANONICAL_PATHNAMES;
873         }
874
875         if (protocol >= PROTOCOL_LANMAN2) {
876                 flags2 |= FLAGS2_LONG_PATH_COMPONENTS;
877                 flags2 |= FLAGS2_EXTENDED_ATTRIBUTES;
878         }
879
880         if (protocol >= PROTOCOL_NT1) {
881                 flags2 |= FLAGS2_IS_LONG_NAME;
882
883                 if (smb1_capabilities & CAP_UNICODE) {
884                         flags2 |= FLAGS2_UNICODE_STRINGS;
885                 }
886                 if (smb1_capabilities & CAP_STATUS32) {
887                         flags2 |= FLAGS2_32_BIT_ERROR_CODES;
888                 }
889                 if (smb1_capabilities & CAP_EXTENDED_SECURITY) {
890                         flags2 |= FLAGS2_EXTENDED_SECURITY;
891                 }
892         }
893
894         flags |= additional_flags;
895         flags &= ~clear_flags;
896         flags2 |= additional_flags2;
897         flags2 &= ~clear_flags2;
898
899         *_flags = flags;
900         *_flags2 = flags2;
901 }
902
903 struct tevent_req *smb1cli_req_create(TALLOC_CTX *mem_ctx,
904                                       struct tevent_context *ev,
905                                       struct smbXcli_conn *conn,
906                                       uint8_t smb_command,
907                                       uint8_t additional_flags,
908                                       uint8_t clear_flags,
909                                       uint16_t additional_flags2,
910                                       uint16_t clear_flags2,
911                                       uint32_t timeout_msec,
912                                       uint32_t pid,
913                                       uint16_t tid,
914                                       uint16_t uid,
915                                       uint8_t wct, uint16_t *vwv,
916                                       int iov_count,
917                                       struct iovec *bytes_iov)
918 {
919         struct tevent_req *req;
920         struct smbXcli_req_state *state;
921         uint8_t flags = 0;
922         uint16_t flags2 = 0;
923
924         if (iov_count > MAX_SMB_IOV) {
925                 /*
926                  * Should not happen :-)
927                  */
928                 return NULL;
929         }
930
931         req = tevent_req_create(mem_ctx, &state,
932                                 struct smbXcli_req_state);
933         if (req == NULL) {
934                 return NULL;
935         }
936         state->ev = ev;
937         state->conn = conn;
938
939         state->smb1.recv_cmd = 0xFF;
940         state->smb1.recv_status = NT_STATUS_INTERNAL_ERROR;
941         state->smb1.recv_iov = talloc_zero_array(state, struct iovec, 3);
942         if (state->smb1.recv_iov == NULL) {
943                 TALLOC_FREE(req);
944                 return NULL;
945         }
946
947         smb1cli_req_flags(conn->protocol,
948                           conn->smb1.capabilities,
949                           smb_command,
950                           additional_flags,
951                           clear_flags,
952                           &flags,
953                           additional_flags2,
954                           clear_flags2,
955                           &flags2);
956
957         SIVAL(state->smb1.hdr, 0,           SMB_MAGIC);
958         SCVAL(state->smb1.hdr, HDR_COM,     smb_command);
959         SIVAL(state->smb1.hdr, HDR_RCLS,    NT_STATUS_V(NT_STATUS_OK));
960         SCVAL(state->smb1.hdr, HDR_FLG,     flags);
961         SSVAL(state->smb1.hdr, HDR_FLG2,    flags2);
962         SSVAL(state->smb1.hdr, HDR_PIDHIGH, pid >> 16);
963         SSVAL(state->smb1.hdr, HDR_TID,     tid);
964         SSVAL(state->smb1.hdr, HDR_PID,     pid);
965         SSVAL(state->smb1.hdr, HDR_UID,     uid);
966         SSVAL(state->smb1.hdr, HDR_MID,     0); /* this comes later */
967         SSVAL(state->smb1.hdr, HDR_WCT,     wct);
968
969         state->smb1.vwv = vwv;
970
971         SSVAL(state->smb1.bytecount_buf, 0, smbXcli_iov_len(bytes_iov, iov_count));
972
973         state->smb1.iov[0].iov_base = (void *)state->length_hdr;
974         state->smb1.iov[0].iov_len  = sizeof(state->length_hdr);
975         state->smb1.iov[1].iov_base = (void *)state->smb1.hdr;
976         state->smb1.iov[1].iov_len  = sizeof(state->smb1.hdr);
977         state->smb1.iov[2].iov_base = (void *)state->smb1.vwv;
978         state->smb1.iov[2].iov_len  = wct * sizeof(uint16_t);
979         state->smb1.iov[3].iov_base = (void *)state->smb1.bytecount_buf;
980         state->smb1.iov[3].iov_len  = sizeof(uint16_t);
981
982         if (iov_count != 0) {
983                 memcpy(&state->smb1.iov[4], bytes_iov,
984                        iov_count * sizeof(*bytes_iov));
985         }
986         state->smb1.iov_count = iov_count + 4;
987
988         if (timeout_msec > 0) {
989                 struct timeval endtime;
990
991                 endtime = timeval_current_ofs_msec(timeout_msec);
992                 if (!tevent_req_set_endtime(req, ev, endtime)) {
993                         return req;
994                 }
995         }
996
997         switch (smb_command) {
998         case SMBtranss:
999         case SMBtranss2:
1000         case SMBnttranss:
1001                 state->one_way = true;
1002                 break;
1003         case SMBntcancel:
1004                 state->one_way = true;
1005                 state->smb1.one_way_seqnum = true;
1006                 break;
1007         case SMBlockingX:
1008                 if ((wct == 8) &&
1009                     (CVAL(vwv+3, 0) == LOCKING_ANDX_OPLOCK_RELEASE)) {
1010                         state->one_way = true;
1011                 }
1012                 break;
1013         }
1014
1015         return req;
1016 }
1017
1018 static NTSTATUS smb1cli_conn_signv(struct smbXcli_conn *conn,
1019                                    struct iovec *iov, int iov_count,
1020                                    uint32_t *seqnum,
1021                                    bool one_way_seqnum)
1022 {
1023         uint8_t *buf;
1024
1025         /*
1026          * Obvious optimization: Make cli_calculate_sign_mac work with struct
1027          * iovec directly. MD5Update would do that just fine.
1028          */
1029
1030         if (iov_count < 4) {
1031                 return NT_STATUS_INVALID_PARAMETER_MIX;
1032         }
1033         if (iov[0].iov_len != NBT_HDR_SIZE) {
1034                 return NT_STATUS_INVALID_PARAMETER_MIX;
1035         }
1036         if (iov[1].iov_len != (MIN_SMB_SIZE-sizeof(uint16_t))) {
1037                 return NT_STATUS_INVALID_PARAMETER_MIX;
1038         }
1039         if (iov[2].iov_len > (0xFF * sizeof(uint16_t))) {
1040                 return NT_STATUS_INVALID_PARAMETER_MIX;
1041         }
1042         if (iov[3].iov_len != sizeof(uint16_t)) {
1043                 return NT_STATUS_INVALID_PARAMETER_MIX;
1044         }
1045
1046         buf = smbXcli_iov_concat(talloc_tos(), iov, iov_count);
1047         if (buf == NULL) {
1048                 return NT_STATUS_NO_MEMORY;
1049         }
1050
1051         *seqnum = smb_signing_next_seqnum(conn->smb1.signing,
1052                                           one_way_seqnum);
1053         smb_signing_sign_pdu(conn->smb1.signing, buf, *seqnum);
1054         memcpy(iov[1].iov_base, buf+4, iov[1].iov_len);
1055
1056         TALLOC_FREE(buf);
1057         return NT_STATUS_OK;
1058 }
1059
1060 static void smb1cli_req_writev_done(struct tevent_req *subreq);
1061 static NTSTATUS smb1cli_conn_dispatch_incoming(struct smbXcli_conn *conn,
1062                                                TALLOC_CTX *tmp_mem,
1063                                                uint8_t *inbuf);
1064
1065 static NTSTATUS smb1cli_req_writev_submit(struct tevent_req *req,
1066                                           struct smbXcli_req_state *state,
1067                                           struct iovec *iov, int iov_count)
1068 {
1069         struct tevent_req *subreq;
1070         NTSTATUS status;
1071         uint16_t mid;
1072
1073         if (!smbXcli_conn_is_connected(state->conn)) {
1074                 return NT_STATUS_CONNECTION_DISCONNECTED;
1075         }
1076
1077         if (state->conn->protocol > PROTOCOL_NT1) {
1078                 return NT_STATUS_REVISION_MISMATCH;
1079         }
1080
1081         if (iov_count < 4) {
1082                 return NT_STATUS_INVALID_PARAMETER_MIX;
1083         }
1084         if (iov[0].iov_len != NBT_HDR_SIZE) {
1085                 return NT_STATUS_INVALID_PARAMETER_MIX;
1086         }
1087         if (iov[1].iov_len != (MIN_SMB_SIZE-sizeof(uint16_t))) {
1088                 return NT_STATUS_INVALID_PARAMETER_MIX;
1089         }
1090         if (iov[2].iov_len > (0xFF * sizeof(uint16_t))) {
1091                 return NT_STATUS_INVALID_PARAMETER_MIX;
1092         }
1093         if (iov[3].iov_len != sizeof(uint16_t)) {
1094                 return NT_STATUS_INVALID_PARAMETER_MIX;
1095         }
1096
1097         if (state->smb1.mid != 0) {
1098                 mid = state->smb1.mid;
1099         } else {
1100                 mid = smb1cli_alloc_mid(state->conn);
1101         }
1102         SSVAL(iov[1].iov_base, HDR_MID, mid);
1103
1104         _smb_setlen_nbt(iov[0].iov_base, smbXcli_iov_len(&iov[1], iov_count-1));
1105
1106         status = smb1cli_conn_signv(state->conn, iov, iov_count,
1107                                     &state->smb1.seqnum,
1108                                     state->smb1.one_way_seqnum);
1109
1110         if (!NT_STATUS_IS_OK(status)) {
1111                 return status;
1112         }
1113
1114         /*
1115          * If we supported multiple encrytion contexts
1116          * here we'd look up based on tid.
1117          */
1118         if (common_encryption_on(state->conn->smb1.trans_enc)) {
1119                 char *buf, *enc_buf;
1120
1121                 buf = (char *)smbXcli_iov_concat(talloc_tos(), iov, iov_count);
1122                 if (buf == NULL) {
1123                         return NT_STATUS_NO_MEMORY;
1124                 }
1125                 status = common_encrypt_buffer(state->conn->smb1.trans_enc,
1126                                                (char *)buf, &enc_buf);
1127                 TALLOC_FREE(buf);
1128                 if (!NT_STATUS_IS_OK(status)) {
1129                         DEBUG(0, ("Error in encrypting client message: %s\n",
1130                                   nt_errstr(status)));
1131                         return status;
1132                 }
1133                 buf = (char *)talloc_memdup(state, enc_buf,
1134                                             smb_len_nbt(enc_buf)+4);
1135                 SAFE_FREE(enc_buf);
1136                 if (buf == NULL) {
1137                         return NT_STATUS_NO_MEMORY;
1138                 }
1139                 iov[0].iov_base = (void *)buf;
1140                 iov[0].iov_len = talloc_get_size(buf);
1141                 iov_count = 1;
1142         }
1143
1144         if (state->conn->dispatch_incoming == NULL) {
1145                 state->conn->dispatch_incoming = smb1cli_conn_dispatch_incoming;
1146         }
1147
1148         subreq = writev_send(state, state->ev, state->conn->outgoing,
1149                              state->conn->fd, false, iov, iov_count);
1150         if (subreq == NULL) {
1151                 return NT_STATUS_NO_MEMORY;
1152         }
1153         tevent_req_set_callback(subreq, smb1cli_req_writev_done, req);
1154         return NT_STATUS_OK;
1155 }
1156
1157 struct tevent_req *smb1cli_req_send(TALLOC_CTX *mem_ctx,
1158                                     struct tevent_context *ev,
1159                                     struct smbXcli_conn *conn,
1160                                     uint8_t smb_command,
1161                                     uint8_t additional_flags,
1162                                     uint8_t clear_flags,
1163                                     uint16_t additional_flags2,
1164                                     uint16_t clear_flags2,
1165                                     uint32_t timeout_msec,
1166                                     uint32_t pid,
1167                                     uint16_t tid,
1168                                     uint16_t uid,
1169                                     uint8_t wct, uint16_t *vwv,
1170                                     uint32_t num_bytes,
1171                                     const uint8_t *bytes)
1172 {
1173         struct tevent_req *req;
1174         struct iovec iov;
1175         NTSTATUS status;
1176
1177         iov.iov_base = discard_const_p(void, bytes);
1178         iov.iov_len = num_bytes;
1179
1180         req = smb1cli_req_create(mem_ctx, ev, conn, smb_command,
1181                                  additional_flags, clear_flags,
1182                                  additional_flags2, clear_flags2,
1183                                  timeout_msec,
1184                                  pid, tid, uid,
1185                                  wct, vwv, 1, &iov);
1186         if (req == NULL) {
1187                 return NULL;
1188         }
1189         if (!tevent_req_is_in_progress(req)) {
1190                 return tevent_req_post(req, ev);
1191         }
1192         status = smb1cli_req_chain_submit(&req, 1);
1193         if (tevent_req_nterror(req, status)) {
1194                 return tevent_req_post(req, ev);
1195         }
1196         return req;
1197 }
1198
1199 static void smb1cli_req_writev_done(struct tevent_req *subreq)
1200 {
1201         struct tevent_req *req =
1202                 tevent_req_callback_data(subreq,
1203                 struct tevent_req);
1204         struct smbXcli_req_state *state =
1205                 tevent_req_data(req,
1206                 struct smbXcli_req_state);
1207         ssize_t nwritten;
1208         int err;
1209
1210         nwritten = writev_recv(subreq, &err);
1211         TALLOC_FREE(subreq);
1212         if (nwritten == -1) {
1213                 NTSTATUS status = map_nt_error_from_unix_common(err);
1214                 smbXcli_conn_disconnect(state->conn, status);
1215                 return;
1216         }
1217
1218         if (state->one_way) {
1219                 state->inbuf = NULL;
1220                 tevent_req_done(req);
1221                 return;
1222         }
1223
1224         if (!smbXcli_req_set_pending(req)) {
1225                 tevent_req_nterror(req, NT_STATUS_NO_MEMORY);
1226                 return;
1227         }
1228 }
1229
1230 static void smbXcli_conn_received(struct tevent_req *subreq)
1231 {
1232         struct smbXcli_conn *conn =
1233                 tevent_req_callback_data(subreq,
1234                 struct smbXcli_conn);
1235         TALLOC_CTX *frame = talloc_stackframe();
1236         NTSTATUS status;
1237         uint8_t *inbuf;
1238         ssize_t received;
1239         int err;
1240
1241         if (subreq != conn->read_smb_req) {
1242                 DEBUG(1, ("Internal error: cli_smb_received called with "
1243                           "unexpected subreq\n"));
1244                 status = NT_STATUS_INTERNAL_ERROR;
1245                 smbXcli_conn_disconnect(conn, status);
1246                 TALLOC_FREE(frame);
1247                 return;
1248         }
1249         conn->read_smb_req = NULL;
1250
1251         received = read_smb_recv(subreq, frame, &inbuf, &err);
1252         TALLOC_FREE(subreq);
1253         if (received == -1) {
1254                 status = map_nt_error_from_unix_common(err);
1255                 smbXcli_conn_disconnect(conn, status);
1256                 TALLOC_FREE(frame);
1257                 return;
1258         }
1259
1260         status = conn->dispatch_incoming(conn, frame, inbuf);
1261         TALLOC_FREE(frame);
1262         if (NT_STATUS_IS_OK(status)) {
1263                 /*
1264                  * We should not do any more processing
1265                  * as the dispatch function called
1266                  * tevent_req_done().
1267                  */
1268                 return;
1269         } else if (!NT_STATUS_EQUAL(status, NT_STATUS_RETRY)) {
1270                 /*
1271                  * We got an error, so notify all pending requests
1272                  */
1273                 smbXcli_conn_disconnect(conn, status);
1274                 return;
1275         }
1276
1277         /*
1278          * We got NT_STATUS_RETRY, so we may ask for a
1279          * next incoming pdu.
1280          */
1281         if (!smbXcli_conn_receive_next(conn)) {
1282                 smbXcli_conn_disconnect(conn, NT_STATUS_NO_MEMORY);
1283         }
1284 }
1285
1286 static NTSTATUS smb1cli_inbuf_parse_chain(uint8_t *buf, TALLOC_CTX *mem_ctx,
1287                                           struct iovec **piov, int *pnum_iov)
1288 {
1289         struct iovec *iov;
1290         int num_iov;
1291         size_t buflen;
1292         size_t taken;
1293         size_t remaining;
1294         uint8_t *hdr;
1295         uint8_t cmd;
1296         uint32_t wct_ofs;
1297
1298         buflen = smb_len_nbt(buf);
1299         taken = 0;
1300
1301         hdr = buf + NBT_HDR_SIZE;
1302
1303         if (buflen < MIN_SMB_SIZE) {
1304                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
1305         }
1306
1307         /*
1308          * This returns iovec elements in the following order:
1309          *
1310          * - SMB header
1311          *
1312          * - Parameter Block
1313          * - Data Block
1314          *
1315          * - Parameter Block
1316          * - Data Block
1317          *
1318          * - Parameter Block
1319          * - Data Block
1320          */
1321         num_iov = 1;
1322
1323         iov = talloc_array(mem_ctx, struct iovec, num_iov);
1324         if (iov == NULL) {
1325                 return NT_STATUS_NO_MEMORY;
1326         }
1327         iov[0].iov_base = hdr;
1328         iov[0].iov_len = HDR_WCT;
1329         taken += HDR_WCT;
1330
1331         cmd = CVAL(hdr, HDR_COM);
1332         wct_ofs = HDR_WCT;
1333
1334         while (true) {
1335                 size_t len = buflen - taken;
1336                 struct iovec *cur;
1337                 struct iovec *iov_tmp;
1338                 uint8_t wct;
1339                 uint32_t bcc_ofs;
1340                 uint16_t bcc;
1341                 size_t needed;
1342
1343                 /*
1344                  * we need at least WCT and BCC
1345                  */
1346                 needed = sizeof(uint8_t) + sizeof(uint16_t);
1347                 if (len < needed) {
1348                         DEBUG(10, ("%s: %d bytes left, expected at least %d\n",
1349                                    __location__, (int)len, (int)needed));
1350                         goto inval;
1351                 }
1352
1353                 /*
1354                  * Now we check if the specified words are there
1355                  */
1356                 wct = CVAL(hdr, wct_ofs);
1357                 needed += wct * sizeof(uint16_t);
1358                 if (len < needed) {
1359                         DEBUG(10, ("%s: %d bytes left, expected at least %d\n",
1360                                    __location__, (int)len, (int)needed));
1361                         goto inval;
1362                 }
1363
1364                 /*
1365                  * Now we check if the specified bytes are there
1366                  */
1367                 bcc_ofs = wct_ofs + sizeof(uint8_t) + wct * sizeof(uint16_t);
1368                 bcc = SVAL(hdr, bcc_ofs);
1369                 needed += bcc * sizeof(uint8_t);
1370                 if (len < needed) {
1371                         DEBUG(10, ("%s: %d bytes left, expected at least %d\n",
1372                                    __location__, (int)len, (int)needed));
1373                         goto inval;
1374                 }
1375
1376                 /*
1377                  * we allocate 2 iovec structures for words and bytes
1378                  */
1379                 iov_tmp = talloc_realloc(mem_ctx, iov, struct iovec,
1380                                          num_iov + 2);
1381                 if (iov_tmp == NULL) {
1382                         TALLOC_FREE(iov);
1383                         return NT_STATUS_NO_MEMORY;
1384                 }
1385                 iov = iov_tmp;
1386                 cur = &iov[num_iov];
1387                 num_iov += 2;
1388
1389                 cur[0].iov_len = wct * sizeof(uint16_t);
1390                 cur[0].iov_base = hdr + (wct_ofs + sizeof(uint8_t));
1391                 cur[1].iov_len = bcc * sizeof(uint8_t);
1392                 cur[1].iov_base = hdr + (bcc_ofs + sizeof(uint16_t));
1393
1394                 taken += needed;
1395
1396                 if (!smb1cli_is_andx_req(cmd)) {
1397                         /*
1398                          * If the current command does not have AndX chanining
1399                          * we are done.
1400                          */
1401                         break;
1402                 }
1403
1404                 if (wct == 0 && bcc == 0) {
1405                         /*
1406                          * An empty response also ends the chain,
1407                          * most likely with an error.
1408                          */
1409                         break;
1410                 }
1411
1412                 if (wct < 2) {
1413                         DEBUG(10, ("%s: wct[%d] < 2 for cmd[0x%02X]\n",
1414                                    __location__, (int)wct, (int)cmd));
1415                         goto inval;
1416                 }
1417                 cmd = CVAL(cur[0].iov_base, 0);
1418                 if (cmd == 0xFF) {
1419                         /*
1420                          * If it is the end of the chain we are also done.
1421                          */
1422                         break;
1423                 }
1424                 wct_ofs = SVAL(cur[0].iov_base, 2);
1425
1426                 if (wct_ofs < taken) {
1427                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
1428                 }
1429                 if (wct_ofs > buflen) {
1430                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
1431                 }
1432
1433                 /*
1434                  * we consumed everything up to the start of the next
1435                  * parameter block.
1436                  */
1437                 taken = wct_ofs;
1438         }
1439
1440         remaining = buflen - taken;
1441
1442         if (remaining > 0 && num_iov >= 3) {
1443                 /*
1444                  * The last DATA block gets the remaining
1445                  * bytes, this is needed to support
1446                  * CAP_LARGE_WRITEX and CAP_LARGE_READX.
1447                  */
1448                 iov[num_iov-1].iov_len += remaining;
1449         }
1450
1451         *piov = iov;
1452         *pnum_iov = num_iov;
1453         return NT_STATUS_OK;
1454
1455 inval:
1456         TALLOC_FREE(iov);
1457         return NT_STATUS_INVALID_NETWORK_RESPONSE;
1458 }
1459
1460 static NTSTATUS smb1cli_conn_dispatch_incoming(struct smbXcli_conn *conn,
1461                                                TALLOC_CTX *tmp_mem,
1462                                                uint8_t *inbuf)
1463 {
1464         struct tevent_req *req;
1465         struct smbXcli_req_state *state;
1466         NTSTATUS status;
1467         size_t num_pending;
1468         size_t i;
1469         uint8_t cmd;
1470         uint16_t mid;
1471         bool oplock_break;
1472         const uint8_t *inhdr = inbuf + NBT_HDR_SIZE;
1473         struct iovec *iov = NULL;
1474         int num_iov = 0;
1475         struct tevent_req **chain = NULL;
1476         size_t num_chained = 0;
1477         size_t num_responses = 0;
1478
1479         if ((IVAL(inhdr, 0) != SMB_MAGIC) /* 0xFF"SMB" */
1480             && (SVAL(inhdr, 0) != 0x45ff)) /* 0xFF"E" */ {
1481                 DEBUG(10, ("Got non-SMB PDU\n"));
1482                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
1483         }
1484
1485         /*
1486          * If we supported multiple encrytion contexts
1487          * here we'd look up based on tid.
1488          */
1489         if (common_encryption_on(conn->smb1.trans_enc)
1490             && (CVAL(inbuf, 0) == 0)) {
1491                 uint16_t enc_ctx_num;
1492
1493                 status = get_enc_ctx_num(inbuf, &enc_ctx_num);
1494                 if (!NT_STATUS_IS_OK(status)) {
1495                         DEBUG(10, ("get_enc_ctx_num returned %s\n",
1496                                    nt_errstr(status)));
1497                         return status;
1498                 }
1499
1500                 if (enc_ctx_num != conn->smb1.trans_enc->enc_ctx_num) {
1501                         DEBUG(10, ("wrong enc_ctx %d, expected %d\n",
1502                                    enc_ctx_num,
1503                                    conn->smb1.trans_enc->enc_ctx_num));
1504                         return NT_STATUS_INVALID_HANDLE;
1505                 }
1506
1507                 status = common_decrypt_buffer(conn->smb1.trans_enc,
1508                                                (char *)inbuf);
1509                 if (!NT_STATUS_IS_OK(status)) {
1510                         DEBUG(10, ("common_decrypt_buffer returned %s\n",
1511                                    nt_errstr(status)));
1512                         return status;
1513                 }
1514         }
1515
1516         mid = SVAL(inhdr, HDR_MID);
1517         num_pending = talloc_array_length(conn->pending);
1518
1519         for (i=0; i<num_pending; i++) {
1520                 if (mid == smb1cli_req_mid(conn->pending[i])) {
1521                         break;
1522                 }
1523         }
1524         if (i == num_pending) {
1525                 /* Dump unexpected reply */
1526                 return NT_STATUS_RETRY;
1527         }
1528
1529         oplock_break = false;
1530
1531         if (mid == 0xffff) {
1532                 /*
1533                  * Paranoia checks that this is really an oplock break request.
1534                  */
1535                 oplock_break = (smb_len_nbt(inbuf) == 51); /* hdr + 8 words */
1536                 oplock_break &= ((CVAL(inhdr, HDR_FLG) & FLAG_REPLY) == 0);
1537                 oplock_break &= (CVAL(inhdr, HDR_COM) == SMBlockingX);
1538                 oplock_break &= (SVAL(inhdr, HDR_VWV+VWV(6)) == 0);
1539                 oplock_break &= (SVAL(inhdr, HDR_VWV+VWV(7)) == 0);
1540
1541                 if (!oplock_break) {
1542                         /* Dump unexpected reply */
1543                         return NT_STATUS_RETRY;
1544                 }
1545         }
1546
1547         req = conn->pending[i];
1548         state = tevent_req_data(req, struct smbXcli_req_state);
1549
1550         if (!oplock_break /* oplock breaks are not signed */
1551             && !smb_signing_check_pdu(conn->smb1.signing,
1552                                       inbuf, state->smb1.seqnum+1)) {
1553                 DEBUG(10, ("cli_check_sign_mac failed\n"));
1554                 return NT_STATUS_ACCESS_DENIED;
1555         }
1556
1557         status = smb1cli_inbuf_parse_chain(inbuf, tmp_mem,
1558                                            &iov, &num_iov);
1559         if (!NT_STATUS_IS_OK(status)) {
1560                 DEBUG(10,("smb1cli_inbuf_parse_chain - %s\n",
1561                           nt_errstr(status)));
1562                 return status;
1563         }
1564
1565         cmd = CVAL(inhdr, HDR_COM);
1566         status = smb1cli_pull_raw_error(inhdr);
1567
1568         if (state->smb1.chained_requests == NULL) {
1569                 if (num_iov != 3) {
1570                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
1571                 }
1572
1573                 smbXcli_req_unset_pending(req);
1574
1575                 state->smb1.recv_cmd = cmd;
1576                 state->smb1.recv_status = status;
1577                 state->inbuf = talloc_move(state->smb1.recv_iov, &inbuf);
1578
1579                 state->smb1.recv_iov[0] = iov[0];
1580                 state->smb1.recv_iov[1] = iov[1];
1581                 state->smb1.recv_iov[2] = iov[2];
1582
1583                 if (talloc_array_length(conn->pending) == 0) {
1584                         tevent_req_done(req);
1585                         return NT_STATUS_OK;
1586                 }
1587
1588                 tevent_req_defer_callback(req, state->ev);
1589                 tevent_req_done(req);
1590                 return NT_STATUS_RETRY;
1591         }
1592
1593         chain = talloc_move(tmp_mem, &state->smb1.chained_requests);
1594         num_chained = talloc_array_length(chain);
1595         num_responses = (num_iov - 1)/2;
1596
1597         if (num_responses > num_chained) {
1598                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
1599         }
1600
1601         for (i=0; i<num_chained; i++) {
1602                 size_t iov_idx = 1 + (i*2);
1603                 struct iovec *cur = &iov[iov_idx];
1604                 uint8_t *inbuf_ref;
1605
1606                 req = chain[i];
1607                 state = tevent_req_data(req, struct smbXcli_req_state);
1608
1609                 smbXcli_req_unset_pending(req);
1610
1611                 /*
1612                  * as we finish multiple requests here
1613                  * we need to defer the callbacks as
1614                  * they could destroy our current stack state.
1615                  */
1616                 tevent_req_defer_callback(req, state->ev);
1617
1618                 if (i >= num_responses) {
1619                         tevent_req_nterror(req, NT_STATUS_REQUEST_ABORTED);
1620                         continue;
1621                 }
1622
1623                 state->smb1.recv_cmd = cmd;
1624
1625                 if (i == (num_responses - 1)) {
1626                         /*
1627                          * The last request in the chain gets the status
1628                          */
1629                         state->smb1.recv_status = status;
1630                 } else {
1631                         cmd = CVAL(cur[0].iov_base, 0);
1632                         state->smb1.recv_status = NT_STATUS_OK;
1633                 }
1634
1635                 state->inbuf = inbuf;
1636
1637                 /*
1638                  * Note: here we use talloc_reference() in a way
1639                  *       that does not expose it to the caller.
1640                  */
1641                 inbuf_ref = talloc_reference(state->smb1.recv_iov, inbuf);
1642                 if (tevent_req_nomem(inbuf_ref, req)) {
1643                         continue;
1644                 }
1645
1646                 /* copy the related buffers */
1647                 state->smb1.recv_iov[0] = iov[0];
1648                 state->smb1.recv_iov[1] = cur[0];
1649                 state->smb1.recv_iov[2] = cur[1];
1650
1651                 tevent_req_done(req);
1652         }
1653
1654         return NT_STATUS_RETRY;
1655 }
1656
1657 NTSTATUS smb1cli_req_recv(struct tevent_req *req,
1658                           TALLOC_CTX *mem_ctx,
1659                           struct iovec **piov,
1660                           uint8_t **phdr,
1661                           uint8_t *pwct,
1662                           uint16_t **pvwv,
1663                           uint32_t *pvwv_offset,
1664                           uint32_t *pnum_bytes,
1665                           uint8_t **pbytes,
1666                           uint32_t *pbytes_offset,
1667                           uint8_t **pinbuf,
1668                           const struct smb1cli_req_expected_response *expected,
1669                           size_t num_expected)
1670 {
1671         struct smbXcli_req_state *state =
1672                 tevent_req_data(req,
1673                 struct smbXcli_req_state);
1674         NTSTATUS status = NT_STATUS_OK;
1675         struct iovec *recv_iov = NULL;
1676         uint8_t *hdr = NULL;
1677         uint8_t wct = 0;
1678         uint32_t vwv_offset = 0;
1679         uint16_t *vwv = NULL;
1680         uint32_t num_bytes = 0;
1681         uint32_t bytes_offset = 0;
1682         uint8_t *bytes = NULL;
1683         size_t i;
1684         bool found_status = false;
1685         bool found_size = false;
1686
1687         if (piov != NULL) {
1688                 *piov = NULL;
1689         }
1690         if (phdr != NULL) {
1691                 *phdr = 0;
1692         }
1693         if (pwct != NULL) {
1694                 *pwct = 0;
1695         }
1696         if (pvwv != NULL) {
1697                 *pvwv = NULL;
1698         }
1699         if (pvwv_offset != NULL) {
1700                 *pvwv_offset = 0;
1701         }
1702         if (pnum_bytes != NULL) {
1703                 *pnum_bytes = 0;
1704         }
1705         if (pbytes != NULL) {
1706                 *pbytes = NULL;
1707         }
1708         if (pbytes_offset != NULL) {
1709                 *pbytes_offset = 0;
1710         }
1711         if (pinbuf != NULL) {
1712                 *pinbuf = NULL;
1713         }
1714
1715         if (state->inbuf != NULL) {
1716                 recv_iov = state->smb1.recv_iov;
1717                 hdr = (uint8_t *)recv_iov[0].iov_base;
1718                 wct = recv_iov[1].iov_len/2;
1719                 vwv = (uint16_t *)recv_iov[1].iov_base;
1720                 vwv_offset = PTR_DIFF(vwv, hdr);
1721                 num_bytes = recv_iov[2].iov_len;
1722                 bytes = (uint8_t *)recv_iov[2].iov_base;
1723                 bytes_offset = PTR_DIFF(bytes, hdr);
1724         }
1725
1726         if (tevent_req_is_nterror(req, &status)) {
1727                 for (i=0; i < num_expected; i++) {
1728                         if (NT_STATUS_EQUAL(status, expected[i].status)) {
1729                                 found_status = true;
1730                                 break;
1731                         }
1732                 }
1733
1734                 if (found_status) {
1735                         return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
1736                 }
1737
1738                 return status;
1739         }
1740
1741         if (num_expected == 0) {
1742                 found_status = true;
1743                 found_size = true;
1744         }
1745
1746         status = state->smb1.recv_status;
1747
1748         for (i=0; i < num_expected; i++) {
1749                 if (!NT_STATUS_EQUAL(status, expected[i].status)) {
1750                         continue;
1751                 }
1752
1753                 found_status = true;
1754                 if (expected[i].wct == 0) {
1755                         found_size = true;
1756                         break;
1757                 }
1758
1759                 if (expected[i].wct == wct) {
1760                         found_size = true;
1761                         break;
1762                 }
1763         }
1764
1765         if (!found_status) {
1766                 return status;
1767         }
1768
1769         if (!found_size) {
1770                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
1771         }
1772
1773         if (piov != NULL) {
1774                 *piov = talloc_move(mem_ctx, &recv_iov);
1775         }
1776
1777         if (phdr != NULL) {
1778                 *phdr = hdr;
1779         }
1780         if (pwct != NULL) {
1781                 *pwct = wct;
1782         }
1783         if (pvwv != NULL) {
1784                 *pvwv = vwv;
1785         }
1786         if (pvwv_offset != NULL) {
1787                 *pvwv_offset = vwv_offset;
1788         }
1789         if (pnum_bytes != NULL) {
1790                 *pnum_bytes = num_bytes;
1791         }
1792         if (pbytes != NULL) {
1793                 *pbytes = bytes;
1794         }
1795         if (pbytes_offset != NULL) {
1796                 *pbytes_offset = bytes_offset;
1797         }
1798         if (pinbuf != NULL) {
1799                 *pinbuf = state->inbuf;
1800         }
1801
1802         return status;
1803 }
1804
1805 size_t smb1cli_req_wct_ofs(struct tevent_req **reqs, int num_reqs)
1806 {
1807         size_t wct_ofs;
1808         int i;
1809
1810         wct_ofs = HDR_WCT;
1811
1812         for (i=0; i<num_reqs; i++) {
1813                 struct smbXcli_req_state *state;
1814                 state = tevent_req_data(reqs[i], struct smbXcli_req_state);
1815                 wct_ofs += smbXcli_iov_len(state->smb1.iov+2,
1816                                            state->smb1.iov_count-2);
1817                 wct_ofs = (wct_ofs + 3) & ~3;
1818         }
1819         return wct_ofs;
1820 }
1821
1822 NTSTATUS smb1cli_req_chain_submit(struct tevent_req **reqs, int num_reqs)
1823 {
1824         struct smbXcli_req_state *first_state =
1825                 tevent_req_data(reqs[0],
1826                 struct smbXcli_req_state);
1827         struct smbXcli_req_state *state;
1828         size_t wct_offset;
1829         size_t chain_padding = 0;
1830         int i, iovlen;
1831         struct iovec *iov = NULL;
1832         struct iovec *this_iov;
1833         NTSTATUS status;
1834         size_t nbt_len;
1835
1836         if (num_reqs == 1) {
1837                 return smb1cli_req_writev_submit(reqs[0], first_state,
1838                                                  first_state->smb1.iov,
1839                                                  first_state->smb1.iov_count);
1840         }
1841
1842         iovlen = 0;
1843         for (i=0; i<num_reqs; i++) {
1844                 if (!tevent_req_is_in_progress(reqs[i])) {
1845                         return NT_STATUS_INTERNAL_ERROR;
1846                 }
1847
1848                 state = tevent_req_data(reqs[i], struct smbXcli_req_state);
1849
1850                 if (state->smb1.iov_count < 4) {
1851                         return NT_STATUS_INVALID_PARAMETER_MIX;
1852                 }
1853
1854                 if (i == 0) {
1855                         /*
1856                          * The NBT and SMB header
1857                          */
1858                         iovlen += 2;
1859                 } else {
1860                         /*
1861                          * Chain padding
1862                          */
1863                         iovlen += 1;
1864                 }
1865
1866                 /*
1867                  * words and bytes
1868                  */
1869                 iovlen += state->smb1.iov_count - 2;
1870         }
1871
1872         iov = talloc_zero_array(first_state, struct iovec, iovlen);
1873         if (iov == NULL) {
1874                 return NT_STATUS_NO_MEMORY;
1875         }
1876
1877         first_state->smb1.chained_requests = (struct tevent_req **)talloc_memdup(
1878                 first_state, reqs, sizeof(*reqs) * num_reqs);
1879         if (first_state->smb1.chained_requests == NULL) {
1880                 TALLOC_FREE(iov);
1881                 return NT_STATUS_NO_MEMORY;
1882         }
1883
1884         wct_offset = HDR_WCT;
1885         this_iov = iov;
1886
1887         for (i=0; i<num_reqs; i++) {
1888                 size_t next_padding = 0;
1889                 uint16_t *vwv;
1890
1891                 state = tevent_req_data(reqs[i], struct smbXcli_req_state);
1892
1893                 if (i < num_reqs-1) {
1894                         if (!smb1cli_is_andx_req(CVAL(state->smb1.hdr, HDR_COM))
1895                             || CVAL(state->smb1.hdr, HDR_WCT) < 2) {
1896                                 TALLOC_FREE(iov);
1897                                 TALLOC_FREE(first_state->smb1.chained_requests);
1898                                 return NT_STATUS_INVALID_PARAMETER_MIX;
1899                         }
1900                 }
1901
1902                 wct_offset += smbXcli_iov_len(state->smb1.iov+2,
1903                                               state->smb1.iov_count-2) + 1;
1904                 if ((wct_offset % 4) != 0) {
1905                         next_padding = 4 - (wct_offset % 4);
1906                 }
1907                 wct_offset += next_padding;
1908                 vwv = state->smb1.vwv;
1909
1910                 if (i < num_reqs-1) {
1911                         struct smbXcli_req_state *next_state =
1912                                 tevent_req_data(reqs[i+1],
1913                                 struct smbXcli_req_state);
1914                         SCVAL(vwv+0, 0, CVAL(next_state->smb1.hdr, HDR_COM));
1915                         SCVAL(vwv+0, 1, 0);
1916                         SSVAL(vwv+1, 0, wct_offset);
1917                 } else if (smb1cli_is_andx_req(CVAL(state->smb1.hdr, HDR_COM))) {
1918                         /* properly end the chain */
1919                         SCVAL(vwv+0, 0, 0xff);
1920                         SCVAL(vwv+0, 1, 0xff);
1921                         SSVAL(vwv+1, 0, 0);
1922                 }
1923
1924                 if (i == 0) {
1925                         /*
1926                          * The NBT and SMB header
1927                          */
1928                         this_iov[0] = state->smb1.iov[0];
1929                         this_iov[1] = state->smb1.iov[1];
1930                         this_iov += 2;
1931                 } else {
1932                         /*
1933                          * This one is a bit subtle. We have to add
1934                          * chain_padding bytes between the requests, and we
1935                          * have to also include the wct field of the
1936                          * subsequent requests. We use the subsequent header
1937                          * for the padding, it contains the wct field in its
1938                          * last byte.
1939                          */
1940                         this_iov[0].iov_len = chain_padding+1;
1941                         this_iov[0].iov_base = (void *)&state->smb1.hdr[
1942                                 sizeof(state->smb1.hdr) - this_iov[0].iov_len];
1943                         memset(this_iov[0].iov_base, 0, this_iov[0].iov_len-1);
1944                         this_iov += 1;
1945                 }
1946
1947                 /*
1948                  * copy the words and bytes
1949                  */
1950                 memcpy(this_iov, state->smb1.iov+2,
1951                        sizeof(struct iovec) * (state->smb1.iov_count-2));
1952                 this_iov += state->smb1.iov_count - 2;
1953                 chain_padding = next_padding;
1954         }
1955
1956         nbt_len = smbXcli_iov_len(&iov[1], iovlen-1);
1957         if (nbt_len > first_state->conn->smb1.max_xmit) {
1958                 TALLOC_FREE(iov);
1959                 TALLOC_FREE(first_state->smb1.chained_requests);
1960                 return NT_STATUS_INVALID_PARAMETER_MIX;
1961         }
1962
1963         status = smb1cli_req_writev_submit(reqs[0], first_state, iov, iovlen);
1964         if (!NT_STATUS_IS_OK(status)) {
1965                 TALLOC_FREE(iov);
1966                 TALLOC_FREE(first_state->smb1.chained_requests);
1967                 return status;
1968         }
1969
1970         return NT_STATUS_OK;
1971 }
1972
1973 bool smbXcli_conn_has_async_calls(struct smbXcli_conn *conn)
1974 {
1975         return ((tevent_queue_length(conn->outgoing) != 0)
1976                 || (talloc_array_length(conn->pending) != 0));
1977 }
1978
1979 uint32_t smb2cli_conn_server_capabilities(struct smbXcli_conn *conn)
1980 {
1981         return conn->smb2.server.capabilities;
1982 }
1983
1984 uint16_t smb2cli_conn_server_security_mode(struct smbXcli_conn *conn)
1985 {
1986         return conn->smb2.server.security_mode;
1987 }
1988
1989 uint32_t smb2cli_conn_max_trans_size(struct smbXcli_conn *conn)
1990 {
1991         return conn->smb2.server.max_trans_size;
1992 }
1993
1994 uint32_t smb2cli_conn_max_read_size(struct smbXcli_conn *conn)
1995 {
1996         return conn->smb2.server.max_read_size;
1997 }
1998
1999 uint32_t smb2cli_conn_max_write_size(struct smbXcli_conn *conn)
2000 {
2001         return conn->smb2.server.max_write_size;
2002 }
2003
2004 void smb2cli_conn_set_max_credits(struct smbXcli_conn *conn,
2005                                   uint16_t max_credits)
2006 {
2007         conn->smb2.max_credits = max_credits;
2008 }
2009
2010 struct tevent_req *smb2cli_req_create(TALLOC_CTX *mem_ctx,
2011                                       struct tevent_context *ev,
2012                                       struct smbXcli_conn *conn,
2013                                       uint16_t cmd,
2014                                       uint32_t additional_flags,
2015                                       uint32_t clear_flags,
2016                                       uint32_t timeout_msec,
2017                                       uint32_t pid,
2018                                       uint32_t tid,
2019                                       struct smbXcli_session *session,
2020                                       const uint8_t *fixed,
2021                                       uint16_t fixed_len,
2022                                       const uint8_t *dyn,
2023                                       uint32_t dyn_len)
2024 {
2025         struct tevent_req *req;
2026         struct smbXcli_req_state *state;
2027         uint32_t flags = 0;
2028         uint64_t uid = 0;
2029
2030         req = tevent_req_create(mem_ctx, &state,
2031                                 struct smbXcli_req_state);
2032         if (req == NULL) {
2033                 return NULL;
2034         }
2035
2036         state->ev = ev;
2037         state->conn = conn;
2038         state->session = session;
2039
2040         if (session) {
2041                 uid = session->smb2.session_id;
2042         }
2043
2044         state->smb2.recv_iov = talloc_zero_array(state, struct iovec, 3);
2045         if (state->smb2.recv_iov == NULL) {
2046                 TALLOC_FREE(req);
2047                 return NULL;
2048         }
2049
2050         flags |= additional_flags;
2051         flags &= ~clear_flags;
2052
2053         state->smb2.fixed = fixed;
2054         state->smb2.fixed_len = fixed_len;
2055         state->smb2.dyn = dyn;
2056         state->smb2.dyn_len = dyn_len;
2057
2058         SIVAL(state->smb2.hdr, SMB2_HDR_PROTOCOL_ID,    SMB2_MAGIC);
2059         SSVAL(state->smb2.hdr, SMB2_HDR_LENGTH,         SMB2_HDR_BODY);
2060         SSVAL(state->smb2.hdr, SMB2_HDR_OPCODE,         cmd);
2061         SIVAL(state->smb2.hdr, SMB2_HDR_FLAGS,          flags);
2062         SIVAL(state->smb2.hdr, SMB2_HDR_PID,            pid);
2063         SIVAL(state->smb2.hdr, SMB2_HDR_TID,            tid);
2064         SBVAL(state->smb2.hdr, SMB2_HDR_SESSION_ID,     uid);
2065
2066         switch (cmd) {
2067         case SMB2_OP_CANCEL:
2068                 state->one_way = true;
2069                 break;
2070         case SMB2_OP_BREAK:
2071                 /*
2072                  * If this is a dummy request, it will have
2073                  * UINT64_MAX as message id.
2074                  * If we send on break acknowledgement,
2075                  * this gets overwritten later.
2076                  */
2077                 SBVAL(state->smb2.hdr, SMB2_HDR_MESSAGE_ID, UINT64_MAX);
2078                 break;
2079         }
2080
2081         if (timeout_msec > 0) {
2082                 struct timeval endtime;
2083
2084                 endtime = timeval_current_ofs_msec(timeout_msec);
2085                 if (!tevent_req_set_endtime(req, ev, endtime)) {
2086                         return req;
2087                 }
2088         }
2089
2090         return req;
2091 }
2092
2093 static void smb2cli_writev_done(struct tevent_req *subreq);
2094 static NTSTATUS smb2cli_conn_dispatch_incoming(struct smbXcli_conn *conn,
2095                                                TALLOC_CTX *tmp_mem,
2096                                                uint8_t *inbuf);
2097
2098 NTSTATUS smb2cli_req_compound_submit(struct tevent_req **reqs,
2099                                      int num_reqs)
2100 {
2101         struct smbXcli_req_state *state;
2102         struct tevent_req *subreq;
2103         struct iovec *iov;
2104         int i, num_iov, nbt_len;
2105
2106         /*
2107          * 1 for the nbt length
2108          * per request: HDR, fixed, dyn, padding
2109          * -1 because the last one does not need padding
2110          */
2111
2112         iov = talloc_array(reqs[0], struct iovec, 1 + 4*num_reqs - 1);
2113         if (iov == NULL) {
2114                 return NT_STATUS_NO_MEMORY;
2115         }
2116
2117         num_iov = 1;
2118         nbt_len = 0;
2119
2120         for (i=0; i<num_reqs; i++) {
2121                 int hdr_iov;
2122                 size_t reqlen;
2123                 bool ret;
2124                 uint64_t avail;
2125                 uint16_t charge;
2126                 uint16_t credits;
2127                 uint64_t mid;
2128                 bool should_sign = false;
2129
2130                 if (!tevent_req_is_in_progress(reqs[i])) {
2131                         return NT_STATUS_INTERNAL_ERROR;
2132                 }
2133
2134                 state = tevent_req_data(reqs[i], struct smbXcli_req_state);
2135
2136                 if (!smbXcli_conn_is_connected(state->conn)) {
2137                         return NT_STATUS_CONNECTION_DISCONNECTED;
2138                 }
2139
2140                 if ((state->conn->protocol != PROTOCOL_NONE) &&
2141                     (state->conn->protocol < PROTOCOL_SMB2_02)) {
2142                         return NT_STATUS_REVISION_MISMATCH;
2143                 }
2144
2145                 avail = UINT64_MAX - state->conn->smb2.mid;
2146                 if (avail < 1) {
2147                         return NT_STATUS_CONNECTION_ABORTED;
2148                 }
2149
2150                 if (state->conn->smb2.server.capabilities & SMB2_CAP_LARGE_MTU) {
2151                         charge = (MAX(state->smb2.dyn_len, 1) - 1)/ 65536 + 1;
2152                 } else {
2153                         charge = 1;
2154                 }
2155
2156                 charge = MAX(state->smb2.credit_charge, charge);
2157
2158                 avail = MIN(avail, state->conn->smb2.cur_credits);
2159                 if (avail < charge) {
2160                         return NT_STATUS_INTERNAL_ERROR;
2161                 }
2162
2163                 credits = 0;
2164                 if (state->conn->smb2.max_credits > state->conn->smb2.cur_credits) {
2165                         credits = state->conn->smb2.max_credits -
2166                                   state->conn->smb2.cur_credits;
2167                 }
2168                 if (state->conn->smb2.max_credits >= state->conn->smb2.cur_credits) {
2169                         credits += 1;
2170                 }
2171
2172                 mid = state->conn->smb2.mid;
2173                 state->conn->smb2.mid += charge;
2174                 state->conn->smb2.cur_credits -= charge;
2175
2176                 if (state->conn->smb2.server.capabilities & SMB2_CAP_LARGE_MTU) {
2177                         SSVAL(state->smb2.hdr, SMB2_HDR_CREDIT_CHARGE, charge);
2178                 }
2179                 SSVAL(state->smb2.hdr, SMB2_HDR_CREDIT, credits);
2180                 SBVAL(state->smb2.hdr, SMB2_HDR_MESSAGE_ID, mid);
2181
2182                 hdr_iov = num_iov;
2183                 iov[num_iov].iov_base = state->smb2.hdr;
2184                 iov[num_iov].iov_len  = sizeof(state->smb2.hdr);
2185                 num_iov += 1;
2186
2187                 iov[num_iov].iov_base = discard_const(state->smb2.fixed);
2188                 iov[num_iov].iov_len  = state->smb2.fixed_len;
2189                 num_iov += 1;
2190
2191                 if (state->smb2.dyn != NULL) {
2192                         iov[num_iov].iov_base = discard_const(state->smb2.dyn);
2193                         iov[num_iov].iov_len  = state->smb2.dyn_len;
2194                         num_iov += 1;
2195                 }
2196
2197                 reqlen  = sizeof(state->smb2.hdr);
2198                 reqlen += state->smb2.fixed_len;
2199                 reqlen += state->smb2.dyn_len;
2200
2201                 if (i < num_reqs-1) {
2202                         if ((reqlen % 8) > 0) {
2203                                 uint8_t pad = 8 - (reqlen % 8);
2204                                 iov[num_iov].iov_base = state->smb2.pad;
2205                                 iov[num_iov].iov_len = pad;
2206                                 num_iov += 1;
2207                                 reqlen += pad;
2208                         }
2209                         SIVAL(state->smb2.hdr, SMB2_HDR_NEXT_COMMAND, reqlen);
2210                 }
2211                 nbt_len += reqlen;
2212
2213                 if (state->session) {
2214                         should_sign = state->session->smb2.should_sign;
2215                         if (state->session->smb2.channel_setup) {
2216                                 should_sign = true;
2217                         }
2218                 }
2219
2220                 if (should_sign) {
2221                         NTSTATUS status;
2222
2223                         status = smb2_signing_sign_pdu(state->session->smb2.signing_key,
2224                                                        &iov[hdr_iov], num_iov - hdr_iov);
2225                         if (!NT_STATUS_IS_OK(status)) {
2226                                 return status;
2227                         }
2228                 }
2229
2230                 ret = smbXcli_req_set_pending(reqs[i]);
2231                 if (!ret) {
2232                         return NT_STATUS_NO_MEMORY;
2233                 }
2234         }
2235
2236         state = tevent_req_data(reqs[0], struct smbXcli_req_state);
2237         _smb_setlen_tcp(state->length_hdr, nbt_len);
2238         iov[0].iov_base = state->length_hdr;
2239         iov[0].iov_len  = sizeof(state->length_hdr);
2240
2241         if (state->conn->dispatch_incoming == NULL) {
2242                 state->conn->dispatch_incoming = smb2cli_conn_dispatch_incoming;
2243         }
2244
2245         subreq = writev_send(state, state->ev, state->conn->outgoing,
2246                              state->conn->fd, false, iov, num_iov);
2247         if (subreq == NULL) {
2248                 return NT_STATUS_NO_MEMORY;
2249         }
2250         tevent_req_set_callback(subreq, smb2cli_writev_done, reqs[0]);
2251         return NT_STATUS_OK;
2252 }
2253
2254 void smb2cli_req_set_credit_charge(struct tevent_req *req, uint16_t charge)
2255 {
2256         struct smbXcli_req_state *state =
2257                 tevent_req_data(req,
2258                 struct smbXcli_req_state);
2259
2260         state->smb2.credit_charge = charge;
2261 }
2262
2263 struct tevent_req *smb2cli_req_send(TALLOC_CTX *mem_ctx,
2264                                     struct tevent_context *ev,
2265                                     struct smbXcli_conn *conn,
2266                                     uint16_t cmd,
2267                                     uint32_t additional_flags,
2268                                     uint32_t clear_flags,
2269                                     uint32_t timeout_msec,
2270                                     uint32_t pid,
2271                                     uint32_t tid,
2272                                     struct smbXcli_session *session,
2273                                     const uint8_t *fixed,
2274                                     uint16_t fixed_len,
2275                                     const uint8_t *dyn,
2276                                     uint32_t dyn_len)
2277 {
2278         struct tevent_req *req;
2279         NTSTATUS status;
2280
2281         req = smb2cli_req_create(mem_ctx, ev, conn, cmd,
2282                                  additional_flags, clear_flags,
2283                                  timeout_msec,
2284                                  pid, tid, session,
2285                                  fixed, fixed_len, dyn, dyn_len);
2286         if (req == NULL) {
2287                 return NULL;
2288         }
2289         if (!tevent_req_is_in_progress(req)) {
2290                 return tevent_req_post(req, ev);
2291         }
2292         status = smb2cli_req_compound_submit(&req, 1);
2293         if (tevent_req_nterror(req, status)) {
2294                 return tevent_req_post(req, ev);
2295         }
2296         return req;
2297 }
2298
2299 static void smb2cli_writev_done(struct tevent_req *subreq)
2300 {
2301         struct tevent_req *req =
2302                 tevent_req_callback_data(subreq,
2303                 struct tevent_req);
2304         struct smbXcli_req_state *state =
2305                 tevent_req_data(req,
2306                 struct smbXcli_req_state);
2307         ssize_t nwritten;
2308         int err;
2309
2310         nwritten = writev_recv(subreq, &err);
2311         TALLOC_FREE(subreq);
2312         if (nwritten == -1) {
2313                 /* here, we need to notify all pending requests */
2314                 NTSTATUS status = map_nt_error_from_unix_common(err);
2315                 smbXcli_conn_disconnect(state->conn, status);
2316                 return;
2317         }
2318 }
2319
2320 static NTSTATUS smb2cli_inbuf_parse_compound(uint8_t *buf, TALLOC_CTX *mem_ctx,
2321                                              struct iovec **piov, int *pnum_iov)
2322 {
2323         struct iovec *iov;
2324         int num_iov;
2325         size_t buflen;
2326         size_t taken;
2327         uint8_t *first_hdr;
2328
2329         num_iov = 0;
2330
2331         iov = talloc_array(mem_ctx, struct iovec, num_iov);
2332         if (iov == NULL) {
2333                 return NT_STATUS_NO_MEMORY;
2334         }
2335
2336         buflen = smb_len_tcp(buf);
2337         taken = 0;
2338         first_hdr = buf + NBT_HDR_SIZE;
2339
2340         while (taken < buflen) {
2341                 size_t len = buflen - taken;
2342                 uint8_t *hdr = first_hdr + taken;
2343                 struct iovec *cur;
2344                 size_t full_size;
2345                 size_t next_command_ofs;
2346                 uint16_t body_size;
2347                 struct iovec *iov_tmp;
2348
2349                 /*
2350                  * We need the header plus the body length field
2351                  */
2352
2353                 if (len < SMB2_HDR_BODY + 2) {
2354                         DEBUG(10, ("%d bytes left, expected at least %d\n",
2355                                    (int)len, SMB2_HDR_BODY));
2356                         goto inval;
2357                 }
2358                 if (IVAL(hdr, 0) != SMB2_MAGIC) {
2359                         DEBUG(10, ("Got non-SMB2 PDU: %x\n",
2360                                    IVAL(hdr, 0)));
2361                         goto inval;
2362                 }
2363                 if (SVAL(hdr, 4) != SMB2_HDR_BODY) {
2364                         DEBUG(10, ("Got HDR len %d, expected %d\n",
2365                                    SVAL(hdr, 4), SMB2_HDR_BODY));
2366                         goto inval;
2367                 }
2368
2369                 full_size = len;
2370                 next_command_ofs = IVAL(hdr, SMB2_HDR_NEXT_COMMAND);
2371                 body_size = SVAL(hdr, SMB2_HDR_BODY);
2372
2373                 if (next_command_ofs != 0) {
2374                         if (next_command_ofs < (SMB2_HDR_BODY + 2)) {
2375                                 goto inval;
2376                         }
2377                         if (next_command_ofs > full_size) {
2378                                 goto inval;
2379                         }
2380                         full_size = next_command_ofs;
2381                 }
2382                 if (body_size < 2) {
2383                         goto inval;
2384                 }
2385                 body_size &= 0xfffe;
2386
2387                 if (body_size > (full_size - SMB2_HDR_BODY)) {
2388                         goto inval;
2389                 }
2390
2391                 iov_tmp = talloc_realloc(mem_ctx, iov, struct iovec,
2392                                          num_iov + 3);
2393                 if (iov_tmp == NULL) {
2394                         TALLOC_FREE(iov);
2395                         return NT_STATUS_NO_MEMORY;
2396                 }
2397                 iov = iov_tmp;
2398                 cur = &iov[num_iov];
2399                 num_iov += 3;
2400
2401                 cur[0].iov_base = hdr;
2402                 cur[0].iov_len  = SMB2_HDR_BODY;
2403                 cur[1].iov_base = hdr + SMB2_HDR_BODY;
2404                 cur[1].iov_len  = body_size;
2405                 cur[2].iov_base = hdr + SMB2_HDR_BODY + body_size;
2406                 cur[2].iov_len  = full_size - (SMB2_HDR_BODY + body_size);
2407
2408                 taken += full_size;
2409         }
2410
2411         *piov = iov;
2412         *pnum_iov = num_iov;
2413         return NT_STATUS_OK;
2414
2415 inval:
2416         TALLOC_FREE(iov);
2417         return NT_STATUS_INVALID_NETWORK_RESPONSE;
2418 }
2419
2420 static struct tevent_req *smb2cli_conn_find_pending(struct smbXcli_conn *conn,
2421                                                     uint64_t mid)
2422 {
2423         size_t num_pending = talloc_array_length(conn->pending);
2424         size_t i;
2425
2426         for (i=0; i<num_pending; i++) {
2427                 struct tevent_req *req = conn->pending[i];
2428                 struct smbXcli_req_state *state =
2429                         tevent_req_data(req,
2430                         struct smbXcli_req_state);
2431
2432                 if (mid == BVAL(state->smb2.hdr, SMB2_HDR_MESSAGE_ID)) {
2433                         return req;
2434                 }
2435         }
2436         return NULL;
2437 }
2438
2439 static NTSTATUS smb2cli_conn_dispatch_incoming(struct smbXcli_conn *conn,
2440                                                TALLOC_CTX *tmp_mem,
2441                                                uint8_t *inbuf)
2442 {
2443         struct tevent_req *req;
2444         struct smbXcli_req_state *state = NULL;
2445         struct iovec *iov;
2446         int i, num_iov;
2447         NTSTATUS status;
2448         bool defer = true;
2449         struct smbXcli_session *last_session = NULL;
2450
2451         status = smb2cli_inbuf_parse_compound(inbuf, tmp_mem,
2452                                               &iov, &num_iov);
2453         if (!NT_STATUS_IS_OK(status)) {
2454                 return status;
2455         }
2456
2457         for (i=0; i<num_iov; i+=3) {
2458                 uint8_t *inbuf_ref = NULL;
2459                 struct iovec *cur = &iov[i];
2460                 uint8_t *inhdr = (uint8_t *)cur[0].iov_base;
2461                 uint16_t opcode = SVAL(inhdr, SMB2_HDR_OPCODE);
2462                 uint32_t flags = IVAL(inhdr, SMB2_HDR_FLAGS);
2463                 uint64_t mid = BVAL(inhdr, SMB2_HDR_MESSAGE_ID);
2464                 uint16_t req_opcode;
2465                 uint32_t req_flags;
2466                 uint16_t credits = SVAL(inhdr, SMB2_HDR_CREDIT);
2467                 uint32_t new_credits;
2468                 struct smbXcli_session *session = NULL;
2469                 const DATA_BLOB *signing_key = NULL;
2470                 bool should_sign = false;
2471
2472                 new_credits = conn->smb2.cur_credits;
2473                 new_credits += credits;
2474                 if (new_credits > UINT16_MAX) {
2475                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
2476                 }
2477                 conn->smb2.cur_credits += credits;
2478
2479                 req = smb2cli_conn_find_pending(conn, mid);
2480                 if (req == NULL) {
2481                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
2482                 }
2483                 state = tevent_req_data(req, struct smbXcli_req_state);
2484
2485                 req_opcode = SVAL(state->smb2.hdr, SMB2_HDR_OPCODE);
2486                 if (opcode != req_opcode) {
2487                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
2488                 }
2489                 req_flags = SVAL(state->smb2.hdr, SMB2_HDR_FLAGS);
2490
2491                 if (!(flags & SMB2_HDR_FLAG_REDIRECT)) {
2492                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
2493                 }
2494
2495                 status = NT_STATUS(IVAL(inhdr, SMB2_HDR_STATUS));
2496                 if ((flags & SMB2_HDR_FLAG_ASYNC) &&
2497                     NT_STATUS_EQUAL(status, STATUS_PENDING)) {
2498                         uint64_t async_id = BVAL(inhdr, SMB2_HDR_ASYNC_ID);
2499
2500                         /*
2501                          * async interim responses are not signed,
2502                          * even if the SMB2_HDR_FLAG_SIGNED flag
2503                          * is set.
2504                          */
2505                         req_flags |= SMB2_HDR_FLAG_ASYNC;
2506                         SBVAL(state->smb2.hdr, SMB2_HDR_FLAGS, req_flags);
2507                         SBVAL(state->smb2.hdr, SMB2_HDR_ASYNC_ID, async_id);
2508                         continue;
2509                 }
2510
2511                 session = state->session;
2512                 if (req_flags & SMB2_HDR_FLAG_CHAINED) {
2513                         session = last_session;
2514                 }
2515                 last_session = session;
2516
2517                 if (session) {
2518                         should_sign = session->smb2.should_sign;
2519                         if (session->smb2.channel_setup) {
2520                                 should_sign = true;
2521                         }
2522                 }
2523
2524                 if (should_sign) {
2525                         if (!(flags & SMB2_HDR_FLAG_SIGNED)) {
2526                                 return NT_STATUS_ACCESS_DENIED;
2527                         }
2528                 }
2529
2530                 if (flags & SMB2_HDR_FLAG_SIGNED) {
2531                         uint64_t uid = BVAL(inhdr, SMB2_HDR_SESSION_ID);
2532
2533                         if (session == NULL) {
2534                                 struct smbXcli_session *s;
2535
2536                                 s = state->conn->sessions;
2537                                 for (; s; s = s->next) {
2538                                         if (s->smb2.session_id != uid) {
2539                                                 continue;
2540                                         }
2541
2542                                         session = s;
2543                                         break;
2544                                 }
2545                         }
2546
2547                         if (session == NULL) {
2548                                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
2549                         }
2550
2551                         last_session = session;
2552                         signing_key = &session->smb2.signing_key;
2553                 }
2554
2555                 if ((opcode == SMB2_OP_SESSSETUP) &&
2556                      NT_STATUS_IS_OK(status)) {
2557                         /*
2558                          * the caller has to check the signing
2559                          * as only the caller knows the correct
2560                          * session key
2561                          */
2562                         signing_key = NULL;
2563                 }
2564
2565                 if (NT_STATUS_EQUAL(status, NT_STATUS_USER_SESSION_DELETED)) {
2566                         /*
2567                          * if the server returns NT_STATUS_USER_SESSION_DELETED
2568                          * the response is not signed and we should
2569                          * propagate the NT_STATUS_USER_SESSION_DELETED
2570                          * status to the caller.
2571                          */
2572                         if (signing_key) {
2573                                 signing_key = NULL;
2574                         }
2575                 }
2576
2577                 if (NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_NAME_DELETED) ||
2578                     NT_STATUS_EQUAL(status, NT_STATUS_FILE_CLOSED) ||
2579                     NT_STATUS_EQUAL(status, NT_STATUS_INVALID_PARAMETER)) {
2580                         /*
2581                          * if the server returns
2582                          * NT_STATUS_NETWORK_NAME_DELETED
2583                          * NT_STATUS_FILE_CLOSED
2584                          * NT_STATUS_INVALID_PARAMETER
2585                          * the response might not be signed
2586                          * as this happens before the signing checks.
2587                          *
2588                          * If server echos the signature (or all zeros)
2589                          * we should report the status from the server
2590                          * to the caller.
2591                          */
2592                         if (signing_key) {
2593                                 int cmp;
2594
2595                                 cmp = memcmp(inhdr+SMB2_HDR_SIGNATURE,
2596                                              state->smb2.hdr+SMB2_HDR_SIGNATURE,
2597                                              16);
2598                                 if (cmp == 0) {
2599                                         state->smb2.signing_skipped = true;
2600                                         signing_key = NULL;
2601                                 }
2602                         }
2603                         if (signing_key) {
2604                                 int cmp;
2605                                 static const uint8_t zeros[16];
2606
2607                                 cmp = memcmp(inhdr+SMB2_HDR_SIGNATURE,
2608                                              zeros,
2609                                              16);
2610                                 if (cmp == 0) {
2611                                         state->smb2.signing_skipped = true;
2612                                         signing_key = NULL;
2613                                 }
2614                         }
2615                 }
2616
2617                 if (signing_key) {
2618                         status = smb2_signing_check_pdu(*signing_key, cur, 3);
2619                         if (!NT_STATUS_IS_OK(status)) {
2620                                 /*
2621                                  * If the signing check fails, we disconnect
2622                                  * the connection.
2623                                  */
2624                                 return status;
2625                         }
2626                 }
2627
2628                 smbXcli_req_unset_pending(req);
2629
2630                 /*
2631                  * There might be more than one response
2632                  * we need to defer the notifications
2633                  */
2634                 if ((num_iov == 4) && (talloc_array_length(conn->pending) == 0)) {
2635                         defer = false;
2636                 }
2637
2638                 if (defer) {
2639                         tevent_req_defer_callback(req, state->ev);
2640                 }
2641
2642                 /*
2643                  * Note: here we use talloc_reference() in a way
2644                  *       that does not expose it to the caller.
2645                  */
2646                 inbuf_ref = talloc_reference(state->smb2.recv_iov, inbuf);
2647                 if (tevent_req_nomem(inbuf_ref, req)) {
2648                         continue;
2649                 }
2650
2651                 /* copy the related buffers */
2652                 state->smb2.recv_iov[0] = cur[0];
2653                 state->smb2.recv_iov[1] = cur[1];
2654                 state->smb2.recv_iov[2] = cur[2];
2655
2656                 tevent_req_done(req);
2657         }
2658
2659         if (defer) {
2660                 return NT_STATUS_RETRY;
2661         }
2662
2663         return NT_STATUS_OK;
2664 }
2665
2666 NTSTATUS smb2cli_req_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
2667                           struct iovec **piov,
2668                           const struct smb2cli_req_expected_response *expected,
2669                           size_t num_expected)
2670 {
2671         struct smbXcli_req_state *state =
2672                 tevent_req_data(req,
2673                 struct smbXcli_req_state);
2674         NTSTATUS status;
2675         size_t body_size;
2676         bool found_status = false;
2677         bool found_size = false;
2678         size_t i;
2679
2680         if (piov != NULL) {
2681                 *piov = NULL;
2682         }
2683
2684         if (tevent_req_is_nterror(req, &status)) {
2685                 for (i=0; i < num_expected; i++) {
2686                         if (NT_STATUS_EQUAL(status, expected[i].status)) {
2687                                 found_status = true;
2688                                 break;
2689                         }
2690                 }
2691
2692                 if (found_status) {
2693                         return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
2694                 }
2695
2696                 return status;
2697         }
2698
2699         if (num_expected == 0) {
2700                 found_status = true;
2701                 found_size = true;
2702         }
2703
2704         status = NT_STATUS(IVAL(state->smb2.recv_iov[0].iov_base, SMB2_HDR_STATUS));
2705         body_size = SVAL(state->smb2.recv_iov[1].iov_base, 0);
2706
2707         for (i=0; i < num_expected; i++) {
2708                 if (!NT_STATUS_EQUAL(status, expected[i].status)) {
2709                         continue;
2710                 }
2711
2712                 found_status = true;
2713                 if (expected[i].body_size == 0) {
2714                         found_size = true;
2715                         break;
2716                 }
2717
2718                 if (expected[i].body_size == body_size) {
2719                         found_size = true;
2720                         break;
2721                 }
2722         }
2723
2724         if (!found_status) {
2725                 return status;
2726         }
2727
2728         if (state->smb2.signing_skipped) {
2729                 if (num_expected > 0) {
2730                         return NT_STATUS_ACCESS_DENIED;
2731                 }
2732                 if (!NT_STATUS_IS_ERR(status)) {
2733                         return NT_STATUS_ACCESS_DENIED;
2734                 }
2735         }
2736
2737         if (!found_size) {
2738                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
2739         }
2740
2741         if (piov != NULL) {
2742                 *piov = talloc_move(mem_ctx, &state->smb2.recv_iov);
2743         }
2744
2745         return status;
2746 }
2747
2748 static const struct {
2749         enum protocol_types proto;
2750         const char *smb1_name;
2751 } smb1cli_prots[] = {
2752         {PROTOCOL_CORE,         "PC NETWORK PROGRAM 1.0"},
2753         {PROTOCOL_COREPLUS,     "MICROSOFT NETWORKS 1.03"},
2754         {PROTOCOL_LANMAN1,      "MICROSOFT NETWORKS 3.0"},
2755         {PROTOCOL_LANMAN1,      "LANMAN1.0"},
2756         {PROTOCOL_LANMAN2,      "LM1.2X002"},
2757         {PROTOCOL_LANMAN2,      "DOS LANMAN2.1"},
2758         {PROTOCOL_LANMAN2,      "LANMAN2.1"},
2759         {PROTOCOL_LANMAN2,      "Samba"},
2760         {PROTOCOL_NT1,          "NT LANMAN 1.0"},
2761         {PROTOCOL_NT1,          "NT LM 0.12"},
2762         {PROTOCOL_SMB2_02,      "SMB 2.002"},
2763         {PROTOCOL_SMB2_10,      "SMB 2.???"},
2764 };
2765
2766 static const struct {
2767         enum protocol_types proto;
2768         uint16_t smb2_dialect;
2769 } smb2cli_prots[] = {
2770         {PROTOCOL_SMB2_02,      SMB2_DIALECT_REVISION_202},
2771         {PROTOCOL_SMB2_10,      SMB2_DIALECT_REVISION_210},
2772         {PROTOCOL_SMB2_22,      SMB2_DIALECT_REVISION_222},
2773 };
2774
2775 struct smbXcli_negprot_state {
2776         struct smbXcli_conn *conn;
2777         struct tevent_context *ev;
2778         uint32_t timeout_msec;
2779         enum protocol_types min_protocol;
2780         enum protocol_types max_protocol;
2781
2782         struct {
2783                 uint8_t fixed[36];
2784                 uint8_t dyn[ARRAY_SIZE(smb2cli_prots)*2];
2785         } smb2;
2786 };
2787
2788 static void smbXcli_negprot_invalid_done(struct tevent_req *subreq);
2789 static struct tevent_req *smbXcli_negprot_smb1_subreq(struct smbXcli_negprot_state *state);
2790 static void smbXcli_negprot_smb1_done(struct tevent_req *subreq);
2791 static struct tevent_req *smbXcli_negprot_smb2_subreq(struct smbXcli_negprot_state *state);
2792 static void smbXcli_negprot_smb2_done(struct tevent_req *subreq);
2793 static NTSTATUS smbXcli_negprot_dispatch_incoming(struct smbXcli_conn *conn,
2794                                                   TALLOC_CTX *frame,
2795                                                   uint8_t *inbuf);
2796
2797 struct tevent_req *smbXcli_negprot_send(TALLOC_CTX *mem_ctx,
2798                                         struct tevent_context *ev,
2799                                         struct smbXcli_conn *conn,
2800                                         uint32_t timeout_msec,
2801                                         enum protocol_types min_protocol,
2802                                         enum protocol_types max_protocol)
2803 {
2804         struct tevent_req *req, *subreq;
2805         struct smbXcli_negprot_state *state;
2806
2807         req = tevent_req_create(mem_ctx, &state,
2808                                 struct smbXcli_negprot_state);
2809         if (req == NULL) {
2810                 return NULL;
2811         }
2812         state->conn = conn;
2813         state->ev = ev;
2814         state->timeout_msec = timeout_msec;
2815         state->min_protocol = min_protocol;
2816         state->max_protocol = max_protocol;
2817
2818         if (min_protocol == PROTOCOL_NONE) {
2819                 tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER_MIX);
2820                 return tevent_req_post(req, ev);
2821         }
2822
2823         if (max_protocol == PROTOCOL_NONE) {
2824                 tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER_MIX);
2825                 return tevent_req_post(req, ev);
2826         }
2827
2828         if (min_protocol > max_protocol) {
2829                 tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER_MIX);
2830                 return tevent_req_post(req, ev);
2831         }
2832
2833         if ((min_protocol < PROTOCOL_SMB2_02) &&
2834             (max_protocol < PROTOCOL_SMB2_02)) {
2835                 /*
2836                  * SMB1 only...
2837                  */
2838                 conn->dispatch_incoming = smb1cli_conn_dispatch_incoming;
2839
2840                 subreq = smbXcli_negprot_smb1_subreq(state);
2841                 if (tevent_req_nomem(subreq, req)) {
2842                         return tevent_req_post(req, ev);
2843                 }
2844                 tevent_req_set_callback(subreq, smbXcli_negprot_smb1_done, req);
2845                 return req;
2846         }
2847
2848         if ((min_protocol >= PROTOCOL_SMB2_02) &&
2849             (max_protocol >= PROTOCOL_SMB2_02)) {
2850                 /*
2851                  * SMB2 only...
2852                  */
2853                 conn->dispatch_incoming = smb2cli_conn_dispatch_incoming;
2854
2855                 subreq = smbXcli_negprot_smb2_subreq(state);
2856                 if (tevent_req_nomem(subreq, req)) {
2857                         return tevent_req_post(req, ev);
2858                 }
2859                 tevent_req_set_callback(subreq, smbXcli_negprot_smb2_done, req);
2860                 return req;
2861         }
2862
2863         /*
2864          * We send an SMB1 negprot with the SMB2 dialects
2865          * and expect a SMB1 or a SMB2 response.
2866          *
2867          * smbXcli_negprot_dispatch_incoming() will fix the
2868          * callback to match protocol of the response.
2869          */
2870         conn->dispatch_incoming = smbXcli_negprot_dispatch_incoming;
2871
2872         subreq = smbXcli_negprot_smb1_subreq(state);
2873         if (tevent_req_nomem(subreq, req)) {
2874                 return tevent_req_post(req, ev);
2875         }
2876         tevent_req_set_callback(subreq, smbXcli_negprot_invalid_done, req);
2877         return req;
2878 }
2879
2880 static void smbXcli_negprot_invalid_done(struct tevent_req *subreq)
2881 {
2882         struct tevent_req *req =
2883                 tevent_req_callback_data(subreq,
2884                 struct tevent_req);
2885         NTSTATUS status;
2886
2887         /*
2888          * we just want the low level error
2889          */
2890         status = tevent_req_simple_recv_ntstatus(subreq);
2891         TALLOC_FREE(subreq);
2892         if (tevent_req_nterror(req, status)) {
2893                 return;
2894         }
2895
2896         /* this should never happen */
2897         tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
2898 }
2899
2900 static struct tevent_req *smbXcli_negprot_smb1_subreq(struct smbXcli_negprot_state *state)
2901 {
2902         size_t i;
2903         DATA_BLOB bytes = data_blob_null;
2904         uint8_t flags;
2905         uint16_t flags2;
2906
2907         /* setup the protocol strings */
2908         for (i=0; i < ARRAY_SIZE(smb1cli_prots); i++) {
2909                 uint8_t c = 2;
2910                 bool ok;
2911
2912                 if (smb1cli_prots[i].proto < state->min_protocol) {
2913                         continue;
2914                 }
2915
2916                 if (smb1cli_prots[i].proto > state->max_protocol) {
2917                         continue;
2918                 }
2919
2920                 ok = data_blob_append(state, &bytes, &c, sizeof(c));
2921                 if (!ok) {
2922                         return NULL;
2923                 }
2924
2925                 /*
2926                  * We now it is already ascii and
2927                  * we want NULL termination.
2928                  */
2929                 ok = data_blob_append(state, &bytes,
2930                                       smb1cli_prots[i].smb1_name,
2931                                       strlen(smb1cli_prots[i].smb1_name)+1);
2932                 if (!ok) {
2933                         return NULL;
2934                 }
2935         }
2936
2937         smb1cli_req_flags(state->max_protocol,
2938                           state->conn->smb1.client.capabilities,
2939                           SMBnegprot,
2940                           0, 0, &flags,
2941                           0, 0, &flags2);
2942
2943         return smb1cli_req_send(state, state->ev, state->conn,
2944                                 SMBnegprot,
2945                                 flags, ~flags,
2946                                 flags2, ~flags2,
2947                                 state->timeout_msec,
2948                                 0xFFFE, 0, 0, /* pid, tid, uid */
2949                                 0, NULL, /* wct, vwv */
2950                                 bytes.length, bytes.data);
2951 }
2952
2953 static void smbXcli_negprot_smb1_done(struct tevent_req *subreq)
2954 {
2955         struct tevent_req *req =
2956                 tevent_req_callback_data(subreq,
2957                 struct tevent_req);
2958         struct smbXcli_negprot_state *state =
2959                 tevent_req_data(req,
2960                 struct smbXcli_negprot_state);
2961         struct smbXcli_conn *conn = state->conn;
2962         struct iovec *recv_iov = NULL;
2963         uint8_t *inhdr;
2964         uint8_t wct;
2965         uint16_t *vwv;
2966         uint32_t num_bytes;
2967         uint8_t *bytes;
2968         NTSTATUS status;
2969         uint16_t protnum;
2970         size_t i;
2971         size_t num_prots = 0;
2972         uint8_t flags;
2973         uint32_t client_capabilities = conn->smb1.client.capabilities;
2974         uint32_t both_capabilities;
2975         uint32_t server_capabilities = 0;
2976         uint32_t capabilities;
2977         uint32_t client_max_xmit = conn->smb1.client.max_xmit;
2978         uint32_t server_max_xmit = 0;
2979         uint32_t max_xmit;
2980         uint32_t server_max_mux = 0;
2981         uint16_t server_security_mode = 0;
2982         uint32_t server_session_key = 0;
2983         bool server_readbraw = false;
2984         bool server_writebraw = false;
2985         bool server_lockread = false;
2986         bool server_writeunlock = false;
2987         struct GUID server_guid = GUID_zero();
2988         DATA_BLOB server_gss_blob = data_blob_null;
2989         uint8_t server_challenge[8];
2990         char *server_workgroup = NULL;
2991         char *server_name = NULL;
2992         int server_time_zone = 0;
2993         NTTIME server_system_time = 0;
2994         static const struct smb1cli_req_expected_response expected[] = {
2995         {
2996                 .status = NT_STATUS_OK,
2997                 .wct = 0x11, /* NT1 */
2998         },
2999         {
3000                 .status = NT_STATUS_OK,
3001                 .wct = 0x0D, /* LM */
3002         },
3003         {
3004                 .status = NT_STATUS_OK,
3005                 .wct = 0x01, /* CORE */
3006         }
3007         };
3008
3009         ZERO_STRUCT(server_challenge);
3010
3011         status = smb1cli_req_recv(subreq, state,
3012                                   &recv_iov,
3013                                   &inhdr,
3014                                   &wct,
3015                                   &vwv,
3016                                   NULL, /* pvwv_offset */
3017                                   &num_bytes,
3018                                   &bytes,
3019                                   NULL, /* pbytes_offset */
3020                                   NULL, /* pinbuf */
3021                                   expected, ARRAY_SIZE(expected));
3022         TALLOC_FREE(subreq);
3023         if (tevent_req_nterror(req, status)) {
3024                 return;
3025         }
3026
3027         flags = CVAL(inhdr, HDR_FLG);
3028
3029         protnum = SVAL(vwv, 0);
3030
3031         for (i=0; i < ARRAY_SIZE(smb1cli_prots); i++) {
3032                 if (smb1cli_prots[i].proto < state->min_protocol) {
3033                         continue;
3034                 }
3035
3036                 if (smb1cli_prots[i].proto > state->max_protocol) {
3037                         continue;
3038                 }
3039
3040                 if (protnum != num_prots) {
3041                         num_prots++;
3042                         continue;
3043                 }
3044
3045                 conn->protocol = smb1cli_prots[i].proto;
3046                 break;
3047         }
3048
3049         if (conn->protocol == PROTOCOL_NONE) {
3050                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3051                 return;
3052         }
3053
3054         if ((conn->protocol < PROTOCOL_NT1) && conn->mandatory_signing) {
3055                 DEBUG(0,("smbXcli_negprot: SMB signing is mandatory "
3056                          "and the selected protocol level doesn't support it.\n"));
3057                 tevent_req_nterror(req, NT_STATUS_ACCESS_DENIED);
3058                 return;
3059         }
3060
3061         if (flags & FLAG_SUPPORT_LOCKREAD) {
3062                 server_lockread = true;
3063                 server_writeunlock = true;
3064         }
3065
3066         if (conn->protocol >= PROTOCOL_NT1) {
3067                 const char *client_signing = NULL;
3068                 bool server_mandatory = false;
3069                 bool server_allowed = false;
3070                 const char *server_signing = NULL;
3071                 bool ok;
3072                 uint8_t key_len;
3073
3074                 if (wct != 0x11) {
3075                         tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3076                         return;
3077                 }
3078
3079                 /* NT protocol */
3080                 server_security_mode = CVAL(vwv + 1, 0);
3081                 server_max_mux = SVAL(vwv + 1, 1);
3082                 server_max_xmit = IVAL(vwv + 3, 1);
3083                 server_session_key = IVAL(vwv + 7, 1);
3084                 server_time_zone = SVALS(vwv + 15, 1);
3085                 server_time_zone *= 60;
3086                 /* this time arrives in real GMT */
3087                 server_system_time = BVAL(vwv + 11, 1);
3088                 server_capabilities = IVAL(vwv + 9, 1);
3089
3090                 key_len = CVAL(vwv + 16, 1);
3091
3092                 if (server_capabilities & CAP_RAW_MODE) {
3093                         server_readbraw = true;
3094                         server_writebraw = true;
3095                 }
3096                 if (server_capabilities & CAP_LOCK_AND_READ) {
3097                         server_lockread = true;
3098                 }
3099
3100                 if (server_capabilities & CAP_EXTENDED_SECURITY) {
3101                         DATA_BLOB blob1, blob2;
3102
3103                         if (num_bytes < 16) {
3104                                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3105                                 return;
3106                         }
3107
3108                         blob1 = data_blob_const(bytes, 16);
3109                         status = GUID_from_data_blob(&blob1, &server_guid);
3110                         if (tevent_req_nterror(req, status)) {
3111                                 return;
3112                         }
3113
3114                         blob1 = data_blob_const(bytes+16, num_bytes-16);
3115                         blob2 = data_blob_dup_talloc(state, blob1);
3116                         if (blob1.length > 0 &&
3117                             tevent_req_nomem(blob2.data, req)) {
3118                                 return;
3119                         }
3120                         server_gss_blob = blob2;
3121                 } else {
3122                         DATA_BLOB blob1, blob2;
3123
3124                         if (num_bytes < key_len) {
3125                                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3126                                 return;
3127                         }
3128
3129                         if (key_len != 0 && key_len != 8) {
3130                                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3131                                 return;
3132                         }
3133
3134                         if (key_len == 8) {
3135                                 memcpy(server_challenge, bytes, 8);
3136                         }
3137
3138                         blob1 = data_blob_const(bytes+key_len, num_bytes-key_len);
3139                         blob2 = data_blob_const(bytes+key_len, num_bytes-key_len);
3140                         if (blob1.length > 0) {
3141                                 size_t len;
3142
3143                                 len = utf16_len_n(blob1.data,
3144                                                   blob1.length);
3145                                 blob1.length = len;
3146
3147                                 ok = convert_string_talloc(state,
3148                                                            CH_UTF16LE,
3149                                                            CH_UNIX,
3150                                                            blob1.data,
3151                                                            blob1.length,
3152                                                            &server_workgroup,
3153                                                            &len);
3154                                 if (!ok) {
3155                                         status = map_nt_error_from_unix_common(errno);
3156                                         tevent_req_nterror(req, status);
3157                                         return;
3158                                 }
3159                         }
3160
3161                         blob2.data += blob1.length;
3162                         blob2.length -= blob1.length;
3163                         if (blob2.length > 0) {
3164                                 size_t len;
3165
3166                                 len = utf16_len_n(blob1.data,
3167                                                   blob1.length);
3168                                 blob1.length = len;
3169
3170                                 ok = convert_string_talloc(state,
3171                                                            CH_UTF16LE,
3172                                                            CH_UNIX,
3173                                                            blob2.data,
3174                                                            blob2.length,
3175                                                            &server_name,
3176                                                            &len);
3177                                 if (!ok) {
3178                                         status = map_nt_error_from_unix_common(errno);
3179                                         tevent_req_nterror(req, status);
3180                                         return;
3181                                 }
3182                         }
3183                 }
3184
3185                 client_signing = "disabled";
3186                 if (conn->allow_signing) {
3187                         client_signing = "allowed";
3188                 }
3189                 if (conn->mandatory_signing) {
3190                         client_signing = "required";
3191                 }
3192
3193                 server_signing = "not supported";
3194                 if (server_security_mode & NEGOTIATE_SECURITY_SIGNATURES_ENABLED) {
3195                         server_signing = "supported";
3196                         server_allowed = true;
3197                 }
3198                 if (server_security_mode & NEGOTIATE_SECURITY_SIGNATURES_REQUIRED) {
3199                         server_signing = "required";
3200                         server_mandatory = true;
3201                 }
3202
3203                 ok = smb_signing_set_negotiated(conn->smb1.signing,
3204                                                 server_allowed,
3205                                                 server_mandatory);
3206                 if (!ok) {
3207                         DEBUG(1,("cli_negprot: SMB signing is required, "
3208                                  "but client[%s] and server[%s] mismatch\n",
3209                                  client_signing, server_signing));
3210                         tevent_req_nterror(req, NT_STATUS_ACCESS_DENIED);
3211                         return;
3212                 }
3213
3214         } else if (conn->protocol >= PROTOCOL_LANMAN1) {
3215                 DATA_BLOB blob1;
3216                 uint8_t key_len;
3217                 time_t t;
3218
3219                 if (wct != 0x0D) {
3220                         tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3221                         return;
3222                 }
3223
3224                 server_security_mode = SVAL(vwv + 1, 0);
3225                 server_max_xmit = SVAL(vwv + 2, 0);
3226                 server_max_mux = SVAL(vwv + 3, 0);
3227                 server_readbraw = ((SVAL(vwv + 5, 0) & 0x1) != 0);
3228                 server_writebraw = ((SVAL(vwv + 5, 0) & 0x2) != 0);
3229                 server_session_key = IVAL(vwv + 6, 0);
3230                 server_time_zone = SVALS(vwv + 10, 0);
3231                 server_time_zone *= 60;
3232                 /* this time is converted to GMT by make_unix_date */
3233                 t = pull_dos_date((const uint8_t *)(vwv + 8), server_time_zone);
3234                 unix_to_nt_time(&server_system_time, t);
3235                 key_len = SVAL(vwv + 11, 0);
3236
3237                 if (num_bytes < key_len) {
3238                         tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3239                         return;
3240                 }
3241
3242                 if (key_len != 0 && key_len != 8) {
3243                         tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3244                         return;
3245                 }
3246
3247                 if (key_len == 8) {
3248                         memcpy(server_challenge, bytes, 8);
3249                 }
3250
3251                 blob1 = data_blob_const(bytes+key_len, num_bytes-key_len);
3252                 if (blob1.length > 0) {
3253                         size_t len;
3254                         bool ok;
3255
3256                         len = utf16_len_n(blob1.data,
3257                                           blob1.length);
3258                         blob1.length = len;
3259
3260                         ok = convert_string_talloc(state,
3261                                                    CH_DOS,
3262                                                    CH_UNIX,
3263                                                    blob1.data,
3264                                                    blob1.length,
3265                                                    &server_workgroup,
3266                                                    &len);
3267                         if (!ok) {
3268                                 status = map_nt_error_from_unix_common(errno);
3269                                 tevent_req_nterror(req, status);
3270                                 return;
3271                         }
3272                 }
3273
3274         } else {
3275                 /* the old core protocol */
3276                 server_time_zone = get_time_zone(time(NULL));
3277                 server_max_xmit = 1024;
3278                 server_max_mux = 1;
3279         }
3280
3281         if (server_max_xmit < 1024) {
3282                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3283                 return;
3284         }
3285
3286         if (server_max_mux < 1) {
3287                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3288                 return;
3289         }
3290
3291         /*
3292          * Now calculate the negotiated capabilities
3293          * based on the mask for:
3294          * - client only flags
3295          * - flags used in both directions
3296          * - server only flags
3297          */
3298         both_capabilities = client_capabilities & server_capabilities;
3299         capabilities = client_capabilities & SMB_CAP_CLIENT_MASK;
3300         capabilities |= both_capabilities & SMB_CAP_BOTH_MASK;
3301         capabilities |= server_capabilities & SMB_CAP_SERVER_MASK;
3302
3303         max_xmit = MIN(client_max_xmit, server_max_xmit);
3304
3305         conn->smb1.server.capabilities = server_capabilities;
3306         conn->smb1.capabilities = capabilities;
3307
3308         conn->smb1.server.max_xmit = server_max_xmit;
3309         conn->smb1.max_xmit = max_xmit;
3310
3311         conn->smb1.server.max_mux = server_max_mux;
3312
3313         conn->smb1.server.security_mode = server_security_mode;
3314
3315         conn->smb1.server.readbraw = server_readbraw;
3316         conn->smb1.server.writebraw = server_writebraw;
3317         conn->smb1.server.lockread = server_lockread;
3318         conn->smb1.server.writeunlock = server_writeunlock;
3319
3320         conn->smb1.server.session_key = server_session_key;
3321
3322         talloc_steal(conn, server_gss_blob.data);
3323         conn->smb1.server.gss_blob = server_gss_blob;
3324         conn->smb1.server.guid = server_guid;
3325         memcpy(conn->smb1.server.challenge, server_challenge, 8);
3326         conn->smb1.server.workgroup = talloc_move(conn, &server_workgroup);
3327         conn->smb1.server.name = talloc_move(conn, &server_name);
3328
3329         conn->smb1.server.time_zone = server_time_zone;
3330         conn->smb1.server.system_time = server_system_time;
3331
3332         tevent_req_done(req);
3333 }
3334
3335 static struct tevent_req *smbXcli_negprot_smb2_subreq(struct smbXcli_negprot_state *state)
3336 {
3337         size_t i;
3338         uint8_t *buf;
3339         uint16_t dialect_count = 0;
3340
3341         buf = state->smb2.dyn;
3342         for (i=0; i < ARRAY_SIZE(smb2cli_prots); i++) {
3343                 if (smb2cli_prots[i].proto < state->min_protocol) {
3344                         continue;
3345                 }
3346
3347                 if (smb2cli_prots[i].proto > state->max_protocol) {
3348                         continue;
3349                 }
3350
3351                 SSVAL(buf, dialect_count*2, smb2cli_prots[i].smb2_dialect);
3352                 dialect_count++;
3353         }
3354
3355         buf = state->smb2.fixed;
3356         SSVAL(buf, 0, 36);
3357         SSVAL(buf, 2, dialect_count);
3358         SSVAL(buf, 4, state->conn->smb2.client.security_mode);
3359         SSVAL(buf, 6, 0);       /* Reserved */
3360         SSVAL(buf, 8, 0);       /* Capabilities */
3361         if (state->max_protocol >= PROTOCOL_SMB2_10) {
3362                 NTSTATUS status;
3363                 DATA_BLOB blob;
3364
3365                 status = GUID_to_ndr_blob(&state->conn->smb2.client.guid,
3366                                           state, &blob);
3367                 if (!NT_STATUS_IS_OK(status)) {
3368                         return NULL;
3369                 }
3370                 memcpy(buf+12, blob.data, 16); /* ClientGuid */
3371         } else {
3372                 memset(buf+12, 0, 16);  /* ClientGuid */
3373         }
3374         SBVAL(buf, 28, 0);      /* ClientStartTime */
3375
3376         return smb2cli_req_send(state, state->ev,
3377                                 state->conn, SMB2_OP_NEGPROT,
3378                                 0, 0, /* flags */
3379                                 state->timeout_msec,
3380                                 0xFEFF, 0, NULL, /* pid, tid, session */
3381                                 state->smb2.fixed, sizeof(state->smb2.fixed),
3382                                 state->smb2.dyn, dialect_count*2);
3383 }
3384
3385 static void smbXcli_negprot_smb2_done(struct tevent_req *subreq)
3386 {
3387         struct tevent_req *req =
3388                 tevent_req_callback_data(subreq,
3389                 struct tevent_req);
3390         struct smbXcli_negprot_state *state =
3391                 tevent_req_data(req,
3392                 struct smbXcli_negprot_state);
3393         struct smbXcli_conn *conn = state->conn;
3394         size_t security_offset, security_length;
3395         DATA_BLOB blob;
3396         NTSTATUS status;
3397         struct iovec *iov;
3398         uint8_t *body;
3399         size_t i;
3400         uint16_t dialect_revision;
3401         static const struct smb2cli_req_expected_response expected[] = {
3402         {
3403                 .status = NT_STATUS_OK,
3404                 .body_size = 0x41
3405         }
3406         };
3407
3408         status = smb2cli_req_recv(subreq, state, &iov,
3409                                   expected, ARRAY_SIZE(expected));
3410         TALLOC_FREE(subreq);
3411         if (tevent_req_nterror(req, status)) {
3412                 return;
3413         }
3414
3415         body = (uint8_t *)iov[1].iov_base;
3416
3417         dialect_revision = SVAL(body, 4);
3418
3419         for (i=0; i < ARRAY_SIZE(smb2cli_prots); i++) {
3420                 if (smb2cli_prots[i].proto < state->min_protocol) {
3421                         continue;
3422                 }
3423
3424                 if (smb2cli_prots[i].proto > state->max_protocol) {
3425                         continue;
3426                 }
3427
3428                 if (smb2cli_prots[i].smb2_dialect != dialect_revision) {
3429                         continue;
3430                 }
3431
3432                 conn->protocol = smb2cli_prots[i].proto;
3433                 break;
3434         }
3435
3436         if (conn->protocol == PROTOCOL_NONE) {
3437                 if (state->min_protocol >= PROTOCOL_SMB2_02) {
3438                         tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3439                         return;
3440                 }
3441
3442                 if (dialect_revision != SMB2_DIALECT_REVISION_2FF) {
3443                         tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3444                         return;
3445                 }
3446
3447                 /* make sure we do not loop forever */
3448                 state->min_protocol = PROTOCOL_SMB2_02;
3449
3450                 /*
3451                  * send a SMB2 negprot, in order to negotiate
3452                  * the SMB2 dialect. This needs to use the
3453                  * message id 1.
3454                  */
3455                 state->conn->smb2.mid = 1;
3456                 subreq = smbXcli_negprot_smb2_subreq(state);
3457                 if (tevent_req_nomem(subreq, req)) {
3458                         return;
3459                 }
3460                 tevent_req_set_callback(subreq, smbXcli_negprot_smb2_done, req);
3461                 return;
3462         }
3463
3464         conn->smb2.server.security_mode = SVAL(body, 2);
3465
3466         blob = data_blob_const(body + 8, 16);
3467         status = GUID_from_data_blob(&blob, &conn->smb2.server.guid);
3468         if (tevent_req_nterror(req, status)) {
3469                 return;
3470         }
3471
3472         conn->smb2.server.capabilities  = IVAL(body, 24);
3473         conn->smb2.server.max_trans_size= IVAL(body, 28);
3474         conn->smb2.server.max_read_size = IVAL(body, 32);
3475         conn->smb2.server.max_write_size= IVAL(body, 36);
3476         conn->smb2.server.system_time   = BVAL(body, 40);
3477         conn->smb2.server.start_time    = BVAL(body, 48);
3478
3479         security_offset = SVAL(body, 56);
3480         security_length = SVAL(body, 58);
3481
3482         if (security_offset != SMB2_HDR_BODY + iov[1].iov_len) {
3483                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3484                 return;
3485         }
3486
3487         if (security_length > iov[2].iov_len) {
3488                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3489                 return;
3490         }
3491
3492         conn->smb2.server.gss_blob = data_blob_talloc(conn,
3493                                                 iov[2].iov_base,
3494                                                 security_length);
3495         if (tevent_req_nomem(conn->smb2.server.gss_blob.data, req)) {
3496                 return;
3497         }
3498
3499         tevent_req_done(req);
3500 }
3501
3502 static NTSTATUS smbXcli_negprot_dispatch_incoming(struct smbXcli_conn *conn,
3503                                                   TALLOC_CTX *tmp_mem,
3504                                                   uint8_t *inbuf)
3505 {
3506         size_t num_pending = talloc_array_length(conn->pending);
3507         struct tevent_req *subreq;
3508         struct smbXcli_req_state *substate;
3509         struct tevent_req *req;
3510         struct smbXcli_negprot_state *state;
3511         uint32_t protocol_magic = IVAL(inbuf, 4);
3512
3513         if (num_pending != 1) {
3514                 return NT_STATUS_INTERNAL_ERROR;
3515         }
3516
3517         subreq = conn->pending[0];
3518         substate = tevent_req_data(subreq, struct smbXcli_req_state);
3519         req = tevent_req_callback_data(subreq, struct tevent_req);
3520         state = tevent_req_data(req, struct smbXcli_negprot_state);
3521
3522         switch (protocol_magic) {
3523         case SMB_MAGIC:
3524                 tevent_req_set_callback(subreq, smbXcli_negprot_smb1_done, req);
3525                 conn->dispatch_incoming = smb1cli_conn_dispatch_incoming;
3526                 return smb1cli_conn_dispatch_incoming(conn, tmp_mem, inbuf);
3527
3528         case SMB2_MAGIC:
3529                 if (substate->smb2.recv_iov == NULL) {
3530                         /*
3531                          * For the SMB1 negprot we have move it.
3532                          */
3533                         substate->smb2.recv_iov = substate->smb1.recv_iov;
3534                         substate->smb1.recv_iov = NULL;
3535                 }
3536
3537                 tevent_req_set_callback(subreq, smbXcli_negprot_smb2_done, req);
3538                 conn->dispatch_incoming = smb2cli_conn_dispatch_incoming;
3539                 return smb2cli_conn_dispatch_incoming(conn, tmp_mem, inbuf);
3540         }
3541
3542         DEBUG(10, ("Got non-SMB PDU\n"));
3543         return NT_STATUS_INVALID_NETWORK_RESPONSE;
3544 }
3545
3546 NTSTATUS smbXcli_negprot_recv(struct tevent_req *req)
3547 {
3548         return tevent_req_simple_recv_ntstatus(req);
3549 }
3550
3551 NTSTATUS smbXcli_negprot(struct smbXcli_conn *conn,
3552                          uint32_t timeout_msec,
3553                          enum protocol_types min_protocol,
3554                          enum protocol_types max_protocol)
3555 {
3556         TALLOC_CTX *frame = talloc_stackframe();
3557         struct tevent_context *ev;
3558         struct tevent_req *req;
3559         NTSTATUS status = NT_STATUS_NO_MEMORY;
3560         bool ok;
3561
3562         if (smbXcli_conn_has_async_calls(conn)) {
3563                 /*
3564                  * Can't use sync call while an async call is in flight
3565                  */
3566                 status = NT_STATUS_INVALID_PARAMETER_MIX;
3567                 goto fail;
3568         }
3569         ev = tevent_context_init(frame);
3570         if (ev == NULL) {
3571                 goto fail;
3572         }
3573         req = smbXcli_negprot_send(frame, ev, conn, timeout_msec,
3574                                    min_protocol, max_protocol);
3575         if (req == NULL) {
3576                 goto fail;
3577         }
3578         ok = tevent_req_poll(req, ev);
3579         if (!ok) {
3580                 status = map_nt_error_from_unix_common(errno);
3581                 goto fail;
3582         }
3583         status = smbXcli_negprot_recv(req);
3584  fail:
3585         TALLOC_FREE(frame);
3586         return status;
3587 }
3588
3589 static int smbXcli_session_destructor(struct smbXcli_session *session)
3590 {
3591         if (session->conn == NULL) {
3592                 return 0;
3593         }
3594
3595         DLIST_REMOVE(session->conn->sessions, session);
3596         return 0;
3597 }
3598
3599 struct smbXcli_session *smbXcli_session_create(TALLOC_CTX *mem_ctx,
3600                                                struct smbXcli_conn *conn)
3601 {
3602         struct smbXcli_session *session;
3603
3604         session = talloc_zero(mem_ctx, struct smbXcli_session);
3605         if (session == NULL) {
3606                 return NULL;
3607         }
3608         talloc_set_destructor(session, smbXcli_session_destructor);
3609
3610         DLIST_ADD_END(conn->sessions, session, struct smbXcli_session *);
3611         session->conn = conn;
3612
3613         return session;
3614 }
3615
3616 uint8_t smb2cli_session_security_mode(struct smbXcli_session *session)
3617 {
3618         struct smbXcli_conn *conn = session->conn;
3619         uint8_t security_mode = 0;
3620
3621         if (conn == NULL) {
3622                 return security_mode;
3623         }
3624
3625         security_mode = SMB2_NEGOTIATE_SIGNING_ENABLED;
3626         if (conn->mandatory_signing) {
3627                 security_mode |= SMB2_NEGOTIATE_SIGNING_REQUIRED;
3628         }
3629
3630         return security_mode;
3631 }
3632
3633 uint64_t smb2cli_session_current_id(struct smbXcli_session *session)
3634 {
3635         return session->smb2.session_id;
3636 }
3637
3638 void smb2cli_session_set_id_and_flags(struct smbXcli_session *session,
3639                                       uint64_t session_id,
3640                                       uint16_t session_flags)
3641 {
3642         session->smb2.session_id = session_id;
3643         session->smb2.session_flags = session_flags;
3644 }
3645
3646 NTSTATUS smb2cli_session_update_session_key(struct smbXcli_session *session,
3647                                             const DATA_BLOB session_key,
3648                                             const struct iovec *recv_iov)
3649 {
3650         struct smbXcli_conn *conn = session->conn;
3651         uint16_t no_sign_flags;
3652         DATA_BLOB signing_key;
3653         NTSTATUS status;
3654
3655         if (conn == NULL) {
3656                 return NT_STATUS_INVALID_PARAMETER_MIX;
3657         }
3658
3659         no_sign_flags = SMB2_SESSION_FLAG_IS_GUEST | SMB2_SESSION_FLAG_IS_NULL;
3660
3661         if (session->smb2.session_flags & no_sign_flags) {
3662                 session->smb2.should_sign = false;
3663                 return NT_STATUS_OK;
3664         }
3665
3666         if (session->smb2.signing_key.length > 0) {
3667                 signing_key = session->smb2.signing_key;
3668         } else {
3669                 signing_key = session_key;
3670         }
3671         if (session->smb2.channel_setup) {
3672                 signing_key = session_key;
3673         }
3674
3675         status = smb2_signing_check_pdu(signing_key, recv_iov, 3);
3676         if (!NT_STATUS_IS_OK(status)) {
3677                 return status;
3678         }
3679
3680         if (!session->smb2.channel_setup) {
3681                 session->smb2.session_key = data_blob_dup_talloc(session,
3682                                                                  session_key);
3683                 if (session->smb2.session_key.data == NULL) {
3684                         return NT_STATUS_NO_MEMORY;
3685                 }
3686         }
3687
3688         if (session->smb2.channel_setup) {
3689                 data_blob_free(&session->smb2.signing_key);
3690                 session->smb2.channel_setup = false;
3691         }
3692
3693         if (session->smb2.signing_key.length > 0) {
3694                 return NT_STATUS_OK;
3695         }
3696
3697         session->smb2.signing_key = data_blob_dup_talloc(session, signing_key);
3698         if (session->smb2.signing_key.data == NULL) {
3699                 return NT_STATUS_NO_MEMORY;
3700         }
3701
3702         session->smb2.should_sign = false;
3703
3704         if (conn->desire_signing) {
3705                 session->smb2.should_sign = true;
3706         }
3707
3708         if (conn->smb2.server.security_mode & SMB2_NEGOTIATE_SIGNING_REQUIRED) {
3709                 session->smb2.should_sign = true;
3710         }
3711
3712         return NT_STATUS_OK;
3713 }
3714
3715 NTSTATUS smb2cli_session_create_channel(TALLOC_CTX *mem_ctx,
3716                                         struct smbXcli_session *session1,
3717                                         struct smbXcli_conn *conn,
3718                                         struct smbXcli_session **_session2)
3719 {
3720         struct smbXcli_session *session2;
3721         uint16_t no_sign_flags;
3722
3723         no_sign_flags = SMB2_SESSION_FLAG_IS_GUEST | SMB2_SESSION_FLAG_IS_NULL;
3724
3725         if (session1->smb2.session_flags & no_sign_flags) {
3726                 return NT_STATUS_INVALID_PARAMETER_MIX;
3727         }
3728
3729         if (session1->smb2.session_key.length == 0) {
3730                 return NT_STATUS_INVALID_PARAMETER_MIX;
3731         }
3732
3733         if (session1->smb2.signing_key.length == 0) {
3734                 return NT_STATUS_INVALID_PARAMETER_MIX;
3735         }
3736
3737         if (conn == NULL) {
3738                 return NT_STATUS_INVALID_PARAMETER_MIX;
3739         }
3740
3741         session2 = talloc_zero(mem_ctx, struct smbXcli_session);
3742         if (session2 == NULL) {
3743                 return NT_STATUS_NO_MEMORY;
3744         }
3745         session2->smb2.session_id = session1->smb2.session_id;
3746         session2->smb2.session_flags = session1->smb2.session_flags;
3747
3748         session2->smb2.session_key = data_blob_dup_talloc(session2,
3749                                                 session1->smb2.session_key);
3750         if (session2->smb2.session_key.data == NULL) {
3751                 return NT_STATUS_NO_MEMORY;
3752         }
3753
3754         session2->smb2.signing_key = data_blob_dup_talloc(session2,
3755                                                 session1->smb2.signing_key);
3756         if (session2->smb2.signing_key.data == NULL) {
3757                 return NT_STATUS_NO_MEMORY;
3758         }
3759
3760         session2->smb2.should_sign = session1->smb2.should_sign;
3761         session2->smb2.channel_setup = true;
3762
3763         talloc_set_destructor(session2, smbXcli_session_destructor);
3764         DLIST_ADD_END(conn->sessions, session2, struct smbXcli_session *);
3765         session2->conn = conn;
3766
3767         *_session2 = session2;
3768         return NT_STATUS_OK;
3769 }