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