Check "auth event notification" param in log_json
[nivanova/samba-autobuild/.git] / auth / gensec / spnego.c
index defffe40ab1440efb162532983490e18becb2bdd..0b3fbdce7acd1b44a85f1109d4e2961e0d5668e0 100644 (file)
@@ -34,6 +34,9 @@
 #include "lib/util/asn1.h"
 #include "lib/util/base64.h"
 
+#undef DBGC_CLASS
+#define DBGC_CLASS DBGC_AUTH
+
 #undef strcasecmp
 
 _PUBLIC_ NTSTATUS gensec_spnego_init(TALLOC_CTX *ctx);
@@ -47,6 +50,74 @@ enum spnego_state_position {
        SPNEGO_DONE
 };
 
+struct spnego_state;
+struct spnego_neg_ops;
+struct spnego_neg_state;
+
+struct spnego_neg_state {
+       const struct spnego_neg_ops *ops;
+       const struct gensec_security_ops_wrapper *all_sec;
+       size_t all_idx;
+       const char * const *mech_types;
+       size_t mech_idx;
+};
+
+struct spnego_neg_ops {
+       const char *name;
+       /*
+        * The start hook does the initial processing on the incoming paket and
+        * may starts the first possible subcontext. It indicates that
+        * gensec_update() is required on the subcontext by returning
+        * NT_STATUS_MORE_PROCESSING_REQUIRED and return something useful in
+        * 'in_next'. Note that 'in_mem_ctx' is just passed as a hint, the
+        * caller should treat 'in_next' as const and don't attempt to free the
+        * content.  NT_STATUS_OK indicates the finish hook should be invoked
+        * directly withing the need of gensec_update() on the subcontext.
+        * Every other error indicates an error that's returned to the caller.
+        */
+       NTSTATUS (*start_fn)(struct gensec_security *gensec_security,
+                            struct spnego_state *spnego_state,
+                            struct spnego_neg_state *n,
+                            struct spnego_data *spnego_in,
+                            TALLOC_CTX *in_mem_ctx,
+                            DATA_BLOB *in_next);
+       /*
+        * The step hook processes the result of a failed gensec_update() and
+        * can decide to ignore a failure and continue the negotiation by
+        * setting up the next possible subcontext. It indicates that
+        * gensec_update() is required on the subcontext by returning
+        * NT_STATUS_MORE_PROCESSING_REQUIRED and return something useful in
+        * 'in_next'. Note that 'in_mem_ctx' is just passed as a hint, the
+        * caller should treat 'in_next' as const and don't attempt to free the
+        * content.  NT_STATUS_OK indicates the finish hook should be invoked
+        * directly withing the need of gensec_update() on the subcontext.
+        * Every other error indicates an error that's returned to the caller.
+        */
+       NTSTATUS (*step_fn)(struct gensec_security *gensec_security,
+                           struct spnego_state *spnego_state,
+                           struct spnego_neg_state *n,
+                           struct spnego_data *spnego_in,
+                           NTSTATUS last_status,
+                           TALLOC_CTX *in_mem_ctx,
+                           DATA_BLOB *in_next);
+       /*
+        * The finish hook processes the result of a successful gensec_update()
+        * (NT_STATUS_OK or NT_STATUS_MORE_PROCESSING_REQUIRED). It forms the
+        * response pdu that will be returned from the toplevel gensec_update()
+        * together with NT_STATUS_OK or NT_STATUS_MORE_PROCESSING_REQUIRED. It
+        * may also alter the state machine to prepare receiving the next pdu
+        * from the peer.
+        */
+       NTSTATUS (*finish_fn)(struct gensec_security *gensec_security,
+                             struct spnego_state *spnego_state,
+                             struct spnego_neg_state *n,
+                             struct spnego_data *spnego_in,
+                             NTSTATUS sub_status,
+                             const DATA_BLOB sub_out,
+                             TALLOC_CTX *out_mem_ctx,
+                             DATA_BLOB *out);
+};
+
 struct spnego_state {
        enum spnego_message_type expected_packet;
        enum spnego_state_position state_position;
@@ -77,7 +148,21 @@ struct spnego_state {
        NTSTATUS out_status;
 };
 
-static void gensec_spnego_update_sub_abort(struct spnego_state *spnego_state)
+static struct spnego_neg_state *gensec_spnego_neg_state(TALLOC_CTX *mem_ctx,
+               const struct spnego_neg_ops *ops)
+{
+       struct spnego_neg_state *n = NULL;
+
+       n = talloc_zero(mem_ctx, struct spnego_neg_state);
+       if (n == NULL) {
+               return NULL;
+       }
+       n->ops = ops;
+
+       return n;
+}
+
+static void gensec_spnego_reset_sub_sec(struct spnego_state *spnego_state)
 {
        spnego_state->sub_sec_ready = false;
        TALLOC_FREE(spnego_state->sub_sec_security);
@@ -203,297 +288,217 @@ static NTSTATUS gensec_spnego_server_try_fallback(struct gensec_security *gensec
        return NT_STATUS_INVALID_PARAMETER;
 }
 
-/* 
-   Parse the netTokenInit, either from the client, to the server, or
-   from the server to the client.
-*/
-
-static NTSTATUS gensec_spnego_parse_negTokenInit(struct gensec_security *gensec_security,
-                                                struct spnego_state *spnego_state, 
-                                                TALLOC_CTX *out_mem_ctx, 
-                                                struct tevent_context *ev,
-                                                struct spnego_data *spnego_in,
-                                                DATA_BLOB *unwrapped_out)
+static NTSTATUS gensec_spnego_create_negTokenInit_start(
+                                       struct gensec_security *gensec_security,
+                                       struct spnego_state *spnego_state,
+                                       struct spnego_neg_state *n,
+                                       struct spnego_data *spnego_in,
+                                       TALLOC_CTX *in_mem_ctx,
+                                       DATA_BLOB *in_next)
 {
-       int i;
-       NTSTATUS nt_status = NT_STATUS_INVALID_PARAMETER;
-       const char * const *mechType = NULL;
-       DATA_BLOB unwrapped_in = data_blob_null;
-       bool ok;
-       const struct gensec_security_ops_wrapper *all_sec = NULL;
-       uint32_t j;
-
-       if (spnego_state->state_position != SPNEGO_SERVER_START) {
-               return NT_STATUS_INTERNAL_ERROR;
-       }
-
-       if (spnego_in->type != SPNEGO_NEG_TOKEN_INIT) {
-               return NT_STATUS_INTERNAL_ERROR;
-       }
-
-       mechType = spnego_in->negTokenInit.mechTypes;
-       if (mechType == NULL) {
-               return NT_STATUS_INVALID_PARAMETER;
+       n->mech_idx = 0;
+       n->mech_types = gensec_security_oids(gensec_security, n,
+                                            GENSEC_OID_SPNEGO);
+       if (n->mech_types == NULL) {
+               DBG_WARNING("gensec_security_oids() failed\n");
+               return NT_STATUS_NO_MEMORY;
        }
-       unwrapped_in = spnego_in->negTokenInit.mechToken;
 
-       all_sec = gensec_security_by_oid_list(gensec_security,
-                                             out_mem_ctx, 
-                                             mechType,
-                                             GENSEC_OID_SPNEGO);
-       if (all_sec == NULL) {
+       n->all_idx = 0;
+       n->all_sec = gensec_security_by_oid_list(gensec_security,
+                                                n, n->mech_types,
+                                                GENSEC_OID_SPNEGO);
+       if (n->all_sec == NULL) {
                DBG_WARNING("gensec_security_by_oid_list() failed\n");
-               return NT_STATUS_INVALID_PARAMETER;
-       }
-
-       ok = spnego_write_mech_types(spnego_state,
-                                    mechType,
-                                    &spnego_state->mech_types);
-       if (!ok) {
-               DEBUG(1, ("SPNEGO: Failed to write mechTypes\n"));
                return NT_STATUS_NO_MEMORY;
        }
 
-       for (j=0; mechType && mechType[j]; j++) {
-               const struct gensec_security_ops_wrapper *cur_sec = NULL;
-
-               for (i=0; all_sec && all_sec[i].op; i++) {
-                       if (strcmp(mechType[j], all_sec[i].oid) == 0) {
-                               cur_sec = &all_sec[i];
-                               break;
-                       }
-               }
+       return n->ops->step_fn(gensec_security, spnego_state, n,
+                              spnego_in, NT_STATUS_OK, in_mem_ctx, in_next);
+}
 
-               if (cur_sec == NULL) {
-                       continue;
-               }
+static NTSTATUS gensec_spnego_create_negTokenInit_step(
+                                       struct gensec_security *gensec_security,
+                                       struct spnego_state *spnego_state,
+                                       struct spnego_neg_state *n,
+                                       struct spnego_data *spnego_in,
+                                       NTSTATUS last_status,
+                                       TALLOC_CTX *in_mem_ctx,
+                                       DATA_BLOB *in_next)
+{
+       if (!NT_STATUS_IS_OK(last_status)) {
+               const struct gensec_security_ops_wrapper *cur_sec =
+                       &n->all_sec[n->all_idx];
+               const struct gensec_security_ops_wrapper *next_sec = NULL;
+               const char *next = NULL;
+               const char *principal = NULL;
+               int dbg_level = DBGLVL_WARNING;
+               NTSTATUS status = last_status;
 
-               nt_status = gensec_subcontext_start(spnego_state,
-                                                   gensec_security,
-                                                   &spnego_state->sub_sec_security);
-               if (!NT_STATUS_IS_OK(nt_status)) {
-                       return nt_status;
-               }
-               /* select the sub context */
-               nt_status = gensec_start_mech_by_ops(spnego_state->sub_sec_security,
-                                                    cur_sec->op);
-               if (!NT_STATUS_IS_OK(nt_status)) {
-                       /*
-                        * Pretend we never started it
-                        */
-                       gensec_spnego_update_sub_abort(spnego_state);
-                       continue;
+               if (cur_sec[1].op != NULL) {
+                       next_sec = &cur_sec[1];
                }
 
-               if (j > 0) {
-                       /* no optimistic token */
-                       spnego_state->neg_oid = cur_sec->oid;
-                       *unwrapped_out = data_blob_null;
-                       nt_status = NT_STATUS_MORE_PROCESSING_REQUIRED;
-                       /*
-                        * Indicate the downgrade and request a
-                        * mic.
-                        */
-                       spnego_state->downgraded = true;
-                       spnego_state->mic_requested = true;
-                       return nt_status;
+               if (next_sec != NULL) {
+                       next = next_sec->op->name;
+                       dbg_level = DBGLVL_NOTICE;
                }
 
-               nt_status = gensec_update_ev(spnego_state->sub_sec_security,
-                                         out_mem_ctx,
-                                         ev,
-                                         unwrapped_in,
-                                         unwrapped_out);
-               if (NT_STATUS_IS_OK(nt_status)) {
-                       spnego_state->sub_sec_ready = true;
+               if (gensec_security->target.principal != NULL) {
+                       principal = gensec_security->target.principal;
+               } else if (gensec_security->target.service != NULL &&
+                          gensec_security->target.hostname != NULL)
+               {
+                       principal = talloc_asprintf(spnego_state->sub_sec_security,
+                                                   "%s/%s",
+                                                   gensec_security->target.service,
+                                                   gensec_security->target.hostname);
+               } else {
+                       principal = gensec_security->target.hostname;
                }
-               if (NT_STATUS_EQUAL(nt_status, NT_STATUS_INVALID_PARAMETER) ||
-                   NT_STATUS_EQUAL(nt_status, NT_STATUS_CANT_ACCESS_DOMAIN_INFO)) {
 
-                       DEBUG(1, ("SPNEGO(%s) NEG_TOKEN_INIT failed to parse contents: %s\n",
-                                 spnego_state->sub_sec_security->ops->name, nt_errstr(nt_status)));
+               DBG_PREFIX(dbg_level, (
+                          "%s: creating NEG_TOKEN_INIT for %s failed "
+                          "(next[%s]): %s\n", cur_sec->op->name,
+                          principal, next, nt_errstr(status)));
 
+               if (next == NULL) {
                        /*
-                        * Pretend we never started it
+                        * A hard error without a possible fallback.
                         */
-                       gensec_spnego_update_sub_abort(spnego_state);
-                       continue;
+                       return status;
                }
 
-               if (GENSEC_UPDATE_IS_NTERROR(nt_status)) {
-                       DEBUG(1, ("SPNEGO(%s) NEG_TOKEN_INIT failed: %s\n",
-                                 spnego_state->sub_sec_security->ops->name,
-                                 nt_errstr(nt_status)));
-                       return nt_status;
-               }
+               /*
+                * Pretend we never started it
+                */
+               gensec_spnego_reset_sub_sec(spnego_state);
 
-               spnego_state->neg_oid = cur_sec->oid;
-               return nt_status; /* OK or MORE PROCESSING */
+               /*
+                * And try the next one...
+                */
+               n->all_idx += 1;
        }
 
-       DEBUG(1, ("SPNEGO: Could not find a suitable mechtype in NEG_TOKEN_INIT\n"));
-       return NT_STATUS_INVALID_PARAMETER;
-}
-
-/** create a negTokenInit 
- *
- * This is the same packet, no matter if the client or server sends it first, but it is always the first packet
-*/
-static NTSTATUS gensec_spnego_create_negTokenInit(struct gensec_security *gensec_security, 
-                                                 struct spnego_state *spnego_state,
-                                                 TALLOC_CTX *out_mem_ctx, 
-                                                 struct tevent_context *ev,
-                                                 DATA_BLOB *out)
-{
-       int i;
-       NTSTATUS nt_status = NT_STATUS_INVALID_PARAMETER;
-       const char **mechTypes = NULL;
-       DATA_BLOB unwrapped_out = data_blob_null;
-       const struct gensec_security_ops_wrapper *all_sec;
-
-       mechTypes = gensec_security_oids(gensec_security, 
-                                        out_mem_ctx, GENSEC_OID_SPNEGO);
-
-       all_sec = gensec_security_by_oid_list(gensec_security, 
-                                             out_mem_ctx, 
-                                             mechTypes,
-                                             GENSEC_OID_SPNEGO);
-       for (i=0; all_sec && all_sec[i].op; i++) {
-               struct spnego_data spnego_out;
-               const char **send_mech_types;
-               bool ok;
+       for (; n->all_sec[n->all_idx].op != NULL; n->all_idx++) {
+               const struct gensec_security_ops_wrapper *cur_sec =
+                       &n->all_sec[n->all_idx];
+               NTSTATUS status;
 
-               nt_status = gensec_subcontext_start(spnego_state,
-                                                   gensec_security,
-                                                   &spnego_state->sub_sec_security);
-               if (!NT_STATUS_IS_OK(nt_status)) {
-                       return nt_status;
+               status = gensec_subcontext_start(spnego_state,
+                                                gensec_security,
+                                                &spnego_state->sub_sec_security);
+               if (!NT_STATUS_IS_OK(status)) {
+                       return status;
                }
+
                /* select the sub context */
-               nt_status = gensec_start_mech_by_ops(spnego_state->sub_sec_security,
-                                                    all_sec[i].op);
-               if (!NT_STATUS_IS_OK(nt_status)) {
-                       gensec_spnego_update_sub_abort(spnego_state);
+               status = gensec_start_mech_by_ops(spnego_state->sub_sec_security,
+                                                 cur_sec->op);
+               if (!NT_STATUS_IS_OK(status)) {
+                       gensec_spnego_reset_sub_sec(spnego_state);
                        continue;
                }
 
                /* In the client, try and produce the first (optimistic) packet */
                if (spnego_state->state_position == SPNEGO_CLIENT_START) {
-                       nt_status = gensec_update_ev(spnego_state->sub_sec_security,
-                                                 out_mem_ctx, 
-                                                 ev,
-                                                 data_blob_null,
-                                                 &unwrapped_out);
-                       if (NT_STATUS_IS_OK(nt_status)) {
-                               spnego_state->sub_sec_ready = true;
-                       }
+                       *in_next = data_blob_null;
+                       return NT_STATUS_MORE_PROCESSING_REQUIRED;
+               }
 
-                       if (GENSEC_UPDATE_IS_NTERROR(nt_status)) {
-                               const char *next = NULL;
-                               const char *principal = NULL;
-                               int dbg_level = DBGLVL_WARNING;
-
-                               if (all_sec[i+1].op != NULL) {
-                                       next = all_sec[i+1].op->name;
-                                       dbg_level = DBGLVL_NOTICE;
-                               }
-
-                               if (gensec_security->target.principal != NULL) {
-                                       principal = gensec_security->target.principal;
-                               } else if (gensec_security->target.service != NULL &&
-                                          gensec_security->target.hostname != NULL)
-                               {
-                                       principal = talloc_asprintf(spnego_state->sub_sec_security,
-                                                                   "%s/%s",
-                                                                   gensec_security->target.service,
-                                                                   gensec_security->target.hostname);
-                               } else {
-                                       principal = gensec_security->target.hostname;
-                               }
-
-                               DEBUG(dbg_level, ("SPNEGO(%s) creating NEG_TOKEN_INIT for %s failed (next[%s]): %s\n",
-                                         spnego_state->sub_sec_security->ops->name,
-                                         principal,
-                                         next, nt_errstr(nt_status)));
+               *in_next = data_blob_null;
+               return NT_STATUS_OK;
+       }
 
-                               /*
-                                * Pretend we never started it
-                                */
-                               gensec_spnego_update_sub_abort(spnego_state);
-                               continue;
-                       }
-               }
+       DBG_WARNING("Failed to setup SPNEGO negTokenInit request\n");
+       return NT_STATUS_INVALID_PARAMETER;
+}
 
-               spnego_out.type = SPNEGO_NEG_TOKEN_INIT;
+static NTSTATUS gensec_spnego_create_negTokenInit_finish(
+                                       struct gensec_security *gensec_security,
+                                       struct spnego_state *spnego_state,
+                                       struct spnego_neg_state *n,
+                                       struct spnego_data *spnego_in,
+                                       NTSTATUS sub_status,
+                                       const DATA_BLOB sub_out,
+                                       TALLOC_CTX *out_mem_ctx,
+                                       DATA_BLOB *out)
+{
+       const struct gensec_security_ops_wrapper *cur_sec =
+                       &n->all_sec[n->all_idx];
+       struct spnego_data spnego_out;
+       bool ok;
 
-               send_mech_types = gensec_security_oids_from_ops_wrapped(out_mem_ctx,
-                                                                       &all_sec[i]);
+       spnego_out.type = SPNEGO_NEG_TOKEN_INIT;
 
-               ok = spnego_write_mech_types(spnego_state,
-                                            send_mech_types,
-                                            &spnego_state->mech_types);
-               if (!ok) {
-                       DEBUG(1, ("SPNEGO: Failed to write mechTypes\n"));
-                       return NT_STATUS_NO_MEMORY;
-               }
+       n->mech_types = gensec_security_oids_from_ops_wrapped(n, cur_sec);
+       if (n->mech_types == NULL) {
+               DBG_WARNING("gensec_security_oids_from_ops_wrapped() failed\n");
+               return NT_STATUS_NO_MEMORY;
+       }
 
-               /* List the remaining mechs as options */
-               spnego_out.negTokenInit.mechTypes = send_mech_types;
-               spnego_out.negTokenInit.reqFlags = data_blob_null;
-               spnego_out.negTokenInit.reqFlagsPadding = 0;
+       ok = spnego_write_mech_types(spnego_state,
+                                    n->mech_types,
+                                    &spnego_state->mech_types);
+       if (!ok) {
+               DBG_ERR("Failed to write mechTypes\n");
+               return NT_STATUS_NO_MEMORY;
+       }
 
-               if (spnego_state->state_position == SPNEGO_SERVER_START) {
-                       spnego_out.negTokenInit.mechListMIC
-                               = data_blob_string_const(ADS_IGNORE_PRINCIPAL);
-               } else {
-                       spnego_out.negTokenInit.mechListMIC = data_blob_null;
-               }
+       /* List the remaining mechs as options */
+       spnego_out.negTokenInit.mechTypes = n->mech_types;
+       spnego_out.negTokenInit.reqFlags = data_blob_null;
+       spnego_out.negTokenInit.reqFlagsPadding = 0;
 
-               spnego_out.negTokenInit.mechToken = unwrapped_out;
+       if (spnego_state->state_position == SPNEGO_SERVER_START) {
+               spnego_out.negTokenInit.mechListMIC
+                       = data_blob_string_const(ADS_IGNORE_PRINCIPAL);
+       } else {
+               spnego_out.negTokenInit.mechListMIC = data_blob_null;
+       }
 
-               if (spnego_write_data(out_mem_ctx, out, &spnego_out) == -1) {
-                       DEBUG(1, ("Failed to write NEG_TOKEN_INIT\n"));
-                               return NT_STATUS_INVALID_PARAMETER;
-               }
+       spnego_out.negTokenInit.mechToken = sub_out;
 
-               /* set next state */
-               spnego_state->neg_oid = all_sec[i].oid;
+       if (spnego_write_data(out_mem_ctx, out, &spnego_out) == -1) {
+               DBG_ERR("Failed to write NEG_TOKEN_INIT\n");
+               return NT_STATUS_INVALID_PARAMETER;
+       }
 
-               if (spnego_state->state_position == SPNEGO_SERVER_START) {
-                       spnego_state->state_position = SPNEGO_SERVER_START;
-                       spnego_state->expected_packet = SPNEGO_NEG_TOKEN_INIT;
-               } else {
-                       spnego_state->state_position = SPNEGO_CLIENT_TARG;
-                       spnego_state->expected_packet = SPNEGO_NEG_TOKEN_TARG;
-               }
+       /*
+        * Note that 'cur_sec' is temporary memory, but
+        * cur_sec->oid points to a const string in the
+        * backends gensec_security_ops structure.
+        */
+       spnego_state->neg_oid = cur_sec->oid;
 
-               return NT_STATUS_MORE_PROCESSING_REQUIRED;
+       /* set next state */
+       if (spnego_state->state_position == SPNEGO_SERVER_START) {
+               spnego_state->state_position = SPNEGO_SERVER_START;
+               spnego_state->expected_packet = SPNEGO_NEG_TOKEN_INIT;
+       } else {
+               spnego_state->state_position = SPNEGO_CLIENT_TARG;
+               spnego_state->expected_packet = SPNEGO_NEG_TOKEN_TARG;
        }
-       gensec_spnego_update_sub_abort(spnego_state);
 
-       DEBUG(10, ("Failed to setup SPNEGO negTokenInit request: %s\n", nt_errstr(nt_status)));
-       return nt_status;
+       return NT_STATUS_MORE_PROCESSING_REQUIRED;
 }
 
-static NTSTATUS gensec_spnego_client_negTokenInit(struct gensec_security *gensec_security,
-                                                 struct spnego_state *spnego_state,
-                                                 struct tevent_context *ev,
-                                                 struct spnego_data *spnego_in,
-                                                 TALLOC_CTX *out_mem_ctx,
-                                                 DATA_BLOB *out)
+static const struct spnego_neg_ops gensec_spnego_create_negTokenInit_ops = {
+       .name      = "create_negTokenInit",
+       .start_fn  = gensec_spnego_create_negTokenInit_start,
+       .step_fn   = gensec_spnego_create_negTokenInit_step,
+       .finish_fn = gensec_spnego_create_negTokenInit_finish,
+};
+
+static NTSTATUS gensec_spnego_client_negTokenInit_start(
+                                       struct gensec_security *gensec_security,
+                                       struct spnego_state *spnego_state,
+                                       struct spnego_neg_state *n,
+                                       struct spnego_data *spnego_in,
+                                       TALLOC_CTX *in_mem_ctx,
+                                       DATA_BLOB *in_next)
 {
-       TALLOC_CTX *frame = talloc_stackframe();
-       DATA_BLOB sub_out = data_blob_null;
        const char *tp = NULL;
-       const char * const *mech_types = NULL;
-       size_t all_idx = 0;
-       const struct gensec_security_ops_wrapper *all_sec = NULL;
-       struct spnego_data spnego_out;
-       const char *my_mechs[] = {NULL, NULL};
-       NTSTATUS status;
-       bool ok;
-
-       *out = data_blob_null;
 
        /* The server offers a list of mechanisms */
 
@@ -505,62 +510,46 @@ static NTSTATUS gensec_spnego_client_negTokenInit(struct gensec_security *gensec
                }
        }
 
-       mech_types = spnego_in->negTokenInit.mechTypes;
-       if (mech_types == NULL) {
-               TALLOC_FREE(frame);
+       n->mech_idx = 0;
+       n->mech_types = spnego_in->negTokenInit.mechTypes;
+       if (n->mech_types == NULL) {
                return NT_STATUS_INVALID_PARAMETER;
        }
 
-       all_sec = gensec_security_by_oid_list(gensec_security,
-                                             frame, mech_types,
-                                             GENSEC_OID_SPNEGO);
-       if (all_sec == NULL) {
+       n->all_idx = 0;
+       n->all_sec = gensec_security_by_oid_list(gensec_security,
+                                                n, n->mech_types,
+                                                GENSEC_OID_SPNEGO);
+       if (n->all_sec == NULL) {
                DBG_WARNING("gensec_security_by_oid_list() failed\n");
-               TALLOC_FREE(frame);
                return NT_STATUS_INVALID_PARAMETER;
        }
 
-       for (; all_sec[all_idx].op; all_idx++) {
+       return n->ops->step_fn(gensec_security, spnego_state, n,
+                              spnego_in, NT_STATUS_OK, in_mem_ctx, in_next);
+}
+
+static NTSTATUS gensec_spnego_client_negTokenInit_step(
+                                       struct gensec_security *gensec_security,
+                                       struct spnego_state *spnego_state,
+                                       struct spnego_neg_state *n,
+                                       struct spnego_data *spnego_in,
+                                       NTSTATUS last_status,
+                                       TALLOC_CTX *in_mem_ctx,
+                                       DATA_BLOB *in_next)
+{
+       if (!NT_STATUS_IS_OK(last_status)) {
                const struct gensec_security_ops_wrapper *cur_sec =
-                       &all_sec[all_idx];
+                       &n->all_sec[n->all_idx];
+               const struct gensec_security_ops_wrapper *next_sec = NULL;
                const char *next = NULL;
                const char *principal = NULL;
                int dbg_level = DBGLVL_WARNING;
                bool allow_fallback = false;
+               NTSTATUS status = last_status;
 
-               status = gensec_subcontext_start(spnego_state,
-                                                gensec_security,
-                                                &spnego_state->sub_sec_security);
-               if (!NT_STATUS_IS_OK(status)) {
-                       TALLOC_FREE(frame);
-                       return status;
-               }
-
-               /* select the sub context */
-               status = gensec_start_mech_by_ops(spnego_state->sub_sec_security,
-                                                 cur_sec->op);
-               if (!NT_STATUS_IS_OK(status)) {
-                       /*
-                        * Pretend we never started it.
-                        */
-                       gensec_spnego_update_sub_abort(spnego_state);
-                       continue;
-               }
-
-               spnego_state->neg_oid = cur_sec->oid;
-
-               /*
-                * As client we don't use an optimistic token from the server.
-                */
-               status = gensec_update_ev(spnego_state->sub_sec_security,
-                                         frame, ev, data_blob_null, &sub_out);
-               if (NT_STATUS_IS_OK(status)) {
-                       spnego_state->sub_sec_ready = true;
-               }
-
-               if (!GENSEC_UPDATE_IS_NTERROR(status)) {
-                       /* OK or MORE_PROCESSING_REQUIRED */
-                       goto reply;
+               if (cur_sec[1].op != NULL) {
+                       next_sec = &cur_sec[1];
                }
 
                /*
@@ -578,8 +567,8 @@ static NTSTATUS gensec_spnego_client_negTokenInit(struct gensec_security *gensec
                        allow_fallback = true;
                }
 
-               if (allow_fallback && cur_sec[1].op != NULL) {
-                       next = cur_sec[1].op->name;
+               if (allow_fallback && next_sec != NULL) {
+                       next = next_sec->op->name;
                        dbg_level = DBGLVL_NOTICE;
                }
 
@@ -597,31 +586,81 @@ static NTSTATUS gensec_spnego_client_negTokenInit(struct gensec_security *gensec
                }
 
                DBG_PREFIX(dbg_level, (
-                          "%s: creating NEG_TOKEN_INIT "
-                          "for %s failed (next[%s]): %s\n",
-                          spnego_state->sub_sec_security->ops->name,
+                          "%s: creating NEG_TOKEN_INIT for %s failed "
+                          "(next[%s]): %s\n", cur_sec->op->name,
                           principal, next, nt_errstr(status)));
 
-               if (allow_fallback && next != NULL) {
+               if (next == NULL) {
                        /*
-                        * Pretend we never started it.
+                        * A hard error without a possible fallback.
                         */
-                       gensec_spnego_update_sub_abort(spnego_state);
+                       return status;
+               }
+
+               /*
+                * Pretend we never started it.
+                */
+               gensec_spnego_reset_sub_sec(spnego_state);
+
+               /*
+                * And try the next one...
+                */
+               n->all_idx += 1;
+       }
+
+       for (; n->all_sec[n->all_idx].op != NULL; n->all_idx++) {
+               const struct gensec_security_ops_wrapper *cur_sec =
+                       &n->all_sec[n->all_idx];
+               NTSTATUS status;
+
+               status = gensec_subcontext_start(spnego_state,
+                                                gensec_security,
+                                                &spnego_state->sub_sec_security);
+               if (!NT_STATUS_IS_OK(status)) {
+                       return status;
+               }
+
+               /* select the sub context */
+               status = gensec_start_mech_by_ops(spnego_state->sub_sec_security,
+                                                 cur_sec->op);
+               if (!NT_STATUS_IS_OK(status)) {
+                       gensec_spnego_reset_sub_sec(spnego_state);
                        continue;
                }
 
                /*
-                * Hard error.
+                * Note that 'cur_sec' is temporary memory, but
+                * cur_sec->oid points to a const string in the
+                * backends gensec_security_ops structure.
                 */
-               TALLOC_FREE(frame);
-               return status;
+               spnego_state->neg_oid = cur_sec->oid;
+
+               /*
+                * As client we don't use an optimistic token from the server.
+                * But try to produce one for the server.
+                */
+               *in_next = data_blob_null;
+               return NT_STATUS_MORE_PROCESSING_REQUIRED;
        }
 
        DBG_WARNING("Could not find a suitable mechtype in NEG_TOKEN_INIT\n");
-       TALLOC_FREE(frame);
        return NT_STATUS_INVALID_PARAMETER;
+}
+
+static NTSTATUS gensec_spnego_client_negTokenInit_finish(
+                                       struct gensec_security *gensec_security,
+                                       struct spnego_state *spnego_state,
+                                       struct spnego_neg_state *n,
+                                       struct spnego_data *spnego_in,
+                                       NTSTATUS sub_status,
+                                       const DATA_BLOB sub_out,
+                                       TALLOC_CTX *out_mem_ctx,
+                                       DATA_BLOB *out)
+{
+       struct spnego_data spnego_out;
+       const char *my_mechs[] = {NULL, NULL};
+       bool ok;
 
- reply:
        my_mechs[0] = spnego_state->neg_oid;
        /* compose reply */
        spnego_out.type = SPNEGO_NEG_TOKEN_INIT;
@@ -633,7 +672,6 @@ static NTSTATUS gensec_spnego_client_negTokenInit(struct gensec_security *gensec
 
        if (spnego_write_data(out_mem_ctx, out, &spnego_out) == -1) {
                DBG_ERR("Failed to write SPNEGO reply to NEG_TOKEN_INIT\n");
-               TALLOC_FREE(frame);
                return NT_STATUS_INVALID_PARAMETER;
        }
 
@@ -642,7 +680,6 @@ static NTSTATUS gensec_spnego_client_negTokenInit(struct gensec_security *gensec
                                     &spnego_state->mech_types);
        if (!ok) {
                DBG_ERR("failed to write mechTypes\n");
-               TALLOC_FREE(frame);
                return NT_STATUS_NO_MEMORY;
        }
 
@@ -650,26 +687,27 @@ static NTSTATUS gensec_spnego_client_negTokenInit(struct gensec_security *gensec
        spnego_state->expected_packet = SPNEGO_NEG_TOKEN_TARG;
        spnego_state->state_position = SPNEGO_CLIENT_TARG;
 
-       TALLOC_FREE(frame);
        return NT_STATUS_MORE_PROCESSING_REQUIRED;
 }
 
-static NTSTATUS gensec_spnego_client_negTokenTarg(struct gensec_security *gensec_security,
-                                                 struct spnego_state *spnego_state,
-                                                 struct tevent_context *ev,
-                                                 struct spnego_data *spnego_in,
-                                                 TALLOC_CTX *out_mem_ctx,
-                                                 DATA_BLOB *out)
+static const struct spnego_neg_ops gensec_spnego_client_negTokenInit_ops = {
+       .name      = "client_negTokenInit",
+       .start_fn  = gensec_spnego_client_negTokenInit_start,
+       .step_fn   = gensec_spnego_client_negTokenInit_step,
+       .finish_fn = gensec_spnego_client_negTokenInit_finish,
+};
+
+static NTSTATUS gensec_spnego_client_negTokenTarg_start(
+                                       struct gensec_security *gensec_security,
+                                       struct spnego_state *spnego_state,
+                                       struct spnego_neg_state *n,
+                                       struct spnego_data *spnego_in,
+                                       TALLOC_CTX *in_mem_ctx,
+                                       DATA_BLOB *in_next)
 {
        struct spnego_negTokenTarg *ta = &spnego_in->negTokenTarg;
-       DATA_BLOB sub_in = ta->responseToken;
-       DATA_BLOB mech_list_mic = data_blob_null;
-       DATA_BLOB sub_out = data_blob_null;
-       struct spnego_data spnego_out;
        NTSTATUS status;
 
-       *out = data_blob_null;
-
        spnego_state->num_targs++;
 
        if (ta->negResult == SPNEGO_REJECT) {
@@ -721,7 +759,7 @@ static NTSTATUS gensec_spnego_client_negTokenTarg(struct gensec_security *gensec
                           client_mech, client_oid, server_mech, server_oid);
 
                spnego_state->downgraded = true;
-               gensec_spnego_update_sub_abort(spnego_state);
+               gensec_spnego_reset_sub_sec(spnego_state);
 
                status = gensec_subcontext_start(spnego_state,
                                                 gensec_security,
@@ -769,8 +807,7 @@ static NTSTATUS gensec_spnego_client_negTokenTarg(struct gensec_security *gensec
                         * https://bugzilla.samba.org/show_bug.cgi?id=11994
                         */
                        spnego_state->needs_mic_check = false;
-                       status = NT_STATUS_OK;
-                       goto client_response;
+                       return NT_STATUS_OK;
                }
 
                status = gensec_check_packet(spnego_state->sub_sec_security,
@@ -786,27 +823,98 @@ static NTSTATUS gensec_spnego_client_negTokenTarg(struct gensec_security *gensec
                }
                spnego_state->needs_mic_check = false;
                spnego_state->done_mic_check = true;
-               goto client_response;
+               return NT_STATUS_OK;
        }
 
        if (!spnego_state->sub_sec_ready) {
-               status = gensec_update_ev(spnego_state->sub_sec_security,
-                                         out_mem_ctx, ev,
-                                         sub_in,
-                                         &sub_out);
-               if (NT_STATUS_IS_OK(status)) {
-                       spnego_state->sub_sec_ready = true;
-               }
-               if (!NT_STATUS_IS_OK(status)) {
-                       goto client_response;
-               }
-       } else {
-               status = NT_STATUS_OK;
+               *in_next = ta->responseToken;
+               return NT_STATUS_MORE_PROCESSING_REQUIRED;
        }
 
-       if (!spnego_state->done_mic_check) {
-               bool have_sign = true;
-               bool new_spnego = false;
+       return NT_STATUS_OK;
+}
+
+static NTSTATUS gensec_spnego_client_negTokenTarg_step(
+                                       struct gensec_security *gensec_security,
+                                       struct spnego_state *spnego_state,
+                                       struct spnego_neg_state *n,
+                                       struct spnego_data *spnego_in,
+                                       NTSTATUS last_status,
+                                       TALLOC_CTX *in_mem_ctx,
+                                       DATA_BLOB *in_next)
+{
+       if (GENSEC_UPDATE_IS_NTERROR(last_status)) {
+               DBG_WARNING("SPNEGO(%s) login failed: %s\n",
+                           spnego_state->sub_sec_security->ops->name,
+                           nt_errstr(last_status));
+               return last_status;
+       }
+
+       /*
+        * This should never be reached!
+        * The step function is only called on errors!
+        */
+       smb_panic(__location__);
+       return NT_STATUS_INTERNAL_ERROR;
+}
+
+static NTSTATUS gensec_spnego_client_negTokenTarg_finish(
+                                       struct gensec_security *gensec_security,
+                                       struct spnego_state *spnego_state,
+                                       struct spnego_neg_state *n,
+                                       struct spnego_data *spnego_in,
+                                       NTSTATUS sub_status,
+                                       const DATA_BLOB sub_out,
+                                       TALLOC_CTX *out_mem_ctx,
+                                       DATA_BLOB *out)
+{
+       const struct spnego_negTokenTarg *ta =
+               &spnego_in->negTokenTarg;
+       DATA_BLOB mech_list_mic = data_blob_null;
+       NTSTATUS status;
+       struct spnego_data spnego_out;
+
+       status = sub_status;
+
+       if (!spnego_state->sub_sec_ready) {
+               /*
+                * We're not yet ready to deal with signatures.
+                */
+               goto client_response;
+       }
+
+       if (spnego_state->done_mic_check) {
+               /*
+                * We already checked the mic,
+                * either the in last round here
+                * in gensec_spnego_client_negTokenTarg_finish()
+                * or during this round in
+                * gensec_spnego_client_negTokenTarg_start().
+                *
+                * Both cases we're sure we don't have to
+                * call gensec_sign_packet().
+                */
+               goto client_response;
+       }
+
+       if (spnego_state->may_skip_mic_check) {
+               /*
+                * This can only be set during
+                * the last round here in
+                * gensec_spnego_client_negTokenTarg_finish()
+                * below. And during this round
+                * we already passed the checks in
+                * gensec_spnego_client_negTokenTarg_start().
+                *
+                * So we need to skip to deal with
+                * any signatures now.
+                */
+               goto client_response;
+       }
+
+       if (!spnego_state->done_mic_check) {
+               bool have_sign = true;
+               bool new_spnego = false;
 
                have_sign = gensec_have_feature(spnego_state->sub_sec_security,
                                                GENSEC_FEATURE_SIGN);
@@ -915,7 +1023,7 @@ static NTSTATUS gensec_spnego_client_negTokenTarg(struct gensec_security *gensec
 
        if (spnego_state->needs_mic_sign) {
                status = gensec_sign_packet(spnego_state->sub_sec_security,
-                                           out_mem_ctx,
+                                           n,
                                            spnego_state->mech_types.data,
                                            spnego_state->mech_types.length,
                                            spnego_state->mech_types.data,
@@ -929,51 +1037,56 @@ static NTSTATUS gensec_spnego_client_negTokenTarg(struct gensec_security *gensec
                spnego_state->needs_mic_sign = false;
        }
 
-       if (spnego_state->needs_mic_check) {
-               status = NT_STATUS_MORE_PROCESSING_REQUIRED;
-       }
-
  client_response:
-       if (GENSEC_UPDATE_IS_NTERROR(status)) {
-               DBG_WARNING("SPNEGO(%s) login failed: %s\n",
-                           spnego_state->sub_sec_security->ops->name,
-                           nt_errstr(status));
-               return status;
-       }
-
-       if (sub_out.length || mech_list_mic.length) {
-               /* compose reply */
-               spnego_out.type = SPNEGO_NEG_TOKEN_TARG;
-               spnego_out.negTokenTarg.negResult = SPNEGO_NONE_RESULT;
-               spnego_out.negTokenTarg.supportedMech = NULL;
-               spnego_out.negTokenTarg.responseToken = sub_out;
-               spnego_out.negTokenTarg.mechListMIC = mech_list_mic;
+       if (sub_out.length == 0 && mech_list_mic.length == 0) {
+               *out = data_blob_null;
 
-               if (spnego_write_data(out_mem_ctx, out, &spnego_out) == -1) {
-                       DBG_WARNING("Failed to write NEG_TOKEN_TARG\n");
-                       return NT_STATUS_INVALID_PARAMETER;
+               if (!spnego_state->sub_sec_ready) {
+                       /* somethings wrong here... */
+                       DBG_ERR("gensec_update not ready without output\n");
+                       return NT_STATUS_INTERNAL_ERROR;
                }
 
-               spnego_state->num_targs++;
-               spnego_state->state_position = SPNEGO_CLIENT_TARG;
-               status = NT_STATUS_MORE_PROCESSING_REQUIRED;
-       } else {
-
-               /* all done - server has accepted, and we agree */
-               *out = data_blob_null;
-
                if (ta->negResult != SPNEGO_ACCEPT_COMPLETED) {
                        /* unless of course it did not accept */
                        DBG_WARNING("gensec_update ok but not accepted\n");
-                       status = NT_STATUS_INVALID_PARAMETER;
+                       return NT_STATUS_INVALID_PARAMETER;
                }
 
-               spnego_state->state_position = SPNEGO_DONE;
+               if (!spnego_state->needs_mic_check) {
+                       spnego_state->state_position = SPNEGO_DONE;
+                       return NT_STATUS_OK;
+               }
        }
 
-       return status;
+       /* compose reply */
+       spnego_out.type = SPNEGO_NEG_TOKEN_TARG;
+       spnego_out.negTokenTarg.negResult = SPNEGO_NONE_RESULT;
+       spnego_out.negTokenTarg.supportedMech = NULL;
+       spnego_out.negTokenTarg.responseToken = sub_out;
+       spnego_out.negTokenTarg.mechListMIC = mech_list_mic;
+
+       if (spnego_write_data(out_mem_ctx, out, &spnego_out) == -1) {
+               DBG_WARNING("Failed to write NEG_TOKEN_TARG\n");
+               return NT_STATUS_INVALID_PARAMETER;
+       }
+
+       spnego_state->num_targs++;
+
+       /* set next state */
+       spnego_state->state_position = SPNEGO_CLIENT_TARG;
+       spnego_state->expected_packet = SPNEGO_NEG_TOKEN_TARG;
+
+       return NT_STATUS_MORE_PROCESSING_REQUIRED;
 }
 
+static const struct spnego_neg_ops gensec_spnego_client_negTokenTarg_ops = {
+       .name      = "client_negTokenTarg",
+       .start_fn  = gensec_spnego_client_negTokenTarg_start,
+       .step_fn   = gensec_spnego_client_negTokenTarg_step,
+       .finish_fn = gensec_spnego_client_negTokenTarg_finish,
+};
+
 /** create a server negTokenTarg 
  *
  * This is the case, where the client is the first one who sends data
@@ -1009,11 +1122,6 @@ static NTSTATUS gensec_spnego_server_response(struct spnego_state *spnego_state,
                }
                spnego_out.negTokenTarg.negResult = SPNEGO_ACCEPT_COMPLETED;
                spnego_state->state_position = SPNEGO_DONE;
-       } else {
-               spnego_out.negTokenTarg.negResult = SPNEGO_REJECT;
-               spnego_out.negTokenTarg.mechListMIC = data_blob_null;
-               DEBUG(2, ("SPNEGO login failed: %s\n", nt_errstr(nt_status)));
-               spnego_state->state_position = SPNEGO_DONE;
        }
 
        if (spnego_write_data(out_mem_ctx, out, &spnego_out) == -1) {
@@ -1027,23 +1135,193 @@ static NTSTATUS gensec_spnego_server_response(struct spnego_state *spnego_state,
        return nt_status;
 }
 
-static NTSTATUS gensec_spnego_server_negTokenInit(struct gensec_security *gensec_security,
-                                                 struct spnego_state *spnego_state,
-                                                 struct tevent_context *ev,
-                                                 struct spnego_data *spnego_in,
-                                                 TALLOC_CTX *out_mem_ctx,
-                                                 DATA_BLOB *out)
+static NTSTATUS gensec_spnego_server_negTokenInit_start(
+                                       struct gensec_security *gensec_security,
+                                       struct spnego_state *spnego_state,
+                                       struct spnego_neg_state *n,
+                                       struct spnego_data *spnego_in,
+                                       TALLOC_CTX *in_mem_ctx,
+                                       DATA_BLOB *in_next)
 {
-       DATA_BLOB sub_out = data_blob_null;
-       DATA_BLOB mech_list_mic = data_blob_null;
-       NTSTATUS status;
+       bool ok;
+
+       n->mech_idx = 0;
+       n->mech_types = spnego_in->negTokenInit.mechTypes;
+       if (n->mech_types == NULL) {
+               return NT_STATUS_INVALID_PARAMETER;
+       }
+
+       n->all_idx = 0;
+       n->all_sec = gensec_security_by_oid_list(gensec_security,
+                                                n, n->mech_types,
+                                                GENSEC_OID_SPNEGO);
+       if (n->all_sec == NULL) {
+               DBG_WARNING("gensec_security_by_oid_list() failed\n");
+               return NT_STATUS_INVALID_PARAMETER;
+       }
+
+       ok = spnego_write_mech_types(spnego_state,
+                                    n->mech_types,
+                                    &spnego_state->mech_types);
+       if (!ok) {
+               DBG_ERR("Failed to write mechTypes\n");
+               return NT_STATUS_NO_MEMORY;
+       }
 
-       status = gensec_spnego_parse_negTokenInit(gensec_security,
-                                                 spnego_state,
-                                                 out_mem_ctx,
-                                                 ev,
-                                                 spnego_in,
-                                                 &sub_out);
+       return n->ops->step_fn(gensec_security, spnego_state, n,
+                              spnego_in, NT_STATUS_OK, in_mem_ctx, in_next);
+}
+
+static NTSTATUS gensec_spnego_server_negTokenInit_step(
+                                       struct gensec_security *gensec_security,
+                                       struct spnego_state *spnego_state,
+                                       struct spnego_neg_state *n,
+                                       struct spnego_data *spnego_in,
+                                       NTSTATUS last_status,
+                                       TALLOC_CTX *in_mem_ctx,
+                                       DATA_BLOB *in_next)
+{
+       if (!NT_STATUS_IS_OK(last_status)) {
+               const struct gensec_security_ops_wrapper *cur_sec =
+                       &n->all_sec[n->all_idx];
+               const char *next_mech = n->mech_types[n->mech_idx+1];
+               const struct gensec_security_ops_wrapper *next_sec = NULL;
+               const char *next = NULL;
+               int dbg_level = DBGLVL_WARNING;
+               bool allow_fallback = false;
+               NTSTATUS status = last_status;
+               size_t i;
+
+               for (i = 0; next_mech != NULL && n->all_sec[i].op != NULL; i++) {
+                       if (strcmp(next_mech, n->all_sec[i].oid) != 0) {
+                               continue;
+                       }
+
+                       next_sec = &n->all_sec[i];
+                       break;
+               }
+
+               if (NT_STATUS_EQUAL(status, NT_STATUS_INVALID_PARAMETER) ||
+                   NT_STATUS_EQUAL(status, NT_STATUS_CANT_ACCESS_DOMAIN_INFO))
+               {
+                       allow_fallback = true;
+               }
+
+               if (allow_fallback && next_sec != NULL) {
+                       next = next_sec->op->name;
+                       dbg_level = DBGLVL_NOTICE;
+               }
+
+               DBG_PREFIX(dbg_level, (
+                          "%s: parsing NEG_TOKEN_INIT content failed "
+                          "(next[%s]): %s\n", cur_sec->op->name,
+                          next, nt_errstr(status)));
+
+               if (next == NULL) {
+                       /*
+                        * A hard error without a possible fallback.
+                        */
+                       return status;
+               }
+
+               /*
+                * Pretend we never started it
+                */
+               gensec_spnego_reset_sub_sec(spnego_state);
+
+               /*
+                * And try the next one, based on the clients
+                * mech type list...
+                */
+               n->mech_idx += 1;
+       }
+
+       /*
+        * we always reset all_idx here, as the negotiation is
+        * done via mech_idx!
+        */
+       n->all_idx = 0;
+
+       for (; n->mech_types[n->mech_idx] != NULL; n->mech_idx++) {
+               const char *cur_mech = n->mech_types[n->mech_idx];
+               const struct gensec_security_ops_wrapper *cur_sec = NULL;
+               NTSTATUS status;
+               DATA_BLOB sub_in = data_blob_null;
+               size_t i;
+
+               for (i = 0; n->all_sec[i].op != NULL; i++) {
+                       if (strcmp(cur_mech, n->all_sec[i].oid) != 0) {
+                               continue;
+                       }
+
+                       cur_sec = &n->all_sec[i];
+                       n->all_idx = i;
+                       break;
+               }
+
+               if (cur_sec == NULL) {
+                       continue;
+               }
+
+               status = gensec_subcontext_start(spnego_state,
+                                                gensec_security,
+                                                &spnego_state->sub_sec_security);
+               if (!NT_STATUS_IS_OK(status)) {
+                       return status;
+               }
+
+               /* select the sub context */
+               status = gensec_start_mech_by_ops(spnego_state->sub_sec_security,
+                                                 cur_sec->op);
+               if (!NT_STATUS_IS_OK(status)) {
+                       /*
+                        * Pretend we never started it
+                        */
+                       gensec_spnego_reset_sub_sec(spnego_state);
+                       continue;
+               }
+
+               if (n->mech_idx == 0) {
+                       /*
+                        * We can use the optimistic token.
+                        */
+                       sub_in = spnego_in->negTokenInit.mechToken;
+               } else {
+                       /*
+                        * Indicate the downgrade and request a
+                        * mic.
+                        */
+                       spnego_state->downgraded = true;
+                       spnego_state->mic_requested = true;
+               }
+
+               /*
+                * Note that 'cur_sec' is temporary memory, but
+                * cur_sec->oid points to a const string in the
+                * backends gensec_security_ops structure.
+                */
+               spnego_state->neg_oid = cur_sec->oid;
+
+               /* we need some content from the mech */
+               *in_next = sub_in;
+               return NT_STATUS_MORE_PROCESSING_REQUIRED;
+       }
+
+       DBG_WARNING("Could not find a suitable mechtype in NEG_TOKEN_INIT\n");
+       return NT_STATUS_INVALID_PARAMETER;
+}
+
+static NTSTATUS gensec_spnego_server_negTokenInit_finish(
+                                       struct gensec_security *gensec_security,
+                                       struct spnego_state *spnego_state,
+                                       struct spnego_neg_state *n,
+                                       struct spnego_data *spnego_in,
+                                       NTSTATUS sub_status,
+                                       const DATA_BLOB sub_out,
+                                       TALLOC_CTX *out_mem_ctx,
+                                       DATA_BLOB *out)
+{
+       DATA_BLOB mech_list_mic = data_blob_null;
 
        if (spnego_state->simulate_w2k) {
                /*
@@ -1059,26 +1337,29 @@ static NTSTATUS gensec_spnego_server_negTokenInit(struct gensec_security *gensec
 
        return gensec_spnego_server_response(spnego_state,
                                             out_mem_ctx,
-                                            status,
+                                            sub_status,
                                             sub_out,
                                             mech_list_mic,
                                             out);
 }
 
-static NTSTATUS gensec_spnego_server_negTokenTarg(struct gensec_security *gensec_security,
-                                                 struct spnego_state *spnego_state,
-                                                 struct tevent_context *ev,
-                                                 struct spnego_data *spnego_in,
-                                                 TALLOC_CTX *out_mem_ctx,
-                                                 DATA_BLOB *out)
+static const struct spnego_neg_ops gensec_spnego_server_negTokenInit_ops = {
+       .name      = "server_negTokenInit",
+       .start_fn  = gensec_spnego_server_negTokenInit_start,
+       .step_fn   = gensec_spnego_server_negTokenInit_step,
+       .finish_fn = gensec_spnego_server_negTokenInit_finish,
+};
+
+static NTSTATUS gensec_spnego_server_negTokenTarg_start(
+                                       struct gensec_security *gensec_security,
+                                       struct spnego_state *spnego_state,
+                                       struct spnego_neg_state *n,
+                                       struct spnego_data *spnego_in,
+                                       TALLOC_CTX *in_mem_ctx,
+                                       DATA_BLOB *in_next)
 {
        const struct spnego_negTokenTarg *ta = &spnego_in->negTokenTarg;
-       DATA_BLOB sub_in = ta->responseToken;
-       DATA_BLOB mech_list_mic = data_blob_null;
-       DATA_BLOB sub_out = data_blob_null;
        NTSTATUS status;
-       bool have_sign = true;
-       bool new_spnego = false;
 
        spnego_state->num_targs++;
 
@@ -1102,26 +1383,83 @@ static NTSTATUS gensec_spnego_server_negTokenTarg(struct gensec_security *gensec
                if (!NT_STATUS_IS_OK(status)) {
                        DBG_WARNING("failed to verify mechListMIC: %s\n",
                                    nt_errstr(status));
-                       goto server_response;
+                       return status;
                }
 
                spnego_state->needs_mic_check = false;
                spnego_state->done_mic_check = true;
-               goto server_response;
+               return NT_STATUS_OK;
        }
 
        if (!spnego_state->sub_sec_ready) {
-               status = gensec_update_ev(spnego_state->sub_sec_security,
-                                         out_mem_ctx, ev,
-                                         sub_in, &sub_out);
-               if (NT_STATUS_IS_OK(status)) {
-                       spnego_state->sub_sec_ready = true;
-               }
-               if (!NT_STATUS_IS_OK(status)) {
-                       goto server_response;
-               }
-       } else {
-               status = NT_STATUS_OK;
+               *in_next = ta->responseToken;
+               return NT_STATUS_MORE_PROCESSING_REQUIRED;
+       }
+
+       return NT_STATUS_OK;
+}
+
+static NTSTATUS gensec_spnego_server_negTokenTarg_step(
+                                       struct gensec_security *gensec_security,
+                                       struct spnego_state *spnego_state,
+                                       struct spnego_neg_state *n,
+                                       struct spnego_data *spnego_in,
+                                       NTSTATUS last_status,
+                                       TALLOC_CTX *in_mem_ctx,
+                                       DATA_BLOB *in_next)
+{
+       if (GENSEC_UPDATE_IS_NTERROR(last_status)) {
+               DBG_NOTICE("SPNEGO(%s) login failed: %s\n",
+                          spnego_state->sub_sec_security->ops->name,
+                          nt_errstr(last_status));
+               return last_status;
+       }
+
+       /*
+        * This should never be reached!
+        * The step function is only called on errors!
+        */
+       smb_panic(__location__);
+       return NT_STATUS_INTERNAL_ERROR;
+}
+
+static NTSTATUS gensec_spnego_server_negTokenTarg_finish(
+                                       struct gensec_security *gensec_security,
+                                       struct spnego_state *spnego_state,
+                                       struct spnego_neg_state *n,
+                                       struct spnego_data *spnego_in,
+                                       NTSTATUS sub_status,
+                                       const DATA_BLOB sub_out,
+                                       TALLOC_CTX *out_mem_ctx,
+                                       DATA_BLOB *out)
+{
+       const struct spnego_negTokenTarg *ta = &spnego_in->negTokenTarg;
+       DATA_BLOB mech_list_mic = data_blob_null;
+       NTSTATUS status;
+       bool have_sign = true;
+       bool new_spnego = false;
+
+       status = sub_status;
+
+       if (!spnego_state->sub_sec_ready) {
+               /*
+                * We're not yet ready to deal with signatures.
+                */
+               goto server_response;
+       }
+
+       if (spnego_state->done_mic_check) {
+               /*
+                * We already checked the mic,
+                * either the in last round here
+                * in gensec_spnego_server_negTokenTarg_finish()
+                * or during this round in
+                * gensec_spnego_server_negTokenTarg_start().
+                *
+                * Both cases we're sure we don't have to
+                * call gensec_sign_packet().
+                */
+               goto server_response;
        }
 
        have_sign = gensec_have_feature(spnego_state->sub_sec_security,
@@ -1150,7 +1488,7 @@ static NTSTATUS gensec_spnego_server_negTokenTarg(struct gensec_security *gensec
                if (!NT_STATUS_IS_OK(status)) {
                        DBG_WARNING("failed to verify mechListMIC: %s\n",
                                    nt_errstr(status));
-                       goto server_response;
+                       return status;
                }
 
                spnego_state->needs_mic_check = false;
@@ -1159,7 +1497,7 @@ static NTSTATUS gensec_spnego_server_negTokenTarg(struct gensec_security *gensec
 
        if (spnego_state->needs_mic_sign) {
                status = gensec_sign_packet(spnego_state->sub_sec_security,
-                                           out_mem_ctx,
+                                           n,
                                            spnego_state->mech_types.data,
                                            spnego_state->mech_types.length,
                                            spnego_state->mech_types.data,
@@ -1186,12 +1524,31 @@ static NTSTATUS gensec_spnego_server_negTokenTarg(struct gensec_security *gensec
                                             out);
 }
 
+static const struct spnego_neg_ops gensec_spnego_server_negTokenTarg_ops = {
+       .name      = "server_negTokenTarg",
+       .start_fn  = gensec_spnego_server_negTokenTarg_start,
+       .step_fn   = gensec_spnego_server_negTokenTarg_step,
+       .finish_fn = gensec_spnego_server_negTokenTarg_finish,
+};
+
 struct gensec_spnego_update_state {
+       struct tevent_context *ev;
        struct gensec_security *gensec;
        struct spnego_state *spnego;
+
        DATA_BLOB full_in;
        struct spnego_data _spnego_in;
        struct spnego_data *spnego_in;
+
+       struct {
+               bool needed;
+               DATA_BLOB in;
+               NTSTATUS status;
+               DATA_BLOB out;
+       } sub;
+
+       struct spnego_neg_state *n;
+
        NTSTATUS status;
        DATA_BLOB out;
 };
@@ -1220,6 +1577,9 @@ static void gensec_spnego_update_cleanup(struct tevent_req *req,
 static NTSTATUS gensec_spnego_update_in(struct gensec_security *gensec_security,
                                        const DATA_BLOB in, TALLOC_CTX *mem_ctx,
                                        DATA_BLOB *full_in);
+static void gensec_spnego_update_pre(struct tevent_req *req);
+static void gensec_spnego_update_done(struct tevent_req *subreq);
+static void gensec_spnego_update_post(struct tevent_req *req);
 static NTSTATUS gensec_spnego_update_out(struct gensec_security *gensec_security,
                                         TALLOC_CTX *out_mem_ctx,
                                         DATA_BLOB *_out);
@@ -1242,6 +1602,7 @@ static struct tevent_req *gensec_spnego_update_send(TALLOC_CTX *mem_ctx,
        if (req == NULL) {
                return NULL;
        }
+       state->ev = ev;
        state->gensec = gensec_security;
        state->spnego = spnego_state;
        tevent_req_set_cleanup_fn(req, gensec_spnego_update_cleanup);
@@ -1288,7 +1649,7 @@ static struct tevent_req *gensec_spnego_update_send(TALLOC_CTX *mem_ctx,
                        return tevent_req_post(req, ev);
                }
 
-               /* fall through */
+               FALL_THROUGH;
        case SPNEGO_CLIENT_START:
        case SPNEGO_SERVER_START:
 
@@ -1347,101 +1708,45 @@ static struct tevent_req *gensec_spnego_update_send(TALLOC_CTX *mem_ctx,
                return NULL;
        }
 
-       /* and switch into the state machine */
-
-       switch (spnego_state->state_position) {
-       case SPNEGO_FALLBACK:
-               status = gensec_update_ev(spnego_state->sub_sec_security,
-                                         state, ev,
-                                         state->full_in,
-                                         &spnego_state->out_frag);
-               break;
-
-       case SPNEGO_CLIENT_START:
-               if (state->spnego_in == NULL) {
-                       /* client to produce negTokenInit */
-                       status = gensec_spnego_create_negTokenInit(gensec_security,
-                                                       spnego_state, state, ev,
-                                                       &spnego_state->out_frag);
-                       break;
-               }
-
-               status = gensec_spnego_client_negTokenInit(gensec_security,
-                                                       spnego_state, ev,
-                                                       state->spnego_in, state,
-                                                       &spnego_state->out_frag);
-               break;
-
-       case SPNEGO_CLIENT_TARG:
-               status = gensec_spnego_client_negTokenTarg(gensec_security,
-                                                       spnego_state, ev,
-                                                       state->spnego_in, state,
-                                                       &spnego_state->out_frag);
-               break;
-
-       case SPNEGO_SERVER_START:
-               if (state->spnego_in == NULL) {
-                       /* server to produce negTokenInit */
-                       status = gensec_spnego_create_negTokenInit(gensec_security,
-                                                       spnego_state, state, ev,
-                                                       &spnego_state->out_frag);
-                       break;
-               }
-
-               status = gensec_spnego_server_negTokenInit(gensec_security,
-                                                       spnego_state, ev,
-                                                       state->spnego_in, state,
-                                                       &spnego_state->out_frag);
-               break;
-
-       case SPNEGO_SERVER_TARG:
-               status = gensec_spnego_server_negTokenTarg(gensec_security,
-                                                       spnego_state, ev,
-                                                       state->spnego_in, state,
-                                                       &spnego_state->out_frag);
-               break;
-
-       default:
-               smb_panic(__location__);
-               return NULL;
-       }
-
-       if (GENSEC_UPDATE_IS_NTERROR(status)) {
-               tevent_req_nterror(req, status);
+       gensec_spnego_update_pre(req);
+       if (!tevent_req_is_in_progress(req)) {
                return tevent_req_post(req, ev);
        }
 
-       if (NT_STATUS_IS_OK(status)) {
-               bool reset_full = true;
-
-               reset_full = !spnego_state->done_mic_check;
+       if (state->sub.needed) {
+               struct tevent_req *subreq = NULL;
 
-               status = gensec_may_reset_crypto(spnego_state->sub_sec_security,
-                                                reset_full);
-               if (tevent_req_nterror(req, status)) {
+               /*
+                * We may need one more roundtrip...
+                */
+               subreq = gensec_update_send(state, state->ev,
+                                           spnego_state->sub_sec_security,
+                                           state->sub.in);
+               if (tevent_req_nomem(subreq, req)) {
                        return tevent_req_post(req, ev);
                }
+               tevent_req_set_callback(subreq,
+                                       gensec_spnego_update_done,
+                                       req);
+               state->sub.needed = false;
+               return req;
        }
 
-       spnego_state->out_status = status;
-
-       status = gensec_spnego_update_out(gensec_security,
-                                         state, &state->out);
-       if (GENSEC_UPDATE_IS_NTERROR(status)) {
-               tevent_req_nterror(req, status);
+       gensec_spnego_update_post(req);
+       if (!tevent_req_is_in_progress(req)) {
                return tevent_req_post(req, ev);
        }
 
-       state->status = status;
-       tevent_req_done(req);
-       return tevent_req_post(req, ev);
+       return req;
 }
 
 static NTSTATUS gensec_spnego_update_in(struct gensec_security *gensec_security,
                                        const DATA_BLOB in, TALLOC_CTX *mem_ctx,
                                        DATA_BLOB *full_in)
 {
-       struct spnego_state *spnego_state = (struct spnego_state *)gensec_security->private_data;
+       struct spnego_state *spnego_state =
+               talloc_get_type_abort(gensec_security->private_data,
+               struct spnego_state);
        size_t expected;
        bool ok;
 
@@ -1545,11 +1850,234 @@ static NTSTATUS gensec_spnego_update_in(struct gensec_security *gensec_security,
        return NT_STATUS_OK;
 }
 
+static void gensec_spnego_update_pre(struct tevent_req *req)
+{
+       struct gensec_spnego_update_state *state =
+               tevent_req_data(req,
+               struct gensec_spnego_update_state);
+       struct spnego_state *spnego_state = state->spnego;
+       const struct spnego_neg_ops *ops = NULL;
+       NTSTATUS status;
+
+       state->sub.needed = false;
+       state->sub.in = data_blob_null;
+       state->sub.status = NT_STATUS_INTERNAL_ERROR;
+       state->sub.out = data_blob_null;
+
+       if (spnego_state->state_position == SPNEGO_FALLBACK) {
+               state->sub.in = state->full_in;
+               state->full_in = data_blob_null;
+               state->sub.needed = true;
+               return;
+       }
+
+       switch (spnego_state->state_position) {
+       case SPNEGO_CLIENT_START:
+               if (state->spnego_in == NULL) {
+                       /* client to produce negTokenInit */
+                       ops = &gensec_spnego_create_negTokenInit_ops;
+                       break;
+               }
+
+               ops = &gensec_spnego_client_negTokenInit_ops;
+               break;
+
+       case SPNEGO_CLIENT_TARG:
+               ops = &gensec_spnego_client_negTokenTarg_ops;
+               break;
+
+       case SPNEGO_SERVER_START:
+               if (state->spnego_in == NULL) {
+                       /* server to produce negTokenInit */
+                       ops = &gensec_spnego_create_negTokenInit_ops;
+                       break;
+               }
+
+               ops = &gensec_spnego_server_negTokenInit_ops;
+               break;
+
+       case SPNEGO_SERVER_TARG:
+               ops = &gensec_spnego_server_negTokenTarg_ops;
+               break;
+
+       default:
+               smb_panic(__location__);
+               return;
+       }
+
+       state->n = gensec_spnego_neg_state(state, ops);
+       if (tevent_req_nomem(state->n, req)) {
+               return;
+       }
+
+       status = ops->start_fn(state->gensec, spnego_state, state->n,
+                              state->spnego_in, state, &state->sub.in);
+       if (GENSEC_UPDATE_IS_NTERROR(status)) {
+               tevent_req_nterror(req, status);
+               return;
+       }
+
+       if (NT_STATUS_IS_OK(status)) {
+               /*
+                * Call finish_fn() with an empty
+                * blob and NT_STATUS_OK.
+                */
+               state->sub.status = NT_STATUS_OK;
+       } else {
+               /*
+                * MORE_PROCESSING_REQUIRED =>
+                * we need to call gensec_update_send().
+                */
+               state->sub.needed = true;
+       }
+}
+
+static void gensec_spnego_update_done(struct tevent_req *subreq)
+{
+       struct tevent_req *req =
+               tevent_req_callback_data(subreq,
+               struct tevent_req);
+       struct gensec_spnego_update_state *state =
+               tevent_req_data(req,
+               struct gensec_spnego_update_state);
+       struct spnego_state *spnego_state = state->spnego;
+
+       state->sub.status = gensec_update_recv(subreq, state, &state->sub.out);
+       TALLOC_FREE(subreq);
+       if (NT_STATUS_IS_OK(state->sub.status)) {
+               spnego_state->sub_sec_ready = true;
+       }
+
+       gensec_spnego_update_post(req);
+}
+
+static void gensec_spnego_update_post(struct tevent_req *req)
+{
+       struct gensec_spnego_update_state *state =
+               tevent_req_data(req,
+               struct gensec_spnego_update_state);
+       struct spnego_state *spnego_state = state->spnego;
+       const struct spnego_neg_ops *ops = NULL;
+       NTSTATUS status;
+
+       state->sub.in = data_blob_null;
+       state->sub.needed = false;
+
+       if (spnego_state->state_position == SPNEGO_FALLBACK) {
+               status = state->sub.status;
+               spnego_state->out_frag = state->sub.out;
+               talloc_steal(spnego_state, spnego_state->out_frag.data);
+               state->sub.out = data_blob_null;
+               goto respond;
+       }
+
+       ops = state->n->ops;
+
+       if (GENSEC_UPDATE_IS_NTERROR(state->sub.status)) {
+
+
+               /*
+                * gensec_update_recv() returned an error,
+                * let's see if the step_fn() want to
+                * handle it and negotiate something else.
+                */
+
+               status = ops->step_fn(state->gensec,
+                                     spnego_state,
+                                     state->n,
+                                     state->spnego_in,
+                                     state->sub.status,
+                                     state,
+                                     &state->sub.in);
+               if (GENSEC_UPDATE_IS_NTERROR(status)) {
+                       tevent_req_nterror(req, status);
+                       return;
+               }
+
+               state->sub.out = data_blob_null;
+               state->sub.status = NT_STATUS_INTERNAL_ERROR;
+
+               if (NT_STATUS_IS_OK(status)) {
+                       /*
+                        * Call finish_fn() with an empty
+                        * blob and NT_STATUS_OK.
+                        */
+                       state->sub.status = NT_STATUS_OK;
+               } else {
+                       /*
+                        * MORE_PROCESSING_REQUIRED...
+                        */
+                       state->sub.needed = true;
+               }
+       }
+
+       if (state->sub.needed) {
+               struct tevent_req *subreq = NULL;
+
+               /*
+                * We may need one more roundtrip...
+                */
+               subreq = gensec_update_send(state, state->ev,
+                                           spnego_state->sub_sec_security,
+                                           state->sub.in);
+               if (tevent_req_nomem(subreq, req)) {
+                       return;
+               }
+               tevent_req_set_callback(subreq,
+                                       gensec_spnego_update_done,
+                                       req);
+               state->sub.needed = false;
+               return;
+       }
+
+       status = ops->finish_fn(state->gensec,
+                               spnego_state,
+                               state->n,
+                               state->spnego_in,
+                               state->sub.status,
+                               state->sub.out,
+                               spnego_state,
+                               &spnego_state->out_frag);
+       TALLOC_FREE(state->n);
+       if (GENSEC_UPDATE_IS_NTERROR(status)) {
+               tevent_req_nterror(req, status);
+               return;
+       }
+
+       if (NT_STATUS_IS_OK(status)) {
+               bool reset_full = true;
+
+               reset_full = !spnego_state->done_mic_check;
+
+               status = gensec_may_reset_crypto(spnego_state->sub_sec_security,
+                                                reset_full);
+               if (tevent_req_nterror(req, status)) {
+                       return;
+               }
+       }
+
+respond:
+       spnego_state->out_status = status;
+
+       status = gensec_spnego_update_out(state->gensec,
+                                         state, &state->out);
+       if (GENSEC_UPDATE_IS_NTERROR(status)) {
+               tevent_req_nterror(req, status);
+               return;
+       }
+
+       state->status = status;
+       tevent_req_done(req);
+       return;
+}
+
 static NTSTATUS gensec_spnego_update_out(struct gensec_security *gensec_security,
                                         TALLOC_CTX *out_mem_ctx,
                                         DATA_BLOB *_out)
 {
-       struct spnego_state *spnego_state = (struct spnego_state *)gensec_security->private_data;
+       struct spnego_state *spnego_state =
+               talloc_get_type_abort(gensec_security->private_data,
+               struct spnego_state);
        DATA_BLOB out = data_blob_null;
        bool ok;
 
@@ -1657,7 +2185,8 @@ static const struct gensec_security_ops gensec_spnego_security_ops = {
        .expire_time      = gensec_child_expire_time,
        .final_auth_type  = gensec_child_final_auth_type,
        .enabled          = true,
-       .priority         = GENSEC_SPNEGO
+       .priority         = GENSEC_SPNEGO,
+       .glue             = true,
 };
 
 _PUBLIC_ NTSTATUS gensec_spnego_init(TALLOC_CTX *ctx)