auth/spnego: make sure we don't return OK without sub_sec_ready in gensec_spnego_clie...
[vlendec/samba-autobuild/.git] / auth / gensec / spnego.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    RFC2478 Compliant SPNEGO implementation
5
6    Copyright (C) Jim McDonough <jmcd@us.ibm.com>      2003
7    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2004-2005
8    Copyright (C) Stefan Metzmacher <metze@samba.org>  2004-2008
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20
21    You should have received a copy of the GNU General Public License
22    along with this program.  If not, see <http://www.gnu.org/licenses/>.
23 */
24
25 #include "includes.h"
26 #include <tevent.h>
27 #include "lib/util/tevent_ntstatus.h"
28 #include "../libcli/auth/spnego.h"
29 #include "librpc/gen_ndr/ndr_dcerpc.h"
30 #include "auth/credentials/credentials.h"
31 #include "auth/gensec/gensec.h"
32 #include "auth/gensec/gensec_internal.h"
33 #include "param/param.h"
34 #include "lib/util/asn1.h"
35 #include "lib/util/base64.h"
36
37 #undef strcasecmp
38
39 _PUBLIC_ NTSTATUS gensec_spnego_init(TALLOC_CTX *ctx);
40
41 enum spnego_state_position {
42         SPNEGO_SERVER_START,
43         SPNEGO_CLIENT_START,
44         SPNEGO_SERVER_TARG,
45         SPNEGO_CLIENT_TARG,
46         SPNEGO_FALLBACK,
47         SPNEGO_DONE
48 };
49
50 struct spnego_state {
51         enum spnego_message_type expected_packet;
52         enum spnego_state_position state_position;
53         struct gensec_security *sub_sec_security;
54         bool sub_sec_ready;
55
56         const char *neg_oid;
57
58         DATA_BLOB mech_types;
59         size_t num_targs;
60         bool downgraded;
61         bool mic_requested;
62         bool needs_mic_sign;
63         bool needs_mic_check;
64         bool may_skip_mic_check;
65         bool done_mic_check;
66
67         bool simulate_w2k;
68
69         /*
70          * The following is used to implement
71          * the update token fragmentation
72          */
73         size_t in_needed;
74         DATA_BLOB in_frag;
75         size_t out_max_length;
76         DATA_BLOB out_frag;
77         NTSTATUS out_status;
78 };
79
80 static void gensec_spnego_update_sub_abort(struct spnego_state *spnego_state)
81 {
82         spnego_state->sub_sec_ready = false;
83         TALLOC_FREE(spnego_state->sub_sec_security);
84 }
85
86 static NTSTATUS gensec_spnego_client_start(struct gensec_security *gensec_security)
87 {
88         struct spnego_state *spnego_state;
89
90         spnego_state = talloc_zero(gensec_security, struct spnego_state);
91         if (!spnego_state) {
92                 return NT_STATUS_NO_MEMORY;
93         }
94
95         spnego_state->expected_packet = SPNEGO_NEG_TOKEN_INIT;
96         spnego_state->state_position = SPNEGO_CLIENT_START;
97         spnego_state->sub_sec_security = NULL;
98         spnego_state->sub_sec_ready = false;
99         spnego_state->mech_types = data_blob_null;
100         spnego_state->out_max_length = gensec_max_update_size(gensec_security);
101         spnego_state->out_status = NT_STATUS_MORE_PROCESSING_REQUIRED;
102
103         spnego_state->simulate_w2k = gensec_setting_bool(gensec_security->settings,
104                                                 "spnego", "simulate_w2k", false);
105
106         gensec_security->private_data = spnego_state;
107         return NT_STATUS_OK;
108 }
109
110 static NTSTATUS gensec_spnego_server_start(struct gensec_security *gensec_security)
111 {
112         struct spnego_state *spnego_state;
113
114         spnego_state = talloc_zero(gensec_security, struct spnego_state);
115         if (!spnego_state) {
116                 return NT_STATUS_NO_MEMORY;
117         }
118
119         spnego_state->expected_packet = SPNEGO_NEG_TOKEN_INIT;
120         spnego_state->state_position = SPNEGO_SERVER_START;
121         spnego_state->sub_sec_security = NULL;
122         spnego_state->sub_sec_ready = false;
123         spnego_state->mech_types = data_blob_null;
124         spnego_state->out_max_length = gensec_max_update_size(gensec_security);
125         spnego_state->out_status = NT_STATUS_MORE_PROCESSING_REQUIRED;
126
127         spnego_state->simulate_w2k = gensec_setting_bool(gensec_security->settings,
128                                                 "spnego", "simulate_w2k", false);
129
130         gensec_security->private_data = spnego_state;
131         return NT_STATUS_OK;
132 }
133
134 /** Fallback to another GENSEC mechanism, based on magic strings 
135  *
136  * This is the 'fallback' case, where we don't get SPNEGO, and have to
137  * try all the other options (and hope they all have a magic string
138  * they check)
139 */
140
141 static NTSTATUS gensec_spnego_server_try_fallback(struct gensec_security *gensec_security, 
142                                                   struct spnego_state *spnego_state,
143                                                   TALLOC_CTX *mem_ctx,
144                                                   const DATA_BLOB in)
145 {
146         int i,j;
147         const struct gensec_security_ops **all_ops;
148
149         all_ops = gensec_security_mechs(gensec_security, mem_ctx);
150
151         for (i=0; all_ops && all_ops[i]; i++) {
152                 bool is_spnego;
153                 NTSTATUS nt_status;
154
155                 if (gensec_security != NULL &&
156                     !gensec_security_ops_enabled(all_ops[i], gensec_security))
157                 {
158                         continue;
159                 }
160
161                 if (!all_ops[i]->oid) {
162                         continue;
163                 }
164
165                 is_spnego = false;
166                 for (j=0; all_ops[i]->oid[j]; j++) {
167                         if (strcasecmp(GENSEC_OID_SPNEGO,all_ops[i]->oid[j]) == 0) {
168                                 is_spnego = true;
169                         }
170                 }
171                 if (is_spnego) {
172                         continue;
173                 }
174
175                 if (!all_ops[i]->magic) {
176                         continue;
177                 }
178
179                 nt_status = all_ops[i]->magic(gensec_security, &in);
180                 if (!NT_STATUS_IS_OK(nt_status)) {
181                         continue;
182                 }
183
184                 spnego_state->state_position = SPNEGO_FALLBACK;
185
186                 nt_status = gensec_subcontext_start(spnego_state, 
187                                                     gensec_security, 
188                                                     &spnego_state->sub_sec_security);
189
190                 if (!NT_STATUS_IS_OK(nt_status)) {
191                         return nt_status;
192                 }
193                 /* select the sub context */
194                 nt_status = gensec_start_mech_by_ops(spnego_state->sub_sec_security,
195                                                      all_ops[i]);
196                 if (!NT_STATUS_IS_OK(nt_status)) {
197                         return nt_status;
198                 }
199
200                 return NT_STATUS_OK;
201         }
202         DEBUG(1, ("Failed to parse SPNEGO request\n"));
203         return NT_STATUS_INVALID_PARAMETER;
204 }
205
206 /** create a negTokenInit 
207  *
208  * This is the same packet, no matter if the client or server sends it first, but it is always the first packet
209 */
210 static NTSTATUS gensec_spnego_create_negTokenInit(struct gensec_security *gensec_security, 
211                                                   struct spnego_state *spnego_state,
212                                                   TALLOC_CTX *out_mem_ctx, 
213                                                   struct tevent_context *ev,
214                                                   DATA_BLOB *out)
215 {
216         NTSTATUS status;
217         const char **mechTypes = NULL;
218         DATA_BLOB unwrapped_out = data_blob_null;
219         size_t all_idx = 0;
220         const struct gensec_security_ops_wrapper *all_sec;
221         const struct gensec_security_ops_wrapper *cur_sec = NULL;
222         const char **send_mech_types = NULL;
223         struct spnego_data spnego_out;
224         bool ok;
225
226         mechTypes = gensec_security_oids(gensec_security, 
227                                          out_mem_ctx, GENSEC_OID_SPNEGO);
228         if (mechTypes == NULL) {
229                 DBG_WARNING("gensec_security_oids() failed\n");
230                 return NT_STATUS_NO_MEMORY;
231         }
232
233         all_sec = gensec_security_by_oid_list(gensec_security, 
234                                               out_mem_ctx, 
235                                               mechTypes,
236                                               GENSEC_OID_SPNEGO);
237         if (all_sec == NULL) {
238                 DBG_WARNING("gensec_security_by_oid_list() failed\n");
239                 return NT_STATUS_NO_MEMORY;
240         }
241
242         for (; all_sec[all_idx].op != NULL; all_idx++) {
243                 const char *next = NULL;
244                 const char *principal = NULL;
245                 int dbg_level = DBGLVL_WARNING;
246
247                 cur_sec = &all_sec[all_idx];
248
249                 status = gensec_subcontext_start(spnego_state,
250                                                  gensec_security,
251                                                  &spnego_state->sub_sec_security);
252                 if (!NT_STATUS_IS_OK(status)) {
253                         return status;
254                 }
255                 /* select the sub context */
256                 status = gensec_start_mech_by_ops(spnego_state->sub_sec_security,
257                                                   cur_sec->op);
258                 if (!NT_STATUS_IS_OK(status)) {
259                         gensec_spnego_update_sub_abort(spnego_state);
260                         continue;
261                 }
262
263                 if (spnego_state->state_position != SPNEGO_CLIENT_START) {
264                         /*
265                          * The server doesn't generate an optimistic token.
266                          */
267                         goto reply;
268                 }
269
270                 /* In the client, try and produce the first (optimistic) packet */
271                 status = gensec_update_ev(spnego_state->sub_sec_security,
272                                           out_mem_ctx,
273                                           ev,
274                                           data_blob_null,
275                                           &unwrapped_out);
276                 if (NT_STATUS_IS_OK(status)) {
277                         spnego_state->sub_sec_ready = true;
278                 }
279
280                 if (!GENSEC_UPDATE_IS_NTERROR(status)) {
281                         goto reply;
282                 }
283
284                 if (cur_sec[1].op != NULL) {
285                         next = cur_sec[1].op->name;
286                         dbg_level = DBGLVL_NOTICE;
287                 }
288
289                 if (gensec_security->target.principal != NULL) {
290                         principal = gensec_security->target.principal;
291                 } else if (gensec_security->target.service != NULL &&
292                            gensec_security->target.hostname != NULL)
293                 {
294                         principal = talloc_asprintf(spnego_state->sub_sec_security,
295                                                     "%s/%s",
296                                                     gensec_security->target.service,
297                                                     gensec_security->target.hostname);
298                 } else {
299                         principal = gensec_security->target.hostname;
300                 }
301
302                 DBG_PREFIX(dbg_level, (
303                            "%s: creating NEG_TOKEN_INIT for %s failed "
304                            "(next[%s]): %s\n", cur_sec->op->name,
305                            principal, next, nt_errstr(status)));
306
307                 if (next == NULL) {
308                         /*
309                          * A hard error without a possible fallback.
310                          */
311                         return status;
312                 }
313
314                 /*
315                  * Pretend we never started it
316                  */
317                 gensec_spnego_update_sub_abort(spnego_state);
318         }
319
320         DBG_WARNING("Failed to setup SPNEGO negTokenInit request\n");
321         return NT_STATUS_INVALID_PARAMETER;
322
323 reply:
324         spnego_out.type = SPNEGO_NEG_TOKEN_INIT;
325
326         send_mech_types = gensec_security_oids_from_ops_wrapped(out_mem_ctx,
327                                                                 cur_sec);
328         if (send_mech_types == NULL) {
329                 DBG_WARNING("gensec_security_oids_from_ops_wrapped() failed\n");
330                 return NT_STATUS_NO_MEMORY;
331         }
332
333         ok = spnego_write_mech_types(spnego_state,
334                                      send_mech_types,
335                                      &spnego_state->mech_types);
336         if (!ok) {
337                 DBG_ERR("Failed to write mechTypes\n");
338                 return NT_STATUS_NO_MEMORY;
339         }
340
341         /* List the remaining mechs as options */
342         spnego_out.negTokenInit.mechTypes = send_mech_types;
343         spnego_out.negTokenInit.reqFlags = data_blob_null;
344         spnego_out.negTokenInit.reqFlagsPadding = 0;
345
346         if (spnego_state->state_position == SPNEGO_SERVER_START) {
347                 spnego_out.negTokenInit.mechListMIC
348                         = data_blob_string_const(ADS_IGNORE_PRINCIPAL);
349         } else {
350                 spnego_out.negTokenInit.mechListMIC = data_blob_null;
351         }
352
353         spnego_out.negTokenInit.mechToken = unwrapped_out;
354
355         if (spnego_write_data(out_mem_ctx, out, &spnego_out) == -1) {
356                 DBG_ERR("Failed to write NEG_TOKEN_INIT\n");
357                 return NT_STATUS_INVALID_PARAMETER;
358         }
359
360         /*
361          * Note that 'cur_sec' is temporary memory, but
362          * cur_sec->oid points to a const string in the
363          * backends gensec_security_ops structure.
364          */
365         spnego_state->neg_oid = cur_sec->oid;
366
367         /* set next state */
368         if (spnego_state->state_position == SPNEGO_SERVER_START) {
369                 spnego_state->state_position = SPNEGO_SERVER_START;
370                 spnego_state->expected_packet = SPNEGO_NEG_TOKEN_INIT;
371         } else {
372                 spnego_state->state_position = SPNEGO_CLIENT_TARG;
373                 spnego_state->expected_packet = SPNEGO_NEG_TOKEN_TARG;
374         }
375
376         return NT_STATUS_MORE_PROCESSING_REQUIRED;
377 }
378
379 static NTSTATUS gensec_spnego_client_negTokenInit(struct gensec_security *gensec_security,
380                                                   struct spnego_state *spnego_state,
381                                                   struct tevent_context *ev,
382                                                   struct spnego_data *spnego_in,
383                                                   TALLOC_CTX *out_mem_ctx,
384                                                   DATA_BLOB *out)
385 {
386         TALLOC_CTX *frame = talloc_stackframe();
387         DATA_BLOB sub_out = data_blob_null;
388         const char *tp = NULL;
389         const char * const *mech_types = NULL;
390         size_t all_idx = 0;
391         const struct gensec_security_ops_wrapper *all_sec = NULL;
392         struct spnego_data spnego_out;
393         const char *my_mechs[] = {NULL, NULL};
394         NTSTATUS status;
395         bool ok;
396
397         *out = data_blob_null;
398
399         /* The server offers a list of mechanisms */
400
401         tp = spnego_in->negTokenInit.targetPrincipal;
402         if (tp != NULL && strcmp(tp, ADS_IGNORE_PRINCIPAL) != 0) {
403                 DBG_INFO("Server claims it's principal name is %s\n", tp);
404                 if (lpcfg_client_use_spnego_principal(gensec_security->settings->lp_ctx)) {
405                         gensec_set_target_principal(gensec_security, tp);
406                 }
407         }
408
409         mech_types = spnego_in->negTokenInit.mechTypes;
410         if (mech_types == NULL) {
411                 TALLOC_FREE(frame);
412                 return NT_STATUS_INVALID_PARAMETER;
413         }
414
415         all_sec = gensec_security_by_oid_list(gensec_security,
416                                               frame, mech_types,
417                                               GENSEC_OID_SPNEGO);
418         if (all_sec == NULL) {
419                 DBG_WARNING("gensec_security_by_oid_list() failed\n");
420                 TALLOC_FREE(frame);
421                 return NT_STATUS_INVALID_PARAMETER;
422         }
423
424         for (; all_sec[all_idx].op; all_idx++) {
425                 const struct gensec_security_ops_wrapper *cur_sec =
426                         &all_sec[all_idx];
427                 const char *next = NULL;
428                 const char *principal = NULL;
429                 int dbg_level = DBGLVL_WARNING;
430                 bool allow_fallback = false;
431
432                 status = gensec_subcontext_start(spnego_state,
433                                                  gensec_security,
434                                                  &spnego_state->sub_sec_security);
435                 if (!NT_STATUS_IS_OK(status)) {
436                         TALLOC_FREE(frame);
437                         return status;
438                 }
439
440                 /* select the sub context */
441                 status = gensec_start_mech_by_ops(spnego_state->sub_sec_security,
442                                                   cur_sec->op);
443                 if (!NT_STATUS_IS_OK(status)) {
444                         /*
445                          * Pretend we never started it.
446                          */
447                         gensec_spnego_update_sub_abort(spnego_state);
448                         continue;
449                 }
450
451                 spnego_state->neg_oid = cur_sec->oid;
452
453                 /*
454                  * As client we don't use an optimistic token from the server.
455                  */
456                 status = gensec_update_ev(spnego_state->sub_sec_security,
457                                           frame, ev, data_blob_null, &sub_out);
458                 if (NT_STATUS_IS_OK(status)) {
459                         spnego_state->sub_sec_ready = true;
460                 }
461
462                 if (!GENSEC_UPDATE_IS_NTERROR(status)) {
463                         /* OK or MORE_PROCESSING_REQUIRED */
464                         goto reply;
465                 }
466
467                 /*
468                  * it is likely that a NULL input token will
469                  * not be liked by most server mechs, but if
470                  * we are in the client, we want the first
471                  * update packet to be able to abort the use
472                  * of this mech
473                  */
474                 if (NT_STATUS_EQUAL(status, NT_STATUS_INVALID_PARAMETER) ||
475                     NT_STATUS_EQUAL(status, NT_STATUS_NO_LOGON_SERVERS) ||
476                     NT_STATUS_EQUAL(status, NT_STATUS_TIME_DIFFERENCE_AT_DC) ||
477                     NT_STATUS_EQUAL(status, NT_STATUS_CANT_ACCESS_DOMAIN_INFO))
478                 {
479                         allow_fallback = true;
480                 }
481
482                 if (allow_fallback && cur_sec[1].op != NULL) {
483                         next = cur_sec[1].op->name;
484                         dbg_level = DBGLVL_NOTICE;
485                 }
486
487                 if (gensec_security->target.principal != NULL) {
488                         principal = gensec_security->target.principal;
489                 } else if (gensec_security->target.service != NULL &&
490                            gensec_security->target.hostname != NULL)
491                 {
492                         principal = talloc_asprintf(spnego_state->sub_sec_security,
493                                                     "%s/%s",
494                                                     gensec_security->target.service,
495                                                     gensec_security->target.hostname);
496                 } else {
497                         principal = gensec_security->target.hostname;
498                 }
499
500                 DBG_PREFIX(dbg_level, (
501                            "%s: creating NEG_TOKEN_INIT "
502                            "for %s failed (next[%s]): %s\n",
503                            spnego_state->sub_sec_security->ops->name,
504                            principal, next, nt_errstr(status)));
505
506                 if (next == NULL) {
507                         /*
508                          * A hard error without a possible fallback.
509                          */
510                         TALLOC_FREE(frame);
511                         return status;
512                 }
513
514                 /*
515                  * Pretend we never started it.
516                  */
517                 gensec_spnego_update_sub_abort(spnego_state);
518         }
519
520         DBG_WARNING("Could not find a suitable mechtype in NEG_TOKEN_INIT\n");
521         TALLOC_FREE(frame);
522         return NT_STATUS_INVALID_PARAMETER;
523
524  reply:
525         my_mechs[0] = spnego_state->neg_oid;
526         /* compose reply */
527         spnego_out.type = SPNEGO_NEG_TOKEN_INIT;
528         spnego_out.negTokenInit.mechTypes = my_mechs;
529         spnego_out.negTokenInit.reqFlags = data_blob_null;
530         spnego_out.negTokenInit.reqFlagsPadding = 0;
531         spnego_out.negTokenInit.mechListMIC = data_blob_null;
532         spnego_out.negTokenInit.mechToken = sub_out;
533
534         if (spnego_write_data(out_mem_ctx, out, &spnego_out) == -1) {
535                 DBG_ERR("Failed to write SPNEGO reply to NEG_TOKEN_INIT\n");
536                 TALLOC_FREE(frame);
537                 return NT_STATUS_INVALID_PARAMETER;
538         }
539
540         ok = spnego_write_mech_types(spnego_state,
541                                      my_mechs,
542                                      &spnego_state->mech_types);
543         if (!ok) {
544                 DBG_ERR("failed to write mechTypes\n");
545                 TALLOC_FREE(frame);
546                 return NT_STATUS_NO_MEMORY;
547         }
548
549         /* set next state */
550         spnego_state->expected_packet = SPNEGO_NEG_TOKEN_TARG;
551         spnego_state->state_position = SPNEGO_CLIENT_TARG;
552
553         TALLOC_FREE(frame);
554         return NT_STATUS_MORE_PROCESSING_REQUIRED;
555 }
556
557 static NTSTATUS gensec_spnego_client_negTokenTarg(struct gensec_security *gensec_security,
558                                                   struct spnego_state *spnego_state,
559                                                   struct tevent_context *ev,
560                                                   struct spnego_data *spnego_in,
561                                                   TALLOC_CTX *out_mem_ctx,
562                                                   DATA_BLOB *out)
563 {
564         struct spnego_negTokenTarg *ta = &spnego_in->negTokenTarg;
565         DATA_BLOB sub_in = ta->responseToken;
566         DATA_BLOB mech_list_mic = data_blob_null;
567         DATA_BLOB sub_out = data_blob_null;
568         struct spnego_data spnego_out;
569         NTSTATUS status;
570
571         *out = data_blob_null;
572
573         spnego_state->num_targs++;
574
575         if (ta->negResult == SPNEGO_REJECT) {
576                 return NT_STATUS_LOGON_FAILURE;
577         }
578
579         if (ta->negResult == SPNEGO_REQUEST_MIC) {
580                 spnego_state->mic_requested = true;
581         }
582
583         if (ta->mechListMIC.length > 0) {
584                 DATA_BLOB *m = &ta->mechListMIC;
585                 const DATA_BLOB *r = &ta->responseToken;
586
587                 /*
588                  * Windows 2000 has a bug, it repeats the
589                  * responseToken in the mechListMIC field.
590                  */
591                 if (m->length == r->length) {
592                         int cmp;
593
594                         cmp = memcmp(m->data, r->data, m->length);
595                         if (cmp == 0) {
596                                 data_blob_free(m);
597                         }
598                 }
599         }
600
601         /* Server didn't like our choice of mech, and chose something else */
602         if (((ta->negResult == SPNEGO_ACCEPT_INCOMPLETE) ||
603              (ta->negResult == SPNEGO_REQUEST_MIC)) &&
604             ta->supportedMech != NULL &&
605             strcmp(ta->supportedMech, spnego_state->neg_oid) != 0)
606         {
607                 const char *client_mech = NULL;
608                 const char *client_oid = NULL;
609                 const char *server_mech = NULL;
610                 const char *server_oid = NULL;
611
612                 client_mech = gensec_get_name_by_oid(gensec_security,
613                                                      spnego_state->neg_oid);
614                 client_oid = spnego_state->neg_oid;
615                 server_mech = gensec_get_name_by_oid(gensec_security,
616                                                      ta->supportedMech);
617                 server_oid = ta->supportedMech;
618
619                 DBG_NOTICE("client preferred mech (%s[%s]) not accepted, "
620                            "server wants: %s[%s]\n",
621                            client_mech, client_oid, server_mech, server_oid);
622
623                 spnego_state->downgraded = true;
624                 gensec_spnego_update_sub_abort(spnego_state);
625
626                 status = gensec_subcontext_start(spnego_state,
627                                                  gensec_security,
628                                                  &spnego_state->sub_sec_security);
629                 if (!NT_STATUS_IS_OK(status)) {
630                         return status;
631                 }
632
633                 /* select the sub context */
634                 status = gensec_start_mech_by_oid(spnego_state->sub_sec_security,
635                                                   ta->supportedMech);
636                 if (!NT_STATUS_IS_OK(status)) {
637                         return status;
638                 }
639
640                 spnego_state->neg_oid = talloc_strdup(spnego_state,
641                                         ta->supportedMech);
642                 if (spnego_state->neg_oid == NULL) {
643                         return NT_STATUS_NO_MEMORY;
644                 }
645         }
646
647         if (ta->mechListMIC.length > 0) {
648                 if (spnego_state->sub_sec_ready) {
649                         spnego_state->needs_mic_check = true;
650                 }
651         }
652
653         if (spnego_state->needs_mic_check) {
654                 if (ta->responseToken.length != 0) {
655                         DBG_WARNING("non empty response token not expected\n");
656                         return NT_STATUS_INVALID_PARAMETER;
657                 }
658
659                 if (ta->mechListMIC.length == 0
660                     && spnego_state->may_skip_mic_check) {
661                         /*
662                          * In this case we don't require
663                          * a mechListMIC from the server.
664                          *
665                          * This works around bugs in the Azure
666                          * and Apple spnego implementations.
667                          *
668                          * See
669                          * https://bugzilla.samba.org/show_bug.cgi?id=11994
670                          */
671                         spnego_state->needs_mic_check = false;
672                         status = NT_STATUS_OK;
673                         goto client_response;
674                 }
675
676                 status = gensec_check_packet(spnego_state->sub_sec_security,
677                                              spnego_state->mech_types.data,
678                                              spnego_state->mech_types.length,
679                                              spnego_state->mech_types.data,
680                                              spnego_state->mech_types.length,
681                                              &ta->mechListMIC);
682                 if (!NT_STATUS_IS_OK(status)) {
683                         DBG_WARNING("failed to verify mechListMIC: %s\n",
684                                     nt_errstr(status));
685                         return status;
686                 }
687                 spnego_state->needs_mic_check = false;
688                 spnego_state->done_mic_check = true;
689                 goto client_response;
690         }
691
692         if (!spnego_state->sub_sec_ready) {
693                 status = gensec_update_ev(spnego_state->sub_sec_security,
694                                           out_mem_ctx, ev,
695                                           sub_in,
696                                           &sub_out);
697                 if (NT_STATUS_IS_OK(status)) {
698                         spnego_state->sub_sec_ready = true;
699                 }
700                 if (!NT_STATUS_IS_OK(status)) {
701                         goto client_response;
702                 }
703         } else {
704                 status = NT_STATUS_OK;
705         }
706
707         if (!spnego_state->done_mic_check) {
708                 bool have_sign = true;
709                 bool new_spnego = false;
710
711                 have_sign = gensec_have_feature(spnego_state->sub_sec_security,
712                                                 GENSEC_FEATURE_SIGN);
713                 if (spnego_state->simulate_w2k) {
714                         have_sign = false;
715                 }
716                 new_spnego = gensec_have_feature(spnego_state->sub_sec_security,
717                                                  GENSEC_FEATURE_NEW_SPNEGO);
718
719                 switch (ta->negResult) {
720                 case SPNEGO_ACCEPT_COMPLETED:
721                 case SPNEGO_NONE_RESULT:
722                         if (spnego_state->num_targs == 1) {
723                                 /*
724                                  * the first exchange doesn't require
725                                  * verification
726                                  */
727                                 new_spnego = false;
728                         }
729
730                         break;
731
732                 case SPNEGO_ACCEPT_INCOMPLETE:
733                         if (ta->mechListMIC.length > 0) {
734                                 new_spnego = true;
735                                 break;
736                         }
737
738                         if (spnego_state->downgraded) {
739                                 /*
740                                  * A downgrade should be protected if
741                                  * supported
742                                  */
743                                 break;
744                         }
745
746                         /*
747                          * The caller may just asked for
748                          * GENSEC_FEATURE_SESSION_KEY, this
749                          * is only reflected in the want_features.
750                          *
751                          * As it will imply
752                          * gensec_have_features(GENSEC_FEATURE_SIGN)
753                          * to return true.
754                          */
755                         if (gensec_security->want_features & GENSEC_FEATURE_SIGN) {
756                                 break;
757                         }
758                         if (gensec_security->want_features & GENSEC_FEATURE_SEAL) {
759                                 break;
760                         }
761                         /*
762                          * Here we're sure our preferred mech was
763                          * selected by the server and our caller doesn't
764                          * need GENSEC_FEATURE_SIGN nor
765                          * GENSEC_FEATURE_SEAL support.
766                          *
767                          * In this case we don't require
768                          * a mechListMIC from the server.
769                          *
770                          * This works around bugs in the Azure
771                          * and Apple spnego implementations.
772                          *
773                          * See
774                          * https://bugzilla.samba.org/show_bug.cgi?id=11994
775                          */
776                         spnego_state->may_skip_mic_check = true;
777                         break;
778
779                 case SPNEGO_REQUEST_MIC:
780                         if (ta->mechListMIC.length > 0) {
781                                 new_spnego = true;
782                         }
783                         break;
784                 default:
785                         break;
786                 }
787
788                 if (spnego_state->mic_requested) {
789                         if (have_sign) {
790                                 new_spnego = true;
791                         }
792                 }
793
794                 if (have_sign && new_spnego) {
795                         spnego_state->needs_mic_check = true;
796                         spnego_state->needs_mic_sign = true;
797                 }
798         }
799
800         if (ta->mechListMIC.length > 0) {
801                 status = gensec_check_packet(spnego_state->sub_sec_security,
802                                              spnego_state->mech_types.data,
803                                              spnego_state->mech_types.length,
804                                              spnego_state->mech_types.data,
805                                              spnego_state->mech_types.length,
806                                              &ta->mechListMIC);
807                 if (!NT_STATUS_IS_OK(status)) {
808                         DBG_WARNING("failed to verify mechListMIC: %s\n",
809                                     nt_errstr(status));
810                         return status;
811                 }
812                 spnego_state->needs_mic_check = false;
813                 spnego_state->done_mic_check = true;
814         }
815
816         if (spnego_state->needs_mic_sign) {
817                 status = gensec_sign_packet(spnego_state->sub_sec_security,
818                                             out_mem_ctx,
819                                             spnego_state->mech_types.data,
820                                             spnego_state->mech_types.length,
821                                             spnego_state->mech_types.data,
822                                             spnego_state->mech_types.length,
823                                             &mech_list_mic);
824                 if (!NT_STATUS_IS_OK(status)) {
825                         DBG_WARNING("failed to sign mechListMIC: %s\n",
826                                     nt_errstr(status));
827                         return status;
828                 }
829                 spnego_state->needs_mic_sign = false;
830         }
831
832         if (spnego_state->needs_mic_check) {
833                 status = NT_STATUS_MORE_PROCESSING_REQUIRED;
834         }
835
836  client_response:
837         if (GENSEC_UPDATE_IS_NTERROR(status)) {
838                 DBG_WARNING("SPNEGO(%s) login failed: %s\n",
839                             spnego_state->sub_sec_security->ops->name,
840                             nt_errstr(status));
841                 return status;
842         }
843
844         if (sub_out.length == 0 && mech_list_mic.length == 0) {
845                 *out = data_blob_null;
846
847                 if (!spnego_state->sub_sec_ready) {
848                         /* somethings wrong here... */
849                         DBG_ERR("gensec_update not ready without output\n");
850                         return NT_STATUS_INTERNAL_ERROR;
851                 }
852
853                 if (ta->negResult != SPNEGO_ACCEPT_COMPLETED) {
854                         /* unless of course it did not accept */
855                         DBG_WARNING("gensec_update ok but not accepted\n");
856                         return NT_STATUS_INVALID_PARAMETER;
857                 }
858
859                 spnego_state->state_position = SPNEGO_DONE;
860                 return status;
861         }
862
863         /* compose reply */
864         spnego_out.type = SPNEGO_NEG_TOKEN_TARG;
865         spnego_out.negTokenTarg.negResult = SPNEGO_NONE_RESULT;
866         spnego_out.negTokenTarg.supportedMech = NULL;
867         spnego_out.negTokenTarg.responseToken = sub_out;
868         spnego_out.negTokenTarg.mechListMIC = mech_list_mic;
869
870         if (spnego_write_data(out_mem_ctx, out, &spnego_out) == -1) {
871                 DBG_WARNING("Failed to write NEG_TOKEN_TARG\n");
872                 return NT_STATUS_INVALID_PARAMETER;
873         }
874
875         spnego_state->num_targs++;
876
877         /* set next state */
878         spnego_state->state_position = SPNEGO_CLIENT_TARG;
879         spnego_state->expected_packet = SPNEGO_NEG_TOKEN_TARG;
880
881         return NT_STATUS_MORE_PROCESSING_REQUIRED;
882 }
883
884 /** create a server negTokenTarg 
885  *
886  * This is the case, where the client is the first one who sends data
887 */
888
889 static NTSTATUS gensec_spnego_server_response(struct spnego_state *spnego_state,
890                                               TALLOC_CTX *out_mem_ctx,
891                                               NTSTATUS nt_status,
892                                               const DATA_BLOB unwrapped_out,
893                                               DATA_BLOB mech_list_mic,
894                                               DATA_BLOB *out)
895 {
896         struct spnego_data spnego_out;
897
898         /* compose reply */
899         spnego_out.type = SPNEGO_NEG_TOKEN_TARG;
900         spnego_out.negTokenTarg.responseToken = unwrapped_out;
901         spnego_out.negTokenTarg.mechListMIC = mech_list_mic;
902         spnego_out.negTokenTarg.supportedMech = NULL;
903
904         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {   
905                 spnego_out.negTokenTarg.supportedMech = spnego_state->neg_oid;
906                 if (spnego_state->mic_requested) {
907                         spnego_out.negTokenTarg.negResult = SPNEGO_REQUEST_MIC;
908                         spnego_state->mic_requested = false;
909                 } else {
910                         spnego_out.negTokenTarg.negResult = SPNEGO_ACCEPT_INCOMPLETE;
911                 }
912                 spnego_state->state_position = SPNEGO_SERVER_TARG;
913         } else if (NT_STATUS_IS_OK(nt_status)) {
914                 if (unwrapped_out.data) {
915                         spnego_out.negTokenTarg.supportedMech = spnego_state->neg_oid;
916                 }
917                 spnego_out.negTokenTarg.negResult = SPNEGO_ACCEPT_COMPLETED;
918                 spnego_state->state_position = SPNEGO_DONE;
919         } else {
920                 spnego_out.negTokenTarg.negResult = SPNEGO_REJECT;
921                 spnego_out.negTokenTarg.mechListMIC = data_blob_null;
922                 DEBUG(2, ("SPNEGO login failed: %s\n", nt_errstr(nt_status)));
923                 spnego_state->state_position = SPNEGO_DONE;
924         }
925
926         if (spnego_write_data(out_mem_ctx, out, &spnego_out) == -1) {
927                 DEBUG(1, ("Failed to write SPNEGO reply to NEG_TOKEN_TARG\n"));
928                 return NT_STATUS_INVALID_PARAMETER;
929         }
930
931         spnego_state->expected_packet = SPNEGO_NEG_TOKEN_TARG;
932         spnego_state->num_targs++;
933
934         return nt_status;
935 }
936
937 static NTSTATUS gensec_spnego_server_negTokenInit(struct gensec_security *gensec_security,
938                                                   struct spnego_state *spnego_state,
939                                                   struct tevent_context *ev,
940                                                   struct spnego_data *spnego_in,
941                                                   TALLOC_CTX *out_mem_ctx,
942                                                   DATA_BLOB *out)
943 {
944         TALLOC_CTX *frame = talloc_stackframe();
945         DATA_BLOB sub_out = data_blob_null;
946         DATA_BLOB mech_list_mic = data_blob_null;
947         const char * const *mech_types = NULL;
948         size_t all_idx = 0;
949         const struct gensec_security_ops_wrapper *all_sec = NULL;
950         size_t mech_idx = 0;
951         NTSTATUS status;
952         bool ok;
953
954         mech_types = spnego_in->negTokenInit.mechTypes;
955         if (mech_types == NULL) {
956                 TALLOC_FREE(frame);
957                 return NT_STATUS_INVALID_PARAMETER;
958         }
959
960         all_sec = gensec_security_by_oid_list(gensec_security, frame,
961                                               mech_types, GENSEC_OID_SPNEGO);
962         if (all_sec == NULL) {
963                 DBG_WARNING("gensec_security_by_oid_list() failed\n");
964                 TALLOC_FREE(frame);
965                 return NT_STATUS_INVALID_PARAMETER;
966         }
967
968         ok = spnego_write_mech_types(spnego_state, mech_types,
969                                      &spnego_state->mech_types);
970         if (!ok) {
971                 DBG_ERR("Failed to write mechTypes\n");
972                 TALLOC_FREE(frame);
973                 return NT_STATUS_NO_MEMORY;
974         }
975
976         /*
977          * First try the preferred mechs from the client.
978          */
979         for (; mech_types[mech_idx]; mech_idx++) {
980                 const char *cur_mech = mech_types[mech_idx];
981                 const struct gensec_security_ops_wrapper *cur_sec = NULL;
982                 DATA_BLOB sub_in = data_blob_null;
983
984                 for (all_idx = 0; all_sec[all_idx].op; all_idx++) {
985                         if (strcmp(cur_mech, all_sec[all_idx].oid) == 0) {
986                                 cur_sec = &all_sec[all_idx];
987                                 break;
988                         }
989                 }
990
991                 if (cur_sec == NULL) {
992                         continue;
993                 }
994
995                 status = gensec_subcontext_start(spnego_state,
996                                                  gensec_security,
997                                                  &spnego_state->sub_sec_security);
998                 if (!NT_STATUS_IS_OK(status)) {
999                         TALLOC_FREE(frame);
1000                         return status;
1001                 }
1002
1003                 /* select the sub context */
1004                 status = gensec_start_mech_by_ops(spnego_state->sub_sec_security,
1005                                                   cur_sec->op);
1006                 if (!NT_STATUS_IS_OK(status)) {
1007                         /*
1008                          * Pretend we never started it
1009                          */
1010                         gensec_spnego_update_sub_abort(spnego_state);
1011                         continue;
1012                 }
1013
1014                 if (mech_idx > 0) {
1015                         /*
1016                          * Indicate the downgrade and request a
1017                          * mic.
1018                          */
1019                         spnego_state->downgraded = true;
1020                         spnego_state->mic_requested = true;
1021                         /* no optimistic token */
1022                         spnego_state->neg_oid = cur_sec->oid;
1023                         sub_out = data_blob_null;
1024                         status = NT_STATUS_MORE_PROCESSING_REQUIRED;
1025                         goto reply;
1026                 }
1027
1028                 /*
1029                  * Try the optimistic token from the client
1030                  */
1031                 sub_in = spnego_in->negTokenInit.mechToken;
1032                 status = gensec_update_ev(spnego_state->sub_sec_security,
1033                                           frame, ev, sub_in, &sub_out);
1034                 if (NT_STATUS_IS_OK(status)) {
1035                         spnego_state->sub_sec_ready = true;
1036                 }
1037                 if (NT_STATUS_EQUAL(status, NT_STATUS_INVALID_PARAMETER) ||
1038                     NT_STATUS_EQUAL(status, NT_STATUS_CANT_ACCESS_DOMAIN_INFO)) {
1039
1040                         DBG_WARNING("%s: NEG_TOKEN_INIT failed to parse contents: %s\n",
1041                                     cur_sec->op->name, nt_errstr(status));
1042
1043                         /*
1044                          * Pretend we never started it
1045                          */
1046                         gensec_spnego_update_sub_abort(spnego_state);
1047                         continue;
1048                 }
1049
1050                 if (GENSEC_UPDATE_IS_NTERROR(status)) {
1051                         DBG_WARNING("%s: NEG_TOKEN_INIT failed: %s\n",
1052                                     cur_sec->op->name, nt_errstr(status));
1053                         goto reply;
1054                 }
1055
1056                 spnego_state->neg_oid = cur_sec->oid;
1057                 goto reply; /* OK or MORE PROCESSING */
1058         }
1059
1060         DBG_WARNING("Could not find a suitable mechtype in NEG_TOKEN_INIT\n");
1061         status = NT_STATUS_INVALID_PARAMETER;
1062
1063  reply:
1064         if (spnego_state->simulate_w2k) {
1065                 /*
1066                  * Windows 2000 returns the unwrapped token
1067                  * also in the mech_list_mic field.
1068                  *
1069                  * In order to verify our client code,
1070                  * we need a way to have a server with this
1071                  * broken behaviour
1072                  */
1073                 mech_list_mic = sub_out;
1074         }
1075
1076         status = gensec_spnego_server_response(spnego_state,
1077                                                out_mem_ctx,
1078                                                status,
1079                                                sub_out,
1080                                                mech_list_mic,
1081                                                out);
1082         TALLOC_FREE(frame);
1083         return status;
1084 }
1085
1086 static NTSTATUS gensec_spnego_server_negTokenTarg(struct gensec_security *gensec_security,
1087                                                   struct spnego_state *spnego_state,
1088                                                   struct tevent_context *ev,
1089                                                   struct spnego_data *spnego_in,
1090                                                   TALLOC_CTX *out_mem_ctx,
1091                                                   DATA_BLOB *out)
1092 {
1093         const struct spnego_negTokenTarg *ta = &spnego_in->negTokenTarg;
1094         DATA_BLOB sub_in = ta->responseToken;
1095         DATA_BLOB mech_list_mic = data_blob_null;
1096         DATA_BLOB sub_out = data_blob_null;
1097         NTSTATUS status;
1098         bool have_sign = true;
1099         bool new_spnego = false;
1100
1101         spnego_state->num_targs++;
1102
1103         if (spnego_state->sub_sec_security == NULL) {
1104                 DBG_ERR("SPNEGO: Did not setup a mech in NEG_TOKEN_INIT\n");
1105                 return NT_STATUS_INVALID_PARAMETER;
1106         }
1107
1108         if (spnego_state->needs_mic_check) {
1109                 if (ta->responseToken.length != 0) {
1110                         DBG_WARNING("non empty response token not expected\n");
1111                         return NT_STATUS_INVALID_PARAMETER;
1112                 }
1113
1114                 status = gensec_check_packet(spnego_state->sub_sec_security,
1115                                              spnego_state->mech_types.data,
1116                                              spnego_state->mech_types.length,
1117                                              spnego_state->mech_types.data,
1118                                              spnego_state->mech_types.length,
1119                                              &ta->mechListMIC);
1120                 if (!NT_STATUS_IS_OK(status)) {
1121                         DBG_WARNING("failed to verify mechListMIC: %s\n",
1122                                     nt_errstr(status));
1123                         goto server_response;
1124                 }
1125
1126                 spnego_state->needs_mic_check = false;
1127                 spnego_state->done_mic_check = true;
1128                 goto server_response;
1129         }
1130
1131         if (!spnego_state->sub_sec_ready) {
1132                 status = gensec_update_ev(spnego_state->sub_sec_security,
1133                                           out_mem_ctx, ev,
1134                                           sub_in, &sub_out);
1135                 if (NT_STATUS_IS_OK(status)) {
1136                         spnego_state->sub_sec_ready = true;
1137                 }
1138                 if (!NT_STATUS_IS_OK(status)) {
1139                         goto server_response;
1140                 }
1141         } else {
1142                 status = NT_STATUS_OK;
1143         }
1144
1145         have_sign = gensec_have_feature(spnego_state->sub_sec_security,
1146                                         GENSEC_FEATURE_SIGN);
1147         if (spnego_state->simulate_w2k) {
1148                 have_sign = false;
1149         }
1150         new_spnego = gensec_have_feature(spnego_state->sub_sec_security,
1151                                          GENSEC_FEATURE_NEW_SPNEGO);
1152         if (ta->mechListMIC.length > 0) {
1153                 new_spnego = true;
1154         }
1155
1156         if (have_sign && new_spnego) {
1157                 spnego_state->needs_mic_check = true;
1158                 spnego_state->needs_mic_sign = true;
1159         }
1160
1161         if (have_sign && ta->mechListMIC.length > 0) {
1162                 status = gensec_check_packet(spnego_state->sub_sec_security,
1163                                              spnego_state->mech_types.data,
1164                                              spnego_state->mech_types.length,
1165                                              spnego_state->mech_types.data,
1166                                              spnego_state->mech_types.length,
1167                                              &ta->mechListMIC);
1168                 if (!NT_STATUS_IS_OK(status)) {
1169                         DBG_WARNING("failed to verify mechListMIC: %s\n",
1170                                     nt_errstr(status));
1171                         goto server_response;
1172                 }
1173
1174                 spnego_state->needs_mic_check = false;
1175                 spnego_state->done_mic_check = true;
1176         }
1177
1178         if (spnego_state->needs_mic_sign) {
1179                 status = gensec_sign_packet(spnego_state->sub_sec_security,
1180                                             out_mem_ctx,
1181                                             spnego_state->mech_types.data,
1182                                             spnego_state->mech_types.length,
1183                                             spnego_state->mech_types.data,
1184                                             spnego_state->mech_types.length,
1185                                             &mech_list_mic);
1186                 if (!NT_STATUS_IS_OK(status)) {
1187                         DBG_WARNING("failed to sign mechListMIC: %s\n",
1188                                     nt_errstr(status));
1189                         return status;
1190                 }
1191                 spnego_state->needs_mic_sign = false;
1192         }
1193
1194         if (spnego_state->needs_mic_check) {
1195                 status = NT_STATUS_MORE_PROCESSING_REQUIRED;
1196         }
1197
1198  server_response:
1199         return gensec_spnego_server_response(spnego_state,
1200                                              out_mem_ctx,
1201                                              status,
1202                                              sub_out,
1203                                              mech_list_mic,
1204                                              out);
1205 }
1206
1207 struct gensec_spnego_update_state {
1208         struct tevent_context *ev;
1209         struct gensec_security *gensec;
1210         struct spnego_state *spnego;
1211
1212         DATA_BLOB full_in;
1213         struct spnego_data _spnego_in;
1214         struct spnego_data *spnego_in;
1215
1216         struct {
1217                 bool needed;
1218                 DATA_BLOB in;
1219                 NTSTATUS status;
1220                 DATA_BLOB out;
1221         } sub;
1222
1223         NTSTATUS status;
1224         DATA_BLOB out;
1225 };
1226
1227 static void gensec_spnego_update_cleanup(struct tevent_req *req,
1228                                          enum tevent_req_state req_state)
1229 {
1230         struct gensec_spnego_update_state *state =
1231                 tevent_req_data(req,
1232                 struct gensec_spnego_update_state);
1233
1234         switch (req_state) {
1235         case TEVENT_REQ_USER_ERROR:
1236         case TEVENT_REQ_TIMED_OUT:
1237         case TEVENT_REQ_NO_MEMORY:
1238                 /*
1239                  * A fatal error, further updates are not allowed.
1240                  */
1241                 state->spnego->state_position = SPNEGO_DONE;
1242                 break;
1243         default:
1244                 break;
1245         }
1246 }
1247
1248 static NTSTATUS gensec_spnego_update_in(struct gensec_security *gensec_security,
1249                                         const DATA_BLOB in, TALLOC_CTX *mem_ctx,
1250                                         DATA_BLOB *full_in);
1251 static void gensec_spnego_update_pre(struct tevent_req *req);
1252 static void gensec_spnego_update_done(struct tevent_req *subreq);
1253 static void gensec_spnego_update_post(struct tevent_req *req);
1254 static NTSTATUS gensec_spnego_update_out(struct gensec_security *gensec_security,
1255                                          TALLOC_CTX *out_mem_ctx,
1256                                          DATA_BLOB *_out);
1257
1258 static struct tevent_req *gensec_spnego_update_send(TALLOC_CTX *mem_ctx,
1259                                                     struct tevent_context *ev,
1260                                                     struct gensec_security *gensec_security,
1261                                                     const DATA_BLOB in)
1262 {
1263         struct spnego_state *spnego_state =
1264                 talloc_get_type_abort(gensec_security->private_data,
1265                 struct spnego_state);
1266         struct tevent_req *req = NULL;
1267         struct gensec_spnego_update_state *state = NULL;
1268         NTSTATUS status;
1269         ssize_t len;
1270
1271         req = tevent_req_create(mem_ctx, &state,
1272                                 struct gensec_spnego_update_state);
1273         if (req == NULL) {
1274                 return NULL;
1275         }
1276         state->ev = ev;
1277         state->gensec = gensec_security;
1278         state->spnego = spnego_state;
1279         tevent_req_set_cleanup_fn(req, gensec_spnego_update_cleanup);
1280
1281         if (spnego_state->out_frag.length > 0) {
1282                 if (in.length > 0) {
1283                         tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER);
1284                         return tevent_req_post(req, ev);
1285                 }
1286
1287                 status = gensec_spnego_update_out(gensec_security,
1288                                                   state, &state->out);
1289                 if (GENSEC_UPDATE_IS_NTERROR(status)) {
1290                         tevent_req_nterror(req, status);
1291                         return tevent_req_post(req, ev);
1292                 }
1293
1294                 state->status = status;
1295                 tevent_req_done(req);
1296                 return tevent_req_post(req, ev);
1297         }
1298
1299         status = gensec_spnego_update_in(gensec_security, in,
1300                                          state, &state->full_in);
1301         state->status = status;
1302         if (NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
1303                 tevent_req_done(req);
1304                 return tevent_req_post(req, ev);
1305         }
1306         if (tevent_req_nterror(req, status)) {
1307                 return tevent_req_post(req, ev);
1308         }
1309
1310         /* Check if we got a valid SPNEGO blob... */
1311
1312         switch (spnego_state->state_position) {
1313         case SPNEGO_FALLBACK:
1314                 break;
1315
1316         case SPNEGO_CLIENT_TARG:
1317         case SPNEGO_SERVER_TARG:
1318                 if (state->full_in.length == 0) {
1319                         tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER);
1320                         return tevent_req_post(req, ev);
1321                 }
1322
1323                 /* fall through */
1324         case SPNEGO_CLIENT_START:
1325         case SPNEGO_SERVER_START:
1326
1327                 if (state->full_in.length == 0) {
1328                         /* create_negTokenInit later */
1329                         break;
1330                 }
1331
1332                 len = spnego_read_data(state,
1333                                        state->full_in,
1334                                        &state->_spnego_in);
1335                 if (len == -1) {
1336                         if (spnego_state->state_position != SPNEGO_SERVER_START) {
1337                                 DEBUG(1, ("Invalid SPNEGO request:\n"));
1338                                 dump_data(1, state->full_in.data,
1339                                           state->full_in.length);
1340                                 tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER);
1341                                 return tevent_req_post(req, ev);
1342                         }
1343
1344                         /*
1345                          * This is the 'fallback' case, where we don't get
1346                          * SPNEGO, and have to try all the other options (and
1347                          * hope they all have a magic string they check)
1348                          */
1349                         status = gensec_spnego_server_try_fallback(gensec_security,
1350                                                                    spnego_state,
1351                                                                    state,
1352                                                                    state->full_in);
1353                         if (tevent_req_nterror(req, status)) {
1354                                 return tevent_req_post(req, ev);
1355                         }
1356
1357                         /*
1358                          * We'll continue with SPNEGO_FALLBACK below...
1359                          */
1360                         break;
1361                 }
1362                 state->spnego_in = &state->_spnego_in;
1363
1364                 /* OK, so it's real SPNEGO, check the packet's the one we expect */
1365                 if (state->spnego_in->type != spnego_state->expected_packet) {
1366                         DEBUG(1, ("Invalid SPNEGO request: %d, expected %d\n",
1367                                   state->spnego_in->type,
1368                                   spnego_state->expected_packet));
1369                         dump_data(1, state->full_in.data,
1370                                   state->full_in.length);
1371                         tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER);
1372                         return tevent_req_post(req, ev);
1373                 }
1374
1375                 break;
1376
1377         default:
1378                 smb_panic(__location__);
1379                 return NULL;
1380         }
1381
1382         gensec_spnego_update_pre(req);
1383         if (!tevent_req_is_in_progress(req)) {
1384                 return tevent_req_post(req, ev);
1385         }
1386
1387         if (state->sub.needed) {
1388                 struct tevent_req *subreq = NULL;
1389
1390                 /*
1391                  * We may need one more roundtrip...
1392                  */
1393                 subreq = gensec_update_send(state, state->ev,
1394                                             spnego_state->sub_sec_security,
1395                                             state->sub.in);
1396                 if (tevent_req_nomem(subreq, req)) {
1397                         return tevent_req_post(req, ev);
1398                 }
1399                 tevent_req_set_callback(subreq,
1400                                         gensec_spnego_update_done,
1401                                         req);
1402                 state->sub.needed = false;
1403                 return req;
1404         }
1405
1406         gensec_spnego_update_post(req);
1407         if (!tevent_req_is_in_progress(req)) {
1408                 return tevent_req_post(req, ev);
1409         }
1410
1411         return req;
1412 }
1413
1414 static NTSTATUS gensec_spnego_update_in(struct gensec_security *gensec_security,
1415                                         const DATA_BLOB in, TALLOC_CTX *mem_ctx,
1416                                         DATA_BLOB *full_in)
1417 {
1418         struct spnego_state *spnego_state = (struct spnego_state *)gensec_security->private_data;
1419         size_t expected;
1420         bool ok;
1421
1422         *full_in = data_blob_null;
1423
1424         switch (spnego_state->state_position) {
1425         case SPNEGO_FALLBACK:
1426                 *full_in = in;
1427                 spnego_state->in_needed = 0;
1428                 return NT_STATUS_OK;
1429
1430         case SPNEGO_CLIENT_START:
1431         case SPNEGO_CLIENT_TARG:
1432         case SPNEGO_SERVER_START:
1433         case SPNEGO_SERVER_TARG:
1434                 break;
1435
1436         case SPNEGO_DONE:
1437         default:
1438                 return NT_STATUS_INVALID_PARAMETER;
1439         }
1440
1441         if (spnego_state->in_needed == 0) {
1442                 size_t size = 0;
1443                 int ret;
1444
1445                 /*
1446                  * try to work out the size of the full
1447                  * input token, it might be fragmented
1448                  */
1449                 ret = asn1_peek_full_tag(in,  ASN1_APPLICATION(0), &size);
1450                 if ((ret != 0) && (ret != EAGAIN)) {
1451                         ret = asn1_peek_full_tag(in, ASN1_CONTEXT(1), &size);
1452                 }
1453
1454                 if ((ret == 0) || (ret == EAGAIN)) {
1455                         spnego_state->in_needed = size;
1456                 } else {
1457                         /*
1458                          * If it is not an asn1 message
1459                          * just call the next layer.
1460                          */
1461                         spnego_state->in_needed = in.length;
1462                 }
1463         }
1464
1465         if (spnego_state->in_needed > UINT16_MAX) {
1466                 /*
1467                  * limit the incoming message to 0xFFFF
1468                  * to avoid DoS attacks.
1469                  */
1470                 return NT_STATUS_INVALID_BUFFER_SIZE;
1471         }
1472
1473         if ((spnego_state->in_needed > 0) && (in.length == 0)) {
1474                 /*
1475                  * If we reach this, we know we got at least
1476                  * part of an asn1 message, getting 0 means
1477                  * the remote peer wants us to spin.
1478                  */
1479                 return NT_STATUS_INVALID_PARAMETER;
1480         }
1481
1482         expected = spnego_state->in_needed - spnego_state->in_frag.length;
1483         if (in.length > expected) {
1484                 /*
1485                  * we got more than expected
1486                  */
1487                 return NT_STATUS_INVALID_PARAMETER;
1488         }
1489
1490         if (in.length == spnego_state->in_needed) {
1491                 /*
1492                  * if the in.length contains the full blob
1493                  * we are done.
1494                  *
1495                  * Note: this implies spnego_state->in_frag.length == 0,
1496                  *       but we do not need to check this explicitly
1497                  *       because we already know that we did not get
1498                  *       more than expected.
1499                  */
1500                 *full_in = in;
1501                 spnego_state->in_needed = 0;
1502                 return NT_STATUS_OK;
1503         }
1504
1505         ok = data_blob_append(spnego_state, &spnego_state->in_frag,
1506                               in.data, in.length);
1507         if (!ok) {
1508                 return NT_STATUS_NO_MEMORY;
1509         }
1510
1511         if (spnego_state->in_needed > spnego_state->in_frag.length) {
1512                 return NT_STATUS_MORE_PROCESSING_REQUIRED;
1513         }
1514
1515         *full_in = spnego_state->in_frag;
1516         talloc_steal(mem_ctx, full_in->data);
1517         spnego_state->in_frag = data_blob_null;
1518         spnego_state->in_needed = 0;
1519         return NT_STATUS_OK;
1520 }
1521
1522 static void gensec_spnego_update_pre(struct tevent_req *req)
1523 {
1524         struct gensec_spnego_update_state *state =
1525                 tevent_req_data(req,
1526                 struct gensec_spnego_update_state);
1527         struct gensec_security *gensec_security = state->gensec;
1528         struct spnego_state *spnego_state = state->spnego;
1529         struct tevent_context *ev = state->ev;
1530         NTSTATUS status;
1531
1532         state->sub.needed = false;
1533         state->sub.in = data_blob_null;
1534         state->sub.status = NT_STATUS_INTERNAL_ERROR;
1535         state->sub.out = data_blob_null;
1536
1537         if (spnego_state->state_position == SPNEGO_FALLBACK) {
1538                 state->sub.in = state->full_in;
1539                 state->full_in = data_blob_null;
1540                 state->sub.needed = true;
1541                 return;
1542         }
1543
1544         switch (spnego_state->state_position) {
1545         case SPNEGO_CLIENT_START:
1546                 if (state->spnego_in == NULL) {
1547                         /* client to produce negTokenInit */
1548                         status = gensec_spnego_create_negTokenInit(gensec_security,
1549                                                         spnego_state, state, ev,
1550                                                         &spnego_state->out_frag);
1551                         if (GENSEC_UPDATE_IS_NTERROR(status)) {
1552                                 tevent_req_nterror(req, status);
1553                                 return;
1554                         }
1555                         break;
1556                 }
1557
1558                 status = gensec_spnego_client_negTokenInit(gensec_security,
1559                                                         spnego_state, ev,
1560                                                         state->spnego_in, state,
1561                                                         &spnego_state->out_frag);
1562                 break;
1563
1564         case SPNEGO_CLIENT_TARG:
1565                 status = gensec_spnego_client_negTokenTarg(gensec_security,
1566                                                         spnego_state, ev,
1567                                                         state->spnego_in, state,
1568                                                         &spnego_state->out_frag);
1569                 if (GENSEC_UPDATE_IS_NTERROR(status)) {
1570                         tevent_req_nterror(req, status);
1571                         return;
1572                 }
1573                 break;
1574
1575         case SPNEGO_SERVER_START:
1576                 if (state->spnego_in == NULL) {
1577                         /* server to produce negTokenInit */
1578                         status = gensec_spnego_create_negTokenInit(gensec_security,
1579                                                         spnego_state, state, ev,
1580                                                         &spnego_state->out_frag);
1581                         if (GENSEC_UPDATE_IS_NTERROR(status)) {
1582                                 tevent_req_nterror(req, status);
1583                                 return;
1584                         }
1585                         break;
1586                 }
1587
1588                 status = gensec_spnego_server_negTokenInit(gensec_security,
1589                                                         spnego_state, ev,
1590                                                         state->spnego_in, state,
1591                                                         &spnego_state->out_frag);
1592                 if (GENSEC_UPDATE_IS_NTERROR(status)) {
1593                         tevent_req_nterror(req, status);
1594                         return;
1595                 }
1596                 break;
1597
1598         case SPNEGO_SERVER_TARG:
1599                 status = gensec_spnego_server_negTokenTarg(gensec_security,
1600                                                         spnego_state, ev,
1601                                                         state->spnego_in, state,
1602                                                         &spnego_state->out_frag);
1603                 if (GENSEC_UPDATE_IS_NTERROR(status)) {
1604                         tevent_req_nterror(req, status);
1605                         return;
1606                 }
1607                 break;
1608
1609         default:
1610                 smb_panic(__location__);
1611                 return;
1612         }
1613
1614         spnego_state->out_status = status;
1615 }
1616
1617 static void gensec_spnego_update_done(struct tevent_req *subreq)
1618 {
1619         struct tevent_req *req =
1620                 tevent_req_callback_data(subreq,
1621                 struct tevent_req);
1622         struct gensec_spnego_update_state *state =
1623                 tevent_req_data(req,
1624                 struct gensec_spnego_update_state);
1625         struct spnego_state *spnego_state = state->spnego;
1626
1627         state->sub.status = gensec_update_recv(subreq, state, &state->sub.out);
1628         TALLOC_FREE(subreq);
1629         if (NT_STATUS_IS_OK(state->sub.status)) {
1630                 spnego_state->sub_sec_ready = true;
1631         }
1632
1633         gensec_spnego_update_post(req);
1634 }
1635
1636 static void gensec_spnego_update_post(struct tevent_req *req)
1637 {
1638         struct gensec_spnego_update_state *state =
1639                 tevent_req_data(req,
1640                 struct gensec_spnego_update_state);
1641         struct spnego_state *spnego_state = state->spnego;
1642         NTSTATUS status;
1643
1644         state->sub.in = data_blob_null;
1645         state->sub.needed = false;
1646
1647         if (spnego_state->state_position == SPNEGO_FALLBACK) {
1648                 status = state->sub.status;
1649                 spnego_state->out_frag = state->sub.out;
1650                 talloc_steal(spnego_state, spnego_state->out_frag.data);
1651                 state->sub.out = data_blob_null;
1652                 goto respond;
1653         }
1654
1655         /*
1656          * For now just handle the sync processing done
1657          * in gensec_spnego_update_pre()
1658          */
1659         status = spnego_state->out_status;
1660
1661         if (NT_STATUS_IS_OK(status)) {
1662                 bool reset_full = true;
1663
1664                 reset_full = !spnego_state->done_mic_check;
1665
1666                 status = gensec_may_reset_crypto(spnego_state->sub_sec_security,
1667                                                  reset_full);
1668                 if (tevent_req_nterror(req, status)) {
1669                         return;
1670                 }
1671         }
1672
1673 respond:
1674         spnego_state->out_status = status;
1675
1676         status = gensec_spnego_update_out(state->gensec,
1677                                           state, &state->out);
1678         if (GENSEC_UPDATE_IS_NTERROR(status)) {
1679                 tevent_req_nterror(req, status);
1680                 return;
1681         }
1682
1683         state->status = status;
1684         tevent_req_done(req);
1685         return;
1686 }
1687
1688 static NTSTATUS gensec_spnego_update_out(struct gensec_security *gensec_security,
1689                                          TALLOC_CTX *out_mem_ctx,
1690                                          DATA_BLOB *_out)
1691 {
1692         struct spnego_state *spnego_state = (struct spnego_state *)gensec_security->private_data;
1693         DATA_BLOB out = data_blob_null;
1694         bool ok;
1695
1696         *_out = data_blob_null;
1697
1698         if (spnego_state->out_frag.length <= spnego_state->out_max_length) {
1699                 /*
1700                  * Fast path, we can deliver everything
1701                  */
1702
1703                 *_out = spnego_state->out_frag;
1704                 if (spnego_state->out_frag.length > 0) {
1705                         talloc_steal(out_mem_ctx, _out->data);
1706                         spnego_state->out_frag = data_blob_null;
1707                 }
1708
1709                 if (!NT_STATUS_IS_OK(spnego_state->out_status)) {
1710                         return spnego_state->out_status;
1711                 }
1712
1713                 /*
1714                  * We're completely done, further updates are not allowed.
1715                  */
1716                 spnego_state->state_position = SPNEGO_DONE;
1717                 return gensec_child_ready(gensec_security,
1718                                           spnego_state->sub_sec_security);
1719         }
1720
1721         out = spnego_state->out_frag;
1722
1723         /*
1724          * copy the remaining bytes
1725          */
1726         spnego_state->out_frag = data_blob_talloc(spnego_state,
1727                                         out.data + spnego_state->out_max_length,
1728                                         out.length - spnego_state->out_max_length);
1729         if (spnego_state->out_frag.data == NULL) {
1730                 return NT_STATUS_NO_MEMORY;
1731         }
1732
1733         /*
1734          * truncate the buffer
1735          */
1736         ok = data_blob_realloc(spnego_state, &out,
1737                                spnego_state->out_max_length);
1738         if (!ok) {
1739                 return NT_STATUS_NO_MEMORY;
1740         }
1741
1742         talloc_steal(out_mem_ctx, out.data);
1743         *_out = out;
1744         return NT_STATUS_MORE_PROCESSING_REQUIRED;
1745 }
1746
1747 static NTSTATUS gensec_spnego_update_recv(struct tevent_req *req,
1748                                           TALLOC_CTX *out_mem_ctx,
1749                                           DATA_BLOB *out)
1750 {
1751         struct gensec_spnego_update_state *state =
1752                 tevent_req_data(req,
1753                 struct gensec_spnego_update_state);
1754         NTSTATUS status;
1755
1756         *out = data_blob_null;
1757
1758         if (tevent_req_is_nterror(req, &status)) {
1759                 tevent_req_received(req);
1760                 return status;
1761         }
1762
1763         *out = state->out;
1764         talloc_steal(out_mem_ctx, state->out.data);
1765         status = state->status;
1766         tevent_req_received(req);
1767         return status;
1768 }
1769
1770 static const char *gensec_spnego_oids[] = { 
1771         GENSEC_OID_SPNEGO,
1772         NULL 
1773 };
1774
1775 static const struct gensec_security_ops gensec_spnego_security_ops = {
1776         .name             = "spnego",
1777         .sasl_name        = "GSS-SPNEGO",
1778         .auth_type        = DCERPC_AUTH_TYPE_SPNEGO,
1779         .oid              = gensec_spnego_oids,
1780         .client_start     = gensec_spnego_client_start,
1781         .server_start     = gensec_spnego_server_start,
1782         .update_send      = gensec_spnego_update_send,
1783         .update_recv      = gensec_spnego_update_recv,
1784         .seal_packet      = gensec_child_seal_packet,
1785         .sign_packet      = gensec_child_sign_packet,
1786         .sig_size         = gensec_child_sig_size,
1787         .max_wrapped_size = gensec_child_max_wrapped_size,
1788         .max_input_size   = gensec_child_max_input_size,
1789         .check_packet     = gensec_child_check_packet,
1790         .unseal_packet    = gensec_child_unseal_packet,
1791         .wrap             = gensec_child_wrap,
1792         .unwrap           = gensec_child_unwrap,
1793         .session_key      = gensec_child_session_key,
1794         .session_info     = gensec_child_session_info,
1795         .want_feature     = gensec_child_want_feature,
1796         .have_feature     = gensec_child_have_feature,
1797         .expire_time      = gensec_child_expire_time,
1798         .final_auth_type  = gensec_child_final_auth_type,
1799         .enabled          = true,
1800         .priority         = GENSEC_SPNEGO
1801 };
1802
1803 _PUBLIC_ NTSTATUS gensec_spnego_init(TALLOC_CTX *ctx)
1804 {
1805         NTSTATUS ret;
1806         ret = gensec_register(ctx, &gensec_spnego_security_ops);
1807         if (!NT_STATUS_IS_OK(ret)) {
1808                 DEBUG(0,("Failed to register '%s' gensec backend!\n",
1809                         gensec_spnego_security_ops.name));
1810                 return ret;
1811         }
1812
1813         return ret;
1814 }