notifyd: Use messaging_register for MSG_SMB_NOTIFY_GET_DB
[vlendec/samba-autobuild/.git] / source3 / smbd / smb2_server.c
index 432b866531f1125fdda38ce02eb949f37884ba63..d95631f2ff4d56407f0a59450ea28bcdceb6ede9 100644 (file)
@@ -30,6 +30,7 @@
 #include "../librpc/gen_ndr/krb5pac.h"
 #include "lib/util/iov_buf.h"
 #include "auth.h"
+#include "lib/crypto/sha512.h"
 
 static void smbd_smb2_connection_handler(struct tevent_context *ev,
                                         struct tevent_fd *fde,
@@ -45,6 +46,7 @@ static const struct smbd_smb2_dispatch_table {
        bool as_root;
        uint16_t fileid_ofs;
        bool allow_invalid_fileid;
+       bool modify;
 } smbd_smb2_table[] = {
 #define _OP(o) .opcode = o, .name = #o
        {
@@ -97,6 +99,7 @@ static const struct smbd_smb2_dispatch_table {
                .need_session = true,
                .need_tcon = true,
                .fileid_ofs = 0x10,
+               .modify = true,
        },{
                _OP(SMB2_OP_LOCK),
                .need_session = true,
@@ -108,6 +111,7 @@ static const struct smbd_smb2_dispatch_table {
                .need_tcon = true,
                .fileid_ofs = 0x08,
                .allow_invalid_fileid = true,
+               .modify = true,
        },{
                _OP(SMB2_OP_CANCEL),
                .as_root = true,
@@ -115,7 +119,7 @@ static const struct smbd_smb2_dispatch_table {
                _OP(SMB2_OP_KEEPALIVE),
                .as_root = true,
        },{
-               _OP(SMB2_OP_FIND),
+               _OP(SMB2_OP_QUERY_DIRECTORY),
                .need_session = true,
                .need_tcon = true,
                .fileid_ofs = 0x08,
@@ -134,6 +138,7 @@ static const struct smbd_smb2_dispatch_table {
                .need_session = true,
                .need_tcon = true,
                .fileid_ofs = 0x10,
+               .modify = true,
        },{
                _OP(SMB2_OP_BREAK),
                .need_session = true,
@@ -199,11 +204,12 @@ bool smbd_is_smb2_header(const uint8_t *inbuf, size_t size)
        return true;
 }
 
-static NTSTATUS smbd_initialize_smb2(struct smbXsrv_connection *xconn)
+static NTSTATUS smbd_initialize_smb2(struct smbXsrv_connection *xconn,
+                                    uint64_t expected_seq_low)
 {
        TALLOC_FREE(xconn->transport.fde);
 
-       xconn->smb2.credits.seq_low = 0;
+       xconn->smb2.credits.seq_low = expected_seq_low;
        xconn->smb2.credits.seq_range = 1;
        xconn->smb2.credits.granted = 1;
        xconn->smb2.credits.max = lp_smb2_max_credits();
@@ -266,6 +272,12 @@ static int smbd_smb2_request_destructor(struct smbd_smb2_request *req)
        return 0;
 }
 
+void smb2_request_set_async_internal(struct smbd_smb2_request *req,
+                                    bool async_internal)
+{
+       req->async_internal = async_internal;
+}
+
 static struct smbd_smb2_request *smbd_smb2_request_allocate(TALLOC_CTX *mem_ctx)
 {
        TALLOC_CTX *mem_pool;
@@ -392,7 +404,8 @@ static NTSTATUS smbd_smb2_inbuf_parse_compound(struct smbXsrv_connection *xconn,
                                goto inval;
                        }
 
-                       status = smb2srv_session_lookup(xconn, uid, now, &s);
+                       status = smb2srv_session_lookup_conn(xconn, uid, now,
+                                                            &s);
                        if (s == NULL) {
                                DEBUG(1, ("invalid session[%llu] in "
                                          "SMB2_TRANSFORM header\n",
@@ -1047,7 +1060,7 @@ static NTSTATUS smbd_smb2_request_setup_out(struct smbd_smb2_request *req)
                return NT_STATUS_INVALID_PARAMETER_MIX;
        }
 
-       DLIST_ADD_END(xconn->smb2.requests, req, struct smbd_smb2_request *);
+       DLIST_ADD_END(xconn->smb2.requests, req);
 
        return NT_STATUS_OK;
 }
@@ -1056,8 +1069,21 @@ void smbd_server_connection_terminate_ex(struct smbXsrv_connection *xconn,
                                         const char *reason,
                                         const char *location)
 {
-       DEBUG(10,("smbd_server_connection_terminate_ex: reason[%s] at %s\n",
-                 reason, location));
+       struct smbXsrv_client *client = xconn->client;
+
+       DEBUG(10,("smbd_server_connection_terminate_ex: conn[%s] reason[%s] at %s\n",
+                 smbXsrv_connection_dbg(xconn), reason, location));
+
+       if (client->connections->next != NULL) {
+               /* TODO: cancel pending requests */
+               DLIST_REMOVE(client->connections, xconn);
+               TALLOC_FREE(xconn);
+               return;
+       }
+
+       /*
+        * The last connection was disconnected
+        */
        exit_server_cleanly(reason);
 }
 
@@ -1288,7 +1314,7 @@ static NTSTATUS smb2_send_async_interim_response(const struct smbd_smb2_request
        nreq->queue_entry.mem_ctx = nreq;
        nreq->queue_entry.vector = nreq->out.vector;
        nreq->queue_entry.count = nreq->out.vector_count;
-       DLIST_ADD_END(xconn->smb2.send_queue, &nreq->queue_entry, NULL);
+       DLIST_ADD_END(xconn->smb2.send_queue, &nreq->queue_entry);
        xconn->smb2.send_queue_len++;
 
        status = smbd_smb2_flush_send_queue(xconn);
@@ -1345,14 +1371,24 @@ NTSTATUS smbd_smb2_request_pending_queue(struct smbd_smb2_request *req,
                return NT_STATUS_OK;
        }
 
+       if (req->async_internal) {
+               /*
+                * An SMB2 request implementation wants to handle the request
+                * asynchronously "internally" while keeping synchronous
+                * behaviour for the SMB2 request. This means we don't send an
+                * interim response and we can allow processing of compound SMB2
+                * requests (cf the subsequent check) for all cases.
+                */
+               return NT_STATUS_OK;
+       }
+
        if (req->in.vector_count > req->current_idx + SMBD_SMB2_NUM_IOV_PER_REQ) {
                /*
-                * We're trying to go async in a compound
-                * request chain.
-                * This is only allowed for opens that
-                * cause an oplock break, otherwise it
-                * is not allowed. See [MS-SMB2].pdf
-                * note <194> on Section 3.3.5.2.7.
+                * We're trying to go async in a compound request
+                * chain. This is only allowed for opens that cause an
+                * oplock break or for the last operation in the
+                * chain, otherwise it is not allowed. See
+                * [MS-SMB2].pdf note <206> on Section 3.3.5.2.7.
                 */
                const uint8_t *inhdr = SMBD_SMB2_IN_HDR_PTR(req);
 
@@ -1458,6 +1494,41 @@ static DATA_BLOB smbd_smb2_signing_key(struct smbXsrv_session *session,
        return key;
 }
 
+static NTSTATUS smb2_get_new_nonce(struct smbXsrv_session *session,
+                                  uint64_t *new_nonce_high,
+                                  uint64_t *new_nonce_low)
+{
+       uint64_t nonce_high;
+       uint64_t nonce_low;
+
+       session->nonce_low += 1;
+       if (session->nonce_low == 0) {
+               session->nonce_low += 1;
+               session->nonce_high += 1;
+       }
+
+       /*
+        * CCM and GCM algorithms must never have their
+        * nonce wrap, or the security of the whole
+        * communication and the keys is destroyed.
+        * We must drop the connection once we have
+        * transfered too much data.
+        *
+        * NOTE: We assume nonces greater than 8 bytes.
+        */
+       if (session->nonce_high >= session->nonce_high_max) {
+               return NT_STATUS_ENCRYPTION_FAILED;
+       }
+
+       nonce_high = session->nonce_high_random;
+       nonce_high += session->nonce_high;
+       nonce_low = session->nonce_low;
+
+       *new_nonce_high = nonce_high;
+       *new_nonce_low = nonce_low;
+       return NT_STATUS_OK;
+}
+
 static void smbd_smb2_request_pending_timer(struct tevent_context *ev,
                                            struct tevent_timer *te,
                                            struct timeval current_time,
@@ -1524,15 +1595,13 @@ static void smbd_smb2_request_pending_timer(struct tevent_context *ev,
        dyn = body + 8;
 
        if (req->do_encryption) {
-               struct smbXsrv_session *x = req->session;
-
-               nonce_high = x->nonce_high;
-               nonce_low = x->nonce_low;
-
-               x->nonce_low += 1;
-               if (x->nonce_low == 0) {
-                       x->nonce_low += 1;
-                       x->nonce_high += 1;
+               status = smb2_get_new_nonce(req->session,
+                                           &nonce_high,
+                                           &nonce_low);
+               if (!NT_STATUS_IS_OK(status)) {
+                       smbd_server_connection_terminate(xconn,
+                                                        nt_errstr(status));
+                       return;
                }
        }
 
@@ -1643,7 +1712,7 @@ static void smbd_smb2_request_pending_timer(struct tevent_context *ev,
        state->queue_entry.mem_ctx = state;
        state->queue_entry.vector = state->vector;
        state->queue_entry.count = ARRAY_SIZE(state->vector);
-       DLIST_ADD_END(xconn->smb2.send_queue, &state->queue_entry, NULL);
+       DLIST_ADD_END(xconn->smb2.send_queue, &state->queue_entry);
        xconn->smb2.send_queue_len++;
 
        status = smbd_smb2_flush_send_queue(xconn);
@@ -1671,11 +1740,12 @@ static NTSTATUS smbd_smb2_request_process_cancel(struct smbd_smb2_request *req)
        search_async_id = BVAL(inhdr, SMB2_HDR_PID);
 
        /*
-        * we don't need the request anymore
-        * cancel requests never have a response
+        * We don't need the request anymore cancel requests never
+        * have a response.
+        *
+        * We defer the TALLOC_FREE(req) to the caller.
         */
        DLIST_REMOVE(xconn->smb2.requests, req);
-       TALLOC_FREE(req);
 
        for (cur = xconn->smb2.requests; cur; cur = cur->next) {
                const uint8_t *outhdr;
@@ -1758,7 +1828,6 @@ static NTSTATUS smbd_smb2_request_check_tcon(struct smbd_smb2_request *req)
                return NT_STATUS_ACCESS_DENIED;
        }
 
-       /* should we pass FLAG_CASELESS_PATHNAMES here? */
        if (!set_current_service(tcon->compat, 0, true)) {
                return NT_STATUS_ACCESS_DENIED;
        }
@@ -1799,10 +1868,26 @@ static NTSTATUS smbd_smb2_request_check_session(struct smbd_smb2_request *req)
 
        req->last_session_id = 0;
 
-       /* lookup an existing session */
-       status = smb2srv_session_lookup(req->xconn,
-                                       in_session_id, now,
-                                       &session);
+       /* look an existing session up */
+       switch (in_opcode) {
+       case SMB2_OP_SESSSETUP:
+               /*
+                * For a session bind request, we don't have the
+                * channel set up at this point yet, so we defer
+                * the verification that the connection belongs
+                * to the session to the session setup code, which
+                * can look at the session binding flags.
+                */
+               status = smb2srv_session_lookup_client(req->xconn->client,
+                                                      in_session_id, now,
+                                                      &session);
+               break;
+       default:
+               status = smb2srv_session_lookup_conn(req->xconn,
+                                                    in_session_id, now,
+                                                    &session);
+               break;
+       }
        if (session) {
                req->session = session;
                req->last_session_id = in_session_id;
@@ -1952,6 +2037,211 @@ NTSTATUS smbd_smb2_request_verify_sizes(struct smbd_smb2_request *req,
        return NT_STATUS_OK;
 }
 
+bool smbXsrv_is_encrypted(uint8_t encryption_flags)
+{
+       return (!(encryption_flags & SMBXSRV_PROCESSED_UNENCRYPTED_PACKET)
+               &&
+               (encryption_flags & (SMBXSRV_PROCESSED_ENCRYPTED_PACKET |
+                                    SMBXSRV_ENCRYPTION_DESIRED |
+                                    SMBXSRV_ENCRYPTION_REQUIRED)));
+}
+
+bool smbXsrv_is_partially_encrypted(uint8_t encryption_flags)
+{
+       return ((encryption_flags & SMBXSRV_PROCESSED_ENCRYPTED_PACKET) &&
+               (encryption_flags & SMBXSRV_PROCESSED_UNENCRYPTED_PACKET));
+}
+
+/* Set a flag if not already set, return true if set */
+bool smbXsrv_set_crypto_flag(uint8_t *flags, uint8_t flag)
+{
+       if ((flag == 0) || (*flags & flag)) {
+               return false;
+       }
+
+       *flags |= flag;
+       return true;
+}
+
+/*
+ * Update encryption state tracking flags, this can be used to
+ * determine whether whether the session or tcon is "encrypted".
+ */
+static void smb2srv_update_crypto_flags(struct smbd_smb2_request *req,
+                                       uint16_t opcode,
+                                       bool *update_session_globalp,
+                                       bool *update_tcon_globalp)
+{
+       /* Default: assume unecrypted and unsigned */
+       struct smbXsrv_session *session = req->session;
+       struct smbXsrv_tcon *tcon = req->tcon;
+       uint8_t encrypt_flag = SMBXSRV_PROCESSED_UNENCRYPTED_PACKET;
+       uint8_t sign_flag = SMBXSRV_PROCESSED_UNSIGNED_PACKET;
+       bool update_session = false;
+       bool update_tcon = false;
+
+       if (req->was_encrypted && req->do_encryption) {
+               encrypt_flag = SMBXSRV_PROCESSED_ENCRYPTED_PACKET;
+               sign_flag = SMBXSRV_PROCESSED_SIGNED_PACKET;
+       } else {
+               /* Unencrypted packet, can be signed */
+               if (req->do_signing) {
+                       sign_flag = SMBXSRV_PROCESSED_SIGNED_PACKET;
+               } else if (opcode == SMB2_OP_CANCEL) {
+                       /* Cancel requests are allowed to skip signing */
+                       sign_flag &= ~SMBXSRV_PROCESSED_UNSIGNED_PACKET;
+               }
+       }
+
+       update_session |= smbXsrv_set_crypto_flag(
+               &session->global->encryption_flags, encrypt_flag);
+       update_session |= smbXsrv_set_crypto_flag(
+               &session->global->signing_flags, sign_flag);
+
+       if (tcon) {
+               update_tcon |= smbXsrv_set_crypto_flag(
+                       &tcon->global->encryption_flags, encrypt_flag);
+               update_tcon |= smbXsrv_set_crypto_flag(
+                       &tcon->global->signing_flags, sign_flag);
+       }
+
+       *update_session_globalp = update_session;
+       *update_tcon_globalp = update_tcon;
+       return;
+}
+
+bool smbXsrv_is_signed(uint8_t signing_flags)
+{
+       /*
+        * Signing is always enabled, so unless we got an unsigned
+        * packet and at least one signed packet that was not
+        * encrypted, the session or tcon is "signed".
+        */
+       return (!(signing_flags & SMBXSRV_PROCESSED_UNSIGNED_PACKET) &&
+               (signing_flags & SMBXSRV_PROCESSED_SIGNED_PACKET));
+}
+
+bool smbXsrv_is_partially_signed(uint8_t signing_flags)
+{
+       return ((signing_flags & SMBXSRV_PROCESSED_UNSIGNED_PACKET) &&
+               (signing_flags & SMBXSRV_PROCESSED_SIGNED_PACKET));
+}
+
+static NTSTATUS smbd_smb2_request_dispatch_update_counts(
+                               struct smbd_smb2_request *req,
+                               bool modify_call)
+{
+       struct smbXsrv_connection *xconn = req->xconn;
+       const uint8_t *inhdr;
+       uint16_t channel_sequence;
+       uint32_t flags;
+       int cmp;
+       struct smbXsrv_open *op;
+       bool update_open = false;
+       NTSTATUS status = NT_STATUS_OK;
+
+       req->request_counters_updated = false;
+
+       if (xconn->protocol < PROTOCOL_SMB2_22) {
+               return NT_STATUS_OK;
+       }
+
+       if (req->compat_chain_fsp == NULL) {
+               return NT_STATUS_OK;
+       }
+
+       op = req->compat_chain_fsp->op;
+       if (op == NULL) {
+               return NT_STATUS_OK;
+       }
+
+       inhdr = SMBD_SMB2_IN_HDR_PTR(req);
+       flags = IVAL(inhdr, SMB2_HDR_FLAGS);
+       channel_sequence = SVAL(inhdr, SMB2_HDR_CHANNEL_SEQUENCE);
+
+       cmp = channel_sequence - op->global->channel_sequence;
+
+       if (abs(cmp) > INT16_MAX) {
+               /*
+                * [MS-SMB2] 3.3.5.2.10 - Verifying the Channel Sequence Number:
+                *
+                * If the channel sequence number of the request and the one
+                * known to the server are not equal, the channel sequence
+                * number and outstanding request counts are only updated
+                * "... if the unsigned difference using 16-bit arithmetic
+                * between ChannelSequence and Open.ChannelSequence is less than
+                * or equal to 0x7FFF ...".
+                * Otherwise, an error is returned for the modifying
+                * calls write, set_info, and ioctl.
+                *
+                * There are currently two issues with the description:
+                *
+                * * For the other calls, the document seems to imply
+                *   that processing continues without adapting the
+                *   counters (if the sequence numbers are not equal).
+                *
+                *   TODO: This needs clarification!
+                *
+                * * Also, the behaviour if the difference is larger
+                *   than 0x7FFF is not clear. The document seems to
+                *   imply that if such a difference is reached,
+                *   the server starts to ignore the counters or
+                *   in the case of the modifying calls, return errors.
+                *
+                *   TODO: This needs clarification!
+                *
+                * At this point Samba tries to be a little more
+                * clever than the description in the MS-SMB2 document
+                * by heuristically detecting and properly treating
+                * a 16 bit overflow of the client-submitted sequence
+                * number:
+                *
+                * If the stored channel squence number is more than
+                * 0x7FFF larger than the one from the request, then
+                * the client-provided sequence number has likely
+                * overflown. We treat this case as valid instead
+                * of as failure.
+                *
+                * The MS-SMB2 behaviour would be setting cmp = -1.
+                */
+               cmp *= -1;
+       }
+
+       if (!(flags & SMB2_HDR_FLAG_REPLAY_OPERATION)) {
+               if (cmp == 0) {
+                       op->request_count += 1;
+                       req->request_counters_updated = true;
+               } else if (cmp > 0) {
+                       op->pre_request_count += op->request_count;
+                       op->request_count = 1;
+                       op->global->channel_sequence = channel_sequence;
+                       update_open = true;
+                       req->request_counters_updated = true;
+               } else if (modify_call) {
+                       return NT_STATUS_FILE_NOT_AVAILABLE;
+               }
+       } else {
+               if (cmp == 0 && op->pre_request_count == 0) {
+                       op->request_count += 1;
+                       req->request_counters_updated = true;
+               } else if (cmp > 0 && op->pre_request_count == 0) {
+                       op->pre_request_count += op->request_count;
+                       op->request_count = 1;
+                       op->global->channel_sequence = channel_sequence;
+                       update_open = true;
+                       req->request_counters_updated = true;
+               } else if (modify_call) {
+                       return NT_STATUS_FILE_NOT_AVAILABLE;
+               }
+       }
+
+       if (update_open) {
+               status = smbXsrv_open_update(op);
+       }
+
+       return status;
+}
+
 NTSTATUS smbd_smb2_request_dispatch(struct smbd_smb2_request *req)
 {
        struct smbXsrv_connection *xconn = req->xconn;
@@ -1967,6 +2257,7 @@ NTSTATUS smbd_smb2_request_dispatch(struct smbd_smb2_request *req)
        NTSTATUS return_value;
        struct smbXsrv_session *x = NULL;
        bool signing_required = false;
+       bool encryption_desired = false;
        bool encryption_required = false;
 
        inhdr = SMBD_SMB2_IN_HDR_PTR(req);
@@ -2013,12 +2304,15 @@ NTSTATUS smbd_smb2_request_dispatch(struct smbd_smb2_request *req)
        session_status = smbd_smb2_request_check_session(req);
        x = req->session;
        if (x != NULL) {
-               signing_required = x->global->signing_required;
-               encryption_required = x->global->encryption_required;
+               signing_required = x->global->signing_flags & SMBXSRV_SIGNING_REQUIRED;
+               encryption_desired = x->global->encryption_flags & SMBXSRV_ENCRYPTION_DESIRED;
+               encryption_required = x->global->encryption_flags & SMBXSRV_ENCRYPTION_REQUIRED;
        }
 
+       req->async_internal = false;
        req->do_signing = false;
        req->do_encryption = false;
+       req->was_encrypted = false;
        if (intf_v->iov_len == SMB2_TF_HDR_SIZE) {
                const uint8_t *intf = SMBD_SMB2_IN_TF_PTR(req);
                uint64_t tf_session_id = BVAL(intf, SMB2_TF_SESSION_ID);
@@ -2040,10 +2334,10 @@ NTSTATUS smbd_smb2_request_dispatch(struct smbd_smb2_request *req)
                                        NT_STATUS_ACCESS_DENIED);
                }
 
-               req->do_encryption = true;
+               req->was_encrypted = true;
        }
 
-       if (encryption_required && !req->do_encryption) {
+       if (encryption_required && !req->was_encrypted) {
                return smbd_smb2_request_error(req,
                                NT_STATUS_ACCESS_DENIED);
        }
@@ -2056,9 +2350,20 @@ NTSTATUS smbd_smb2_request_dispatch(struct smbd_smb2_request *req)
        allowed_flags = SMB2_HDR_FLAG_CHAINED |
                        SMB2_HDR_FLAG_SIGNED |
                        SMB2_HDR_FLAG_DFS;
+       if (xconn->protocol >= PROTOCOL_SMB3_11) {
+               allowed_flags |= SMB2_HDR_FLAG_PRIORITY_MASK;
+       }
+       if (opcode == SMB2_OP_NEGPROT) {
+               if (lp_server_max_protocol() >= PROTOCOL_SMB3_11) {
+                       allowed_flags |= SMB2_HDR_FLAG_PRIORITY_MASK;
+               }
+       }
        if (opcode == SMB2_OP_CANCEL) {
                allowed_flags |= SMB2_HDR_FLAG_ASYNC;
        }
+       if (xconn->protocol >= PROTOCOL_SMB2_22) {
+               allowed_flags |= SMB2_HDR_FLAG_REPLAY_OPERATION;
+       }
        if ((flags & ~allowed_flags) != 0) {
                return smbd_smb2_request_error(req, NT_STATUS_INVALID_PARAMETER);
        }
@@ -2075,7 +2380,7 @@ NTSTATUS smbd_smb2_request_dispatch(struct smbd_smb2_request *req)
                req->compat_chain_fsp = NULL;
        }
 
-       if (req->do_encryption) {
+       if (req->was_encrypted) {
                signing_required = false;
        } else if (signing_required || (flags & SMB2_HDR_FLAG_SIGNED)) {
                DATA_BLOB signing_key = data_blob_null;
@@ -2161,15 +2466,44 @@ NTSTATUS smbd_smb2_request_dispatch(struct smbd_smb2_request *req)
                if (!NT_STATUS_IS_OK(status)) {
                        return smbd_smb2_request_error(req, status);
                }
-               if (req->tcon->global->encryption_required) {
+               if (req->tcon->global->encryption_flags & SMBXSRV_ENCRYPTION_DESIRED) {
+                       encryption_desired = true;
+               }
+               if (req->tcon->global->encryption_flags & SMBXSRV_ENCRYPTION_REQUIRED) {
                        encryption_required = true;
                }
-               if (encryption_required && !req->do_encryption) {
+               if (encryption_required && !req->was_encrypted) {
                        return smbd_smb2_request_error(req,
                                NT_STATUS_ACCESS_DENIED);
                }
        }
 
+       if (req->was_encrypted || encryption_desired) {
+               req->do_encryption = true;
+       }
+
+       if (req->session) {
+               bool update_session_global = false;
+               bool update_tcon_global = false;
+
+               smb2srv_update_crypto_flags(req, opcode,
+                                           &update_session_global,
+                                           &update_tcon_global);
+
+               if (update_session_global) {
+                       status = smbXsrv_session_update(x);
+                       if (!NT_STATUS_IS_OK(status)) {
+                               return smbd_smb2_request_error(req, status);
+                       }
+               }
+               if (update_tcon_global) {
+                       status = smbXsrv_tcon_update(req->tcon);
+                       if (!NT_STATUS_IS_OK(status)) {
+                               return smbd_smb2_request_error(req, status);
+                       }
+               }
+       }
+
        if (call->fileid_ofs != 0) {
                size_t needed = call->fileid_ofs + 16;
                const uint8_t *body = SMBD_SMB2_IN_BODY_PTR(req);
@@ -2206,6 +2540,11 @@ NTSTATUS smbd_smb2_request_dispatch(struct smbd_smb2_request *req)
                }
        }
 
+       status = smbd_smb2_request_dispatch_update_counts(req, call->modify);
+       if (!NT_STATUS_IS_OK(status)) {
+               return smbd_smb2_request_error(req, status);
+       }
+
        if (call->as_root) {
                SMB_ASSERT(call->fileid_ofs == 0);
                /* This call needs to be run as root */
@@ -2299,6 +2638,16 @@ NTSTATUS smbd_smb2_request_dispatch(struct smbd_smb2_request *req)
                                               req->profile, _INBYTES(req));
                return_value = smbd_smb2_request_process_cancel(req);
                SMBPROFILE_IOBYTES_ASYNC_END(req->profile, 0);
+
+               /*
+                * We don't need the request anymore cancel requests never
+                * have a response.
+                *
+                * smbd_smb2_request_process_cancel() already called
+                * DLIST_REMOVE(xconn->smb2.requests, req);
+                */
+               TALLOC_FREE(req);
+
                break;
 
        case SMB2_OP_KEEPALIVE:
@@ -2307,10 +2656,10 @@ NTSTATUS smbd_smb2_request_dispatch(struct smbd_smb2_request *req)
                return_value = smbd_smb2_request_process_keepalive(req);
                break;
 
-       case SMB2_OP_FIND:
+       case SMB2_OP_QUERY_DIRECTORY:
                SMBPROFILE_IOBYTES_ASYNC_START(smb2_find, profile_p,
                                               req->profile, _INBYTES(req));
-               return_value = smbd_smb2_request_process_find(req);
+               return_value = smbd_smb2_request_process_query_directory(req);
                break;
 
        case SMB2_OP_NOTIFY:
@@ -2344,6 +2693,42 @@ NTSTATUS smbd_smb2_request_dispatch(struct smbd_smb2_request *req)
        return return_value;
 }
 
+static void smbd_smb2_request_reply_update_counts(struct smbd_smb2_request *req)
+{
+       struct smbXsrv_connection *xconn = req->xconn;
+       const uint8_t *inhdr;
+       uint16_t channel_sequence;
+       struct smbXsrv_open *op;
+
+       if (!req->request_counters_updated) {
+               return;
+       }
+
+       if (xconn->protocol < PROTOCOL_SMB2_22) {
+               return;
+       }
+
+       if (req->compat_chain_fsp == NULL) {
+               return;
+       }
+
+       op = req->compat_chain_fsp->op;
+       if (op == NULL) {
+               return;
+       }
+
+       inhdr = SMBD_SMB2_IN_HDR_PTR(req);
+       channel_sequence = SVAL(inhdr, SMB2_HDR_CHANNEL_SEQUENCE);
+
+       if (op->global->channel_sequence == channel_sequence) {
+               SMB_ASSERT(op->request_count > 0);
+               op->request_count -= 1;
+       } else {
+               SMB_ASSERT(op->pre_request_count > 0);
+               op->pre_request_count -= 1;
+       }
+}
+
 static NTSTATUS smbd_smb2_request_reply(struct smbd_smb2_request *req)
 {
        struct smbXsrv_connection *xconn = req->xconn;
@@ -2357,6 +2742,9 @@ static NTSTATUS smbd_smb2_request_reply(struct smbd_smb2_request *req)
        req->subreq = NULL;
        TALLOC_FREE(req->async_te);
 
+       /* MS-SMB2: 3.3.4.1 Sending Any Outgoing Message */
+       smbd_smb2_request_reply_update_counts(req);
+
        if (req->do_encryption &&
            (firsttf->iov_len == 0) &&
            (req->first_key.length == 0) &&
@@ -2366,17 +2754,14 @@ static NTSTATUS smbd_smb2_request_reply(struct smbd_smb2_request *req)
                DATA_BLOB encryption_key = req->session->global->encryption_key;
                uint8_t *tf;
                uint64_t session_id = req->session->global->session_wire_id;
-               struct smbXsrv_session *x = req->session;
                uint64_t nonce_high;
                uint64_t nonce_low;
 
-               nonce_high = x->nonce_high;
-               nonce_low = x->nonce_low;
-
-               x->nonce_low += 1;
-               if (x->nonce_low == 0) {
-                       x->nonce_low += 1;
-                       x->nonce_high += 1;
+               status = smb2_get_new_nonce(req->session,
+                                           &nonce_high,
+                                           &nonce_low);
+               if (!NT_STATUS_IS_OK(status)) {
+                       return status;
                }
 
                /*
@@ -2516,6 +2901,33 @@ static NTSTATUS smbd_smb2_request_reply(struct smbd_smb2_request *req)
                data_blob_clear_free(&req->first_key);
        }
 
+       if (req->preauth != NULL) {
+               struct hc_sha512state sctx;
+               int i;
+
+               samba_SHA512_Init(&sctx);
+               samba_SHA512_Update(&sctx, req->preauth->sha512_value,
+                                   sizeof(req->preauth->sha512_value));
+               for (i = 1; i < req->in.vector_count; i++) {
+                       samba_SHA512_Update(&sctx,
+                                           req->in.vector[i].iov_base,
+                                           req->in.vector[i].iov_len);
+               }
+               samba_SHA512_Final(req->preauth->sha512_value, &sctx);
+
+               samba_SHA512_Init(&sctx);
+               samba_SHA512_Update(&sctx, req->preauth->sha512_value,
+                                   sizeof(req->preauth->sha512_value));
+               for (i = 1; i < req->out.vector_count; i++) {
+                       samba_SHA512_Update(&sctx,
+                                           req->out.vector[i].iov_base,
+                                           req->out.vector[i].iov_len);
+               }
+               samba_SHA512_Final(req->preauth->sha512_value, &sctx);
+
+               req->preauth = NULL;
+       }
+
        /* I am a sick, sick man... :-). Sendfile hack ... JRA. */
        if (req->out.vector_count < (2*SMBD_SMB2_NUM_IOV_PER_REQ) &&
            outdyn->iov_base == NULL && outdyn->iov_len != 0) {
@@ -2533,7 +2945,7 @@ static NTSTATUS smbd_smb2_request_reply(struct smbd_smb2_request *req)
        req->queue_entry.mem_ctx = req;
        req->queue_entry.vector = req->out.vector;
        req->queue_entry.count = req->out.vector_count;
-       DLIST_ADD_END(xconn->smb2.send_queue, &req->queue_entry, NULL);
+       DLIST_ADD_END(xconn->smb2.send_queue, &req->queue_entry);
        xconn->smb2.send_queue_len++;
 
        status = smbd_smb2_flush_send_queue(xconn);
@@ -2619,8 +3031,13 @@ NTSTATUS smbd_smb2_request_done_ex(struct smbd_smb2_request *req,
                outdyn_v->iov_len = 0;
        }
 
-       /* see if we need to recalculate the offset to the next response */
-       if (next_command_ofs > 0) {
+       /*
+        * See if we need to recalculate the offset to the next response
+        *
+        * Note that all responses may require padding (including the very last
+        * one).
+        */
+       if (req->out.vector_count >= (2 * SMBD_SMB2_NUM_IOV_PER_REQ)) {
                next_command_ofs  = SMB2_HDR_BODY;
                next_command_ofs += SMBD_SMB2_OUT_BODY_LEN(req);
                next_command_ofs += SMBD_SMB2_OUT_DYN_LEN(req);
@@ -2674,8 +3091,11 @@ NTSTATUS smbd_smb2_request_done_ex(struct smbd_smb2_request *req,
                next_command_ofs += pad_size;
        }
 
-       SIVAL(outhdr, SMB2_HDR_NEXT_COMMAND, next_command_ofs);
-
+       if ((req->current_idx + SMBD_SMB2_NUM_IOV_PER_REQ) >= req->out.vector_count) {
+               SIVAL(outhdr, SMB2_HDR_NEXT_COMMAND, 0);
+       } else {
+               SIVAL(outhdr, SMB2_HDR_NEXT_COMMAND, next_command_ofs);
+       }
        return smbd_smb2_request_reply(req);
 }
 
@@ -2690,9 +3110,9 @@ NTSTATUS smbd_smb2_request_error_ex(struct smbd_smb2_request *req,
        uint8_t *outhdr = SMBD_SMB2_OUT_HDR_PTR(req);
        size_t unread_bytes = smbd_smb2_unread_bytes(req);
 
-       DEBUG(10,("smbd_smb2_request_error_ex: idx[%d] status[%s] |%s| at %s\n",
-                 req->current_idx, nt_errstr(status), info ? " +info" : "",
-                 location));
+       DBG_NOTICE("smbd_smb2_request_error_ex: idx[%d] status[%s] |%s| "
+                  "at %s\n", req->current_idx, nt_errstr(status),
+                  info ? " +info" : "", location);
 
        if (unread_bytes) {
                /* Recvfile error. Drain incoming socket. */
@@ -2770,8 +3190,8 @@ static NTSTATUS smbd_smb2_send_break(struct smbXsrv_connection *xconn,
 
        if (session != NULL) {
                session_wire_id = session->global->session_wire_id;
-               do_encryption = session->global->encryption_required;
-               if (tcon->global->encryption_required) {
+               do_encryption = session->global->encryption_flags & SMBXSRV_ENCRYPTION_DESIRED;
+               if (tcon->global->encryption_flags & SMBXSRV_ENCRYPTION_DESIRED) {
                        do_encryption = true;
                }
        }
@@ -2786,13 +3206,11 @@ static NTSTATUS smbd_smb2_send_break(struct smbXsrv_connection *xconn,
        talloc_set_name_const(state, "struct smbd_smb2_send_break_state");
 
        if (do_encryption) {
-               nonce_high = session->nonce_high;
-               nonce_low = session->nonce_low;
-
-               session->nonce_low += 1;
-               if (session->nonce_low == 0) {
-                       session->nonce_low += 1;
-                       session->nonce_high += 1;
+               status = smb2_get_new_nonce(session,
+                                           &nonce_high,
+                                           &nonce_low);
+               if (!NT_STATUS_IS_OK(status)) {
+                       return status;
                }
        }
 
@@ -2869,7 +3287,7 @@ static NTSTATUS smbd_smb2_send_break(struct smbXsrv_connection *xconn,
        state->queue_entry.mem_ctx = state;
        state->queue_entry.vector = state->vector;
        state->queue_entry.count = ARRAY_SIZE(state->vector);
-       DLIST_ADD_END(xconn->smb2.send_queue, &state->queue_entry, NULL);
+       DLIST_ADD_END(xconn->smb2.send_queue, &state->queue_entry);
        xconn->smb2.send_queue_len++;
 
        status = smbd_smb2_flush_send_queue(xconn);
@@ -2895,7 +3313,7 @@ NTSTATUS smbd_smb2_send_oplock_break(struct smbXsrv_connection *xconn,
        SBVAL(body, 0x08, op->global->open_persistent_id);
        SBVAL(body, 0x10, op->global->open_volatile_id);
 
-       return smbd_smb2_send_break(xconn, session, tcon, body, sizeof(body));
+       return smbd_smb2_send_break(xconn, NULL, NULL, body, sizeof(body));
 }
 
 NTSTATUS smbd_smb2_send_lease_break(struct smbXsrv_connection *xconn,
@@ -3051,8 +3469,9 @@ static NTSTATUS smbd_smb2_request_next_incoming(struct smbXsrv_connection *xconn
        return NT_STATUS_OK;
 }
 
-void smbd_smb2_first_negprot(struct smbXsrv_connection *xconn,
-                            const uint8_t *inpdu, size_t size)
+void smbd_smb2_process_negprot(struct smbXsrv_connection *xconn,
+                              uint64_t expected_seq_low,
+                              const uint8_t *inpdu, size_t size)
 {
        struct smbd_server_connection *sconn = xconn->client->sconn;
        NTSTATUS status;
@@ -3061,7 +3480,7 @@ void smbd_smb2_first_negprot(struct smbXsrv_connection *xconn,
        DEBUG(10,("smbd_smb2_first_negprot: packet length %u\n",
                 (unsigned int)size));
 
-       status = smbd_initialize_smb2(xconn);
+       status = smbd_initialize_smb2(xconn, expected_seq_low);
        if (!NT_STATUS_IS_OK(status)) {
                smbd_server_connection_terminate(xconn, nt_errstr(status));
                return;
@@ -3090,8 +3509,8 @@ void smbd_smb2_first_negprot(struct smbXsrv_connection *xconn,
         * this was already counted at the SMB1 layer =>
         * smbd_smb2_request_dispatch() should not count it twice.
         */
-       if (profile_p->request_stats.count > 0) {
-               profile_p->request_stats.count--;
+       if (profile_p->values.request_stats.count > 0) {
+               profile_p->values.request_stats.count--;
        }
 #endif
        status = smbd_smb2_request_dispatch(req);
@@ -3165,6 +3584,7 @@ static NTSTATUS smbd_smb2_flush_send_queue(struct smbXsrv_connection *xconn)
        int ret;
        int err;
        bool retry;
+       NTSTATUS status;
 
        if (xconn->smb2.send_queue == NULL) {
                TEVENT_FD_NOT_WRITEABLE(xconn->transport.fde);
@@ -3176,11 +3596,12 @@ static NTSTATUS smbd_smb2_flush_send_queue(struct smbXsrv_connection *xconn)
                bool ok;
 
                if (e->sendfile_header != NULL) {
-                       NTSTATUS status = NT_STATUS_INTERNAL_ERROR;
                        size_t size = 0;
                        size_t i = 0;
                        uint8_t *buf;
 
+                       status = NT_STATUS_INTERNAL_ERROR;
+
                        for (i=0; i < e->count; i++) {
                                size += e->vector[i].iov_len;
                        }
@@ -3252,6 +3673,16 @@ static NTSTATUS smbd_smb2_flush_send_queue(struct smbXsrv_connection *xconn)
                talloc_free(e->mem_ctx);
        }
 
+       /*
+        * Restart reads if we were blocked on
+        * draining the send queue.
+        */
+
+       status = smbd_smb2_request_next_incoming(xconn);
+       if (!NT_STATUS_IS_OK(status)) {
+               return status;
+       }
+
        return NT_STATUS_OK;
 }