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