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