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