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