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