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