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