Ensure that we call the server_cert_cb, if present, for server certificates
[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 peerValidateServer(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
433     // Truncate the identity to just the username
434     char* at = strchr(identity, '@');
435     if (at != NULL) {
436         *at = '\0';
437     }
438     
439     cert_len = cert_to_byte_array(cert, &cert_bytes);
440     hash_len = sha256(cert_bytes, cert_len, hash);
441     GSSEAP_FREE(cert_bytes);
442     
443     if (hash_len != 32) {
444         printf("peerValidateServer: Error: hash_len=%d, not 32!\n", hash_len);
445         return FALSE;
446     }
447
448     /* This is ugly, but it works -- anonymous_identity is '@' + realm
449      *  (see peerConfigInit)
450      */
451     realm = ((char *) eap_config->anonymous_identity) + 1;
452
453     ok_so_far = moonshot_confirm_ca_certificate(identity, realm, hash, 32, &error);
454     free(identity);
455
456     printf("peerValidateServer: Returning %d\n", ok_so_far);
457     return ok_so_far;
458 }
459
460
461 static OM_uint32
462 peerConfigInit(OM_uint32 *minor, gss_ctx_id_t ctx)
463 {
464     OM_uint32 major;
465     krb5_context krbContext;
466     struct eap_peer_config *eapPeerConfig = &ctx->initiatorCtx.eapPeerConfig;
467     struct wpa_config_blob *configBlobs = ctx->initiatorCtx.configBlobs;
468     gss_buffer_desc identity = GSS_C_EMPTY_BUFFER;
469     gss_buffer_desc realm = GSS_C_EMPTY_BUFFER;
470     gss_cred_id_t cred = ctx->cred;
471
472     eapPeerConfig->identity = NULL;
473     eapPeerConfig->identity_len = 0;
474     eapPeerConfig->anonymous_identity = NULL;
475     eapPeerConfig->anonymous_identity_len = 0;
476     eapPeerConfig->password = NULL;
477     eapPeerConfig->password_len = 0;
478     eapPeerConfig->eap_methods = (struct eap_method_type *) allowed_eap_method_types;
479
480     GSSEAP_ASSERT(cred != GSS_C_NO_CREDENTIAL);
481
482     GSSEAP_KRB_INIT(&krbContext);
483
484     eapPeerConfig->fragment_size = 1024;
485     
486     GSSEAP_ASSERT(cred->name != GSS_C_NO_NAME);
487
488     if ((cred->name->flags & (NAME_FLAG_NAI | NAME_FLAG_SERVICE)) == 0) {
489         *minor = GSSEAP_BAD_INITIATOR_NAME;
490         return GSS_S_BAD_NAME;
491     }
492
493     /* identity */
494     major = gssEapDisplayName(minor, cred->name, &identity, NULL);
495     if (GSS_ERROR(major))
496         return major;
497
498     eapPeerConfig->identity = (unsigned char *)identity.value;
499     eapPeerConfig->identity_len = identity.length;
500
501     krbPrincRealmToGssBuffer(cred->name->krbPrincipal, &realm);
502
503     /* anonymous_identity */
504     eapPeerConfig->anonymous_identity = GSSEAP_MALLOC(realm.length + 2);
505     if (eapPeerConfig->anonymous_identity == NULL) {
506         *minor = ENOMEM;
507         return GSS_S_FAILURE;
508     }
509
510     eapPeerConfig->anonymous_identity[0] = '@';
511     memcpy(eapPeerConfig->anonymous_identity + 1, realm.value, realm.length);
512     eapPeerConfig->anonymous_identity[1 + realm.length] = '\0';
513     eapPeerConfig->anonymous_identity_len = 1 + realm.length;
514
515     /* password */
516     if ((cred->flags & CRED_FLAG_CERTIFICATE) == 0) {
517         eapPeerConfig->password = (unsigned char *)cred->password.value;
518         eapPeerConfig->password_len = cred->password.length;
519     }
520
521     /* certs */
522     eapPeerConfig->ca_cert = (unsigned char *)cred->caCertificate.value;
523     eapPeerConfig->subject_match = (unsigned char *)cred->subjectNameConstraint.value;
524     eapPeerConfig->altsubject_match = (unsigned char *)cred->subjectAltNameConstraint.value;
525     configBlobs[CONFIG_BLOB_CA_CERT].data = cred->caCertificateBlob.value;
526     configBlobs[CONFIG_BLOB_CA_CERT].len = cred->caCertificateBlob.length;
527
528     /* eap channel binding */
529     if (ctx->initiatorCtx.chbindData != NULL) {
530         struct eap_peer_chbind_config *chbind_config =
531             (struct eap_peer_chbind_config *)GSSEAP_MALLOC(sizeof(struct eap_peer_chbind_config));
532         if (chbind_config == NULL) {
533             *minor = ENOMEM;
534             return GSS_S_FAILURE;
535         }
536
537         chbind_config->req_data = wpabuf_mhead_u8(ctx->initiatorCtx.chbindData);
538         chbind_config->req_data_len = wpabuf_len(ctx->initiatorCtx.chbindData);
539         chbind_config->nsid = CHBIND_NSID_RADIUS;
540         chbind_config->response_cb = &peerProcessChbindResponse;
541         chbind_config->ctx = ctx;
542         eapPeerConfig->chbind_config = chbind_config;
543         eapPeerConfig->chbind_config_len = 1;
544     } else {
545         eapPeerConfig->chbind_config = NULL;
546         eapPeerConfig->chbind_config_len = 0;
547     }
548     if (cred->flags & CRED_FLAG_CERTIFICATE) {
549         /*
550          * CRED_FLAG_CONFIG_BLOB is an internal flag which will be used in the
551          * future to directly pass certificate and private key data to the
552          * EAP implementation, rather than an indirected string pointer.
553          */
554         if (cred->flags & CRED_FLAG_CONFIG_BLOB) {
555             eapPeerConfig->client_cert = (unsigned char *)"blob://client-cert";
556             configBlobs[CONFIG_BLOB_CLIENT_CERT].data = cred->clientCertificate.value;
557             configBlobs[CONFIG_BLOB_CLIENT_CERT].len  = cred->clientCertificate.length;
558
559             eapPeerConfig->client_cert = (unsigned char *)"blob://private-key";
560             configBlobs[CONFIG_BLOB_PRIVATE_KEY].data = cred->clientCertificate.value;
561             configBlobs[CONFIG_BLOB_PRIVATE_KEY].len  = cred->privateKey.length;
562         } else {
563             eapPeerConfig->client_cert = (unsigned char *)cred->clientCertificate.value;
564             eapPeerConfig->private_key = (unsigned char *)cred->privateKey.value;
565         }
566         eapPeerConfig->private_key_passwd = (char *)cred->password.value;
567     }
568
569     eapPeerConfig->server_cert_cb = peerValidateServer;
570     eapPeerConfig->server_cert_ctx = eapPeerConfig;
571
572     *minor = 0;
573     return GSS_S_COMPLETE;
574 }
575
576 static OM_uint32
577 peerConfigFree(OM_uint32 *minor,
578                gss_ctx_id_t ctx)
579 {
580     struct eap_peer_config *eapPeerConfig = &ctx->initiatorCtx.eapPeerConfig;
581
582     if (eapPeerConfig->identity != NULL) {
583         GSSEAP_FREE(eapPeerConfig->identity);
584         eapPeerConfig->identity = NULL;
585         eapPeerConfig->identity_len = 0;
586     }
587
588     if (eapPeerConfig->anonymous_identity != NULL) {
589         GSSEAP_FREE(eapPeerConfig->anonymous_identity);
590         eapPeerConfig->anonymous_identity = NULL;
591         eapPeerConfig->anonymous_identity_len = 0;
592     }
593
594     *minor = 0;
595     return GSS_S_COMPLETE;
596 }
597
598 /*
599  * Mark an initiator context as ready for cryptographic operations
600  */
601 static OM_uint32
602 initReady(OM_uint32 *minor, gss_ctx_id_t ctx)
603 {
604     OM_uint32 major;
605     const unsigned char *key;
606     size_t keyLength;
607
608     /* Cache encryption type derived from selected mechanism OID */
609     major = gssEapOidToEnctype(minor, ctx->mechanismUsed, &ctx->encryptionType);
610     if (GSS_ERROR(major))
611         return major;
612
613     if (!eap_key_available(ctx->initiatorCtx.eap)) {
614         *minor = GSSEAP_KEY_UNAVAILABLE;
615         return GSS_S_UNAVAILABLE;
616     }
617
618     key = eap_get_eapKeyData(ctx->initiatorCtx.eap, &keyLength);
619
620     if (keyLength < EAP_EMSK_LEN) {
621         *minor = GSSEAP_KEY_TOO_SHORT;
622         return GSS_S_UNAVAILABLE;
623     }
624
625     major = gssEapDeriveRfc3961Key(minor,
626                                    &key[EAP_EMSK_LEN / 2],
627                                    EAP_EMSK_LEN / 2,
628                                    ctx->encryptionType,
629                                    &ctx->rfc3961Key);
630        if (GSS_ERROR(major))
631            return major;
632
633     major = rfc3961ChecksumTypeForKey(minor, &ctx->rfc3961Key,
634                                       &ctx->checksumType);
635     if (GSS_ERROR(major))
636         return major;
637
638     major = sequenceInit(minor,
639                          &ctx->seqState,
640                          ctx->recvSeq,
641                          ((ctx->gssFlags & GSS_C_REPLAY_FLAG) != 0),
642                          ((ctx->gssFlags & GSS_C_SEQUENCE_FLAG) != 0),
643                          TRUE);
644     if (GSS_ERROR(major))
645         return major;
646
647     *minor = 0;
648     return GSS_S_COMPLETE;
649 }
650
651 static OM_uint32
652 initBegin(OM_uint32 *minor,
653           gss_ctx_id_t ctx,
654           gss_name_t target,
655           gss_OID mech,
656           OM_uint32 reqFlags GSSEAP_UNUSED,
657           OM_uint32 timeReq,
658           gss_channel_bindings_t chanBindings GSSEAP_UNUSED)
659 {
660     OM_uint32 major;
661     gss_cred_id_t cred = ctx->cred;
662
663     GSSEAP_ASSERT(cred != GSS_C_NO_CREDENTIAL);
664
665     if (cred->expiryTime)
666         ctx->expiryTime = cred->expiryTime;
667     else if (timeReq == 0 || timeReq == GSS_C_INDEFINITE)
668         ctx->expiryTime = 0;
669     else
670         ctx->expiryTime = time(NULL) + timeReq;
671
672     /*
673      * The credential mutex protects its name, however we need to
674      * explicitly lock the acceptor name (unlikely as it may be
675      * that it has attributes set on it).
676      */
677     major = gssEapDuplicateName(minor, cred->name, &ctx->initiatorName);
678     if (GSS_ERROR(major))
679         return major;
680
681     if (target != GSS_C_NO_NAME) {
682         GSSEAP_MUTEX_LOCK(&target->mutex);
683
684         major = gssEapDuplicateName(minor, target, &ctx->acceptorName);
685         if (GSS_ERROR(major)) {
686             GSSEAP_MUTEX_UNLOCK(&target->mutex);
687             return major;
688         }
689
690         GSSEAP_MUTEX_UNLOCK(&target->mutex);
691     }
692
693     major = gssEapCanonicalizeOid(minor,
694                                   mech,
695                                   OID_FLAG_NULL_VALID | OID_FLAG_MAP_NULL_TO_DEFAULT_MECH,
696                                   &ctx->mechanismUsed);
697     if (GSS_ERROR(major))
698         return major;
699
700     /* If credentials were provided, check they're usable with this mech */
701     if (!gssEapCredAvailable(cred, ctx->mechanismUsed)) {
702         *minor = GSSEAP_CRED_MECH_MISMATCH;
703         return GSS_S_BAD_MECH;
704     }
705
706     *minor = 0;
707     return GSS_S_COMPLETE;
708 }
709
710 static OM_uint32
711 eapGssSmInitError(OM_uint32 *minor,
712                   gss_cred_id_t cred GSSEAP_UNUSED,
713                   gss_ctx_id_t ctx GSSEAP_UNUSED,
714                   gss_name_t target GSSEAP_UNUSED,
715                   gss_OID mech GSSEAP_UNUSED,
716                   OM_uint32 reqFlags GSSEAP_UNUSED,
717                   OM_uint32 timeReq GSSEAP_UNUSED,
718                   gss_channel_bindings_t chanBindings GSSEAP_UNUSED,
719                   gss_buffer_t inputToken,
720                   gss_buffer_t outputToken GSSEAP_UNUSED,
721                   OM_uint32 *smFlags GSSEAP_UNUSED)
722 {
723     OM_uint32 major;
724     unsigned char *p;
725
726     if (inputToken->length < 8) {
727         *minor = GSSEAP_TOK_TRUNC;
728         return GSS_S_DEFECTIVE_TOKEN;
729     }
730
731     p = (unsigned char *)inputToken->value;
732
733     major = load_uint32_be(&p[0]);
734     *minor =  load_uint32_be(&p[4]);
735     if ((*minor >0) && (*minor < 128))
736       * minor += ERROR_TABLE_BASE_eapg;
737     else *minor = 0;
738
739     if (!GSS_ERROR(major) || !IS_WIRE_ERROR(*minor)) {
740         major = GSS_S_FAILURE;
741         *minor = GSSEAP_BAD_ERROR_TOKEN;
742     }
743
744     GSSEAP_ASSERT(GSS_ERROR(major));
745
746     return major;
747 }
748
749 #ifdef GSSEAP_ENABLE_REAUTH
750 static OM_uint32
751 eapGssSmInitGssReauth(OM_uint32 *minor,
752                       gss_cred_id_t cred,
753                       gss_ctx_id_t ctx,
754                       gss_name_t target,
755                       gss_OID mech GSSEAP_UNUSED,
756                       OM_uint32 reqFlags,
757                       OM_uint32 timeReq,
758                       gss_channel_bindings_t chanBindings,
759                       gss_buffer_t inputToken,
760                       gss_buffer_t outputToken,
761                       OM_uint32 *smFlags GSSEAP_UNUSED)
762 {
763     OM_uint32 major, tmpMinor;
764     gss_name_t mechTarget = GSS_C_NO_NAME;
765     gss_OID actualMech = GSS_C_NO_OID;
766     OM_uint32 gssFlags, timeRec;
767
768     /*
769      * Here we use the passed in credential handle because the resolved
770      * context credential does not currently have the reauth creds.
771      */
772     if (GSSEAP_SM_STATE(ctx) == GSSEAP_STATE_INITIAL) {
773         if (!gssEapCanReauthP(cred, target, timeReq))
774             return GSS_S_CONTINUE_NEEDED;
775
776         ctx->flags |= CTX_FLAG_KRB_REAUTH;
777     } else if ((ctx->flags & CTX_FLAG_KRB_REAUTH) == 0) {
778         major = GSS_S_DEFECTIVE_TOKEN;
779         *minor = GSSEAP_WRONG_ITOK;
780         goto cleanup;
781     }
782
783     GSSEAP_ASSERT(cred != GSS_C_NO_CREDENTIAL);
784
785     major = gssEapMechToGlueName(minor, target, &mechTarget);
786     if (GSS_ERROR(major))
787         goto cleanup;
788
789     major = gssInitSecContext(minor,
790                               cred->reauthCred,
791                               &ctx->reauthCtx,
792                               mechTarget,
793                               (gss_OID)gss_mech_krb5,
794                               reqFlags | GSS_C_MUTUAL_FLAG,
795                               timeReq,
796                               chanBindings,
797                               inputToken,
798                               &actualMech,
799                               outputToken,
800                               &gssFlags,
801                               &timeRec);
802     if (GSS_ERROR(major))
803         goto cleanup;
804
805     ctx->gssFlags = gssFlags;
806
807     if (major == GSS_S_COMPLETE) {
808         GSSEAP_ASSERT(GSSEAP_SM_STATE(ctx) == GSSEAP_STATE_REAUTHENTICATE);
809
810         major = gssEapReauthComplete(minor, ctx, cred, actualMech, timeRec);
811         if (GSS_ERROR(major))
812             goto cleanup;
813         GSSEAP_SM_TRANSITION(ctx, GSSEAP_STATE_ESTABLISHED);
814     } else {
815         GSSEAP_SM_TRANSITION(ctx, GSSEAP_STATE_REAUTHENTICATE);
816     }
817
818 cleanup:
819     gssReleaseName(&tmpMinor, &mechTarget);
820
821     return major;
822 }
823 #endif /* GSSEAP_ENABLE_REAUTH */
824
825 #ifdef GSSEAP_DEBUG
826 static OM_uint32
827 eapGssSmInitVendorInfo(OM_uint32 *minor,
828                        gss_cred_id_t cred GSSEAP_UNUSED,
829                        gss_ctx_id_t ctx GSSEAP_UNUSED,
830                        gss_name_t target GSSEAP_UNUSED,
831                        gss_OID mech GSSEAP_UNUSED,
832                        OM_uint32 reqFlags GSSEAP_UNUSED,
833                        OM_uint32 timeReq GSSEAP_UNUSED,
834                        gss_channel_bindings_t chanBindings GSSEAP_UNUSED,
835                        gss_buffer_t inputToken GSSEAP_UNUSED,
836                        gss_buffer_t outputToken,
837                        OM_uint32 *smFlags GSSEAP_UNUSED)
838 {
839     OM_uint32 major;
840
841     major = makeStringBuffer(minor, "JANET(UK)", outputToken);
842     if (GSS_ERROR(major))
843         return major;
844
845     return GSS_S_CONTINUE_NEEDED;
846 }
847 #endif
848
849 static OM_uint32
850 eapGssSmInitAcceptorName(OM_uint32 *minor,
851                          gss_cred_id_t cred GSSEAP_UNUSED,
852                          gss_ctx_id_t ctx,
853                          gss_name_t target GSSEAP_UNUSED,
854                          gss_OID mech GSSEAP_UNUSED,
855                          OM_uint32 reqFlags GSSEAP_UNUSED,
856                          OM_uint32 timeReq GSSEAP_UNUSED,
857                          gss_channel_bindings_t chanBindings GSSEAP_UNUSED,
858                          gss_buffer_t inputToken GSSEAP_UNUSED,
859                          gss_buffer_t outputToken,
860                          OM_uint32 *smFlags GSSEAP_UNUSED)
861 {
862     OM_uint32 major;
863
864     if (GSSEAP_SM_STATE(ctx) == GSSEAP_STATE_INITIAL &&
865         ctx->acceptorName != GSS_C_NO_NAME) {
866
867         /* Send desired target name to acceptor */
868         major = gssEapDisplayName(minor, ctx->acceptorName,
869                                   outputToken, NULL);
870         if (GSS_ERROR(major))
871             return major;
872     } else if (inputToken != GSS_C_NO_BUFFER) {
873         OM_uint32 tmpMinor;
874         gss_name_t nameHint;
875         int equal;
876
877         /* Accept target name hint from acceptor or verify acceptor */
878         major = gssEapImportName(minor, inputToken,
879                                  GSS_C_NT_USER_NAME,
880                                  ctx->mechanismUsed,
881                                  &nameHint);
882         if (GSS_ERROR(major))
883             return major;
884
885         if (ctx->acceptorName != GSS_C_NO_NAME) {
886             /* verify name hint matched asserted acceptor name  */
887             major = gssEapCompareName(minor,
888                                       nameHint,
889                                       ctx->acceptorName,
890                                       COMPARE_NAME_FLAG_IGNORE_EMPTY_REALMS,
891                                       &equal);
892             if (GSS_ERROR(major)) {
893                 gssEapReleaseName(&tmpMinor, &nameHint);
894                 return major;
895             }
896
897             gssEapReleaseName(&tmpMinor, &nameHint);
898
899             if (!equal) {
900                 *minor = GSSEAP_WRONG_ACCEPTOR_NAME;
901                 return GSS_S_DEFECTIVE_TOKEN;
902             }
903         } else { /* acceptor name is no_name */
904             /* accept acceptor name hint */
905             ctx->acceptorName = nameHint;
906             nameHint = GSS_C_NO_NAME;
907         }
908     }
909
910
911     /*
912      * Currently, other parts of the code assume that the acceptor name
913      * is available, hence this check.
914      */
915     if (ctx->acceptorName == GSS_C_NO_NAME) {
916         *minor = GSSEAP_NO_ACCEPTOR_NAME;
917         return GSS_S_FAILURE;
918     }
919
920     /*
921      * Generate channel binding data
922      */
923     if (ctx->initiatorCtx.chbindData == NULL) {
924         major = peerInitEapChannelBinding(minor, ctx);
925         if (GSS_ERROR(major))
926             return major;
927     }
928
929     return GSS_S_CONTINUE_NEEDED;
930 }
931
932 static OM_uint32
933 eapGssSmInitIdentity(OM_uint32 *minor,
934                      gss_cred_id_t cred GSSEAP_UNUSED,
935                      gss_ctx_id_t ctx,
936                      gss_name_t target GSSEAP_UNUSED,
937                      gss_OID mech GSSEAP_UNUSED,
938                      OM_uint32 reqFlags GSSEAP_UNUSED,
939                      OM_uint32 timeReq GSSEAP_UNUSED,
940                      gss_channel_bindings_t chanBindings GSSEAP_UNUSED,
941                      gss_buffer_t inputToken GSSEAP_UNUSED,
942                      gss_buffer_t outputToken GSSEAP_UNUSED,
943                      OM_uint32 *smFlags)
944 {
945     struct eap_config eapConfig;
946     memset(&eapConfig, 0, sizeof(eapConfig));
947     eapConfig.cert_in_cb = 1;
948
949 #ifdef GSSEAP_ENABLE_REAUTH
950     if (GSSEAP_SM_STATE(ctx) == GSSEAP_STATE_REAUTHENTICATE) {
951         OM_uint32 tmpMinor;
952
953         /* server didn't support reauthentication, sent EAP request */
954         gssDeleteSecContext(&tmpMinor, &ctx->reauthCtx, GSS_C_NO_BUFFER);
955         ctx->flags &= ~(CTX_FLAG_KRB_REAUTH);
956         GSSEAP_SM_TRANSITION(ctx, GSSEAP_STATE_INITIAL);
957     } else
958 #endif
959         *smFlags |= SM_FLAG_FORCE_SEND_TOKEN;
960
961     GSSEAP_ASSERT((ctx->flags & CTX_FLAG_KRB_REAUTH) == 0);
962     GSSEAP_ASSERT(inputToken == GSS_C_NO_BUFFER);
963
964     ctx->initiatorCtx.eap = eap_peer_sm_init(ctx,
965                                              &gssEapPolicyCallbacks,
966                                              NULL, /* ctx?? */
967                                              &eapConfig);
968     if (ctx->initiatorCtx.eap == NULL) {
969         *minor = GSSEAP_PEER_SM_INIT_FAILURE;
970         return GSS_S_FAILURE;
971     }
972
973     ctx->flags |= CTX_FLAG_EAP_RESTART | CTX_FLAG_EAP_PORT_ENABLED;
974
975     /* poke EAP state machine */
976     if (eap_peer_sm_step(ctx->initiatorCtx.eap) != 0) {
977         *minor = GSSEAP_PEER_SM_STEP_FAILURE;
978         return GSS_S_FAILURE;
979     }
980
981     GSSEAP_SM_TRANSITION_NEXT(ctx);
982
983     *minor = 0;
984
985     return GSS_S_CONTINUE_NEEDED;
986 }
987
988 static OM_uint32
989 eapGssSmInitAuthenticate(OM_uint32 *minor,
990                          gss_cred_id_t cred GSSEAP_UNUSED,
991                          gss_ctx_id_t ctx,
992                          gss_name_t target GSSEAP_UNUSED,
993                          gss_OID mech GSSEAP_UNUSED,
994                          OM_uint32 reqFlags GSSEAP_UNUSED,
995                          OM_uint32 timeReq GSSEAP_UNUSED,
996                          gss_channel_bindings_t chanBindings GSSEAP_UNUSED,
997                          gss_buffer_t inputToken GSSEAP_UNUSED,
998                          gss_buffer_t outputToken,
999                          OM_uint32 *smFlags)
1000 {
1001     OM_uint32 major;
1002     OM_uint32 tmpMinor;
1003     struct wpabuf *resp = NULL;
1004
1005     *minor = 0;
1006
1007     GSSEAP_ASSERT(inputToken != GSS_C_NO_BUFFER);
1008
1009     major = peerConfigInit(minor, ctx);
1010     if (GSS_ERROR(major))
1011         goto cleanup;
1012
1013     GSSEAP_ASSERT(ctx->initiatorCtx.eap != NULL);
1014     GSSEAP_ASSERT(ctx->flags & CTX_FLAG_EAP_PORT_ENABLED);
1015
1016     ctx->flags |= CTX_FLAG_EAP_REQ; /* we have a Request from the acceptor */
1017
1018     wpabuf_set(&ctx->initiatorCtx.reqData,
1019                inputToken->value, inputToken->length);
1020
1021     major = GSS_S_CONTINUE_NEEDED;
1022
1023     eap_peer_sm_step(ctx->initiatorCtx.eap);
1024     if (ctx->flags & CTX_FLAG_EAP_RESP) {
1025         ctx->flags &= ~(CTX_FLAG_EAP_RESP);
1026
1027         resp = eap_get_eapRespData(ctx->initiatorCtx.eap);
1028     } else if (ctx->flags & CTX_FLAG_EAP_SUCCESS) {
1029         major = initReady(minor, ctx);
1030         if (GSS_ERROR(major))
1031             goto cleanup;
1032
1033         ctx->flags &= ~(CTX_FLAG_EAP_SUCCESS);
1034         major = GSS_S_CONTINUE_NEEDED;
1035         GSSEAP_SM_TRANSITION_NEXT(ctx);
1036     } else if (ctx->flags & CTX_FLAG_EAP_FAIL) {
1037         major = GSS_S_DEFECTIVE_CREDENTIAL;
1038         *minor = GSSEAP_PEER_AUTH_FAILURE;
1039     } else {
1040         major = GSS_S_DEFECTIVE_TOKEN;
1041         *minor = GSSEAP_PEER_BAD_MESSAGE;
1042     }
1043
1044 cleanup:
1045     if (resp != NULL) {
1046         OM_uint32 tmpMajor;
1047         gss_buffer_desc respBuf;
1048
1049         GSSEAP_ASSERT(major == GSS_S_CONTINUE_NEEDED);
1050
1051         respBuf.length = wpabuf_len(resp);
1052         respBuf.value = (void *)wpabuf_head(resp);
1053
1054         tmpMajor = duplicateBuffer(&tmpMinor, &respBuf, outputToken);
1055         if (GSS_ERROR(tmpMajor)) {
1056             major = tmpMajor;
1057             *minor = tmpMinor;
1058         }
1059
1060         *smFlags |= SM_FLAG_OUTPUT_TOKEN_CRITICAL;
1061     }
1062
1063     wpabuf_set(&ctx->initiatorCtx.reqData, NULL, 0);
1064     peerConfigFree(&tmpMinor, ctx);
1065
1066     return major;
1067 }
1068
1069 static OM_uint32
1070 eapGssSmInitGssFlags(OM_uint32 *minor,
1071                      gss_cred_id_t cred GSSEAP_UNUSED,
1072                      gss_ctx_id_t ctx,
1073                      gss_name_t target GSSEAP_UNUSED,
1074                      gss_OID mech GSSEAP_UNUSED,
1075                      OM_uint32 reqFlags GSSEAP_UNUSED,
1076                      OM_uint32 timeReq GSSEAP_UNUSED,
1077                      gss_channel_bindings_t chanBindings GSSEAP_UNUSED,
1078                      gss_buffer_t inputToken GSSEAP_UNUSED,
1079                      gss_buffer_t outputToken,
1080                      OM_uint32 *smFlags GSSEAP_UNUSED)
1081 {
1082     unsigned char wireFlags[4];
1083     gss_buffer_desc flagsBuf;
1084
1085     /*
1086      * As a temporary measure, force mutual authentication until channel binding is
1087      * more widely deployed.
1088      */
1089     ctx->gssFlags |= GSS_C_MUTUAL_FLAG;
1090     store_uint32_be(ctx->gssFlags & GSSEAP_WIRE_FLAGS_MASK, wireFlags);
1091
1092     flagsBuf.length = sizeof(wireFlags);
1093     flagsBuf.value = wireFlags;
1094
1095     return duplicateBuffer(minor, &flagsBuf, outputToken);
1096 }
1097
1098 static OM_uint32
1099 eapGssSmInitGssChannelBindings(OM_uint32 *minor,
1100                                gss_cred_id_t cred GSSEAP_UNUSED,
1101                                gss_ctx_id_t ctx,
1102                                gss_name_t target GSSEAP_UNUSED,
1103                                gss_OID mech GSSEAP_UNUSED,
1104                                OM_uint32 reqFlags GSSEAP_UNUSED,
1105                                OM_uint32 timeReq GSSEAP_UNUSED,
1106                                gss_channel_bindings_t chanBindings,
1107                                gss_buffer_t inputToken GSSEAP_UNUSED,
1108                                gss_buffer_t outputToken,
1109                                OM_uint32 *smFlags)
1110 {
1111     OM_uint32 major;
1112     krb5_error_code code;
1113     krb5_context krbContext;
1114     krb5_data data;
1115     krb5_checksum cksum;
1116     gss_buffer_desc cksumBuffer;
1117
1118     if (chanBindings == GSS_C_NO_CHANNEL_BINDINGS ||
1119         chanBindings->application_data.length == 0)
1120         return GSS_S_CONTINUE_NEEDED;
1121
1122     GSSEAP_KRB_INIT(&krbContext);
1123
1124     KRB_DATA_INIT(&data);
1125
1126     gssBufferToKrbData(&chanBindings->application_data, &data);
1127
1128     code = krb5_c_make_checksum(krbContext, ctx->checksumType,
1129                                 &ctx->rfc3961Key,
1130                                 KEY_USAGE_GSSEAP_CHBIND_MIC,
1131                                 &data, &cksum);
1132     if (code != 0) {
1133         *minor = code;
1134         return GSS_S_FAILURE;
1135     }
1136
1137     cksumBuffer.length = KRB_CHECKSUM_LENGTH(&cksum);
1138     cksumBuffer.value  = KRB_CHECKSUM_DATA(&cksum);
1139
1140     major = duplicateBuffer(minor, &cksumBuffer, outputToken);
1141     if (GSS_ERROR(major)) {
1142         krb5_free_checksum_contents(krbContext, &cksum);
1143         return major;
1144     }
1145
1146     *minor = 0;
1147     *smFlags |= SM_FLAG_OUTPUT_TOKEN_CRITICAL;
1148
1149     krb5_free_checksum_contents(krbContext, &cksum);
1150
1151     return GSS_S_CONTINUE_NEEDED;
1152 }
1153
1154 static OM_uint32
1155 eapGssSmInitInitiatorMIC(OM_uint32 *minor,
1156                          gss_cred_id_t cred GSSEAP_UNUSED,
1157                          gss_ctx_id_t ctx,
1158                          gss_name_t target GSSEAP_UNUSED,
1159                          gss_OID mech GSSEAP_UNUSED,
1160                          OM_uint32 reqFlags GSSEAP_UNUSED,
1161                          OM_uint32 timeReq GSSEAP_UNUSED,
1162                          gss_channel_bindings_t chanBindings GSSEAP_UNUSED,
1163                          gss_buffer_t inputToken GSSEAP_UNUSED,
1164                          gss_buffer_t outputToken,
1165                          OM_uint32 *smFlags)
1166 {
1167     OM_uint32 major;
1168
1169     major = gssEapMakeTokenMIC(minor, ctx, outputToken);
1170     if (GSS_ERROR(major))
1171         return major;
1172
1173     GSSEAP_SM_TRANSITION_NEXT(ctx);
1174
1175     *minor = 0;
1176     *smFlags |= SM_FLAG_OUTPUT_TOKEN_CRITICAL;
1177
1178     return GSS_S_CONTINUE_NEEDED;
1179 }
1180
1181 #ifdef GSSEAP_ENABLE_REAUTH
1182 static OM_uint32
1183 eapGssSmInitReauthCreds(OM_uint32 *minor,
1184                         gss_cred_id_t cred,
1185                         gss_ctx_id_t ctx,
1186                         gss_name_t target GSSEAP_UNUSED,
1187                         gss_OID mech GSSEAP_UNUSED,
1188                         OM_uint32 reqFlags GSSEAP_UNUSED,
1189                         OM_uint32 timeReq GSSEAP_UNUSED,
1190                         gss_channel_bindings_t chanBindings GSSEAP_UNUSED,
1191                         gss_buffer_t inputToken,
1192                         gss_buffer_t outputToken GSSEAP_UNUSED,
1193                         OM_uint32 *smFlags GSSEAP_UNUSED)
1194 {
1195     OM_uint32 major;
1196
1197     if (ctx->gssFlags & GSS_C_MUTUAL_FLAG) {
1198         major = gssEapStoreReauthCreds(minor, ctx, cred, inputToken);
1199         if (GSS_ERROR(major))
1200             return major;
1201     }
1202
1203     *minor = 0;
1204     return GSS_S_CONTINUE_NEEDED;
1205 }
1206 #endif /* GSSEAP_ENABLE_REAUTH */
1207
1208 static OM_uint32
1209 eapGssSmInitAcceptorMIC(OM_uint32 *minor,
1210                         gss_cred_id_t cred GSSEAP_UNUSED,
1211                         gss_ctx_id_t ctx,
1212                         gss_name_t target GSSEAP_UNUSED,
1213                         gss_OID mech GSSEAP_UNUSED,
1214                         OM_uint32 reqFlags GSSEAP_UNUSED,
1215                         OM_uint32 timeReq GSSEAP_UNUSED,
1216                         gss_channel_bindings_t chanBindings GSSEAP_UNUSED,
1217                         gss_buffer_t inputToken,
1218                         gss_buffer_t outputToken GSSEAP_UNUSED,
1219                         OM_uint32 *smFlags GSSEAP_UNUSED)
1220 {
1221     OM_uint32 major;
1222
1223     major = gssEapVerifyTokenMIC(minor, ctx, inputToken);
1224     if (GSS_ERROR(major))
1225         return major;
1226
1227     GSSEAP_SM_TRANSITION(ctx, GSSEAP_STATE_ESTABLISHED);
1228
1229     *minor = 0;
1230
1231     return GSS_S_COMPLETE;
1232 }
1233
1234 static struct gss_eap_sm eapGssInitiatorSm[] = {
1235     {
1236         ITOK_TYPE_CONTEXT_ERR,
1237         ITOK_TYPE_NONE,
1238         GSSEAP_STATE_ALL & ~(GSSEAP_STATE_INITIAL),
1239         0,
1240         eapGssSmInitError
1241     },
1242     {
1243         ITOK_TYPE_ACCEPTOR_NAME_RESP,
1244         ITOK_TYPE_ACCEPTOR_NAME_REQ,
1245         GSSEAP_STATE_INITIAL | GSSEAP_STATE_AUTHENTICATE |
1246         GSSEAP_STATE_ACCEPTOR_EXTS,
1247         0,
1248         eapGssSmInitAcceptorName
1249     },
1250 #ifdef GSSEAP_DEBUG
1251     {
1252         ITOK_TYPE_NONE,
1253         ITOK_TYPE_VENDOR_INFO,
1254         GSSEAP_STATE_INITIAL,
1255         0,
1256         eapGssSmInitVendorInfo
1257     },
1258 #endif
1259 #ifdef GSSEAP_ENABLE_REAUTH
1260     {
1261         ITOK_TYPE_REAUTH_RESP,
1262         ITOK_TYPE_REAUTH_REQ,
1263         GSSEAP_STATE_INITIAL | GSSEAP_STATE_REAUTHENTICATE,
1264         0,
1265         eapGssSmInitGssReauth
1266     },
1267 #endif
1268     {
1269         ITOK_TYPE_NONE,
1270         ITOK_TYPE_NONE,
1271 #ifdef GSSEAP_ENABLE_REAUTH
1272         GSSEAP_STATE_REAUTHENTICATE |
1273 #endif
1274         GSSEAP_STATE_INITIAL,
1275         SM_ITOK_FLAG_REQUIRED,
1276         eapGssSmInitIdentity
1277     },
1278     {
1279         ITOK_TYPE_EAP_REQ,
1280         ITOK_TYPE_EAP_RESP,
1281         GSSEAP_STATE_AUTHENTICATE,
1282         SM_ITOK_FLAG_REQUIRED,
1283         eapGssSmInitAuthenticate
1284     },
1285     {
1286         ITOK_TYPE_NONE,
1287         ITOK_TYPE_GSS_FLAGS,
1288         GSSEAP_STATE_INITIATOR_EXTS,
1289         0,
1290         eapGssSmInitGssFlags
1291     },
1292     {
1293         ITOK_TYPE_NONE,
1294         ITOK_TYPE_GSS_CHANNEL_BINDINGS,
1295         GSSEAP_STATE_INITIATOR_EXTS,
1296         0,
1297         eapGssSmInitGssChannelBindings
1298     },
1299     {
1300         ITOK_TYPE_NONE,
1301         ITOK_TYPE_INITIATOR_MIC,
1302         GSSEAP_STATE_INITIATOR_EXTS,
1303         SM_ITOK_FLAG_REQUIRED,
1304         eapGssSmInitInitiatorMIC
1305     },
1306 #ifdef GSSEAP_ENABLE_REAUTH
1307     {
1308         ITOK_TYPE_REAUTH_CREDS,
1309         ITOK_TYPE_NONE,
1310         GSSEAP_STATE_ACCEPTOR_EXTS,
1311         0,
1312         eapGssSmInitReauthCreds
1313     },
1314 #endif
1315     /* other extensions go here */
1316     {
1317         ITOK_TYPE_ACCEPTOR_MIC,
1318         ITOK_TYPE_NONE,
1319         GSSEAP_STATE_ACCEPTOR_EXTS,
1320         SM_ITOK_FLAG_REQUIRED,
1321         eapGssSmInitAcceptorMIC
1322     }
1323 };
1324
1325 OM_uint32
1326 gssEapInitSecContext(OM_uint32 *minor,
1327                      gss_cred_id_t cred,
1328                      gss_ctx_id_t ctx,
1329                      gss_name_t target_name,
1330                      gss_OID mech_type,
1331                      OM_uint32 req_flags,
1332                      OM_uint32 time_req,
1333                      gss_channel_bindings_t input_chan_bindings,
1334                      gss_buffer_t input_token,
1335                      gss_OID *actual_mech_type,
1336                      gss_buffer_t output_token,
1337                      OM_uint32 *ret_flags,
1338                      OM_uint32 *time_rec)
1339 {
1340     OM_uint32 major, tmpMinor;
1341     int initialContextToken = (ctx->mechanismUsed == GSS_C_NO_OID);
1342
1343     /*
1344      * XXX is acquiring the credential lock here necessary? The password is
1345      * mutable but the contract could specify that this is not updated whilst
1346      * a context is being initialized.
1347      */
1348     if (cred != GSS_C_NO_CREDENTIAL)
1349         GSSEAP_MUTEX_LOCK(&cred->mutex);
1350
1351     if (ctx->cred == GSS_C_NO_CREDENTIAL) {
1352         major = gssEapResolveInitiatorCred(minor, cred, target_name, &ctx->cred);
1353         if (GSS_ERROR(major))
1354             goto cleanup;
1355
1356         GSSEAP_ASSERT(ctx->cred != GSS_C_NO_CREDENTIAL);
1357     }
1358
1359     GSSEAP_MUTEX_LOCK(&ctx->cred->mutex);
1360
1361     GSSEAP_ASSERT(ctx->cred->flags & CRED_FLAG_RESOLVED);
1362     GSSEAP_ASSERT(ctx->cred->flags & CRED_FLAG_INITIATE);
1363
1364     if (initialContextToken) {
1365         major = initBegin(minor, ctx, target_name, mech_type,
1366                           req_flags, time_req, input_chan_bindings);
1367         if (GSS_ERROR(major))
1368             goto cleanup;
1369     }
1370
1371     major = gssEapSmStep(minor,
1372                          cred,
1373                          ctx,
1374                          target_name,
1375                          mech_type,
1376                          req_flags,
1377                          time_req,
1378                          input_chan_bindings,
1379                          input_token,
1380                          output_token,
1381                          eapGssInitiatorSm,
1382                          sizeof(eapGssInitiatorSm) / sizeof(eapGssInitiatorSm[0]));
1383     if (GSS_ERROR(major))
1384         goto cleanup;
1385
1386     if (actual_mech_type != NULL) {
1387         OM_uint32 tmpMajor;
1388
1389         tmpMajor = gssEapCanonicalizeOid(&tmpMinor, ctx->mechanismUsed, 0, actual_mech_type);
1390         if (GSS_ERROR(tmpMajor)) {
1391             major = tmpMajor;
1392             *minor = tmpMinor;
1393             goto cleanup;
1394         }
1395     }
1396
1397     if (ret_flags != NULL)
1398         *ret_flags = ctx->gssFlags;
1399
1400     if (time_rec != NULL)
1401         gssEapContextTime(&tmpMinor, ctx, time_rec);
1402
1403     GSSEAP_ASSERT(CTX_IS_ESTABLISHED(ctx) || major == GSS_S_CONTINUE_NEEDED);
1404
1405 cleanup:
1406     if (cred != GSS_C_NO_CREDENTIAL)
1407         GSSEAP_MUTEX_UNLOCK(&cred->mutex);
1408     if (ctx->cred != GSS_C_NO_CREDENTIAL)
1409         GSSEAP_MUTEX_UNLOCK(&ctx->cred->mutex);
1410
1411     return major;
1412 }
1413
1414 OM_uint32 GSSAPI_CALLCONV
1415 gss_init_sec_context(OM_uint32 *minor,
1416                      gss_cred_id_t cred,
1417                      gss_ctx_id_t *context_handle,
1418                      gss_name_t target_name,
1419                      gss_OID mech_type,
1420                      OM_uint32 req_flags,
1421                      OM_uint32 time_req,
1422                      gss_channel_bindings_t input_chan_bindings,
1423                      gss_buffer_t input_token,
1424                      gss_OID *actual_mech_type,
1425                      gss_buffer_t output_token,
1426                      OM_uint32 *ret_flags,
1427                      OM_uint32 *time_rec)
1428 {
1429     OM_uint32 major, tmpMinor;
1430     gss_ctx_id_t ctx = *context_handle;
1431
1432     *minor = 0;
1433
1434     output_token->length = 0;
1435     output_token->value = NULL;
1436
1437     if (ctx == GSS_C_NO_CONTEXT) {
1438         if (input_token != GSS_C_NO_BUFFER && input_token->length != 0) {
1439             *minor = GSSEAP_WRONG_SIZE;
1440             return GSS_S_DEFECTIVE_TOKEN;
1441         }
1442
1443         major = gssEapAllocContext(minor, &ctx);
1444         if (GSS_ERROR(major))
1445             return major;
1446
1447         ctx->flags |= CTX_FLAG_INITIATOR;
1448
1449         *context_handle = ctx;
1450     }
1451
1452     GSSEAP_MUTEX_LOCK(&ctx->mutex);
1453
1454     major = gssEapInitSecContext(minor,
1455                                  cred,
1456                                  ctx,
1457                                  target_name,
1458                                  mech_type,
1459                                  req_flags,
1460                                  time_req,
1461                                  input_chan_bindings,
1462                                  input_token,
1463                                  actual_mech_type,
1464                                  output_token,
1465                                  ret_flags,
1466                                  time_rec);
1467
1468     GSSEAP_MUTEX_UNLOCK(&ctx->mutex);
1469
1470     if (GSS_ERROR(major))
1471         gssEapReleaseContext(&tmpMinor, context_handle);
1472
1473     gssEapTraceStatus( "gss_init_sec_context", major, *minor);
1474     return major;
1475 }
1476