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