Mech_eap: only output debugging when GSSEAP_TRACE is set
[mech_eap.git] / mech_eap / init_sec_context.c
1 /*
2  * Copyright (c) 2011, JANET(UK)
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * 3. Neither the name of JANET(UK) nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32
33 /*
34  * Establish a security context on the initiator (client). These functions
35  * wrap around libeap.
36  */
37
38 #include "gssapiP_eap.h"
39 #include "radius/radius.h"
40 #include "util_radius.h"
41 #include "utils/radius_utils.h"
42
43 /* methods allowed for phase1 authentication*/
44 static const struct eap_method_type allowed_eap_method_types[] = {
45     {EAP_VENDOR_IETF, EAP_TYPE_TTLS},
46     {EAP_VENDOR_IETF, EAP_TYPE_NONE}};
47
48 static OM_uint32
49 policyVariableToFlag(enum eapol_bool_var variable)
50 {
51     OM_uint32 flag = 0;
52
53     switch (variable) {
54     case EAPOL_eapSuccess:
55         flag = CTX_FLAG_EAP_SUCCESS;
56         break;
57     case EAPOL_eapRestart:
58         flag = CTX_FLAG_EAP_RESTART;
59         break;
60     case EAPOL_eapFail:
61         flag = CTX_FLAG_EAP_FAIL;
62         break;
63     case EAPOL_eapResp:
64         flag = CTX_FLAG_EAP_RESP;
65         break;
66     case EAPOL_eapNoResp:
67         flag = CTX_FLAG_EAP_NO_RESP;
68         break;
69     case EAPOL_eapReq:
70         flag = CTX_FLAG_EAP_REQ;
71         break;
72     case EAPOL_portEnabled:
73         flag = CTX_FLAG_EAP_PORT_ENABLED;
74         break;
75     case EAPOL_altAccept:
76         flag = CTX_FLAG_EAP_ALT_ACCEPT;
77         break;
78     case EAPOL_altReject:
79         flag = CTX_FLAG_EAP_ALT_REJECT;
80         break;
81     }
82
83     return flag;
84 }
85
86 static struct eap_peer_config *
87 peerGetConfig(void *ctx)
88 {
89     gss_ctx_id_t gssCtx = (gss_ctx_id_t)ctx;
90
91     return &gssCtx->initiatorCtx.eapPeerConfig;
92 }
93
94 static Boolean
95 peerGetBool(void *data, enum eapol_bool_var variable)
96 {
97     gss_ctx_id_t ctx = data;
98     OM_uint32 flag;
99
100     if (ctx == GSS_C_NO_CONTEXT)
101         return FALSE;
102
103     flag = policyVariableToFlag(variable);
104
105     return ((ctx->flags & flag) != 0);
106 }
107
108 static void
109 peerSetBool(void *data, enum eapol_bool_var variable,
110             Boolean value)
111 {
112     gss_ctx_id_t ctx = data;
113     OM_uint32 flag;
114
115     if (ctx == GSS_C_NO_CONTEXT)
116         return;
117
118     flag = policyVariableToFlag(variable);
119
120     if (value)
121         ctx->flags |= flag;
122     else
123         ctx->flags &= ~(flag);
124 }
125
126 static unsigned int
127 peerGetInt(void *data, enum eapol_int_var variable)
128 {
129     gss_ctx_id_t ctx = data;
130
131     if (ctx == GSS_C_NO_CONTEXT)
132         return FALSE;
133
134     GSSEAP_ASSERT(CTX_IS_INITIATOR(ctx));
135
136     switch (variable) {
137     case EAPOL_idleWhile:
138         return ctx->initiatorCtx.idleWhile;
139         break;
140     }
141
142     return 0;
143 }
144
145 static void
146 peerSetInt(void *data, enum eapol_int_var variable,
147            unsigned int value)
148 {
149     gss_ctx_id_t ctx = data;
150
151     if (ctx == GSS_C_NO_CONTEXT)
152         return;
153
154     GSSEAP_ASSERT(CTX_IS_INITIATOR(ctx));
155
156     switch (variable) {
157     case EAPOL_idleWhile:
158         ctx->initiatorCtx.idleWhile = value;
159         break;
160     }
161 }
162
163 static struct wpabuf *
164 peerGetEapReqData(void *ctx)
165 {
166     gss_ctx_id_t gssCtx = (gss_ctx_id_t)ctx;
167
168     return &gssCtx->initiatorCtx.reqData;
169 }
170
171 static void
172 peerSetConfigBlob(void *ctx GSSEAP_UNUSED,
173                   struct wpa_config_blob *blob GSSEAP_UNUSED)
174 {
175 }
176
177 static const struct wpa_config_blob *
178 peerGetConfigBlob(void *ctx,
179                   const char *name)
180 {
181     gss_ctx_id_t gssCtx = (gss_ctx_id_t)ctx;
182     size_t index;
183
184     if (strcmp(name, "client-cert") == 0)
185         index = CONFIG_BLOB_CLIENT_CERT;
186     else if (strcmp(name, "private-key") == 0)
187         index = CONFIG_BLOB_PRIVATE_KEY;
188     else if (strcmp(name, "ca-cert") == 0)
189         index = CONFIG_BLOB_CA_CERT;
190     else
191         return NULL;
192
193     return &gssCtx->initiatorCtx.configBlobs[index];
194 }
195
196 static void
197 peerNotifyPending(void *ctx GSSEAP_UNUSED)
198 {
199 }
200
201 static struct eapol_callbacks gssEapPolicyCallbacks = {
202     peerGetConfig,
203     peerGetBool,
204     peerSetBool,
205     peerGetInt,
206     peerSetInt,
207     peerGetEapReqData,
208     peerSetConfigBlob,
209     peerGetConfigBlob,
210     peerNotifyPending,
211 };
212
213 extern int wpa_debug_level;
214
215 #define CHBIND_SERVICE_NAME_FLAG        0x01
216 #define CHBIND_HOST_NAME_FLAG           0x02
217 #define CHBIND_SERVICE_SPECIFIC_FLAG    0x04
218 #define CHBIND_REALM_NAME_FLAG          0x08
219
220 static OM_uint32
221 peerInitEapChannelBinding(OM_uint32 *minor, gss_ctx_id_t ctx)
222 {
223     struct wpabuf *buf = NULL;
224     unsigned int chbindReqFlags = 0;
225     krb5_principal princ = NULL;
226     gss_buffer_desc nameBuf = GSS_C_EMPTY_BUFFER;
227     OM_uint32 major = GSS_S_COMPLETE;
228     krb5_context krbContext = NULL;
229
230     /* XXX is this check redundant? */
231     if (ctx->acceptorName == GSS_C_NO_NAME) {
232         major = GSS_S_BAD_NAME;
233         *minor = GSSEAP_NO_ACCEPTOR_NAME;
234         goto cleanup;
235     }
236
237     princ = ctx->acceptorName->krbPrincipal;
238
239     krbPrincComponentToGssBuffer(princ, 0, &nameBuf);
240     if (nameBuf.length > 0) {
241         major = gssEapRadiusAddAttr(minor, &buf, PW_GSS_ACCEPTOR_SERVICE_NAME,
242                                     0, &nameBuf);
243         if (GSS_ERROR(major))
244             goto cleanup;
245
246         chbindReqFlags |= CHBIND_SERVICE_NAME_FLAG;
247     }
248
249     krbPrincComponentToGssBuffer(princ, 1, &nameBuf);
250     if (nameBuf.length > 0) {
251         major = gssEapRadiusAddAttr(minor, &buf, PW_GSS_ACCEPTOR_HOST_NAME,
252                                     0, &nameBuf);
253         if (GSS_ERROR(major))
254             goto cleanup;
255
256         chbindReqFlags |= CHBIND_HOST_NAME_FLAG;
257     }
258
259     GSSEAP_KRB_INIT(&krbContext);
260
261     *minor = krbPrincUnparseServiceSpecifics(krbContext, princ, &nameBuf);
262     if (*minor != 0)
263         goto cleanup;
264
265     if (nameBuf.length > 0) {
266         major = gssEapRadiusAddAttr(minor, &buf,
267                                     PW_GSS_ACCEPTOR_SERVICE_SPECIFICS,
268                                     0, &nameBuf);
269         if (GSS_ERROR(major))
270             goto cleanup;
271
272         chbindReqFlags |= CHBIND_SERVICE_SPECIFIC_FLAG;
273     }
274
275     krbFreeUnparsedName(krbContext, &nameBuf);
276     krbPrincRealmToGssBuffer(princ, &nameBuf);
277
278     if (nameBuf.length > 0) {
279         major = gssEapRadiusAddAttr(minor, &buf,
280                                     PW_GSS_ACCEPTOR_REALM_NAME,
281                                     0, &nameBuf);
282         if (GSS_ERROR(major))
283             goto cleanup;
284
285         chbindReqFlags |= CHBIND_REALM_NAME_FLAG;
286     }
287
288     if (chbindReqFlags == 0) {
289         major = GSS_S_BAD_NAME;
290         *minor = GSSEAP_BAD_ACCEPTOR_NAME;
291         goto cleanup;
292     }
293
294     ctx->initiatorCtx.chbindData = buf;
295     ctx->initiatorCtx.chbindReqFlags = chbindReqFlags;
296
297     buf = NULL;
298
299     major = GSS_S_COMPLETE;
300     *minor = 0;
301
302 cleanup:
303     /*namebuf is freed when used and may be left with a unowned pointer*/
304     wpabuf_free(buf);
305
306     return major;
307 }
308
309 static void
310 peerProcessChbindResponse(void *context, int code, int nsid,
311                           u8 *data, size_t len)
312 {
313     radius_parser msg;
314     gss_ctx_id_t ctx = (gss_ctx_id_t )context;
315     void *vsadata;
316     u8 type;
317     u32 vendor_id;
318     u32 chbindRetFlags = 0;
319     size_t vsadata_len;
320
321     if (nsid != CHBIND_NSID_RADIUS)
322         return;
323
324     if (data == NULL)
325         return;
326     msg = radius_parser_start(data, len);
327     if (msg == NULL)
328         return;
329
330     while (radius_parser_parse_tlv(msg, &type, &vendor_id, &vsadata,
331                                    &vsadata_len) == 0) {
332         switch (type) {
333         case PW_GSS_ACCEPTOR_SERVICE_NAME:
334             chbindRetFlags |= CHBIND_SERVICE_NAME_FLAG;
335             break;
336         case PW_GSS_ACCEPTOR_HOST_NAME:
337             chbindRetFlags |= CHBIND_HOST_NAME_FLAG;
338             break;
339         case PW_GSS_ACCEPTOR_SERVICE_SPECIFICS:
340             chbindRetFlags |= CHBIND_SERVICE_SPECIFIC_FLAG;
341             break;
342         case PW_GSS_ACCEPTOR_REALM_NAME:
343             chbindRetFlags |= CHBIND_REALM_NAME_FLAG;
344             break;
345         }
346     }
347
348     radius_parser_finish(msg);
349
350     if (code == CHBIND_CODE_SUCCESS &&
351         ((chbindRetFlags & ctx->initiatorCtx.chbindReqFlags) == ctx->initiatorCtx.chbindReqFlags)) {
352         ctx->flags |= CTX_FLAG_EAP_CHBIND_ACCEPT;
353         ctx->gssFlags |= GSS_C_MUTUAL_FLAG;
354     } /* else log failures? */
355 }
356
357 static OM_uint32
358 peerConfigInit(OM_uint32 *minor, gss_ctx_id_t ctx)
359 {
360     OM_uint32 major;
361     krb5_context krbContext;
362     struct eap_peer_config *eapPeerConfig = &ctx->initiatorCtx.eapPeerConfig;
363     struct wpa_config_blob *configBlobs = ctx->initiatorCtx.configBlobs;
364     gss_buffer_desc identity = GSS_C_EMPTY_BUFFER;
365     gss_buffer_desc realm = GSS_C_EMPTY_BUFFER;
366     gss_cred_id_t cred = ctx->cred;
367     char *debug_file = NULL;
368
369     eapPeerConfig->identity = NULL;
370     eapPeerConfig->identity_len = 0;
371     eapPeerConfig->anonymous_identity = NULL;
372     eapPeerConfig->anonymous_identity_len = 0;
373     eapPeerConfig->password = NULL;
374     eapPeerConfig->password_len = 0;
375     eapPeerConfig->eap_methods = (struct eap_method_type *) allowed_eap_method_types;
376
377     GSSEAP_ASSERT(cred != GSS_C_NO_CREDENTIAL);
378
379     GSSEAP_KRB_INIT(&krbContext);
380
381     eapPeerConfig->fragment_size = 1024;
382     wpa_debug_level = MSG_ERROR;
383     if ((debug_file = getenv("GSSEAP_TRACE")) != NULL) {
384             wpa_debug_open_file(debug_file);
385             wpa_debug_level = 0;
386         }
387     
388     GSSEAP_ASSERT(cred->name != GSS_C_NO_NAME);
389
390     if ((cred->name->flags & (NAME_FLAG_NAI | NAME_FLAG_SERVICE)) == 0) {
391         *minor = GSSEAP_BAD_INITIATOR_NAME;
392         return GSS_S_BAD_NAME;
393     }
394
395     /* identity */
396     major = gssEapDisplayName(minor, cred->name, &identity, NULL);
397     if (GSS_ERROR(major))
398         return major;
399
400     eapPeerConfig->identity = (unsigned char *)identity.value;
401     eapPeerConfig->identity_len = identity.length;
402
403     krbPrincRealmToGssBuffer(cred->name->krbPrincipal, &realm);
404
405     /* anonymous_identity */
406     eapPeerConfig->anonymous_identity = GSSEAP_MALLOC(realm.length + 2);
407     if (eapPeerConfig->anonymous_identity == NULL) {
408         *minor = ENOMEM;
409         return GSS_S_FAILURE;
410     }
411
412     eapPeerConfig->anonymous_identity[0] = '@';
413     memcpy(eapPeerConfig->anonymous_identity + 1, realm.value, realm.length);
414     eapPeerConfig->anonymous_identity[1 + realm.length] = '\0';
415     eapPeerConfig->anonymous_identity_len = 1 + realm.length;
416
417     /* password */
418     if ((cred->flags & CRED_FLAG_CERTIFICATE) == 0) {
419         eapPeerConfig->password = (unsigned char *)cred->password.value;
420         eapPeerConfig->password_len = cred->password.length;
421     }
422
423     /* certs */
424     eapPeerConfig->ca_cert = (unsigned char *)cred->caCertificate.value;
425     eapPeerConfig->subject_match = (unsigned char *)cred->subjectNameConstraint.value;
426     eapPeerConfig->altsubject_match = (unsigned char *)cred->subjectAltNameConstraint.value;
427     configBlobs[CONFIG_BLOB_CA_CERT].data = cred->caCertificateBlob.value;
428     configBlobs[CONFIG_BLOB_CA_CERT].len = cred->caCertificateBlob.length;
429
430     /* eap channel binding */
431     if (ctx->initiatorCtx.chbindData != NULL) {
432         struct eap_peer_chbind_config *chbind_config =
433             (struct eap_peer_chbind_config *)GSSEAP_MALLOC(sizeof(struct eap_peer_chbind_config));
434         if (chbind_config == NULL) {
435             *minor = ENOMEM;
436             return GSS_S_FAILURE;
437         }
438
439         chbind_config->req_data = wpabuf_mhead_u8(ctx->initiatorCtx.chbindData);
440         chbind_config->req_data_len = wpabuf_len(ctx->initiatorCtx.chbindData);
441         chbind_config->nsid = CHBIND_NSID_RADIUS;
442         chbind_config->response_cb = &peerProcessChbindResponse;
443         chbind_config->ctx = ctx;
444         eapPeerConfig->chbind_config = chbind_config;
445         eapPeerConfig->chbind_config_len = 1;
446     } else {
447         eapPeerConfig->chbind_config = NULL;
448         eapPeerConfig->chbind_config_len = 0;
449     }
450     if (cred->flags & CRED_FLAG_CERTIFICATE) {
451         /*
452          * CRED_FLAG_CONFIG_BLOB is an internal flag which will be used in the
453          * future to directly pass certificate and private key data to the
454          * EAP implementation, rather than an indirected string pointer.
455          */
456         if (cred->flags & CRED_FLAG_CONFIG_BLOB) {
457             eapPeerConfig->client_cert = (unsigned char *)"blob://client-cert";
458             configBlobs[CONFIG_BLOB_CLIENT_CERT].data = cred->clientCertificate.value;
459             configBlobs[CONFIG_BLOB_CLIENT_CERT].len  = cred->clientCertificate.length;
460
461             eapPeerConfig->client_cert = (unsigned char *)"blob://private-key";
462             configBlobs[CONFIG_BLOB_PRIVATE_KEY].data = cred->clientCertificate.value;
463             configBlobs[CONFIG_BLOB_PRIVATE_KEY].len  = cred->privateKey.length;
464         } else {
465             eapPeerConfig->client_cert = (unsigned char *)cred->clientCertificate.value;
466             eapPeerConfig->private_key = (unsigned char *)cred->privateKey.value;
467         }
468         eapPeerConfig->private_key_passwd = (unsigned char *)cred->password.value;
469     }
470
471     *minor = 0;
472     return GSS_S_COMPLETE;
473 }
474
475 static OM_uint32
476 peerConfigFree(OM_uint32 *minor,
477                gss_ctx_id_t ctx)
478 {
479     struct eap_peer_config *eapPeerConfig = &ctx->initiatorCtx.eapPeerConfig;
480
481     if (eapPeerConfig->identity != NULL) {
482         GSSEAP_FREE(eapPeerConfig->identity);
483         eapPeerConfig->identity = NULL;
484         eapPeerConfig->identity_len = 0;
485     }
486
487     if (eapPeerConfig->anonymous_identity != NULL) {
488         GSSEAP_FREE(eapPeerConfig->anonymous_identity);
489         eapPeerConfig->anonymous_identity = NULL;
490         eapPeerConfig->anonymous_identity_len = 0;
491     }
492
493     *minor = 0;
494     return GSS_S_COMPLETE;
495 }
496
497 /*
498  * Mark an initiator context as ready for cryptographic operations
499  */
500 static OM_uint32
501 initReady(OM_uint32 *minor, gss_ctx_id_t ctx)
502 {
503     OM_uint32 major;
504     const unsigned char *key;
505     size_t keyLength;
506
507     /* Cache encryption type derived from selected mechanism OID */
508     major = gssEapOidToEnctype(minor, ctx->mechanismUsed, &ctx->encryptionType);
509     if (GSS_ERROR(major))
510         return major;
511
512     if (!eap_key_available(ctx->initiatorCtx.eap)) {
513         *minor = GSSEAP_KEY_UNAVAILABLE;
514         return GSS_S_UNAVAILABLE;
515     }
516
517     key = eap_get_eapKeyData(ctx->initiatorCtx.eap, &keyLength);
518
519     if (keyLength < EAP_EMSK_LEN) {
520         *minor = GSSEAP_KEY_TOO_SHORT;
521         return GSS_S_UNAVAILABLE;
522     }
523
524     major = gssEapDeriveRfc3961Key(minor,
525                                    &key[EAP_EMSK_LEN / 2],
526                                    EAP_EMSK_LEN / 2,
527                                    ctx->encryptionType,
528                                    &ctx->rfc3961Key);
529        if (GSS_ERROR(major))
530            return major;
531
532     major = rfc3961ChecksumTypeForKey(minor, &ctx->rfc3961Key,
533                                       &ctx->checksumType);
534     if (GSS_ERROR(major))
535         return major;
536
537     major = sequenceInit(minor,
538                          &ctx->seqState,
539                          ctx->recvSeq,
540                          ((ctx->gssFlags & GSS_C_REPLAY_FLAG) != 0),
541                          ((ctx->gssFlags & GSS_C_SEQUENCE_FLAG) != 0),
542                          TRUE);
543     if (GSS_ERROR(major))
544         return major;
545
546     *minor = 0;
547     return GSS_S_COMPLETE;
548 }
549
550 static OM_uint32
551 initBegin(OM_uint32 *minor,
552           gss_ctx_id_t ctx,
553           gss_name_t target,
554           gss_OID mech,
555           OM_uint32 reqFlags GSSEAP_UNUSED,
556           OM_uint32 timeReq,
557           gss_channel_bindings_t chanBindings GSSEAP_UNUSED)
558 {
559     OM_uint32 major;
560     gss_cred_id_t cred = ctx->cred;
561
562     GSSEAP_ASSERT(cred != GSS_C_NO_CREDENTIAL);
563
564     if (cred->expiryTime)
565         ctx->expiryTime = cred->expiryTime;
566     else if (timeReq == 0 || timeReq == GSS_C_INDEFINITE)
567         ctx->expiryTime = 0;
568     else
569         ctx->expiryTime = time(NULL) + timeReq;
570
571     /*
572      * The credential mutex protects its name, however we need to
573      * explicitly lock the acceptor name (unlikely as it may be
574      * that it has attributes set on it).
575      */
576     major = gssEapDuplicateName(minor, cred->name, &ctx->initiatorName);
577     if (GSS_ERROR(major))
578         return major;
579
580     if (target != GSS_C_NO_NAME) {
581         GSSEAP_MUTEX_LOCK(&target->mutex);
582
583         major = gssEapDuplicateName(minor, target, &ctx->acceptorName);
584         if (GSS_ERROR(major)) {
585             GSSEAP_MUTEX_UNLOCK(&target->mutex);
586             return major;
587         }
588
589         GSSEAP_MUTEX_UNLOCK(&target->mutex);
590     }
591
592     major = gssEapCanonicalizeOid(minor,
593                                   mech,
594                                   OID_FLAG_NULL_VALID | OID_FLAG_MAP_NULL_TO_DEFAULT_MECH,
595                                   &ctx->mechanismUsed);
596     if (GSS_ERROR(major))
597         return major;
598
599     /* If credentials were provided, check they're usable with this mech */
600     if (!gssEapCredAvailable(cred, ctx->mechanismUsed)) {
601         *minor = GSSEAP_CRED_MECH_MISMATCH;
602         return GSS_S_BAD_MECH;
603     }
604
605     *minor = 0;
606     return GSS_S_COMPLETE;
607 }
608
609 static OM_uint32
610 eapGssSmInitError(OM_uint32 *minor,
611                   gss_cred_id_t cred GSSEAP_UNUSED,
612                   gss_ctx_id_t ctx GSSEAP_UNUSED,
613                   gss_name_t target GSSEAP_UNUSED,
614                   gss_OID mech GSSEAP_UNUSED,
615                   OM_uint32 reqFlags GSSEAP_UNUSED,
616                   OM_uint32 timeReq GSSEAP_UNUSED,
617                   gss_channel_bindings_t chanBindings GSSEAP_UNUSED,
618                   gss_buffer_t inputToken,
619                   gss_buffer_t outputToken GSSEAP_UNUSED,
620                   OM_uint32 *smFlags GSSEAP_UNUSED)
621 {
622     OM_uint32 major;
623     unsigned char *p;
624
625     if (inputToken->length < 8) {
626         *minor = GSSEAP_TOK_TRUNC;
627         return GSS_S_DEFECTIVE_TOKEN;
628     }
629
630     p = (unsigned char *)inputToken->value;
631
632     major = load_uint32_be(&p[0]);
633     *minor = ERROR_TABLE_BASE_eapg + load_uint32_be(&p[4]);
634
635     if (!GSS_ERROR(major) || !IS_WIRE_ERROR(*minor)) {
636         major = GSS_S_FAILURE;
637         *minor = GSSEAP_BAD_ERROR_TOKEN;
638     }
639
640     GSSEAP_ASSERT(GSS_ERROR(major));
641
642     return major;
643 }
644
645 #ifdef GSSEAP_ENABLE_REAUTH
646 static OM_uint32
647 eapGssSmInitGssReauth(OM_uint32 *minor,
648                       gss_cred_id_t cred,
649                       gss_ctx_id_t ctx,
650                       gss_name_t target,
651                       gss_OID mech GSSEAP_UNUSED,
652                       OM_uint32 reqFlags,
653                       OM_uint32 timeReq,
654                       gss_channel_bindings_t chanBindings,
655                       gss_buffer_t inputToken,
656                       gss_buffer_t outputToken,
657                       OM_uint32 *smFlags GSSEAP_UNUSED)
658 {
659     OM_uint32 major, tmpMinor;
660     gss_name_t mechTarget = GSS_C_NO_NAME;
661     gss_OID actualMech = GSS_C_NO_OID;
662     OM_uint32 gssFlags, timeRec;
663
664     /*
665      * Here we use the passed in credential handle because the resolved
666      * context credential does not currently have the reauth creds.
667      */
668     if (GSSEAP_SM_STATE(ctx) == GSSEAP_STATE_INITIAL) {
669         if (!gssEapCanReauthP(cred, target, timeReq))
670             return GSS_S_CONTINUE_NEEDED;
671
672         ctx->flags |= CTX_FLAG_KRB_REAUTH;
673     } else if ((ctx->flags & CTX_FLAG_KRB_REAUTH) == 0) {
674         major = GSS_S_DEFECTIVE_TOKEN;
675         *minor = GSSEAP_WRONG_ITOK;
676         goto cleanup;
677     }
678
679     GSSEAP_ASSERT(cred != GSS_C_NO_CREDENTIAL);
680
681     major = gssEapMechToGlueName(minor, target, &mechTarget);
682     if (GSS_ERROR(major))
683         goto cleanup;
684
685     major = gssInitSecContext(minor,
686                               cred->reauthCred,
687                               &ctx->reauthCtx,
688                               mechTarget,
689                               (gss_OID)gss_mech_krb5,
690                               reqFlags | GSS_C_MUTUAL_FLAG,
691                               timeReq,
692                               chanBindings,
693                               inputToken,
694                               &actualMech,
695                               outputToken,
696                               &gssFlags,
697                               &timeRec);
698     if (GSS_ERROR(major))
699         goto cleanup;
700
701     ctx->gssFlags = gssFlags;
702
703     if (major == GSS_S_COMPLETE) {
704         GSSEAP_ASSERT(GSSEAP_SM_STATE(ctx) == GSSEAP_STATE_REAUTHENTICATE);
705
706         major = gssEapReauthComplete(minor, ctx, cred, actualMech, timeRec);
707         if (GSS_ERROR(major))
708             goto cleanup;
709         GSSEAP_SM_TRANSITION(ctx, GSSEAP_STATE_ESTABLISHED);
710     } else {
711         GSSEAP_SM_TRANSITION(ctx, GSSEAP_STATE_REAUTHENTICATE);
712     }
713
714 cleanup:
715     gssReleaseName(&tmpMinor, &mechTarget);
716
717     return major;
718 }
719 #endif /* GSSEAP_ENABLE_REAUTH */
720
721 #ifdef GSSEAP_DEBUG
722 static OM_uint32
723 eapGssSmInitVendorInfo(OM_uint32 *minor,
724                        gss_cred_id_t cred GSSEAP_UNUSED,
725                        gss_ctx_id_t ctx GSSEAP_UNUSED,
726                        gss_name_t target GSSEAP_UNUSED,
727                        gss_OID mech GSSEAP_UNUSED,
728                        OM_uint32 reqFlags GSSEAP_UNUSED,
729                        OM_uint32 timeReq GSSEAP_UNUSED,
730                        gss_channel_bindings_t chanBindings GSSEAP_UNUSED,
731                        gss_buffer_t inputToken GSSEAP_UNUSED,
732                        gss_buffer_t outputToken,
733                        OM_uint32 *smFlags GSSEAP_UNUSED)
734 {
735     OM_uint32 major;
736
737     major = makeStringBuffer(minor, "JANET(UK)", outputToken);
738     if (GSS_ERROR(major))
739         return major;
740
741     return GSS_S_CONTINUE_NEEDED;
742 }
743 #endif
744
745 static OM_uint32
746 eapGssSmInitAcceptorName(OM_uint32 *minor,
747                          gss_cred_id_t cred GSSEAP_UNUSED,
748                          gss_ctx_id_t ctx,
749                          gss_name_t target GSSEAP_UNUSED,
750                          gss_OID mech GSSEAP_UNUSED,
751                          OM_uint32 reqFlags GSSEAP_UNUSED,
752                          OM_uint32 timeReq GSSEAP_UNUSED,
753                          gss_channel_bindings_t chanBindings GSSEAP_UNUSED,
754                          gss_buffer_t inputToken GSSEAP_UNUSED,
755                          gss_buffer_t outputToken,
756                          OM_uint32 *smFlags GSSEAP_UNUSED)
757 {
758     OM_uint32 major;
759
760     if (GSSEAP_SM_STATE(ctx) == GSSEAP_STATE_INITIAL &&
761         ctx->acceptorName != GSS_C_NO_NAME) {
762
763         /* Send desired target name to acceptor */
764         major = gssEapDisplayName(minor, ctx->acceptorName,
765                                   outputToken, NULL);
766         if (GSS_ERROR(major))
767             return major;
768     } else if (inputToken != GSS_C_NO_BUFFER) {
769         OM_uint32 tmpMinor;
770         gss_name_t nameHint;
771         int equal;
772
773         /* Accept target name hint from acceptor or verify acceptor */
774         major = gssEapImportName(minor, inputToken,
775                                  GSS_C_NT_USER_NAME,
776                                  ctx->mechanismUsed,
777                                  &nameHint);
778         if (GSS_ERROR(major))
779             return major;
780
781         if (ctx->acceptorName != GSS_C_NO_NAME) {
782             /* verify name hint matched asserted acceptor name  */
783             major = gssEapCompareName(minor,
784                                       nameHint,
785                                       ctx->acceptorName,
786                                       COMPARE_NAME_FLAG_IGNORE_EMPTY_REALMS,
787                                       &equal);
788             if (GSS_ERROR(major)) {
789                 gssEapReleaseName(&tmpMinor, &nameHint);
790                 return major;
791             }
792
793             gssEapReleaseName(&tmpMinor, &nameHint);
794
795             if (!equal) {
796                 *minor = GSSEAP_WRONG_ACCEPTOR_NAME;
797                 return GSS_S_DEFECTIVE_TOKEN;
798             }
799         } else { /* acceptor name is no_name */
800             /* accept acceptor name hint */
801             ctx->acceptorName = nameHint;
802             nameHint = GSS_C_NO_NAME;
803         }
804     }
805
806
807     /*
808      * Currently, other parts of the code assume that the acceptor name
809      * is available, hence this check.
810      */
811     if (ctx->acceptorName == GSS_C_NO_NAME) {
812         *minor = GSSEAP_NO_ACCEPTOR_NAME;
813         return GSS_S_FAILURE;
814     }
815
816     /*
817      * Generate channel binding data
818      */
819     if (ctx->initiatorCtx.chbindData == NULL) {
820         major = peerInitEapChannelBinding(minor, ctx);
821         if (GSS_ERROR(major))
822             return major;
823     }
824
825     return GSS_S_CONTINUE_NEEDED;
826 }
827
828 static OM_uint32
829 eapGssSmInitIdentity(OM_uint32 *minor,
830                      gss_cred_id_t cred GSSEAP_UNUSED,
831                      gss_ctx_id_t ctx,
832                      gss_name_t target GSSEAP_UNUSED,
833                      gss_OID mech GSSEAP_UNUSED,
834                      OM_uint32 reqFlags GSSEAP_UNUSED,
835                      OM_uint32 timeReq GSSEAP_UNUSED,
836                      gss_channel_bindings_t chanBindings GSSEAP_UNUSED,
837                      gss_buffer_t inputToken GSSEAP_UNUSED,
838                      gss_buffer_t outputToken GSSEAP_UNUSED,
839                      OM_uint32 *smFlags)
840 {
841     struct eap_config eapConfig;
842
843 #ifdef GSSEAP_ENABLE_REAUTH
844     if (GSSEAP_SM_STATE(ctx) == GSSEAP_STATE_REAUTHENTICATE) {
845         OM_uint32 tmpMinor;
846
847         /* server didn't support reauthentication, sent EAP request */
848         gssDeleteSecContext(&tmpMinor, &ctx->reauthCtx, GSS_C_NO_BUFFER);
849         ctx->flags &= ~(CTX_FLAG_KRB_REAUTH);
850         GSSEAP_SM_TRANSITION(ctx, GSSEAP_STATE_INITIAL);
851     } else
852 #endif
853         *smFlags |= SM_FLAG_FORCE_SEND_TOKEN;
854
855     GSSEAP_ASSERT((ctx->flags & CTX_FLAG_KRB_REAUTH) == 0);
856     GSSEAP_ASSERT(inputToken == GSS_C_NO_BUFFER);
857
858     memset(&eapConfig, 0, sizeof(eapConfig));
859
860     ctx->initiatorCtx.eap = eap_peer_sm_init(ctx,
861                                              &gssEapPolicyCallbacks,
862                                              ctx,
863                                              &eapConfig);
864     if (ctx->initiatorCtx.eap == NULL) {
865         *minor = GSSEAP_PEER_SM_INIT_FAILURE;
866         return GSS_S_FAILURE;
867     }
868
869     ctx->flags |= CTX_FLAG_EAP_RESTART | CTX_FLAG_EAP_PORT_ENABLED;
870
871     /* poke EAP state machine */
872     if (eap_peer_sm_step(ctx->initiatorCtx.eap) != 0) {
873         *minor = GSSEAP_PEER_SM_STEP_FAILURE;
874         return GSS_S_FAILURE;
875     }
876
877     GSSEAP_SM_TRANSITION_NEXT(ctx);
878
879     *minor = 0;
880
881     return GSS_S_CONTINUE_NEEDED;
882 }
883
884 static OM_uint32
885 eapGssSmInitAuthenticate(OM_uint32 *minor,
886                          gss_cred_id_t cred GSSEAP_UNUSED,
887                          gss_ctx_id_t ctx,
888                          gss_name_t target GSSEAP_UNUSED,
889                          gss_OID mech GSSEAP_UNUSED,
890                          OM_uint32 reqFlags GSSEAP_UNUSED,
891                          OM_uint32 timeReq GSSEAP_UNUSED,
892                          gss_channel_bindings_t chanBindings GSSEAP_UNUSED,
893                          gss_buffer_t inputToken GSSEAP_UNUSED,
894                          gss_buffer_t outputToken,
895                          OM_uint32 *smFlags)
896 {
897     OM_uint32 major;
898     OM_uint32 tmpMinor;
899     struct wpabuf *resp = NULL;
900
901     *minor = 0;
902
903     GSSEAP_ASSERT(inputToken != GSS_C_NO_BUFFER);
904
905     major = peerConfigInit(minor, ctx);
906     if (GSS_ERROR(major))
907         goto cleanup;
908
909     GSSEAP_ASSERT(ctx->initiatorCtx.eap != NULL);
910     GSSEAP_ASSERT(ctx->flags & CTX_FLAG_EAP_PORT_ENABLED);
911
912     ctx->flags |= CTX_FLAG_EAP_REQ; /* we have a Request from the acceptor */
913
914     wpabuf_set(&ctx->initiatorCtx.reqData,
915                inputToken->value, inputToken->length);
916
917     major = GSS_S_CONTINUE_NEEDED;
918
919     eap_peer_sm_step(ctx->initiatorCtx.eap);
920     if (ctx->flags & CTX_FLAG_EAP_RESP) {
921         ctx->flags &= ~(CTX_FLAG_EAP_RESP);
922
923         resp = eap_get_eapRespData(ctx->initiatorCtx.eap);
924     } else if (ctx->flags & CTX_FLAG_EAP_SUCCESS) {
925         major = initReady(minor, ctx);
926         if (GSS_ERROR(major))
927             goto cleanup;
928
929         ctx->flags &= ~(CTX_FLAG_EAP_SUCCESS);
930         major = GSS_S_CONTINUE_NEEDED;
931         GSSEAP_SM_TRANSITION_NEXT(ctx);
932     } else if (ctx->flags & CTX_FLAG_EAP_FAIL) {
933         major = GSS_S_DEFECTIVE_CREDENTIAL;
934         *minor = GSSEAP_PEER_AUTH_FAILURE;
935     } else {
936         major = GSS_S_DEFECTIVE_TOKEN;
937         *minor = GSSEAP_PEER_BAD_MESSAGE;
938     }
939
940 cleanup:
941     if (resp != NULL) {
942         OM_uint32 tmpMajor;
943         gss_buffer_desc respBuf;
944
945         GSSEAP_ASSERT(major == GSS_S_CONTINUE_NEEDED);
946
947         respBuf.length = wpabuf_len(resp);
948         respBuf.value = (void *)wpabuf_head(resp);
949
950         tmpMajor = duplicateBuffer(&tmpMinor, &respBuf, outputToken);
951         if (GSS_ERROR(tmpMajor)) {
952             major = tmpMajor;
953             *minor = tmpMinor;
954         }
955
956         *smFlags |= SM_FLAG_OUTPUT_TOKEN_CRITICAL;
957     }
958
959     wpabuf_set(&ctx->initiatorCtx.reqData, NULL, 0);
960     peerConfigFree(&tmpMinor, ctx);
961
962     return major;
963 }
964
965 static OM_uint32
966 eapGssSmInitGssFlags(OM_uint32 *minor,
967                      gss_cred_id_t cred GSSEAP_UNUSED,
968                      gss_ctx_id_t ctx,
969                      gss_name_t target GSSEAP_UNUSED,
970                      gss_OID mech GSSEAP_UNUSED,
971                      OM_uint32 reqFlags GSSEAP_UNUSED,
972                      OM_uint32 timeReq GSSEAP_UNUSED,
973                      gss_channel_bindings_t chanBindings GSSEAP_UNUSED,
974                      gss_buffer_t inputToken GSSEAP_UNUSED,
975                      gss_buffer_t outputToken,
976                      OM_uint32 *smFlags GSSEAP_UNUSED)
977 {
978     unsigned char wireFlags[4];
979     gss_buffer_desc flagsBuf;
980
981     /*
982      * As a temporary measure, force mutual authentication until channel binding is
983      * more widely deployed.
984      */
985     ctx->gssFlags |= GSS_C_MUTUAL_FLAG;
986     store_uint32_be(ctx->gssFlags & GSSEAP_WIRE_FLAGS_MASK, wireFlags);
987
988     flagsBuf.length = sizeof(wireFlags);
989     flagsBuf.value = wireFlags;
990
991     return duplicateBuffer(minor, &flagsBuf, outputToken);
992 }
993
994 static OM_uint32
995 eapGssSmInitGssChannelBindings(OM_uint32 *minor,
996                                gss_cred_id_t cred GSSEAP_UNUSED,
997                                gss_ctx_id_t ctx,
998                                gss_name_t target GSSEAP_UNUSED,
999                                gss_OID mech GSSEAP_UNUSED,
1000                                OM_uint32 reqFlags GSSEAP_UNUSED,
1001                                OM_uint32 timeReq GSSEAP_UNUSED,
1002                                gss_channel_bindings_t chanBindings,
1003                                gss_buffer_t inputToken GSSEAP_UNUSED,
1004                                gss_buffer_t outputToken,
1005                                OM_uint32 *smFlags)
1006 {
1007     OM_uint32 major;
1008     krb5_error_code code;
1009     krb5_context krbContext;
1010     krb5_data data;
1011     krb5_checksum cksum;
1012     gss_buffer_desc cksumBuffer;
1013
1014     if (chanBindings == GSS_C_NO_CHANNEL_BINDINGS ||
1015         chanBindings->application_data.length == 0)
1016         return GSS_S_CONTINUE_NEEDED;
1017
1018     GSSEAP_KRB_INIT(&krbContext);
1019
1020     KRB_DATA_INIT(&data);
1021
1022     gssBufferToKrbData(&chanBindings->application_data, &data);
1023
1024     code = krb5_c_make_checksum(krbContext, ctx->checksumType,
1025                                 &ctx->rfc3961Key,
1026                                 KEY_USAGE_GSSEAP_CHBIND_MIC,
1027                                 &data, &cksum);
1028     if (code != 0) {
1029         *minor = code;
1030         return GSS_S_FAILURE;
1031     }
1032
1033     cksumBuffer.length = KRB_CHECKSUM_LENGTH(&cksum);
1034     cksumBuffer.value  = KRB_CHECKSUM_DATA(&cksum);
1035
1036     major = duplicateBuffer(minor, &cksumBuffer, outputToken);
1037     if (GSS_ERROR(major)) {
1038         krb5_free_checksum_contents(krbContext, &cksum);
1039         return major;
1040     }
1041
1042     *minor = 0;
1043     *smFlags |= SM_FLAG_OUTPUT_TOKEN_CRITICAL;
1044
1045     krb5_free_checksum_contents(krbContext, &cksum);
1046
1047     return GSS_S_CONTINUE_NEEDED;
1048 }
1049
1050 static OM_uint32
1051 eapGssSmInitInitiatorMIC(OM_uint32 *minor,
1052                          gss_cred_id_t cred GSSEAP_UNUSED,
1053                          gss_ctx_id_t ctx,
1054                          gss_name_t target GSSEAP_UNUSED,
1055                          gss_OID mech GSSEAP_UNUSED,
1056                          OM_uint32 reqFlags GSSEAP_UNUSED,
1057                          OM_uint32 timeReq GSSEAP_UNUSED,
1058                          gss_channel_bindings_t chanBindings GSSEAP_UNUSED,
1059                          gss_buffer_t inputToken GSSEAP_UNUSED,
1060                          gss_buffer_t outputToken,
1061                          OM_uint32 *smFlags)
1062 {
1063     OM_uint32 major;
1064
1065     major = gssEapMakeTokenMIC(minor, ctx, outputToken);
1066     if (GSS_ERROR(major))
1067         return major;
1068
1069     GSSEAP_SM_TRANSITION_NEXT(ctx);
1070
1071     *minor = 0;
1072     *smFlags |= SM_FLAG_OUTPUT_TOKEN_CRITICAL;
1073
1074     return GSS_S_CONTINUE_NEEDED;
1075 }
1076
1077 #ifdef GSSEAP_ENABLE_REAUTH
1078 static OM_uint32
1079 eapGssSmInitReauthCreds(OM_uint32 *minor,
1080                         gss_cred_id_t cred,
1081                         gss_ctx_id_t ctx,
1082                         gss_name_t target GSSEAP_UNUSED,
1083                         gss_OID mech GSSEAP_UNUSED,
1084                         OM_uint32 reqFlags GSSEAP_UNUSED,
1085                         OM_uint32 timeReq GSSEAP_UNUSED,
1086                         gss_channel_bindings_t chanBindings GSSEAP_UNUSED,
1087                         gss_buffer_t inputToken,
1088                         gss_buffer_t outputToken GSSEAP_UNUSED,
1089                         OM_uint32 *smFlags GSSEAP_UNUSED)
1090 {
1091     OM_uint32 major;
1092
1093     if (ctx->gssFlags & GSS_C_MUTUAL_FLAG) {
1094         major = gssEapStoreReauthCreds(minor, ctx, cred, inputToken);
1095         if (GSS_ERROR(major))
1096             return major;
1097     }
1098
1099     *minor = 0;
1100     return GSS_S_CONTINUE_NEEDED;
1101 }
1102 #endif /* GSSEAP_ENABLE_REAUTH */
1103
1104 static OM_uint32
1105 eapGssSmInitAcceptorMIC(OM_uint32 *minor,
1106                         gss_cred_id_t cred GSSEAP_UNUSED,
1107                         gss_ctx_id_t ctx,
1108                         gss_name_t target GSSEAP_UNUSED,
1109                         gss_OID mech GSSEAP_UNUSED,
1110                         OM_uint32 reqFlags GSSEAP_UNUSED,
1111                         OM_uint32 timeReq GSSEAP_UNUSED,
1112                         gss_channel_bindings_t chanBindings GSSEAP_UNUSED,
1113                         gss_buffer_t inputToken,
1114                         gss_buffer_t outputToken GSSEAP_UNUSED,
1115                         OM_uint32 *smFlags GSSEAP_UNUSED)
1116 {
1117     OM_uint32 major;
1118
1119     major = gssEapVerifyTokenMIC(minor, ctx, inputToken);
1120     if (GSS_ERROR(major))
1121         return major;
1122
1123     GSSEAP_SM_TRANSITION(ctx, GSSEAP_STATE_ESTABLISHED);
1124
1125     *minor = 0;
1126
1127     return GSS_S_COMPLETE;
1128 }
1129
1130 static struct gss_eap_sm eapGssInitiatorSm[] = {
1131     {
1132         ITOK_TYPE_CONTEXT_ERR,
1133         ITOK_TYPE_NONE,
1134         GSSEAP_STATE_ALL & ~(GSSEAP_STATE_INITIAL),
1135         0,
1136         eapGssSmInitError
1137     },
1138     {
1139         ITOK_TYPE_ACCEPTOR_NAME_RESP,
1140         ITOK_TYPE_ACCEPTOR_NAME_REQ,
1141         GSSEAP_STATE_INITIAL | GSSEAP_STATE_AUTHENTICATE |
1142         GSSEAP_STATE_ACCEPTOR_EXTS,
1143         0,
1144         eapGssSmInitAcceptorName
1145     },
1146 #ifdef GSSEAP_DEBUG
1147     {
1148         ITOK_TYPE_NONE,
1149         ITOK_TYPE_VENDOR_INFO,
1150         GSSEAP_STATE_INITIAL,
1151         0,
1152         eapGssSmInitVendorInfo
1153     },
1154 #endif
1155 #ifdef GSSEAP_ENABLE_REAUTH
1156     {
1157         ITOK_TYPE_REAUTH_RESP,
1158         ITOK_TYPE_REAUTH_REQ,
1159         GSSEAP_STATE_INITIAL | GSSEAP_STATE_REAUTHENTICATE,
1160         0,
1161         eapGssSmInitGssReauth
1162     },
1163 #endif
1164     {
1165         ITOK_TYPE_NONE,
1166         ITOK_TYPE_NONE,
1167 #ifdef GSSEAP_ENABLE_REAUTH
1168         GSSEAP_STATE_REAUTHENTICATE |
1169 #endif
1170         GSSEAP_STATE_INITIAL,
1171         SM_ITOK_FLAG_REQUIRED,
1172         eapGssSmInitIdentity
1173     },
1174     {
1175         ITOK_TYPE_EAP_REQ,
1176         ITOK_TYPE_EAP_RESP,
1177         GSSEAP_STATE_AUTHENTICATE,
1178         SM_ITOK_FLAG_REQUIRED,
1179         eapGssSmInitAuthenticate
1180     },
1181     {
1182         ITOK_TYPE_NONE,
1183         ITOK_TYPE_GSS_FLAGS,
1184         GSSEAP_STATE_INITIATOR_EXTS,
1185         0,
1186         eapGssSmInitGssFlags
1187     },
1188     {
1189         ITOK_TYPE_NONE,
1190         ITOK_TYPE_GSS_CHANNEL_BINDINGS,
1191         GSSEAP_STATE_INITIATOR_EXTS,
1192         0,
1193         eapGssSmInitGssChannelBindings
1194     },
1195     {
1196         ITOK_TYPE_NONE,
1197         ITOK_TYPE_INITIATOR_MIC,
1198         GSSEAP_STATE_INITIATOR_EXTS,
1199         SM_ITOK_FLAG_REQUIRED,
1200         eapGssSmInitInitiatorMIC
1201     },
1202 #ifdef GSSEAP_ENABLE_REAUTH
1203     {
1204         ITOK_TYPE_REAUTH_CREDS,
1205         ITOK_TYPE_NONE,
1206         GSSEAP_STATE_ACCEPTOR_EXTS,
1207         0,
1208         eapGssSmInitReauthCreds
1209     },
1210 #endif
1211     /* other extensions go here */
1212     {
1213         ITOK_TYPE_ACCEPTOR_MIC,
1214         ITOK_TYPE_NONE,
1215         GSSEAP_STATE_ACCEPTOR_EXTS,
1216         SM_ITOK_FLAG_REQUIRED,
1217         eapGssSmInitAcceptorMIC
1218     }
1219 };
1220
1221 OM_uint32
1222 gssEapInitSecContext(OM_uint32 *minor,
1223                      gss_cred_id_t cred,
1224                      gss_ctx_id_t ctx,
1225                      gss_name_t target_name,
1226                      gss_OID mech_type,
1227                      OM_uint32 req_flags,
1228                      OM_uint32 time_req,
1229                      gss_channel_bindings_t input_chan_bindings,
1230                      gss_buffer_t input_token,
1231                      gss_OID *actual_mech_type,
1232                      gss_buffer_t output_token,
1233                      OM_uint32 *ret_flags,
1234                      OM_uint32 *time_rec)
1235 {
1236     OM_uint32 major, tmpMinor;
1237     int initialContextToken = (ctx->mechanismUsed == GSS_C_NO_OID);
1238
1239     /*
1240      * XXX is acquiring the credential lock here necessary? The password is
1241      * mutable but the contract could specify that this is not updated whilst
1242      * a context is being initialized.
1243      */
1244     if (cred != GSS_C_NO_CREDENTIAL)
1245         GSSEAP_MUTEX_LOCK(&cred->mutex);
1246
1247     if (ctx->cred == GSS_C_NO_CREDENTIAL) {
1248         major = gssEapResolveInitiatorCred(minor, cred, target_name, &ctx->cred);
1249         if (GSS_ERROR(major))
1250             goto cleanup;
1251
1252         GSSEAP_ASSERT(ctx->cred != GSS_C_NO_CREDENTIAL);
1253     }
1254
1255     GSSEAP_MUTEX_LOCK(&ctx->cred->mutex);
1256
1257     GSSEAP_ASSERT(ctx->cred->flags & CRED_FLAG_RESOLVED);
1258     GSSEAP_ASSERT(ctx->cred->flags & CRED_FLAG_INITIATE);
1259
1260     if (initialContextToken) {
1261         major = initBegin(minor, ctx, target_name, mech_type,
1262                           req_flags, time_req, input_chan_bindings);
1263         if (GSS_ERROR(major))
1264             goto cleanup;
1265     }
1266
1267     major = gssEapSmStep(minor,
1268                          cred,
1269                          ctx,
1270                          target_name,
1271                          mech_type,
1272                          req_flags,
1273                          time_req,
1274                          input_chan_bindings,
1275                          input_token,
1276                          output_token,
1277                          eapGssInitiatorSm,
1278                          sizeof(eapGssInitiatorSm) / sizeof(eapGssInitiatorSm[0]));
1279     if (GSS_ERROR(major))
1280         goto cleanup;
1281
1282     if (actual_mech_type != NULL) {
1283         OM_uint32 tmpMajor;
1284
1285         tmpMajor = gssEapCanonicalizeOid(&tmpMinor, ctx->mechanismUsed, 0, actual_mech_type);
1286         if (GSS_ERROR(tmpMajor)) {
1287             major = tmpMajor;
1288             *minor = tmpMinor;
1289             goto cleanup;
1290         }
1291     }
1292
1293     if (ret_flags != NULL)
1294         *ret_flags = ctx->gssFlags;
1295
1296     if (time_rec != NULL)
1297         gssEapContextTime(&tmpMinor, ctx, time_rec);
1298
1299     GSSEAP_ASSERT(CTX_IS_ESTABLISHED(ctx) || major == GSS_S_CONTINUE_NEEDED);
1300
1301 cleanup:
1302     if (cred != GSS_C_NO_CREDENTIAL)
1303         GSSEAP_MUTEX_UNLOCK(&cred->mutex);
1304     if (ctx->cred != GSS_C_NO_CREDENTIAL)
1305         GSSEAP_MUTEX_UNLOCK(&ctx->cred->mutex);
1306
1307     return major;
1308 }
1309
1310 OM_uint32 GSSAPI_CALLCONV
1311 gss_init_sec_context(OM_uint32 *minor,
1312                      gss_cred_id_t cred,
1313                      gss_ctx_id_t *context_handle,
1314                      gss_name_t target_name,
1315                      gss_OID mech_type,
1316                      OM_uint32 req_flags,
1317                      OM_uint32 time_req,
1318                      gss_channel_bindings_t input_chan_bindings,
1319                      gss_buffer_t input_token,
1320                      gss_OID *actual_mech_type,
1321                      gss_buffer_t output_token,
1322                      OM_uint32 *ret_flags,
1323                      OM_uint32 *time_rec)
1324 {
1325     OM_uint32 major, tmpMinor;
1326     gss_ctx_id_t ctx = *context_handle;
1327
1328     *minor = 0;
1329
1330     output_token->length = 0;
1331     output_token->value = NULL;
1332
1333     if (ctx == GSS_C_NO_CONTEXT) {
1334         if (input_token != GSS_C_NO_BUFFER && input_token->length != 0) {
1335             *minor = GSSEAP_WRONG_SIZE;
1336             return GSS_S_DEFECTIVE_TOKEN;
1337         }
1338
1339         major = gssEapAllocContext(minor, &ctx);
1340         if (GSS_ERROR(major))
1341             return major;
1342
1343         ctx->flags |= CTX_FLAG_INITIATOR;
1344
1345         *context_handle = ctx;
1346     }
1347
1348     GSSEAP_MUTEX_LOCK(&ctx->mutex);
1349
1350     major = gssEapInitSecContext(minor,
1351                                  cred,
1352                                  ctx,
1353                                  target_name,
1354                                  mech_type,
1355                                  req_flags,
1356                                  time_req,
1357                                  input_chan_bindings,
1358                                  input_token,
1359                                  actual_mech_type,
1360                                  output_token,
1361                                  ret_flags,
1362                                  time_rec);
1363
1364     GSSEAP_MUTEX_UNLOCK(&ctx->mutex);
1365
1366     if (GSS_ERROR(major))
1367         gssEapReleaseContext(&tmpMinor, context_handle);
1368
1369     return major;
1370 }