More Heimdal reauth portability
[mech_eap.git] / 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 = { 0 };
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 = krbMakeCred(krbContext, authContext, &creds, &credsData);
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
382     if (major == GSS_S_COMPLETE) {
383         *minor = code;
384         major = (code != 0) ? GSS_S_FAILURE : GSS_S_COMPLETE;
385     }
386
387     return major;
388 }
389
390 static int
391 isTicketGrantingServiceP(krb5_context krbContext,
392                          krb5_const_principal principal)
393 {
394     if (KRB_PRINC_LENGTH(principal) == 2 &&
395 #ifdef HAVE_HEIMDAL_VERSION
396         strcmp(KRB_PRINC_NAME(principal)[0], "krbtgt") == 0
397 #else
398         krb5_princ_component(krbContext, principal, 0)->length == 6 &&
399         memcmp(krb5_princ_component(krbContext,
400                                     principal, 0)->data, "krbtgt", 6) == 0
401 #endif
402         )
403         return TRUE;
404
405     return FALSE;
406 }
407
408 /*
409  * Returns TRUE if the configuration variable reauth_use_ccache is
410  * set in krb5.conf for the eap_gss application and the client realm.
411  */
412 static int
413 reauthUseCredsCache(krb5_context krbContext,
414                     krb5_principal principal)
415 {
416     int reauthUseCCache;
417
418     /* if reauth_use_ccache, use default credentials cache if ticket is for us */
419     krb5_appdefault_boolean(krbContext, "eap_gss",
420                             KRB_PRINC_REALM(principal),
421                             "reauth_use_ccache", 0, &reauthUseCCache);
422
423     return reauthUseCCache;
424 }
425
426 /*
427  * Look in default credentials cache for reauthentication credentials,
428  * if policy allows.
429  */
430 static OM_uint32
431 getDefaultReauthCredentials(OM_uint32 *minor,
432                             gss_cred_id_t cred,
433                             gss_name_t target,
434                             time_t now,
435                             OM_uint32 timeReq)
436 {
437     OM_uint32 major = GSS_S_CRED_UNAVAIL;
438     krb5_context krbContext = NULL;
439     krb5_error_code code = 0;
440     krb5_ccache ccache = NULL;
441     krb5_creds match = { 0 };
442     krb5_creds creds = { 0 };
443
444     GSSEAP_KRB_INIT(&krbContext);
445
446     assert(cred != GSS_C_NO_CREDENTIAL);
447     assert(target != GSS_C_NO_NAME);
448
449     if (cred->name == GSS_C_NO_NAME ||
450         !reauthUseCredsCache(krbContext, cred->name->krbPrincipal))
451         goto cleanup;
452
453     match.client = cred->name->krbPrincipal;
454     match.server = target->krbPrincipal;
455     if (timeReq != 0 && timeReq != GSS_C_INDEFINITE)
456         match.times.endtime = now + timeReq;
457
458     code = krb5_cc_default(krbContext, &ccache);
459     if (code != 0)
460         goto cleanup;
461
462     code = krb5_cc_retrieve_cred(krbContext, ccache, 0, &match, &creds);
463     if (code != 0)
464         goto cleanup;
465
466     cred->flags |= CRED_FLAG_DEFAULT_CCACHE;
467     cred->krbCredCache = ccache;
468     ccache = NULL;
469
470     major = gss_krb5_import_cred(minor, cred->krbCredCache, NULL, NULL,
471                                  &cred->krbCred);
472
473 cleanup:
474     if (major == GSS_S_CRED_UNAVAIL)
475         *minor = code;
476
477     if (ccache != NULL)
478         krb5_cc_close(krbContext, ccache);
479     krb5_free_cred_contents(krbContext, &creds);
480
481     return major;
482 }
483
484 /*
485  * Returns TRUE if the credential handle's reauth credentials are
486  * valid or if we can use the default credentials cache. Credentials
487  * handle must be locked.
488  */
489 int
490 gssEapCanReauthP(gss_cred_id_t cred,
491                  gss_name_t target,
492                  OM_uint32 timeReq)
493 {
494     time_t now, expiryReq;
495     OM_uint32 minor;
496
497     assert(cred != GSS_C_NO_CREDENTIAL);
498
499     now = time(NULL);
500     expiryReq = now;
501     if (timeReq != GSS_C_INDEFINITE)
502         expiryReq += timeReq;
503
504     if (cred->krbCredCache != NULL && cred->expiryTime > expiryReq)
505         return TRUE;
506
507     if (getDefaultReauthCredentials(&minor, cred, target,
508                                     now, timeReq) == GSS_S_COMPLETE)
509         return TRUE;
510
511     return FALSE;
512 }
513
514 /*
515  * Store re-authentication (Kerberos) credentials in a credential handle.
516  * Credentials handle must be locked.
517  */
518 OM_uint32
519 gssEapStoreReauthCreds(OM_uint32 *minor,
520                        gss_ctx_id_t ctx,
521                        gss_cred_id_t cred,
522                        gss_buffer_t credBuf)
523 {
524     OM_uint32 major = GSS_S_COMPLETE;
525     krb5_error_code code;
526     krb5_context krbContext = NULL;
527     krb5_auth_context authContext = NULL;
528     krb5_data credData = { 0 };
529     krb5_creds **creds = NULL;
530     krb5_principal canonPrinc;
531     krb5_principal ccPrinc = NULL;
532     int i;
533
534     if (credBuf->length == 0 || cred == GSS_C_NO_CREDENTIAL)
535         return GSS_S_COMPLETE;
536
537     GSSEAP_KRB_INIT(&krbContext);
538
539     code = krb5_auth_con_init(krbContext, &authContext);
540     if (code != 0)
541         goto cleanup;
542
543     code = krb5_auth_con_setflags(krbContext, authContext, 0);
544     if (code != 0)
545         goto cleanup;
546
547     code = krb5_auth_con_setrecvsubkey(krbContext, authContext,
548                                        &ctx->rfc3961Key);
549     if (code != 0)
550         goto cleanup;
551
552     gssBufferToKrbData(credBuf, &credData);
553
554     code = krb5_rd_cred(krbContext, authContext, &credData, &creds, NULL);
555     if (code != 0)
556         goto cleanup;
557
558     if (creds == NULL || creds[0] == NULL)
559         goto cleanup;
560
561     code = krb5_copy_principal(krbContext, creds[0]->client, &canonPrinc);
562     if (code != 0)
563         goto cleanup;
564
565     krb5_free_principal(krbContext, cred->name->krbPrincipal);
566     cred->name->krbPrincipal = canonPrinc;
567
568     if (creds[0]->times.endtime == KRB_TIME_FOREVER)
569         cred->expiryTime = 0;
570     else
571         cred->expiryTime = creds[0]->times.endtime;
572
573     if (cred->krbCredCache == NULL) {
574         if (reauthUseCredsCache(krbContext, creds[0]->client) &&
575             krb5_cc_default(krbContext, &cred->krbCredCache) == 0)
576             cred->flags |= CRED_FLAG_DEFAULT_CCACHE;
577     } else {
578         /*
579          * If we already have an associated credentials cache, possibly from
580          * the last time we stored a reauthentication credential, then we
581          * need to clear it out and release the associated GSS credential.
582          */
583         if (cred->flags & CRED_FLAG_DEFAULT_CCACHE) {
584             krb5_cc_remove_cred(krbContext, cred->krbCredCache, 0, creds[0]);
585         } else {
586             krb5_cc_destroy(krbContext, cred->krbCredCache);
587             cred->krbCredCache = NULL;
588         }
589         gssReleaseCred(minor, &cred->krbCred);
590     }
591
592     if (cred->krbCredCache == NULL) {
593         code = krb5_cc_new_unique(krbContext, "MEMORY", NULL, &cred->krbCredCache);
594         if (code != 0)
595             goto cleanup;
596     }
597
598     if ((cred->flags & CRED_FLAG_DEFAULT_CCACHE) == 0 ||
599         krb5_cc_get_principal(krbContext, cred->krbCredCache, &ccPrinc) != 0) {
600         code = krb5_cc_initialize(krbContext, cred->krbCredCache,
601                                   creds[0]->client);
602         if (code != 0)
603             goto cleanup;
604     }
605
606     for (i = 0; creds[i] != NULL; i++) {
607         krb5_creds kcred = *(creds[i]);
608
609         /*
610          * Swap in the acceptor name the client asked for so
611          * get_credentials() works. We're making the assumption that
612          * any service tickets returned are for us. We'll need to
613          * reflect some more on whether that is a safe assumption.
614          */
615         if (!isTicketGrantingServiceP(krbContext, kcred.server))
616             kcred.server = ctx->acceptorName->krbPrincipal;
617
618         code = krb5_cc_store_cred(krbContext, cred->krbCredCache, &kcred);
619         if (code != 0)
620             goto cleanup;
621     }
622
623     major = gss_krb5_import_cred(minor, cred->krbCredCache, NULL, NULL,
624                                  &cred->krbCred);
625     if (GSS_ERROR(major))
626         goto cleanup;
627
628 cleanup:
629     *minor = code;
630
631     krb5_free_principal(krbContext, ccPrinc);
632     krb5_auth_con_free(krbContext, authContext);
633     if (creds != NULL) {
634         for (i = 0; creds[i] != NULL; i++)
635             krb5_free_creds(krbContext, creds[i]);
636         GSSEAP_FREE(creds);
637     }
638     if (major == GSS_S_COMPLETE)
639         major = *minor ? GSS_S_FAILURE : GSS_S_COMPLETE;
640
641     return major;
642 }
643
644 #ifndef HAVE_HEIMDAL_VERSION
645 static gss_buffer_desc radiusAvpKrbAttr = {
646     sizeof("urn:authdata-radius-avp") - 1, "urn:authdata-radius-avp"
647 };
648 #endif
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_ctx_id_t glueContext,
669                    gss_name_t glueName,
670                    gss_name_t mechName)
671 {
672     OM_uint32 major, tmpMinor;
673 #ifdef HAVE_HEIMDAL_VERSION
674     gss_OID_desc oid = { 0 };
675     gss_buffer_set_t authData = GSS_C_NO_BUFFER_SET;
676 #else
677     gss_buffer_desc authData = GSS_C_EMPTY_BUFFER;
678     gss_buffer_desc authDataDisplay = GSS_C_EMPTY_BUFFER;
679     int more = -1;
680     int authenticated, complete;
681 #endif
682
683 #ifdef HAVE_HEIMDAL_VERSION
684     major = composeOid(minor,
685                        GSS_KRB5_EXTRACT_AUTHZ_DATA_FROM_SEC_CONTEXT_X->elements,
686                        GSS_KRB5_EXTRACT_AUTHZ_DATA_FROM_SEC_CONTEXT_X->length,
687                        KRB5_AUTHDATA_RADIUS_AVP, &oid);
688     if (GSS_ERROR(major))
689         return major;
690
691     /* XXX we are assuming that this verifies AD-KDCIssued signature */
692     major = gssInquireSecContextByOid(minor, glueContext,
693                                       &oid, &authData);
694     if (major == GSS_S_COMPLETE) {
695         if (authData == GSS_C_NO_BUFFER_SET || authData->count != 1)
696             major = GSS_S_FAILURE;
697         else
698             major = gssEapImportAttrContext(minor, authData->elements, mechName);
699     } else if (major == GSS_S_FAILURE && *minor == ENOENT) {
700         /* This is the equivalent of GSS_S_UNAVAILABLE for MIT attr APIs */
701         *minor = 0;
702         major = GSS_S_COMPLETE;
703     }
704
705     gss_release_buffer_set(&tmpMinor, &authData);
706     GSSEAP_FREE(oid.elements);
707 #else
708     major = gssGetNameAttribute(minor, glueName, &radiusAvpKrbAttr,
709                                 &authenticated, &complete,
710                                 &authData, &authDataDisplay, &more);
711     if (major == GSS_S_COMPLETE) {
712         if (authenticated == 0)
713             major = GSS_S_BAD_NAME;
714         else
715             major = gssEapImportAttrContext(minor, &authData, mechName);
716     } else if (major == GSS_S_UNAVAILABLE) {
717         major = GSS_S_COMPLETE;
718     }
719
720     gss_release_buffer(&tmpMinor, &authData);
721     gss_release_buffer(&tmpMinor, &authDataDisplay);
722 #endif /* HAVE_HEIMDAL_VERSION */
723
724     return major;
725 }
726
727 /*
728  * Convert a mechanism glue to an EAP mechanism name by displaying and
729  * importing it. This also handles the RADIUS attributes.
730  */
731 OM_uint32
732 gssEapGlueToMechName(OM_uint32 *minor,
733                      gss_ctx_id_t glueContext,
734                      gss_name_t glueName,
735                      gss_name_t *pMechName)
736 {
737     OM_uint32 major, tmpMinor;
738     gss_buffer_desc nameBuf = GSS_C_EMPTY_BUFFER;
739
740     *pMechName = GSS_C_NO_NAME;
741
742     major = gssDisplayName(minor, glueName, &nameBuf, NULL);
743     if (GSS_ERROR(major))
744         goto cleanup;
745
746     major = gssEapImportName(minor, &nameBuf, GSS_C_NT_USER_NAME,
747                              pMechName);
748     if (GSS_ERROR(major))
749         goto cleanup;
750
751     major = defrostAttrContext(minor, glueContext, glueName, *pMechName);
752     if (GSS_ERROR(major))
753         goto cleanup;
754
755 cleanup:
756     if (GSS_ERROR(major)) {
757         gssReleaseName(&tmpMinor, pMechName);
758         *pMechName = GSS_C_NO_NAME;
759     }
760
761     gss_release_buffer(&tmpMinor, &nameBuf);
762
763     return major;
764 }
765
766 /*
767  * Convert an EAP mechanism name to a mechanism glue name by displaying
768  * and importing it.
769  */
770 OM_uint32
771 gssEapMechToGlueName(OM_uint32 *minor,
772                      gss_name_t mechName,
773                      gss_name_t *pGlueName)
774 {
775     OM_uint32 major, tmpMinor;
776     gss_buffer_desc nameBuf = GSS_C_EMPTY_BUFFER;
777
778     *pGlueName = GSS_C_NO_NAME;
779
780     major = gssEapDisplayName(minor, mechName, &nameBuf, NULL);
781     if (GSS_ERROR(major))
782         goto cleanup;
783
784     major = gssImportName(minor, &nameBuf, GSS_C_NT_USER_NAME,
785                           pGlueName);
786     if (GSS_ERROR(major))
787         goto cleanup;
788
789 cleanup:
790     gss_release_buffer(&tmpMinor, &nameBuf);
791
792     return major;
793 }
794
795 /*
796  * Suck out the analgous elements of a Kerberos GSS context into an EAP
797  * one so that the application doesn't know the difference.
798  */
799 OM_uint32
800 gssEapReauthComplete(OM_uint32 *minor,
801                     gss_ctx_id_t ctx,
802                     gss_cred_id_t cred,
803                     const gss_OID mech,
804                     OM_uint32 timeRec)
805 {
806     OM_uint32 major, tmpMinor;
807     gss_buffer_set_t keyData = GSS_C_NO_BUFFER_SET;
808     krb5_context krbContext = NULL;
809 #ifdef HAVE_HEIMDAL_VERSION
810     krb5_storage *sp = NULL;
811 #endif
812
813     GSSEAP_KRB_INIT(&krbContext);
814
815     if (!oidEqual(mech, gss_mech_krb5)) {
816         major = GSS_S_BAD_MECH;
817         goto cleanup;
818     }
819
820     /* Get the raw subsession key and encryption type */
821 #ifdef HAVE_HEIMDAL_VERSION
822 #define KRB_GSS_SUBKEY_COUNT    1 /* encoded session key */
823     major = gssInquireSecContextByOid(minor, ctx->kerberosCtx,
824                                       GSS_KRB5_GET_SUBKEY_X, &keyData);
825 #else
826 #define KRB_GSS_SUBKEY_COUNT    2 /* raw session key, enctype OID */
827     major = gssInquireSecContextByOid(minor, ctx->kerberosCtx,
828                                       GSS_C_INQ_SSPI_SESSION_KEY, &keyData);
829 #endif
830     if (GSS_ERROR(major))
831         goto cleanup;
832
833     if (keyData == GSS_C_NO_BUFFER_SET || keyData->count < KRB_GSS_SUBKEY_COUNT) {
834         *minor = GSSEAP_KEY_UNAVAILABLE;
835         major = GSS_S_FAILURE;
836         goto cleanup;
837     }
838
839 #ifdef HAVE_HEIMDAL_VERSION
840     sp = krb5_storage_from_mem(keyData->elements[0].value,
841                                keyData->elements[0].length);
842     if (sp == NULL) {
843         *minor = ENOMEM;
844         major = GSS_S_FAILURE;
845         goto cleanup;
846     }
847
848     *minor = krb5_ret_keyblock(sp, &ctx->rfc3961Key);
849     if (*minor != 0) {
850         major = GSS_S_FAILURE;
851         goto cleanup;
852     }
853 #else
854     {
855         gss_OID_desc oid;
856         int suffix;
857
858         oid.length = keyData->elements[1].length;
859         oid.elements = keyData->elements[1].value;
860
861         /* GSS_KRB5_SESSION_KEY_ENCTYPE_OID */
862         major = decomposeOid(minor,
863                              "\x2a\x86\x48\x86\xf7\x12\x01\x02\x02\x04",
864                              10, &oid, &suffix);
865         if (GSS_ERROR(major))
866             goto cleanup;
867
868         ctx->encryptionType = suffix;
869     }
870
871     {
872         krb5_keyblock key;
873
874         KRB_KEY_LENGTH(&key) = keyData->elements[0].length;
875         KRB_KEY_DATA(&key)   = keyData->elements[0].value;
876         KRB_KEY_TYPE(&key)   = ctx->encryptionType;
877
878         *minor = krb5_copy_keyblock_contents(krbContext,
879                                              &key, &ctx->rfc3961Key);
880         if (*minor != 0) {
881             major = GSS_S_FAILURE;
882             goto cleanup;
883         }
884     }
885 #endif /* HAVE_HEIMDAL_VERSION */
886
887     major = rfc3961ChecksumTypeForKey(minor, &ctx->rfc3961Key,
888                                       &ctx->checksumType);
889     if (GSS_ERROR(major))
890         goto cleanup;
891
892     if (timeRec != GSS_C_INDEFINITE)
893         ctx->expiryTime = time(NULL) + timeRec;
894
895     /* Initialize our sequence state */
896     major = sequenceInit(minor,
897                          &ctx->seqState, ctx->recvSeq,
898                          ((ctx->gssFlags & GSS_C_REPLAY_FLAG) != 0),
899                          ((ctx->gssFlags & GSS_C_SEQUENCE_FLAG) != 0),
900                          TRUE);
901     if (GSS_ERROR(major))
902         goto cleanup;
903
904     major = GSS_S_COMPLETE;
905
906 cleanup:
907 #ifdef HAVE_HEIMDAL_VERSION
908     if (sp != NULL)
909         krb5_storage_free(sp);
910 #endif
911     gss_release_buffer_set(&tmpMinor, &keyData);
912
913     return major;
914 }
915
916 /*
917  * The remainder of this file consists of wrappers so we can call into the
918  * mechanism glue without calling ourselves.
919  */
920 static OM_uint32
921 (*gssInitSecContextNext)(OM_uint32 *,
922                          gss_cred_id_t,
923                          gss_ctx_id_t *,
924                          gss_name_t,
925                          gss_OID,
926                          OM_uint32,
927                          OM_uint32,
928                          gss_channel_bindings_t,
929                          gss_buffer_t,
930                          gss_OID *,
931                          gss_buffer_t,
932                          OM_uint32 *,
933                          OM_uint32 *);
934
935 static OM_uint32
936 (*gssAcceptSecContextNext)(OM_uint32 *,
937                            gss_ctx_id_t *,
938                            gss_cred_id_t,
939                            gss_buffer_t,
940                            gss_channel_bindings_t,
941                            gss_name_t *,
942                            gss_OID *,
943                            gss_buffer_t,
944                            OM_uint32 *,
945                            OM_uint32 *,
946                            gss_cred_id_t *);
947
948 static OM_uint32
949 (*gssReleaseCredNext)(OM_uint32 *, gss_cred_id_t *);
950
951 static OM_uint32
952 (*gssReleaseNameNext)(OM_uint32 *, gss_name_t *);
953
954 static OM_uint32
955 (*gssInquireSecContextByOidNext)(OM_uint32 *,
956                                  const gss_ctx_id_t,
957                                  const gss_OID,
958                                  gss_buffer_set_t *);
959
960 static OM_uint32
961 (*gssDeleteSecContextNext)(OM_uint32 *,
962                           gss_ctx_id_t *,
963                           gss_buffer_t);
964
965 static OM_uint32
966 (*gssDisplayNameNext)(OM_uint32 *,
967                       gss_name_t,
968                       gss_buffer_t,
969                       gss_OID *);
970
971 static OM_uint32
972 (*gssImportNameNext)(OM_uint32 *,
973                      gss_buffer_t,
974                      gss_OID,
975                      gss_name_t *);
976
977 static OM_uint32
978 (*gssStoreCredNext)(OM_uint32 *,
979                     const gss_cred_id_t,
980                     gss_cred_usage_t,
981                     const gss_OID,
982                     OM_uint32,
983                     OM_uint32,
984                     gss_OID_set *,
985                     gss_cred_usage_t *);
986
987 static OM_uint32
988 (*gssGetNameAttributeNext)(OM_uint32 *,
989                           gss_name_t,
990                           gss_buffer_t,
991                           int *,
992                           int *,
993                           gss_buffer_t,
994                           gss_buffer_t,
995                           int *);
996
997 #define NEXT_SYMBOL(local, global)  do {        \
998         ((local) = dlsym(RTLD_NEXT, (global))); \
999         if ((local) == NULL) {                  \
1000             *minor = GSSEAP_NO_MECHGLUE_SYMBOL; \
1001             major = GSS_S_UNAVAILABLE;          \
1002             /* but continue */                  \
1003         }                                       \
1004     } while (0)
1005
1006 OM_uint32
1007 gssEapReauthInitialize(OM_uint32 *minor)
1008 {
1009     OM_uint32 major = GSS_S_COMPLETE;
1010
1011     NEXT_SYMBOL(gssInitSecContextNext,         "gss_init_sec_context");
1012     NEXT_SYMBOL(gssAcceptSecContextNext,       "gss_accept_sec_context");
1013     NEXT_SYMBOL(gssReleaseCredNext,            "gss_release_cred");
1014     NEXT_SYMBOL(gssReleaseNameNext,            "gss_release_name");
1015     NEXT_SYMBOL(gssInquireSecContextByOidNext, "gss_inquire_sec_context_by_oid");
1016     NEXT_SYMBOL(gssDeleteSecContextNext,       "gss_delete_sec_context");
1017     NEXT_SYMBOL(gssDisplayNameNext,            "gss_display_name");
1018     NEXT_SYMBOL(gssImportNameNext,             "gss_import_name");
1019     NEXT_SYMBOL(gssStoreCredNext,              "gss_store_cred");
1020     NEXT_SYMBOL(gssGetNameAttributeNext,       "gss_get_name_attribute");
1021
1022     return major;
1023 }
1024
1025 OM_uint32
1026 gssInitSecContext(OM_uint32 *minor,
1027                   gss_cred_id_t cred,
1028                   gss_ctx_id_t *context_handle,
1029                   gss_name_t target_name,
1030                   gss_OID mech_type,
1031                   OM_uint32 req_flags,
1032                   OM_uint32 time_req,
1033                   gss_channel_bindings_t input_chan_bindings,
1034                   gss_buffer_t input_token,
1035                   gss_OID *actual_mech_type,
1036                   gss_buffer_t output_token,
1037                   OM_uint32 *ret_flags,
1038                   OM_uint32 *time_rec)
1039 {
1040     if (gssInitSecContextNext == NULL) {
1041         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1042         return GSS_S_UNAVAILABLE;
1043     }
1044
1045     return gssInitSecContextNext(minor, cred, context_handle,
1046                                  target_name, mech_type, req_flags,
1047                                  time_req, input_chan_bindings,
1048                                  input_token, actual_mech_type,
1049                                  output_token, ret_flags, time_rec);
1050 }
1051
1052 OM_uint32
1053 gssAcceptSecContext(OM_uint32 *minor,
1054                     gss_ctx_id_t *context_handle,
1055                     gss_cred_id_t cred,
1056                     gss_buffer_t input_token,
1057                     gss_channel_bindings_t input_chan_bindings,
1058                     gss_name_t *src_name,
1059                     gss_OID *mech_type,
1060                     gss_buffer_t output_token,
1061                     OM_uint32 *ret_flags,
1062                     OM_uint32 *time_rec,
1063                     gss_cred_id_t *delegated_cred_handle)
1064 {
1065     if (gssAcceptSecContextNext == NULL) {
1066         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1067         return GSS_S_UNAVAILABLE;
1068     }
1069
1070     return gssAcceptSecContextNext(minor, context_handle, cred,
1071                                    input_token, input_chan_bindings,
1072                                    src_name, mech_type, output_token,
1073                                    ret_flags, time_rec, delegated_cred_handle);
1074 }
1075
1076 OM_uint32
1077 gssReleaseCred(OM_uint32 *minor,
1078                gss_cred_id_t *cred_handle)
1079 {
1080     if (gssReleaseCredNext == NULL) {
1081         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1082         return GSS_S_UNAVAILABLE;
1083     }
1084
1085     return gssReleaseCredNext(minor, cred_handle);
1086 }
1087
1088 OM_uint32
1089 gssReleaseName(OM_uint32 *minor,
1090                gss_name_t *name)
1091 {
1092     if (gssReleaseName == NULL) {
1093         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1094         return GSS_S_UNAVAILABLE;
1095     }
1096
1097     return gssReleaseNameNext(minor, name);
1098 }
1099
1100 OM_uint32
1101 gssDeleteSecContext(OM_uint32 *minor,
1102                     gss_ctx_id_t *context_handle,
1103                     gss_buffer_t output_token)
1104 {
1105     if (gssDeleteSecContextNext == NULL) {
1106         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1107         return GSS_S_UNAVAILABLE;
1108     }
1109
1110     return gssDeleteSecContextNext(minor, context_handle, output_token);
1111 }
1112
1113 static OM_uint32
1114 gssDisplayName(OM_uint32 *minor,
1115                gss_name_t name,
1116                gss_buffer_t buffer,
1117                gss_OID *name_type)
1118 {
1119     if (gssDisplayNameNext == NULL) {
1120         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1121         return GSS_S_UNAVAILABLE;
1122     }
1123
1124     return gssDisplayNameNext(minor, name, buffer, name_type);
1125 }
1126
1127 static OM_uint32
1128 gssImportName(OM_uint32 *minor,
1129               gss_buffer_t buffer,
1130               gss_OID name_type,
1131               gss_name_t *name)
1132 {
1133     if (gssImportNameNext == NULL) {
1134         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1135         return GSS_S_UNAVAILABLE;
1136     }
1137
1138     return gssImportNameNext(minor, buffer, name_type, name);
1139 }
1140
1141 OM_uint32
1142 gssInquireSecContextByOid(OM_uint32 *minor,
1143                           const gss_ctx_id_t context_handle,
1144                           const gss_OID desired_object,
1145                           gss_buffer_set_t *data_set)
1146 {
1147     if (gssInquireSecContextByOidNext == NULL) {
1148         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1149         return GSS_S_UNAVAILABLE;
1150     }
1151
1152     return gssInquireSecContextByOidNext(minor, context_handle,
1153                                          desired_object, data_set);
1154 }
1155
1156 OM_uint32
1157 gssStoreCred(OM_uint32 *minor,
1158              const gss_cred_id_t input_cred_handle,
1159              gss_cred_usage_t input_usage,
1160              const gss_OID desired_mech,
1161              OM_uint32 overwrite_cred,
1162              OM_uint32 default_cred,
1163              gss_OID_set *elements_stored,
1164              gss_cred_usage_t *cred_usage_stored)
1165 {
1166     if (gssStoreCredNext == NULL) {
1167         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1168         return GSS_S_UNAVAILABLE;
1169     }
1170
1171     return gssStoreCredNext(minor, input_cred_handle, input_usage,
1172                             desired_mech, overwrite_cred, default_cred,
1173                             elements_stored, cred_usage_stored);
1174 }
1175
1176 OM_uint32
1177 gssGetNameAttribute(OM_uint32 *minor,
1178                     gss_name_t name,
1179                     gss_buffer_t attr,
1180                     int *authenticated,
1181                     int *complete,
1182                     gss_buffer_t value,
1183                     gss_buffer_t display_value,
1184                     int *more)
1185 {
1186     if (gssGetNameAttributeNext == NULL) {
1187         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1188         return GSS_S_UNAVAILABLE;
1189     }
1190
1191     return gssGetNameAttributeNext(minor, name, attr, authenticated, complete,
1192                                    value, display_value, more);
1193 }