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