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