Partial build of reauth code against Heimdal
[mech_eap.orig] / util_reauth.c
1 /*
2  * Copyright (c) 2010, 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  * Fast reauthentication support.
35  */
36
37 #include "gssapiP_eap.h"
38
39 #include <dlfcn.h>
40
41 /*
42  * Fast reauthentication support for EAP GSS.
43  */
44
45 krb5_error_code
46 krb5_encrypt_tkt_part(krb5_context, const krb5_keyblock *, krb5_ticket *);
47
48 krb5_error_code
49 encode_krb5_ticket(const krb5_ticket *rep, krb5_data **code);
50
51 static OM_uint32
52 gssDisplayName(OM_uint32 *minor,
53                gss_name_t name,
54                gss_buffer_t buffer,
55                gss_OID *name_type);
56
57 static OM_uint32
58 gssImportName(OM_uint32 *minor,
59               gss_buffer_t buffer,
60               gss_OID name_type,
61               gss_name_t *name);
62
63 static krb5_error_code
64 getAcceptorKey(krb5_context krbContext,
65                gss_ctx_id_t ctx,
66                gss_cred_id_t cred,
67                krb5_principal *princ,
68                krb5_keyblock *key)
69 {
70     krb5_error_code code;
71     krb5_keytab keytab = NULL;
72     krb5_keytab_entry ktent = { 0 };
73 #ifdef HAVE_HEIMDAL_VERSION
74     krb5_kt_cursor cursor = { 0 };
75 #else
76     krb5_kt_cursor cursor = NULL;
77 #endif
78
79     *princ = NULL;
80     memset(key, 0, sizeof(*key));
81
82     code = krb5_kt_default(krbContext, &keytab);
83     if (code != 0)
84         goto cleanup;
85
86     if (cred != GSS_C_NO_CREDENTIAL && cred->name != GSS_C_NO_NAME) {
87         code = krb5_kt_get_entry(krbContext, keytab,
88                                  cred->name->krbPrincipal, 0,
89                                  ctx->encryptionType, &ktent);
90         if (code != 0)
91             goto cleanup;
92     } else {
93         /*
94          * It's not clear that looking encrypting the ticket in the
95          * requested EAP enctype provides any value.
96          */
97         code = krb5_kt_start_seq_get(krbContext, keytab, &cursor);
98         if (code != 0)
99             goto cleanup;
100
101         while ((code = krb5_kt_next_entry(krbContext, keytab,
102                                           &ktent, &cursor)) == 0) {
103 #ifdef HAVE_HEIMDAL_VERSION
104             if (ktent.keyblock.keytype == ctx->encryptionType)
105                 break;
106             else
107                 krb5_kt_free_entry(krbContext, &ktent);
108 #else
109             if (ktent.key.enctype == ctx->encryptionType)
110                 break;
111             else
112                 krb5_free_keytab_entry_contents(krbContext, &ktent);
113 #endif
114         }
115     }
116
117     if (code == 0) {
118         *princ = ktent.principal;
119 #ifdef HAVE_HEIMDAL_VERSION
120         *key = ktent.keyblock;
121 #else
122         *key = ktent.key;
123 #endif
124     }
125
126 cleanup:
127     if (cred == GSS_C_NO_CREDENTIAL || cred->name == GSS_C_NO_NAME)
128         krb5_kt_end_seq_get(krbContext, keytab, &cursor);
129     krb5_kt_close(krbContext, keytab);
130
131     if (code != 0)
132 #ifdef HAVE_HEIMDAL_VERSION
133         krb5_kt_free_entry(krbContext, &ktent);
134 #else
135         krb5_free_keytab_entry_contents(krbContext, &ktent);
136 #endif
137
138     return code;
139 }
140
141 static OM_uint32
142 freezeAttrContext(OM_uint32 *minor,
143                   gss_name_t initiatorName,
144                   krb5_const_principal acceptorPrinc,
145                   krb5_keyblock *session,
146 #ifdef HAVE_HEIMDAL_VERSION
147                   krb5_authdata *authdata
148 #else
149                   krb5_authdata ***authdata
150 #endif
151                   )
152 {
153     OM_uint32 major, tmpMinor;
154     krb5_error_code code;
155     gss_buffer_desc attrBuf = GSS_C_EMPTY_BUFFER;
156 #ifdef HAVE_HEIMDAL_VERSION
157     AuthorizationData authDataBuf, *authData = &authDataBuf;
158     AuthorizationDataElement authDatum = { 0 };
159 #else
160     krb5_authdata *authData[2], authDatum = { 0 };
161 #endif
162     krb5_context krbContext;
163
164     GSSEAP_KRB_INIT(&krbContext);
165
166     major = gssEapExportAttrContext(minor, initiatorName, &attrBuf);
167     if (GSS_ERROR(major))
168         return major;
169
170     authDatum.ad_type = KRB5_AUTHDATA_RADIUS_AVP;
171 #ifdef HAVE_HEIMDAL_VERSION
172     authDatum.ad_data.length = attrBuf.length;
173     authDatum.ad_data.data = attrBuf.value;
174     authData->len = 1;
175     authData->val = &authDatum;
176 #else
177     authDatum.length = attrBuf.length;
178     authDatum.contents = attrBuf.value;
179     authData[0] = &authDatum;
180     authData[1] = NULL;
181 #endif
182
183     code = krbMakeAuthDataKdcIssued(krbContext, session, acceptorPrinc,
184                                     authData, authdata);
185     if (code != 0) {
186         major = GSS_S_FAILURE;
187         *minor = code;
188     } else {
189         major = GSS_S_COMPLETE;
190     }
191
192     gss_release_buffer(&tmpMinor, &attrBuf);
193
194     return major;
195 }
196
197 /*
198  * Fabricate a ticket to ourselves given a GSS EAP context.
199  */
200 OM_uint32
201 gssEapMakeReauthCreds(OM_uint32 *minor,
202                       gss_ctx_id_t ctx,
203                       gss_cred_id_t cred,
204                       gss_buffer_t credBuf)
205 {
206     OM_uint32 major = GSS_S_COMPLETE;
207     krb5_error_code code;
208     krb5_context krbContext = NULL;
209     krb5_keyblock session = { 0 }, acceptorKey = { 0 };
210     krb5_principal server = NULL;
211 #ifdef HAVE_HEIMDAL_VERSION
212     Ticket ticket;
213     EncTicketPart enc_part;
214     AuthorizationData authData = { 0 };
215     krb5_crypto krbCrypto = NULL;
216     unsigned char *buf = NULL;
217     size_t buf_size, len;
218 #else
219     krb5_ticket ticket;
220     krb5_enc_tkt_part enc_part;
221 #endif
222     krb5_data *ticketData = NULL, *credsData = NULL;
223     krb5_creds creds = { 0 };
224     krb5_auth_context authContext = NULL;
225
226     memset(&ticket, 0, sizeof(ticket));
227     memset(&enc_part, 0, sizeof(enc_part));
228
229     credBuf->length = 0;
230     credBuf->value = NULL;
231
232     GSSEAP_KRB_INIT(&krbContext);
233
234     code = getAcceptorKey(krbContext, ctx, cred, &server, &acceptorKey);
235     if (code == KRB5_KT_NOTFOUND) {
236         *minor = code;
237         return GSS_S_UNAVAILABLE;
238     } else if (code != 0)
239         goto cleanup;
240
241 #ifdef HAVE_HEIMDAL_VERSION
242     ticket.realm = server->realm;
243     ticket.sname = server->name;
244 #else
245     ticket.server = server;
246 #endif
247
248     /*
249      * Generate a random session key to place in the ticket and
250      * sign the "KDC-Issued" authorization data element.
251      */
252     code = krb5_c_make_random_key(krbContext, ctx->encryptionType,
253                                   &session);
254     if (code != 0)
255         goto cleanup;
256
257 #ifdef HAVE_HEIMDAL_VERSION
258     enc_part.flags.initial = 1;
259     enc_part.key = session;
260     enc_part.crealm = ctx->initiatorName->krbPrincipal->realm;
261     enc_part.cname = ctx->initiatorName->krbPrincipal->name;
262     enc_part.authtime = time(NULL);
263     enc_part.starttime = &enc_part.authtime;
264     enc_part.endtime = (ctx->expiryTime != 0)
265                        ? ctx->expiryTime : KRB_TIME_FOREVER;
266     enc_part.renew_till = NULL;
267     enc_part.authorization_data = &authData;
268
269     major = freezeAttrContext(minor, ctx->initiatorName, server,
270                               &session, &authData);
271     if (GSS_ERROR(major))
272         goto cleanup;
273
274     ASN1_MALLOC_ENCODE(EncTicketPart, buf, buf_size, &enc_part, &len, code);
275     if (code != 0)
276         goto cleanup;
277
278     code = krb5_crypto_init(krbContext, &acceptorKey, 0, &krbCrypto);
279     if (code != 0)
280         goto cleanup;
281
282     code = krb5_encrypt_EncryptedData(krbContext,
283                                       krbCrypto,
284                                       KRB5_KU_TICKET,
285                                       buf,
286                                       len,
287                                       0,
288                                       &ticket.enc_part);
289     if (code != 0)
290         goto cleanup;
291
292     GSSEAP_FREE(buf);
293     buf = NULL;
294
295     ASN1_MALLOC_ENCODE(Ticket, buf, buf_size, &ticket, &len, code);
296     if (code != 0)
297         goto cleanup;
298 #else
299     enc_part.flags = TKT_FLG_INITIAL;
300     enc_part.session = &session;
301     enc_part.client = ctx->initiatorName->krbPrincipal;
302     enc_part.times.authtime = time(NULL);
303     enc_part.times.starttime = enc_part.times.authtime;
304     enc_part.times.endtime = (ctx->expiryTime != 0)
305                              ? ctx->expiryTime
306                              : KRB_TIME_FOREVER;
307     enc_part.times.renew_till = 0;
308
309     major = freezeAttrContext(minor, ctx->initiatorName, server,
310                               &session, &enc_part.authorization_data);
311     if (GSS_ERROR(major))
312         goto cleanup;
313
314     ticket.enc_part2 = &enc_part;
315
316     code = krb5_encrypt_tkt_part(krbContext, &acceptorKey, &ticket);
317     if (code != 0)
318         goto cleanup;
319
320     code = encode_krb5_ticket(&ticket, &ticketData);
321     if (code != 0)
322         goto cleanup;
323 #endif /* HAVE_HEIMDAL_VERSION */
324
325     creds.client = ctx->initiatorName->krbPrincipal;
326     creds.server = server;
327 #ifdef HAVE_HEIMDAL_VERSION
328     creds.session = session;
329     creds.times.authtime = enc_part.authtime;
330     creds.times.starttime = *enc_part.starttime;
331     creds.times.endtime = enc_part.endtime;
332     creds.times.renew_till = 0;
333     creds.flags.b = enc_part.flags;
334     creds.ticket = *ticketData;
335     creds.authdata = authData;
336 #else
337     creds.keyblock = session;
338     creds.times = enc_part.times;
339     creds.ticket_flags = enc_part.flags;
340     creds.ticket = *ticketData;
341     creds.authdata = enc_part.authorization_data;
342 #endif
343
344     code = krb5_auth_con_init(krbContext, &authContext);
345     if (code != 0)
346         goto cleanup;
347
348     code = krb5_auth_con_setflags(krbContext, authContext, 0);
349     if (code != 0)
350         goto cleanup;
351
352     code = krb5_auth_con_setsendsubkey(krbContext, authContext,
353                                        &ctx->rfc3961Key);
354     if (code != 0)
355         goto cleanup;
356
357     code = krb5_mk_1cred(krbContext, authContext, &creds, &credsData, NULL);
358     if (code != 0)
359         goto cleanup;
360
361     krbDataToGssBuffer(credsData, credBuf);
362
363 cleanup:
364 #ifdef HAVE_HEIMDAL_VERSION
365     if (krbCrypto != NULL)
366         krb5_crypto_destroy(krbContext, krbCrypto);
367     if (buf != NULL)
368         GSSEAP_FREE(buf);
369     free_AuthorizationData(&authData);
370     free_EncryptedData(&ticket.enc_part);
371 #else
372     krb5_free_authdata(krbContext, enc_part.authorization_data);
373     if (ticket.enc_part.ciphertext.data != NULL)
374         GSSEAP_FREE(ticket.enc_part.ciphertext.data);
375 #endif
376     krb5_free_keyblock_contents(krbContext, &session);
377     krb5_free_principal(krbContext, server);
378     krb5_free_keyblock_contents(krbContext, &acceptorKey);
379     krb5_free_data(krbContext, ticketData);
380     krb5_auth_con_free(krbContext, authContext);
381     if (credsData != NULL)
382         GSSEAP_FREE(credsData);
383
384     if (major == GSS_S_COMPLETE) {
385         *minor = code;
386         major = (code != 0) ? GSS_S_FAILURE : GSS_S_COMPLETE;
387     }
388
389     return major;
390 }
391
392 static int
393 isTicketGrantingServiceP(krb5_context krbContext,
394                          krb5_const_principal principal)
395 {
396     if (KRB_PRINC_LENGTH(principal) == 2 &&
397 #ifdef HAVE_HEIMDAL_VERSION
398         strcmp(KRB_PRINC_NAME(principal)[0], "krbtgt") == 0
399 #else
400         krb5_princ_component(krbContext, principal, 0)->length == 6 &&
401         memcmp(krb5_princ_component(krbContext,
402                                     principal, 0)->data, "krbtgt", 6) == 0
403 #endif
404         )
405         return TRUE;
406
407     return FALSE;
408 }
409
410 /*
411  * Returns TRUE if the configuration variable reauth_use_ccache is
412  * set in krb5.conf for the eap_gss application and the client realm.
413  */
414 static int
415 reauthUseCredsCache(krb5_context krbContext,
416                     krb5_principal principal)
417 {
418     int reauthUseCCache;
419
420     /* if reauth_use_ccache, use default credentials cache if ticket is for us */
421     krb5_appdefault_boolean(krbContext, "eap_gss",
422                             KRB_PRINC_REALM(principal),
423                             "reauth_use_ccache", 0, &reauthUseCCache);
424
425     return reauthUseCCache;
426 }
427
428 /*
429  * Look in default credentials cache for reauthentication credentials,
430  * if policy allows.
431  */
432 static OM_uint32
433 getDefaultReauthCredentials(OM_uint32 *minor,
434                             gss_cred_id_t cred,
435                             gss_name_t target,
436                             time_t now,
437                             OM_uint32 timeReq)
438 {
439     OM_uint32 major = GSS_S_CRED_UNAVAIL;
440     krb5_context krbContext = NULL;
441     krb5_error_code code = 0;
442     krb5_ccache ccache = NULL;
443     krb5_creds match = { 0 };
444     krb5_creds creds = { 0 };
445
446     GSSEAP_KRB_INIT(&krbContext);
447
448     assert(cred != GSS_C_NO_CREDENTIAL);
449     assert(target != GSS_C_NO_NAME);
450
451     if (cred->name == GSS_C_NO_NAME ||
452         !reauthUseCredsCache(krbContext, cred->name->krbPrincipal))
453         goto cleanup;
454
455     match.client = cred->name->krbPrincipal;
456     match.server = target->krbPrincipal;
457     if (timeReq != 0 && timeReq != GSS_C_INDEFINITE)
458         match.times.endtime = now + timeReq;
459
460     code = krb5_cc_default(krbContext, &ccache);
461     if (code != 0)
462         goto cleanup;
463
464     code = krb5_cc_retrieve_cred(krbContext, ccache, 0, &match, &creds);
465     if (code != 0)
466         goto cleanup;
467
468     cred->flags |= CRED_FLAG_DEFAULT_CCACHE;
469     cred->krbCredCache = ccache;
470     ccache = NULL;
471
472     major = gss_krb5_import_cred(minor, cred->krbCredCache, NULL, NULL,
473                                  &cred->krbCred);
474
475 cleanup:
476     if (major == GSS_S_CRED_UNAVAIL)
477         *minor = code;
478
479     if (ccache != NULL)
480         krb5_cc_close(krbContext, ccache);
481     krb5_free_cred_contents(krbContext, &creds);
482
483     return major;
484 }
485
486 /*
487  * Returns TRUE if the credential handle's reauth credentials are
488  * valid or if we can use the default credentials cache. Credentials
489  * handle must be locked.
490  */
491 int
492 gssEapCanReauthP(gss_cred_id_t cred,
493                  gss_name_t target,
494                  OM_uint32 timeReq)
495 {
496     time_t now, expiryReq;
497     OM_uint32 minor;
498
499     assert(cred != GSS_C_NO_CREDENTIAL);
500
501     now = time(NULL);
502     expiryReq = now;
503     if (timeReq != GSS_C_INDEFINITE)
504         expiryReq += timeReq;
505
506     if (cred->krbCredCache != NULL && cred->expiryTime > expiryReq)
507         return TRUE;
508
509     if (getDefaultReauthCredentials(&minor, cred, target,
510                                     now, timeReq) == GSS_S_COMPLETE)
511         return TRUE;
512
513     return FALSE;
514 }
515
516 /*
517  * Store re-authentication (Kerberos) credentials in a credential handle.
518  * Credentials handle must be locked.
519  */
520 OM_uint32
521 gssEapStoreReauthCreds(OM_uint32 *minor,
522                        gss_ctx_id_t ctx,
523                        gss_cred_id_t cred,
524                        gss_buffer_t credBuf)
525 {
526     OM_uint32 major = GSS_S_COMPLETE;
527     krb5_error_code code;
528     krb5_context krbContext = NULL;
529     krb5_auth_context authContext = NULL;
530     krb5_data credData = { 0 };
531     krb5_creds **creds = NULL;
532     krb5_principal canonPrinc;
533     krb5_principal ccPrinc = NULL;
534     int i;
535
536     if (credBuf->length == 0 || cred == GSS_C_NO_CREDENTIAL)
537         return GSS_S_COMPLETE;
538
539     GSSEAP_KRB_INIT(&krbContext);
540
541     code = krb5_auth_con_init(krbContext, &authContext);
542     if (code != 0)
543         goto cleanup;
544
545     code = krb5_auth_con_setflags(krbContext, authContext, 0);
546     if (code != 0)
547         goto cleanup;
548
549     code = krb5_auth_con_setrecvsubkey(krbContext, authContext,
550                                        &ctx->rfc3961Key);
551     if (code != 0)
552         goto cleanup;
553
554     gssBufferToKrbData(credBuf, &credData);
555
556     code = krb5_rd_cred(krbContext, authContext, &credData, &creds, NULL);
557     if (code != 0)
558         goto cleanup;
559
560     if (creds == NULL || creds[0] == NULL)
561         goto cleanup;
562
563     code = krb5_copy_principal(krbContext, creds[0]->client, &canonPrinc);
564     if (code != 0)
565         goto cleanup;
566
567     krb5_free_principal(krbContext, cred->name->krbPrincipal);
568     cred->name->krbPrincipal = canonPrinc;
569
570     if (creds[0]->times.endtime == KRB_TIME_FOREVER)
571         cred->expiryTime = 0;
572     else
573         cred->expiryTime = creds[0]->times.endtime;
574
575     if (cred->krbCredCache == NULL) {
576         if (reauthUseCredsCache(krbContext, creds[0]->client) &&
577             krb5_cc_default(krbContext, &cred->krbCredCache) == 0)
578             cred->flags |= CRED_FLAG_DEFAULT_CCACHE;
579     } else {
580         /*
581          * If we already have an associated credentials cache, possibly from
582          * the last time we stored a reauthentication credential, then we
583          * need to clear it out and release the associated GSS credential.
584          */
585         if (cred->flags & CRED_FLAG_DEFAULT_CCACHE) {
586             krb5_cc_remove_cred(krbContext, cred->krbCredCache, 0, creds[0]);
587         } else {
588             krb5_cc_destroy(krbContext, cred->krbCredCache);
589             cred->krbCredCache = NULL;
590         }
591         gssReleaseCred(minor, &cred->krbCred);
592     }
593
594     if (cred->krbCredCache == NULL) {
595         code = krb5_cc_new_unique(krbContext, "MEMORY", NULL, &cred->krbCredCache);
596         if (code != 0)
597             goto cleanup;
598     }
599
600     if ((cred->flags & CRED_FLAG_DEFAULT_CCACHE) == 0 ||
601         krb5_cc_get_principal(krbContext, cred->krbCredCache, &ccPrinc) != 0) {
602         code = krb5_cc_initialize(krbContext, cred->krbCredCache,
603                                   creds[0]->client);
604         if (code != 0)
605             goto cleanup;
606     }
607
608     for (i = 0; creds[i] != NULL; i++) {
609         krb5_creds kcred = *(creds[i]);
610
611         /*
612          * Swap in the acceptor name the client asked for so
613          * get_credentials() works. We're making the assumption that
614          * any service tickets returned are for us. We'll need to
615          * reflect some more on whether that is a safe assumption.
616          */
617         if (!isTicketGrantingServiceP(krbContext, kcred.server))
618             kcred.server = ctx->acceptorName->krbPrincipal;
619
620         code = krb5_cc_store_cred(krbContext, cred->krbCredCache, &kcred);
621         if (code != 0)
622             goto cleanup;
623     }
624
625     major = gss_krb5_import_cred(minor, cred->krbCredCache, NULL, NULL,
626                                  &cred->krbCred);
627     if (GSS_ERROR(major))
628         goto cleanup;
629
630 cleanup:
631     *minor = code;
632
633     krb5_free_principal(krbContext, ccPrinc);
634     krb5_auth_con_free(krbContext, authContext);
635     if (creds != NULL) {
636         for (i = 0; creds[i] != NULL; i++)
637             krb5_free_creds(krbContext, creds[i]);
638         GSSEAP_FREE(creds);
639     }
640     if (major == GSS_S_COMPLETE)
641         major = *minor ? GSS_S_FAILURE : GSS_S_COMPLETE;
642
643     return major;
644 }
645
646 static gss_buffer_desc radiusAvpKrbAttr = {
647     sizeof("urn:authdata-radius-avp") - 1, "urn:authdata-radius-avp"
648 };
649
650 /*
651  * Unfortunately extracting an AD-KDCIssued authorization data element
652  * is pretty implementation-dependent. It's not possible to verify the
653  * signature ourselves because the ticket session key is not exposed
654  * outside GSS. In an ideal world, all AD-KDCIssued elements would be
655  * verified by the Kerberos library and authentication would fail if
656  * verification failed. We're not quite there yet and as a result have
657  * to go through some hoops to get this to work. The alternative would
658  * be to sign the authorization data with our long-term key, but it
659  * seems a pity to compromise the design because of current implementation
660  * limitations.
661  *
662  * (Specifically, the hoops involve a libkrb5 authorisation data plugin
663  * that exposes the verified and serialised attribute context through
664  * the Kerberos GSS mechanism's naming extensions API.)
665  */
666 static OM_uint32
667 defrostAttrContext(OM_uint32 *minor,
668                    gss_name_t glueName,
669                    gss_name_t mechName)
670 {
671     OM_uint32 major, tmpMinor;
672     gss_buffer_desc authData = GSS_C_EMPTY_BUFFER;
673     gss_buffer_desc authDataDisplay = GSS_C_EMPTY_BUFFER;
674     int more = -1;
675     int authenticated, complete;
676
677     major = gssGetNameAttribute(minor, glueName, &radiusAvpKrbAttr,
678                                 &authenticated, &complete,
679                                 &authData, &authDataDisplay, &more);
680     if (major == GSS_S_COMPLETE) {
681         if (authenticated == 0)
682             major = GSS_S_BAD_NAME;
683         else
684             major = gssEapImportAttrContext(minor, &authData, mechName);
685     } else if (major == GSS_S_UNAVAILABLE) {
686         major = GSS_S_COMPLETE;
687     }
688
689     gss_release_buffer(&tmpMinor, &authData);
690     gss_release_buffer(&tmpMinor, &authDataDisplay);
691
692     return major;
693 }
694
695 /*
696  * Convert a mechanism glue to an EAP mechanism name by displaying and
697  * importing it. This also handles the RADIUS attributes.
698  */
699 OM_uint32
700 gssEapGlueToMechName(OM_uint32 *minor,
701                      gss_name_t glueName,
702                      gss_name_t *pMechName)
703 {
704     OM_uint32 major, tmpMinor;
705     gss_buffer_desc nameBuf = GSS_C_EMPTY_BUFFER;
706
707     *pMechName = GSS_C_NO_NAME;
708
709     major = gssDisplayName(minor, glueName, &nameBuf, NULL);
710     if (GSS_ERROR(major))
711         goto cleanup;
712
713     major = gssEapImportName(minor, &nameBuf, GSS_C_NT_USER_NAME,
714                              pMechName);
715     if (GSS_ERROR(major))
716         goto cleanup;
717
718     major = defrostAttrContext(minor, glueName, *pMechName);
719     if (GSS_ERROR(major))
720         goto cleanup;
721
722 cleanup:
723     if (GSS_ERROR(major)) {
724         gssReleaseName(&tmpMinor, pMechName);
725         *pMechName = GSS_C_NO_NAME;
726     }
727
728     gss_release_buffer(&tmpMinor, &nameBuf);
729
730     return major;
731 }
732
733 /*
734  * Convert an EAP mechanism name to a mechanism glue name by displaying
735  * and importing it.
736  */
737 OM_uint32
738 gssEapMechToGlueName(OM_uint32 *minor,
739                      gss_name_t mechName,
740                      gss_name_t *pGlueName)
741 {
742     OM_uint32 major, tmpMinor;
743     gss_buffer_desc nameBuf = GSS_C_EMPTY_BUFFER;
744
745     *pGlueName = GSS_C_NO_NAME;
746
747     major = gssEapDisplayName(minor, mechName, &nameBuf, NULL);
748     if (GSS_ERROR(major))
749         goto cleanup;
750
751     major = gssImportName(minor, &nameBuf, GSS_C_NT_USER_NAME,
752                           pGlueName);
753     if (GSS_ERROR(major))
754         goto cleanup;
755
756 cleanup:
757     gss_release_buffer(&tmpMinor, &nameBuf);
758
759     return major;
760 }
761
762 /*
763  * Suck out the analgous elements of a Kerberos GSS context into an EAP
764  * one so that the application doesn't know the difference.
765  */
766 OM_uint32
767 gssEapReauthComplete(OM_uint32 *minor,
768                     gss_ctx_id_t ctx,
769                     gss_cred_id_t cred,
770                     const gss_OID mech,
771                     OM_uint32 timeRec)
772 {
773     OM_uint32 major, tmpMinor;
774     gss_buffer_set_t keyData = GSS_C_NO_BUFFER_SET;
775     krb5_context krbContext = NULL;
776 #ifdef HAVE_HEIMDAL_VERSION
777     krb5_storage *sp = NULL;
778 #endif
779
780     GSSEAP_KRB_INIT(&krbContext);
781
782     if (!oidEqual(mech, gss_mech_krb5)) {
783         major = GSS_S_BAD_MECH;
784         goto cleanup;
785     }
786
787     /* Get the raw subsession key and encryption type */
788 #ifdef HAVE_HEIMDAL_VERSION
789 #define KRB_GSS_SUBKEY_COUNT    1 /* encoded session key */
790     major = gssInquireSecContextByOid(minor, ctx->kerberosCtx,
791                                       GSS_KRB5_GET_SUBKEY_X, &keyData);
792 #else
793 #define KRB_GSS_SUBKEY_COUNT    2 /* raw session key, enctype OID */
794     major = gssInquireSecContextByOid(minor, ctx->kerberosCtx,
795                                       GSS_C_INQ_SSPI_SESSION_KEY, &keyData);
796 #endif
797     if (GSS_ERROR(major))
798         goto cleanup;
799
800     if (keyData == GSS_C_NO_BUFFER_SET || keyData->count < KRB_GSS_SUBKEY_COUNT) {
801         *minor = GSSEAP_KEY_UNAVAILABLE;
802         major = GSS_S_FAILURE;
803         goto cleanup;
804     }
805
806 #ifdef HAVE_HEIMDAL_VERSION
807     sp = krb5_storage_from_mem(keyData->elements[0].value,
808                                keyData->elements[0].length);
809     if (sp == NULL) {
810         *minor = ENOMEM;
811         major = GSS_S_FAILURE;
812         goto cleanup;
813     }
814
815     *minor = krb5_ret_keyblock(sp, &ctx->rfc3961Key);
816     if (*minor != 0) {
817         major = GSS_S_FAILURE;
818         goto cleanup;
819     }
820 #else
821     {
822         gss_OID_desc oid;
823         int suffix;
824
825         oid.length = keyData->elements[1].length;
826         oid.elements = keyData->elements[1].value;
827
828         /* GSS_KRB5_SESSION_KEY_ENCTYPE_OID */
829         major = decomposeOid(minor,
830                              "\x2a\x86\x48\x86\xf7\x12\x01\x02\x02\x04",
831                              10, &oid, &suffix);
832         if (GSS_ERROR(major))
833             goto cleanup;
834
835         ctx->encryptionType = suffix;
836     }
837
838     {
839         krb5_keyblock key;
840
841         KRB_KEY_LENGTH(&key) = keyData->elements[0].length;
842         KRB_KEY_DATA(&key)   = keyData->elements[0].value;
843         KRB_KEY_TYPE(&key)   = ctx->encryptionType;
844
845         *minor = krb5_copy_keyblock_contents(krbContext,
846                                              &key, &ctx->rfc3961Key);
847         if (*minor != 0) {
848             major = GSS_S_FAILURE;
849             goto cleanup;
850         }
851     }
852 #endif /* HAVE_HEIMDAL_VERSION */
853
854     major = rfc3961ChecksumTypeForKey(minor, &ctx->rfc3961Key,
855                                       &ctx->checksumType);
856     if (GSS_ERROR(major))
857         goto cleanup;
858
859     if (timeRec != GSS_C_INDEFINITE)
860         ctx->expiryTime = time(NULL) + timeRec;
861
862     /* Initialize our sequence state */
863     major = sequenceInit(minor,
864                          &ctx->seqState, ctx->recvSeq,
865                          ((ctx->gssFlags & GSS_C_REPLAY_FLAG) != 0),
866                          ((ctx->gssFlags & GSS_C_SEQUENCE_FLAG) != 0),
867                          TRUE);
868     if (GSS_ERROR(major))
869         goto cleanup;
870
871     major = GSS_S_COMPLETE;
872
873 cleanup:
874 #ifdef HAVE_HEIMDAL_VERSION
875     if (sp != NULL)
876         krb5_storage_free(sp);
877 #endif
878     gss_release_buffer_set(&tmpMinor, &keyData);
879
880     return major;
881 }
882
883 /*
884  * The remainder of this file consists of wrappers so we can call into the
885  * mechanism glue without calling ourselves.
886  */
887 static OM_uint32
888 (*gssInitSecContextNext)(OM_uint32 *,
889                          gss_cred_id_t,
890                          gss_ctx_id_t *,
891                          gss_name_t,
892                          gss_OID,
893                          OM_uint32,
894                          OM_uint32,
895                          gss_channel_bindings_t,
896                          gss_buffer_t,
897                          gss_OID *,
898                          gss_buffer_t,
899                          OM_uint32 *,
900                          OM_uint32 *);
901
902 static OM_uint32
903 (*gssAcceptSecContextNext)(OM_uint32 *,
904                            gss_ctx_id_t *,
905                            gss_cred_id_t,
906                            gss_buffer_t,
907                            gss_channel_bindings_t,
908                            gss_name_t *,
909                            gss_OID *,
910                            gss_buffer_t,
911                            OM_uint32 *,
912                            OM_uint32 *,
913                            gss_cred_id_t *);
914
915 static OM_uint32
916 (*gssReleaseCredNext)(OM_uint32 *, gss_cred_id_t *);
917
918 static OM_uint32
919 (*gssReleaseNameNext)(OM_uint32 *, gss_name_t *);
920
921 static OM_uint32
922 (*gssInquireSecContextByOidNext)(OM_uint32 *,
923                                  const gss_ctx_id_t,
924                                  const gss_OID,
925                                  gss_buffer_set_t *);
926
927 static OM_uint32
928 (*gssDeleteSecContextNext)(OM_uint32 *,
929                           gss_ctx_id_t *,
930                           gss_buffer_t);
931
932 static OM_uint32
933 (*gssDisplayNameNext)(OM_uint32 *,
934                       gss_name_t,
935                       gss_buffer_t,
936                       gss_OID *);
937
938 static OM_uint32
939 (*gssImportNameNext)(OM_uint32 *,
940                      gss_buffer_t,
941                      gss_OID,
942                      gss_name_t *);
943
944 static OM_uint32
945 (*gssStoreCredNext)(OM_uint32 *,
946                     const gss_cred_id_t,
947                     gss_cred_usage_t,
948                     const gss_OID,
949                     OM_uint32,
950                     OM_uint32,
951                     gss_OID_set *,
952                     gss_cred_usage_t *);
953
954 static OM_uint32
955 (*gssGetNameAttributeNext)(OM_uint32 *,
956                           gss_name_t,
957                           gss_buffer_t,
958                           int *,
959                           int *,
960                           gss_buffer_t,
961                           gss_buffer_t,
962                           int *);
963
964 #define NEXT_SYMBOL(local, global)  do {        \
965         ((local) = dlsym(RTLD_NEXT, (global))); \
966         if ((local) == NULL) {                  \
967             *minor = GSSEAP_NO_MECHGLUE_SYMBOL; \
968             major = GSS_S_UNAVAILABLE;          \
969             /* but continue */                  \
970         }                                       \
971     } while (0)
972
973 OM_uint32
974 gssEapReauthInitialize(OM_uint32 *minor)
975 {
976     OM_uint32 major = GSS_S_COMPLETE;
977
978     NEXT_SYMBOL(gssInitSecContextNext,         "gss_init_sec_context");
979     NEXT_SYMBOL(gssAcceptSecContextNext,       "gss_accept_sec_context");
980     NEXT_SYMBOL(gssReleaseCredNext,            "gss_release_cred");
981     NEXT_SYMBOL(gssReleaseNameNext,            "gss_release_name");
982     NEXT_SYMBOL(gssInquireSecContextByOidNext, "gss_inquire_sec_context_by_oid");
983     NEXT_SYMBOL(gssDeleteSecContextNext,       "gss_delete_sec_context");
984     NEXT_SYMBOL(gssDisplayNameNext,            "gss_display_name");
985     NEXT_SYMBOL(gssImportNameNext,             "gss_import_name");
986     NEXT_SYMBOL(gssStoreCredNext,              "gss_store_cred");
987     NEXT_SYMBOL(gssGetNameAttributeNext,       "gss_get_name_attribute");
988
989     return major;
990 }
991
992 OM_uint32
993 gssInitSecContext(OM_uint32 *minor,
994                   gss_cred_id_t cred,
995                   gss_ctx_id_t *context_handle,
996                   gss_name_t target_name,
997                   gss_OID mech_type,
998                   OM_uint32 req_flags,
999                   OM_uint32 time_req,
1000                   gss_channel_bindings_t input_chan_bindings,
1001                   gss_buffer_t input_token,
1002                   gss_OID *actual_mech_type,
1003                   gss_buffer_t output_token,
1004                   OM_uint32 *ret_flags,
1005                   OM_uint32 *time_rec)
1006 {
1007     if (gssInitSecContextNext == NULL) {
1008         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1009         return GSS_S_UNAVAILABLE;
1010     }
1011
1012     return gssInitSecContextNext(minor, cred, context_handle,
1013                                  target_name, mech_type, req_flags,
1014                                  time_req, input_chan_bindings,
1015                                  input_token, actual_mech_type,
1016                                  output_token, ret_flags, time_rec);
1017 }
1018
1019 OM_uint32
1020 gssAcceptSecContext(OM_uint32 *minor,
1021                     gss_ctx_id_t *context_handle,
1022                     gss_cred_id_t cred,
1023                     gss_buffer_t input_token,
1024                     gss_channel_bindings_t input_chan_bindings,
1025                     gss_name_t *src_name,
1026                     gss_OID *mech_type,
1027                     gss_buffer_t output_token,
1028                     OM_uint32 *ret_flags,
1029                     OM_uint32 *time_rec,
1030                     gss_cred_id_t *delegated_cred_handle)
1031 {
1032     if (gssAcceptSecContextNext == NULL) {
1033         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1034         return GSS_S_UNAVAILABLE;
1035     }
1036
1037     return gssAcceptSecContextNext(minor, context_handle, cred,
1038                                    input_token, input_chan_bindings,
1039                                    src_name, mech_type, output_token,
1040                                    ret_flags, time_rec, delegated_cred_handle);
1041 }
1042
1043 OM_uint32
1044 gssReleaseCred(OM_uint32 *minor,
1045                gss_cred_id_t *cred_handle)
1046 {
1047     if (gssReleaseCredNext == NULL) {
1048         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1049         return GSS_S_UNAVAILABLE;
1050     }
1051
1052     return gssReleaseCredNext(minor, cred_handle);
1053 }
1054
1055 OM_uint32
1056 gssReleaseName(OM_uint32 *minor,
1057                gss_name_t *name)
1058 {
1059     if (gssReleaseName == NULL) {
1060         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1061         return GSS_S_UNAVAILABLE;
1062     }
1063
1064     return gssReleaseNameNext(minor, name);
1065 }
1066
1067 OM_uint32
1068 gssDeleteSecContext(OM_uint32 *minor,
1069                     gss_ctx_id_t *context_handle,
1070                     gss_buffer_t output_token)
1071 {
1072     if (gssDeleteSecContextNext == NULL) {
1073         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1074         return GSS_S_UNAVAILABLE;
1075     }
1076
1077     return gssDeleteSecContextNext(minor, context_handle, output_token);
1078 }
1079
1080 static OM_uint32
1081 gssDisplayName(OM_uint32 *minor,
1082                gss_name_t name,
1083                gss_buffer_t buffer,
1084                gss_OID *name_type)
1085 {
1086     if (gssDisplayNameNext == NULL) {
1087         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1088         return GSS_S_UNAVAILABLE;
1089     }
1090
1091     return gssDisplayNameNext(minor, name, buffer, name_type);
1092 }
1093
1094 static OM_uint32
1095 gssImportName(OM_uint32 *minor,
1096               gss_buffer_t buffer,
1097               gss_OID name_type,
1098               gss_name_t *name)
1099 {
1100     if (gssImportNameNext == NULL) {
1101         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1102         return GSS_S_UNAVAILABLE;
1103     }
1104
1105     return gssImportNameNext(minor, buffer, name_type, name);
1106 }
1107
1108 OM_uint32
1109 gssInquireSecContextByOid(OM_uint32 *minor,
1110                           const gss_ctx_id_t context_handle,
1111                           const gss_OID desired_object,
1112                           gss_buffer_set_t *data_set)
1113 {
1114     if (gssInquireSecContextByOidNext == NULL) {
1115         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1116         return GSS_S_UNAVAILABLE;
1117     }
1118
1119     return gssInquireSecContextByOidNext(minor, context_handle,
1120                                          desired_object, data_set);
1121 }
1122
1123 OM_uint32
1124 gssStoreCred(OM_uint32 *minor,
1125              const gss_cred_id_t input_cred_handle,
1126              gss_cred_usage_t input_usage,
1127              const gss_OID desired_mech,
1128              OM_uint32 overwrite_cred,
1129              OM_uint32 default_cred,
1130              gss_OID_set *elements_stored,
1131              gss_cred_usage_t *cred_usage_stored)
1132 {
1133     if (gssStoreCredNext == NULL) {
1134         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1135         return GSS_S_UNAVAILABLE;
1136     }
1137
1138     return gssStoreCredNext(minor, input_cred_handle, input_usage,
1139                             desired_mech, overwrite_cred, default_cred,
1140                             elements_stored, cred_usage_stored);
1141 }
1142
1143 OM_uint32
1144 gssGetNameAttribute(OM_uint32 *minor,
1145                     gss_name_t name,
1146                     gss_buffer_t attr,
1147                     int *authenticated,
1148                     int *complete,
1149                     gss_buffer_t value,
1150                     gss_buffer_t display_value,
1151                     int *more)
1152 {
1153     if (gssGetNameAttributeNext == NULL) {
1154         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1155         return GSS_S_UNAVAILABLE;
1156     }
1157
1158     return gssGetNameAttributeNext(minor, name, attr, authenticated, complete,
1159                                    value, display_value, more);
1160 }