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