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