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