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