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