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