better documentation on default realm
[mech_eap.orig] / 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_ctx_id_t glueContext GSSEAP_UNUSED,
658 #endif
659                    gss_name_t glueName,
660                    gss_name_t mechName)
661 {
662     OM_uint32 major, tmpMinor;
663 #ifdef HAVE_HEIMDAL_VERSION
664     gss_OID_desc oid = { 0 };
665     gss_buffer_set_t authData = GSS_C_NO_BUFFER_SET;
666 #else
667     gss_buffer_desc authData = GSS_C_EMPTY_BUFFER;
668     gss_buffer_desc authDataDisplay = GSS_C_EMPTY_BUFFER;
669     int more = -1;
670     int authenticated, complete;
671 #endif
672
673 #ifdef HAVE_HEIMDAL_VERSION
674     major = composeOid(minor,
675                        GSS_KRB5_EXTRACT_AUTHZ_DATA_FROM_SEC_CONTEXT_X->elements,
676                        GSS_KRB5_EXTRACT_AUTHZ_DATA_FROM_SEC_CONTEXT_X->length,
677                        KRB5_AUTHDATA_RADIUS_AVP, &oid);
678     if (GSS_ERROR(major))
679         return major;
680
681     /* XXX we are assuming that this verifies AD-KDCIssued signature */
682     major = gssInquireSecContextByOid(minor, glueContext,
683                                       &oid, &authData);
684     if (major == GSS_S_COMPLETE) {
685         if (authData == GSS_C_NO_BUFFER_SET || authData->count != 1)
686             major = GSS_S_FAILURE;
687         else
688             major = gssEapImportAttrContext(minor, authData->elements, mechName);
689     } else if (major == GSS_S_FAILURE && *minor == ENOENT) {
690         /* This is the equivalent of GSS_S_UNAVAILABLE for MIT attr APIs */
691         *minor = 0;
692         major = GSS_S_COMPLETE;
693     }
694
695     gss_release_buffer_set(&tmpMinor, &authData);
696     GSSEAP_FREE(oid.elements);
697 #else
698     major = gssGetNameAttribute(minor, glueName, &radiusAvpKrbAttr,
699                                 &authenticated, &complete,
700                                 &authData, &authDataDisplay, &more);
701     if (major == GSS_S_COMPLETE) {
702         if (authenticated == 0)
703             major = GSS_S_BAD_NAME;
704         else
705             major = gssEapImportAttrContext(minor, &authData, mechName);
706     } else if (major == GSS_S_UNAVAILABLE) {
707         major = GSS_S_COMPLETE;
708     }
709
710     gss_release_buffer(&tmpMinor, &authData);
711     gss_release_buffer(&tmpMinor, &authDataDisplay);
712 #endif /* HAVE_HEIMDAL_VERSION */
713
714     return major;
715 }
716
717 /*
718  * Convert a mechanism glue to an EAP mechanism name by displaying and
719  * importing it. This also handles the RADIUS attributes.
720  */
721 OM_uint32
722 gssEapGlueToMechName(OM_uint32 *minor,
723                      gss_ctx_id_t ctx,
724                      gss_name_t glueName,
725                      gss_name_t *pMechName)
726 {
727     OM_uint32 major, tmpMinor;
728     gss_buffer_desc nameBuf = GSS_C_EMPTY_BUFFER;
729
730     *pMechName = GSS_C_NO_NAME;
731
732     major = gssDisplayName(minor, glueName, &nameBuf, NULL);
733     if (GSS_ERROR(major))
734         goto cleanup;
735
736     major = gssEapImportName(minor, &nameBuf, GSS_C_NT_USER_NAME,
737                              ctx->mechanismUsed, pMechName);
738     if (GSS_ERROR(major))
739         goto cleanup;
740
741     major = defrostAttrContext(minor, ctx->kerberosCtx, glueName, *pMechName);
742     if (GSS_ERROR(major))
743         goto cleanup;
744
745 cleanup:
746     if (GSS_ERROR(major)) {
747         gssReleaseName(&tmpMinor, pMechName);
748         *pMechName = GSS_C_NO_NAME;
749     }
750
751     gss_release_buffer(&tmpMinor, &nameBuf);
752
753     return major;
754 }
755
756 /*
757  * Convert an EAP mechanism name to a mechanism glue name by displaying
758  * and importing it.
759  */
760 OM_uint32
761 gssEapMechToGlueName(OM_uint32 *minor,
762                      gss_name_t mechName,
763                      gss_name_t *pGlueName)
764 {
765     OM_uint32 major, tmpMinor;
766     gss_buffer_desc nameBuf = GSS_C_EMPTY_BUFFER;
767
768     *pGlueName = GSS_C_NO_NAME;
769
770     major = gssEapDisplayName(minor, mechName, &nameBuf, NULL);
771     if (GSS_ERROR(major))
772         goto cleanup;
773
774     major = gssImportName(minor, &nameBuf, GSS_C_NT_USER_NAME,
775                           pGlueName);
776     if (GSS_ERROR(major))
777         goto cleanup;
778
779 cleanup:
780     gss_release_buffer(&tmpMinor, &nameBuf);
781
782     return major;
783 }
784
785 /*
786  * Suck out the analgous elements of a Kerberos GSS context into an EAP
787  * one so that the application doesn't know the difference.
788  */
789 OM_uint32
790 gssEapReauthComplete(OM_uint32 *minor,
791                      gss_ctx_id_t ctx,
792                      gss_cred_id_t cred GSSEAP_UNUSED,
793                      const gss_OID mech,
794                      OM_uint32 timeRec)
795 {
796     OM_uint32 major, tmpMinor;
797     gss_buffer_set_t keyData = GSS_C_NO_BUFFER_SET;
798     krb5_context krbContext = NULL;
799 #ifdef HAVE_HEIMDAL_VERSION
800     krb5_storage *sp = NULL;
801 #endif
802
803     GSSEAP_KRB_INIT(&krbContext);
804
805     if (!oidEqual(mech, gss_mech_krb5)) {
806         major = GSS_S_BAD_MECH;
807         goto cleanup;
808     }
809
810     /* Get the raw subsession key and encryption type */
811 #ifdef HAVE_HEIMDAL_VERSION
812 #define KRB_GSS_SUBKEY_COUNT    1 /* encoded session key */
813     major = gssInquireSecContextByOid(minor, ctx->kerberosCtx,
814                                       GSS_KRB5_GET_SUBKEY_X, &keyData);
815 #else
816 #define KRB_GSS_SUBKEY_COUNT    2 /* raw session key, enctype OID */
817     major = gssInquireSecContextByOid(minor, ctx->kerberosCtx,
818                                       GSS_C_INQ_SSPI_SESSION_KEY, &keyData);
819 #endif
820     if (GSS_ERROR(major))
821         goto cleanup;
822
823     if (keyData == GSS_C_NO_BUFFER_SET || keyData->count < KRB_GSS_SUBKEY_COUNT) {
824         *minor = GSSEAP_KEY_UNAVAILABLE;
825         major = GSS_S_FAILURE;
826         goto cleanup;
827     }
828
829 #ifdef HAVE_HEIMDAL_VERSION
830     sp = krb5_storage_from_mem(keyData->elements[0].value,
831                                keyData->elements[0].length);
832     if (sp == NULL) {
833         *minor = ENOMEM;
834         major = GSS_S_FAILURE;
835         goto cleanup;
836     }
837
838     *minor = krb5_ret_keyblock(sp, &ctx->rfc3961Key);
839     if (*minor != 0) {
840         major = GSS_S_FAILURE;
841         goto cleanup;
842     }
843 #else
844     {
845         gss_OID_desc oid;
846         int suffix;
847
848         oid.length = keyData->elements[1].length;
849         oid.elements = keyData->elements[1].value;
850
851         /* GSS_KRB5_SESSION_KEY_ENCTYPE_OID */
852         major = decomposeOid(minor,
853                              "\x2a\x86\x48\x86\xf7\x12\x01\x02\x02\x04",
854                              10, &oid, &suffix);
855         if (GSS_ERROR(major))
856             goto cleanup;
857
858         ctx->encryptionType = suffix;
859     }
860
861     {
862         krb5_keyblock key;
863
864         KRB_KEY_LENGTH(&key) = keyData->elements[0].length;
865         KRB_KEY_DATA(&key)   = keyData->elements[0].value;
866         KRB_KEY_TYPE(&key)   = ctx->encryptionType;
867
868         *minor = krb5_copy_keyblock_contents(krbContext,
869                                              &key, &ctx->rfc3961Key);
870         if (*minor != 0) {
871             major = GSS_S_FAILURE;
872             goto cleanup;
873         }
874     }
875 #endif /* HAVE_HEIMDAL_VERSION */
876
877     major = rfc3961ChecksumTypeForKey(minor, &ctx->rfc3961Key,
878                                       &ctx->checksumType);
879     if (GSS_ERROR(major))
880         goto cleanup;
881
882     if (timeRec != GSS_C_INDEFINITE)
883         ctx->expiryTime = time(NULL) + timeRec;
884
885     /* Initialize our sequence state */
886     major = sequenceInit(minor,
887                          &ctx->seqState, ctx->recvSeq,
888                          ((ctx->gssFlags & GSS_C_REPLAY_FLAG) != 0),
889                          ((ctx->gssFlags & GSS_C_SEQUENCE_FLAG) != 0),
890                          TRUE);
891     if (GSS_ERROR(major))
892         goto cleanup;
893
894     major = GSS_S_COMPLETE;
895
896 cleanup:
897 #ifdef HAVE_HEIMDAL_VERSION
898     if (sp != NULL)
899         krb5_storage_free(sp);
900 #endif
901     gss_release_buffer_set(&tmpMinor, &keyData);
902
903     return major;
904 }
905
906 /*
907  * The remainder of this file consists of wrappers so we can call into the
908  * mechanism glue without calling ourselves.
909  */
910 static OM_uint32
911 (*gssInitSecContextNext)(OM_uint32 *,
912                          gss_cred_id_t,
913                          gss_ctx_id_t *,
914                          gss_name_t,
915                          gss_OID,
916                          OM_uint32,
917                          OM_uint32,
918                          gss_channel_bindings_t,
919                          gss_buffer_t,
920                          gss_OID *,
921                          gss_buffer_t,
922                          OM_uint32 *,
923                          OM_uint32 *);
924
925 static OM_uint32
926 (*gssAcceptSecContextNext)(OM_uint32 *,
927                            gss_ctx_id_t *,
928                            gss_cred_id_t,
929                            gss_buffer_t,
930                            gss_channel_bindings_t,
931                            gss_name_t *,
932                            gss_OID *,
933                            gss_buffer_t,
934                            OM_uint32 *,
935                            OM_uint32 *,
936                            gss_cred_id_t *);
937
938 static OM_uint32
939 (*gssReleaseCredNext)(OM_uint32 *, gss_cred_id_t *);
940
941 static OM_uint32
942 (*gssReleaseNameNext)(OM_uint32 *, gss_name_t *);
943
944 static OM_uint32
945 (*gssInquireSecContextByOidNext)(OM_uint32 *,
946                                  const gss_ctx_id_t,
947                                  const gss_OID,
948                                  gss_buffer_set_t *);
949
950 static OM_uint32
951 (*gssDeleteSecContextNext)(OM_uint32 *,
952                           gss_ctx_id_t *,
953                           gss_buffer_t);
954
955 static OM_uint32
956 (*gssDisplayNameNext)(OM_uint32 *,
957                       gss_name_t,
958                       gss_buffer_t,
959                       gss_OID *);
960
961 static OM_uint32
962 (*gssImportNameNext)(OM_uint32 *,
963                      gss_buffer_t,
964                      gss_OID,
965                      gss_name_t *);
966
967 static OM_uint32
968 (*gssStoreCredNext)(OM_uint32 *,
969                     const gss_cred_id_t,
970                     gss_cred_usage_t,
971                     const gss_OID,
972                     OM_uint32,
973                     OM_uint32,
974                     gss_OID_set *,
975                     gss_cred_usage_t *);
976
977 static OM_uint32
978 (*gssGetNameAttributeNext)(OM_uint32 *,
979                           gss_name_t,
980                           gss_buffer_t,
981                           int *,
982                           int *,
983                           gss_buffer_t,
984                           gss_buffer_t,
985                           int *);
986
987 #define NEXT_SYMBOL(local, global)  do {        \
988         ((local) = dlsym(RTLD_NEXT, (global))); \
989         if ((local) == NULL) {                  \
990             *minor = GSSEAP_NO_MECHGLUE_SYMBOL; \
991             major = GSS_S_UNAVAILABLE;          \
992             /* but continue */                  \
993         }                                       \
994     } while (0)
995
996 OM_uint32
997 gssEapReauthInitialize(OM_uint32 *minor)
998 {
999     OM_uint32 major = GSS_S_COMPLETE;
1000
1001     NEXT_SYMBOL(gssInitSecContextNext,         "gss_init_sec_context");
1002     NEXT_SYMBOL(gssAcceptSecContextNext,       "gss_accept_sec_context");
1003     NEXT_SYMBOL(gssReleaseCredNext,            "gss_release_cred");
1004     NEXT_SYMBOL(gssReleaseNameNext,            "gss_release_name");
1005     NEXT_SYMBOL(gssInquireSecContextByOidNext, "gss_inquire_sec_context_by_oid");
1006     NEXT_SYMBOL(gssDeleteSecContextNext,       "gss_delete_sec_context");
1007     NEXT_SYMBOL(gssDisplayNameNext,            "gss_display_name");
1008     NEXT_SYMBOL(gssImportNameNext,             "gss_import_name");
1009     NEXT_SYMBOL(gssStoreCredNext,              "gss_store_cred");
1010 #ifndef HAVE_HEIMDAL_VERSION
1011     NEXT_SYMBOL(gssGetNameAttributeNext,       "gss_get_name_attribute");
1012 #endif
1013
1014     return major;
1015 }
1016
1017 OM_uint32
1018 gssInitSecContext(OM_uint32 *minor,
1019                   gss_cred_id_t cred,
1020                   gss_ctx_id_t *context_handle,
1021                   gss_name_t target_name,
1022                   gss_OID mech_type,
1023                   OM_uint32 req_flags,
1024                   OM_uint32 time_req,
1025                   gss_channel_bindings_t input_chan_bindings,
1026                   gss_buffer_t input_token,
1027                   gss_OID *actual_mech_type,
1028                   gss_buffer_t output_token,
1029                   OM_uint32 *ret_flags,
1030                   OM_uint32 *time_rec)
1031 {
1032     if (gssInitSecContextNext == NULL) {
1033         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1034         return GSS_S_UNAVAILABLE;
1035     }
1036
1037     return gssInitSecContextNext(minor, cred, context_handle,
1038                                  target_name, mech_type, req_flags,
1039                                  time_req, input_chan_bindings,
1040                                  input_token, actual_mech_type,
1041                                  output_token, ret_flags, time_rec);
1042 }
1043
1044 OM_uint32
1045 gssAcceptSecContext(OM_uint32 *minor,
1046                     gss_ctx_id_t *context_handle,
1047                     gss_cred_id_t cred,
1048                     gss_buffer_t input_token,
1049                     gss_channel_bindings_t input_chan_bindings,
1050                     gss_name_t *src_name,
1051                     gss_OID *mech_type,
1052                     gss_buffer_t output_token,
1053                     OM_uint32 *ret_flags,
1054                     OM_uint32 *time_rec,
1055                     gss_cred_id_t *delegated_cred_handle)
1056 {
1057     if (gssAcceptSecContextNext == NULL) {
1058         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1059         return GSS_S_UNAVAILABLE;
1060     }
1061
1062     return gssAcceptSecContextNext(minor, context_handle, cred,
1063                                    input_token, input_chan_bindings,
1064                                    src_name, mech_type, output_token,
1065                                    ret_flags, time_rec, delegated_cred_handle);
1066 }
1067
1068 OM_uint32
1069 gssReleaseCred(OM_uint32 *minor,
1070                gss_cred_id_t *cred_handle)
1071 {
1072     if (gssReleaseCredNext == NULL) {
1073         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1074         return GSS_S_UNAVAILABLE;
1075     }
1076
1077     return gssReleaseCredNext(minor, cred_handle);
1078 }
1079
1080 OM_uint32
1081 gssReleaseName(OM_uint32 *minor,
1082                gss_name_t *name)
1083 {
1084     if (gssReleaseName == NULL) {
1085         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1086         return GSS_S_UNAVAILABLE;
1087     }
1088
1089     return gssReleaseNameNext(minor, name);
1090 }
1091
1092 OM_uint32
1093 gssDeleteSecContext(OM_uint32 *minor,
1094                     gss_ctx_id_t *context_handle,
1095                     gss_buffer_t output_token)
1096 {
1097     if (gssDeleteSecContextNext == NULL) {
1098         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1099         return GSS_S_UNAVAILABLE;
1100     }
1101
1102     return gssDeleteSecContextNext(minor, context_handle, output_token);
1103 }
1104
1105 static OM_uint32
1106 gssDisplayName(OM_uint32 *minor,
1107                gss_name_t name,
1108                gss_buffer_t buffer,
1109                gss_OID *name_type)
1110 {
1111     if (gssDisplayNameNext == NULL) {
1112         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1113         return GSS_S_UNAVAILABLE;
1114     }
1115
1116     return gssDisplayNameNext(minor, name, buffer, name_type);
1117 }
1118
1119 static OM_uint32
1120 gssImportName(OM_uint32 *minor,
1121               gss_buffer_t buffer,
1122               gss_OID name_type,
1123               gss_name_t *name)
1124 {
1125     if (gssImportNameNext == NULL) {
1126         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1127         return GSS_S_UNAVAILABLE;
1128     }
1129
1130     return gssImportNameNext(minor, buffer, name_type, name);
1131 }
1132
1133 OM_uint32
1134 gssInquireSecContextByOid(OM_uint32 *minor,
1135                           const gss_ctx_id_t context_handle,
1136                           const gss_OID desired_object,
1137                           gss_buffer_set_t *data_set)
1138 {
1139     if (gssInquireSecContextByOidNext == NULL) {
1140         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1141         return GSS_S_UNAVAILABLE;
1142     }
1143
1144     return gssInquireSecContextByOidNext(minor, context_handle,
1145                                          desired_object, data_set);
1146 }
1147
1148 OM_uint32
1149 gssStoreCred(OM_uint32 *minor,
1150              const gss_cred_id_t input_cred_handle,
1151              gss_cred_usage_t input_usage,
1152              const gss_OID desired_mech,
1153              OM_uint32 overwrite_cred,
1154              OM_uint32 default_cred,
1155              gss_OID_set *elements_stored,
1156              gss_cred_usage_t *cred_usage_stored)
1157 {
1158     if (gssStoreCredNext == NULL) {
1159         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1160         return GSS_S_UNAVAILABLE;
1161     }
1162
1163     return gssStoreCredNext(minor, input_cred_handle, input_usage,
1164                             desired_mech, overwrite_cred, default_cred,
1165                             elements_stored, cred_usage_stored);
1166 }
1167
1168 OM_uint32
1169 gssGetNameAttribute(OM_uint32 *minor,
1170                     gss_name_t name,
1171                     gss_buffer_t attr,
1172                     int *authenticated,
1173                     int *complete,
1174                     gss_buffer_t value,
1175                     gss_buffer_t display_value,
1176                     int *more)
1177 {
1178     if (gssGetNameAttributeNext == NULL) {
1179         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1180         return GSS_S_UNAVAILABLE;
1181     }
1182
1183     return gssGetNameAttributeNext(minor, name, attr, authenticated, complete,
1184                                    value, display_value, more);
1185 }