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