fix incorrect reauth cred assert check
[mech_eap.orig] / 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     if (cred == GSS_C_NO_CREDENTIAL)
489         return FALSE;
490
491     now = time(NULL);
492     expiryReq = now;
493     if (timeReq != GSS_C_INDEFINITE)
494         expiryReq += timeReq;
495
496     if (cred->krbCredCache != NULL && cred->expiryTime > expiryReq)
497         return TRUE;
498
499     if (getDefaultReauthCredentials(&minor, cred, target,
500                                     now, timeReq) == GSS_S_COMPLETE)
501         return TRUE;
502
503     return FALSE;
504 }
505
506 /*
507  * Store re-authentication (Kerberos) credentials in a credential handle.
508  * Credentials handle must be locked.
509  */
510 OM_uint32
511 gssEapStoreReauthCreds(OM_uint32 *minor,
512                        gss_ctx_id_t ctx,
513                        gss_cred_id_t cred,
514                        gss_buffer_t credBuf)
515 {
516     OM_uint32 major = GSS_S_COMPLETE;
517     krb5_error_code code;
518     krb5_context krbContext = NULL;
519     krb5_auth_context authContext = NULL;
520     krb5_data credData = { 0 };
521     krb5_creds **creds = NULL;
522     krb5_principal canonPrinc;
523     krb5_principal ccPrinc = NULL;
524     int i;
525
526     if (credBuf->length == 0 || cred == GSS_C_NO_CREDENTIAL)
527         return GSS_S_COMPLETE;
528
529     GSSEAP_KRB_INIT(&krbContext);
530
531     code = krb5_auth_con_init(krbContext, &authContext);
532     if (code != 0)
533         goto cleanup;
534
535     code = krb5_auth_con_setflags(krbContext, authContext, 0);
536     if (code != 0)
537         goto cleanup;
538
539     code = krb5_auth_con_setrecvsubkey(krbContext, authContext,
540                                        &ctx->rfc3961Key);
541     if (code != 0)
542         goto cleanup;
543
544     gssBufferToKrbData(credBuf, &credData);
545
546     code = krb5_rd_cred(krbContext, authContext, &credData, &creds, NULL);
547     if (code != 0)
548         goto cleanup;
549
550     if (creds == NULL || creds[0] == NULL)
551         goto cleanup;
552
553     code = krb5_copy_principal(krbContext, creds[0]->client, &canonPrinc);
554     if (code != 0)
555         goto cleanup;
556
557     krb5_free_principal(krbContext, cred->name->krbPrincipal);
558     cred->name->krbPrincipal = canonPrinc;
559
560     if (creds[0]->times.endtime == KRB_TIME_FOREVER)
561         cred->expiryTime = 0;
562     else
563         cred->expiryTime = creds[0]->times.endtime;
564
565     if (cred->krbCredCache == NULL) {
566         if (reauthUseCredsCache(krbContext, creds[0]->client) &&
567             krb5_cc_default(krbContext, &cred->krbCredCache) == 0)
568             cred->flags |= CRED_FLAG_DEFAULT_CCACHE;
569     } else {
570         /*
571          * If we already have an associated credentials cache, possibly from
572          * the last time we stored a reauthentication credential, then we
573          * need to clear it out and release the associated GSS credential.
574          */
575         if (cred->flags & CRED_FLAG_DEFAULT_CCACHE) {
576             krb5_cc_remove_cred(krbContext, cred->krbCredCache, 0, creds[0]);
577         } else {
578             krb5_cc_destroy(krbContext, cred->krbCredCache);
579             cred->krbCredCache = NULL;
580         }
581         gssReleaseCred(minor, &cred->reauthCred);
582     }
583
584     if (cred->krbCredCache == NULL) {
585         code = krb5_cc_new_unique(krbContext, "MEMORY", NULL, &cred->krbCredCache);
586         if (code != 0)
587             goto cleanup;
588     }
589
590     if ((cred->flags & CRED_FLAG_DEFAULT_CCACHE) == 0 ||
591         krb5_cc_get_principal(krbContext, cred->krbCredCache, &ccPrinc) != 0) {
592         code = krb5_cc_initialize(krbContext, cred->krbCredCache,
593                                   creds[0]->client);
594         if (code != 0)
595             goto cleanup;
596     }
597
598     for (i = 0; creds[i] != NULL; i++) {
599         krb5_creds kcred = *(creds[i]);
600
601         /*
602          * Swap in the acceptor name the client asked for so
603          * get_credentials() works. We're making the assumption that
604          * any service tickets returned are for us. We'll need to
605          * reflect some more on whether that is a safe assumption.
606          */
607         if (!isTicketGrantingServiceP(krbContext, kcred.server))
608             kcred.server = ctx->acceptorName->krbPrincipal;
609
610         code = krb5_cc_store_cred(krbContext, cred->krbCredCache, &kcred);
611         if (code != 0)
612             goto cleanup;
613     }
614
615     major = gss_krb5_import_cred(minor, cred->krbCredCache, NULL, NULL,
616                                  &cred->reauthCred);
617     if (GSS_ERROR(major))
618         goto cleanup;
619
620 cleanup:
621     *minor = code;
622
623     krb5_free_principal(krbContext, ccPrinc);
624     krb5_auth_con_free(krbContext, authContext);
625     if (creds != NULL) {
626         for (i = 0; creds[i] != NULL; i++)
627             krb5_free_creds(krbContext, creds[i]);
628         GSSEAP_FREE(creds);
629     }
630     if (major == GSS_S_COMPLETE)
631         major = *minor ? GSS_S_FAILURE : GSS_S_COMPLETE;
632
633     return major;
634 }
635
636 #ifndef HAVE_HEIMDAL_VERSION
637 static gss_buffer_desc radiusAvpKrbAttr = {
638     sizeof("urn:authdata-radius-avp") - 1, "urn:authdata-radius-avp"
639 };
640 #endif
641
642 /*
643  * Unfortunately extracting an AD-KDCIssued authorization data element
644  * is pretty implementation-dependent. It's not possible to verify the
645  * signature ourselves because the ticket session key is not exposed
646  * outside GSS. In an ideal world, all AD-KDCIssued elements would be
647  * verified by the Kerberos library and authentication would fail if
648  * verification failed. We're not quite there yet and as a result have
649  * to go through some hoops to get this to work. The alternative would
650  * be to sign the authorization data with our long-term key, but it
651  * seems a pity to compromise the design because of current implementation
652  * limitations.
653  *
654  * (Specifically, the hoops involve a libkrb5 authorisation data plugin
655  * that exposes the verified and serialised attribute context through
656  * the Kerberos GSS mechanism's naming extensions API.)
657  */
658 static OM_uint32
659 defrostAttrContext(OM_uint32 *minor,
660 #ifdef HAVE_HEIMDAL_VERSION
661                    gss_ctx_id_t glueContext,
662 #else
663                    gss_name_t glueName,
664 #endif
665                    gss_name_t mechName)
666 {
667     OM_uint32 major, tmpMinor;
668 #ifdef HAVE_HEIMDAL_VERSION
669     gss_OID_desc oid = { 0 };
670     gss_buffer_set_t authData = GSS_C_NO_BUFFER_SET;
671 #else
672     gss_buffer_desc authData = GSS_C_EMPTY_BUFFER;
673     gss_buffer_desc authDataDisplay = GSS_C_EMPTY_BUFFER;
674     int more = -1;
675     int authenticated, complete;
676 #endif
677
678 #ifdef HAVE_HEIMDAL_VERSION
679     major = composeOid(minor,
680                        GSS_KRB5_EXTRACT_AUTHZ_DATA_FROM_SEC_CONTEXT_X->elements,
681                        GSS_KRB5_EXTRACT_AUTHZ_DATA_FROM_SEC_CONTEXT_X->length,
682                        KRB5_AUTHDATA_RADIUS_AVP, &oid);
683     if (GSS_ERROR(major))
684         return major;
685
686     /* XXX we are assuming that this verifies AD-KDCIssued signature */
687     major = gssInquireSecContextByOid(minor, glueContext,
688                                       &oid, &authData);
689     if (major == GSS_S_COMPLETE) {
690         if (authData == GSS_C_NO_BUFFER_SET || authData->count != 1)
691             major = GSS_S_FAILURE;
692         else
693             major = gssEapImportAttrContext(minor, authData->elements, mechName);
694     } else if (major == GSS_S_FAILURE && *minor == ENOENT) {
695         /* This is the equivalent of GSS_S_UNAVAILABLE for MIT attr APIs */
696         *minor = 0;
697         major = GSS_S_COMPLETE;
698     }
699
700     gss_release_buffer_set(&tmpMinor, &authData);
701     GSSEAP_FREE(oid.elements);
702 #else
703     major = gssGetNameAttribute(minor, glueName, &radiusAvpKrbAttr,
704                                 &authenticated, &complete,
705                                 &authData, &authDataDisplay, &more);
706     if (major == GSS_S_COMPLETE) {
707         if (authenticated == 0)
708             major = GSS_S_BAD_NAME;
709         else
710             major = gssEapImportAttrContext(minor, &authData, mechName);
711     } else if (major == GSS_S_UNAVAILABLE) {
712         major = GSS_S_COMPLETE;
713     }
714
715     gss_release_buffer(&tmpMinor, &authData);
716     gss_release_buffer(&tmpMinor, &authDataDisplay);
717 #endif /* HAVE_HEIMDAL_VERSION */
718
719     return major;
720 }
721
722 /*
723  * Convert a mechanism glue to an EAP mechanism name by displaying and
724  * importing it. This also handles the RADIUS attributes.
725  */
726 OM_uint32
727 gssEapGlueToMechName(OM_uint32 *minor,
728                      gss_ctx_id_t ctx,
729                      gss_name_t glueName,
730                      gss_name_t *pMechName)
731 {
732     OM_uint32 major, tmpMinor;
733     gss_buffer_desc nameBuf = GSS_C_EMPTY_BUFFER;
734
735     *pMechName = GSS_C_NO_NAME;
736
737     major = gssDisplayName(minor, glueName, &nameBuf, NULL);
738     if (GSS_ERROR(major))
739         goto cleanup;
740
741     major = gssEapImportName(minor, &nameBuf, GSS_C_NT_USER_NAME,
742                              ctx->mechanismUsed, pMechName);
743     if (GSS_ERROR(major))
744         goto cleanup;
745
746     major = defrostAttrContext(minor,
747 #ifdef HAVE_HEIMDAL_VERSION
748                                ctx->reauthCtx,
749 #else
750                                glueName,
751 #endif
752                                *pMechName);
753     if (GSS_ERROR(major))
754         goto cleanup;
755
756 cleanup:
757     if (GSS_ERROR(major)) {
758         gssReleaseName(&tmpMinor, pMechName);
759         *pMechName = GSS_C_NO_NAME;
760     }
761
762     gss_release_buffer(&tmpMinor, &nameBuf);
763
764     return major;
765 }
766
767 /*
768  * Convert an EAP mechanism name to a mechanism glue name by displaying
769  * and importing it.
770  */
771 OM_uint32
772 gssEapMechToGlueName(OM_uint32 *minor,
773                      gss_name_t mechName,
774                      gss_name_t *pGlueName)
775 {
776     OM_uint32 major, tmpMinor;
777     gss_buffer_desc nameBuf = GSS_C_EMPTY_BUFFER;
778
779     *pGlueName = GSS_C_NO_NAME;
780
781     major = gssEapDisplayName(minor, mechName, &nameBuf, NULL);
782     if (GSS_ERROR(major))
783         goto cleanup;
784
785     major = gssImportName(minor, &nameBuf, GSS_C_NT_USER_NAME,
786                           pGlueName);
787     if (GSS_ERROR(major))
788         goto cleanup;
789
790 cleanup:
791     gss_release_buffer(&tmpMinor, &nameBuf);
792
793     return major;
794 }
795
796 /*
797  * Suck out the analgous elements of a Kerberos GSS context into an EAP
798  * one so that the application doesn't know the difference.
799  */
800 OM_uint32
801 gssEapReauthComplete(OM_uint32 *minor,
802                      gss_ctx_id_t ctx,
803                      gss_cred_id_t cred GSSEAP_UNUSED,
804                      const gss_OID mech,
805                      OM_uint32 timeRec)
806 {
807     OM_uint32 major, tmpMinor;
808     gss_buffer_set_t keyData = GSS_C_NO_BUFFER_SET;
809     krb5_context krbContext = NULL;
810 #ifdef HAVE_HEIMDAL_VERSION
811     krb5_storage *sp = NULL;
812 #endif
813
814     GSSEAP_KRB_INIT(&krbContext);
815
816     if (!oidEqual(mech, gss_mech_krb5)) {
817         major = GSS_S_BAD_MECH;
818         goto cleanup;
819     }
820
821     /* Get the raw subsession key and encryption type */
822 #ifdef HAVE_HEIMDAL_VERSION
823 #define KRB_GSS_SUBKEY_COUNT    1 /* encoded session key */
824     major = gssInquireSecContextByOid(minor, ctx->reauthCtx,
825                                       GSS_KRB5_GET_SUBKEY_X, &keyData);
826 #else
827 #define KRB_GSS_SUBKEY_COUNT    2 /* raw session key, enctype OID */
828     major = gssInquireSecContextByOid(minor, ctx->reauthCtx,
829                                       GSS_C_INQ_SSPI_SESSION_KEY, &keyData);
830 #endif
831     if (GSS_ERROR(major))
832         goto cleanup;
833
834     if (keyData == GSS_C_NO_BUFFER_SET || keyData->count < KRB_GSS_SUBKEY_COUNT) {
835         *minor = GSSEAP_KEY_UNAVAILABLE;
836         major = GSS_S_FAILURE;
837         goto cleanup;
838     }
839
840 #ifdef HAVE_HEIMDAL_VERSION
841     sp = krb5_storage_from_mem(keyData->elements[0].value,
842                                keyData->elements[0].length);
843     if (sp == NULL) {
844         *minor = ENOMEM;
845         major = GSS_S_FAILURE;
846         goto cleanup;
847     }
848
849     *minor = krb5_ret_keyblock(sp, &ctx->rfc3961Key);
850     if (*minor != 0) {
851         major = GSS_S_FAILURE;
852         goto cleanup;
853     }
854 #else
855     {
856         gss_OID_desc oid;
857         int suffix;
858
859         oid.length = keyData->elements[1].length;
860         oid.elements = keyData->elements[1].value;
861
862         /* GSS_KRB5_SESSION_KEY_ENCTYPE_OID */
863         major = decomposeOid(minor,
864                              "\x2a\x86\x48\x86\xf7\x12\x01\x02\x02\x04",
865                              10, &oid, &suffix);
866         if (GSS_ERROR(major))
867             goto cleanup;
868
869         ctx->encryptionType = suffix;
870     }
871
872     {
873         krb5_keyblock key;
874
875         KRB_KEY_LENGTH(&key) = keyData->elements[0].length;
876         KRB_KEY_DATA(&key)   = keyData->elements[0].value;
877         KRB_KEY_TYPE(&key)   = ctx->encryptionType;
878
879         *minor = krb5_copy_keyblock_contents(krbContext,
880                                              &key, &ctx->rfc3961Key);
881         if (*minor != 0) {
882             major = GSS_S_FAILURE;
883             goto cleanup;
884         }
885     }
886 #endif /* HAVE_HEIMDAL_VERSION */
887
888     major = rfc3961ChecksumTypeForKey(minor, &ctx->rfc3961Key,
889                                       &ctx->checksumType);
890     if (GSS_ERROR(major))
891         goto cleanup;
892
893     if (timeRec != GSS_C_INDEFINITE)
894         ctx->expiryTime = time(NULL) + timeRec;
895
896     /* Initialize our sequence state */
897     major = sequenceInit(minor,
898                          &ctx->seqState, ctx->recvSeq,
899                          ((ctx->gssFlags & GSS_C_REPLAY_FLAG) != 0),
900                          ((ctx->gssFlags & GSS_C_SEQUENCE_FLAG) != 0),
901                          TRUE);
902     if (GSS_ERROR(major))
903         goto cleanup;
904
905     major = GSS_S_COMPLETE;
906
907 cleanup:
908 #ifdef HAVE_HEIMDAL_VERSION
909     if (sp != NULL)
910         krb5_storage_free(sp);
911 #endif
912     gss_release_buffer_set(&tmpMinor, &keyData);
913
914     return major;
915 }
916
917 /*
918  * The remainder of this file consists of wrappers so we can call into the
919  * mechanism glue without calling ourselves.
920  */
921 static OM_uint32
922 (*gssInitSecContextNext)(OM_uint32 *,
923                          gss_cred_id_t,
924                          gss_ctx_id_t *,
925                          gss_name_t,
926                          gss_OID,
927                          OM_uint32,
928                          OM_uint32,
929                          gss_channel_bindings_t,
930                          gss_buffer_t,
931                          gss_OID *,
932                          gss_buffer_t,
933                          OM_uint32 *,
934                          OM_uint32 *);
935
936 static OM_uint32
937 (*gssAcceptSecContextNext)(OM_uint32 *,
938                            gss_ctx_id_t *,
939                            gss_cred_id_t,
940                            gss_buffer_t,
941                            gss_channel_bindings_t,
942                            gss_name_t *,
943                            gss_OID *,
944                            gss_buffer_t,
945                            OM_uint32 *,
946                            OM_uint32 *,
947                            gss_cred_id_t *);
948
949 static OM_uint32
950 (*gssReleaseCredNext)(OM_uint32 *, gss_cred_id_t *);
951
952 static OM_uint32
953 (*gssReleaseNameNext)(OM_uint32 *, gss_name_t *);
954
955 static OM_uint32
956 (*gssInquireSecContextByOidNext)(OM_uint32 *,
957                                  const gss_ctx_id_t,
958                                  const gss_OID,
959                                  gss_buffer_set_t *);
960
961 static OM_uint32
962 (*gssDeleteSecContextNext)(OM_uint32 *,
963                           gss_ctx_id_t *,
964                           gss_buffer_t);
965
966 static OM_uint32
967 (*gssDisplayNameNext)(OM_uint32 *,
968                       gss_name_t,
969                       gss_buffer_t,
970                       gss_OID *);
971
972 static OM_uint32
973 (*gssImportNameNext)(OM_uint32 *,
974                      gss_buffer_t,
975                      gss_OID,
976                      gss_name_t *);
977
978 static OM_uint32
979 (*gssStoreCredNext)(OM_uint32 *,
980                     const gss_cred_id_t,
981                     gss_cred_usage_t,
982                     const gss_OID,
983                     OM_uint32,
984                     OM_uint32,
985                     gss_OID_set *,
986                     gss_cred_usage_t *);
987
988 static OM_uint32
989 (*gssGetNameAttributeNext)(OM_uint32 *,
990                           gss_name_t,
991                           gss_buffer_t,
992                           int *,
993                           int *,
994                           gss_buffer_t,
995                           gss_buffer_t,
996                           int *);
997
998 #define NEXT_SYMBOL(local, global)  do {        \
999         ((local) = dlsym(RTLD_NEXT, (global))); \
1000         if ((local) == NULL) {                  \
1001             *minor = GSSEAP_NO_MECHGLUE_SYMBOL; \
1002             major = GSS_S_UNAVAILABLE;          \
1003             /* but continue */                  \
1004         }                                       \
1005     } while (0)
1006
1007 OM_uint32
1008 gssEapReauthInitialize(OM_uint32 *minor)
1009 {
1010     OM_uint32 major = GSS_S_COMPLETE;
1011
1012     NEXT_SYMBOL(gssInitSecContextNext,         "gss_init_sec_context");
1013     NEXT_SYMBOL(gssAcceptSecContextNext,       "gss_accept_sec_context");
1014     NEXT_SYMBOL(gssReleaseCredNext,            "gss_release_cred");
1015     NEXT_SYMBOL(gssReleaseNameNext,            "gss_release_name");
1016     NEXT_SYMBOL(gssInquireSecContextByOidNext, "gss_inquire_sec_context_by_oid");
1017     NEXT_SYMBOL(gssDeleteSecContextNext,       "gss_delete_sec_context");
1018     NEXT_SYMBOL(gssDisplayNameNext,            "gss_display_name");
1019     NEXT_SYMBOL(gssImportNameNext,             "gss_import_name");
1020     NEXT_SYMBOL(gssStoreCredNext,              "gss_store_cred");
1021 #ifndef HAVE_HEIMDAL_VERSION
1022     NEXT_SYMBOL(gssGetNameAttributeNext,       "gss_get_name_attribute");
1023 #endif
1024
1025     return major;
1026 }
1027
1028 OM_uint32
1029 gssInitSecContext(OM_uint32 *minor,
1030                   gss_cred_id_t cred,
1031                   gss_ctx_id_t *context_handle,
1032                   gss_name_t target_name,
1033                   gss_OID mech_type,
1034                   OM_uint32 req_flags,
1035                   OM_uint32 time_req,
1036                   gss_channel_bindings_t input_chan_bindings,
1037                   gss_buffer_t input_token,
1038                   gss_OID *actual_mech_type,
1039                   gss_buffer_t output_token,
1040                   OM_uint32 *ret_flags,
1041                   OM_uint32 *time_rec)
1042 {
1043     if (gssInitSecContextNext == NULL) {
1044         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1045         return GSS_S_UNAVAILABLE;
1046     }
1047
1048     return gssInitSecContextNext(minor, cred, context_handle,
1049                                  target_name, mech_type, req_flags,
1050                                  time_req, input_chan_bindings,
1051                                  input_token, actual_mech_type,
1052                                  output_token, ret_flags, time_rec);
1053 }
1054
1055 OM_uint32
1056 gssAcceptSecContext(OM_uint32 *minor,
1057                     gss_ctx_id_t *context_handle,
1058                     gss_cred_id_t cred,
1059                     gss_buffer_t input_token,
1060                     gss_channel_bindings_t input_chan_bindings,
1061                     gss_name_t *src_name,
1062                     gss_OID *mech_type,
1063                     gss_buffer_t output_token,
1064                     OM_uint32 *ret_flags,
1065                     OM_uint32 *time_rec,
1066                     gss_cred_id_t *delegated_cred_handle)
1067 {
1068     if (gssAcceptSecContextNext == NULL) {
1069         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1070         return GSS_S_UNAVAILABLE;
1071     }
1072
1073     return gssAcceptSecContextNext(minor, context_handle, cred,
1074                                    input_token, input_chan_bindings,
1075                                    src_name, mech_type, output_token,
1076                                    ret_flags, time_rec, delegated_cred_handle);
1077 }
1078
1079 OM_uint32
1080 gssReleaseCred(OM_uint32 *minor,
1081                gss_cred_id_t *cred_handle)
1082 {
1083     if (gssReleaseCredNext == NULL) {
1084         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1085         return GSS_S_UNAVAILABLE;
1086     }
1087
1088     return gssReleaseCredNext(minor, cred_handle);
1089 }
1090
1091 OM_uint32
1092 gssReleaseName(OM_uint32 *minor,
1093                gss_name_t *name)
1094 {
1095     if (gssReleaseName == NULL) {
1096         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1097         return GSS_S_UNAVAILABLE;
1098     }
1099
1100     return gssReleaseNameNext(minor, name);
1101 }
1102
1103 OM_uint32
1104 gssDeleteSecContext(OM_uint32 *minor,
1105                     gss_ctx_id_t *context_handle,
1106                     gss_buffer_t output_token)
1107 {
1108     if (gssDeleteSecContextNext == NULL) {
1109         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1110         return GSS_S_UNAVAILABLE;
1111     }
1112
1113     return gssDeleteSecContextNext(minor, context_handle, output_token);
1114 }
1115
1116 static OM_uint32
1117 gssDisplayName(OM_uint32 *minor,
1118                gss_name_t name,
1119                gss_buffer_t buffer,
1120                gss_OID *name_type)
1121 {
1122     if (gssDisplayNameNext == NULL) {
1123         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1124         return GSS_S_UNAVAILABLE;
1125     }
1126
1127     return gssDisplayNameNext(minor, name, buffer, name_type);
1128 }
1129
1130 static OM_uint32
1131 gssImportName(OM_uint32 *minor,
1132               gss_buffer_t buffer,
1133               gss_OID name_type,
1134               gss_name_t *name)
1135 {
1136     if (gssImportNameNext == NULL) {
1137         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1138         return GSS_S_UNAVAILABLE;
1139     }
1140
1141     return gssImportNameNext(minor, buffer, name_type, name);
1142 }
1143
1144 OM_uint32
1145 gssInquireSecContextByOid(OM_uint32 *minor,
1146                           const gss_ctx_id_t context_handle,
1147                           const gss_OID desired_object,
1148                           gss_buffer_set_t *data_set)
1149 {
1150     if (gssInquireSecContextByOidNext == NULL) {
1151         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1152         return GSS_S_UNAVAILABLE;
1153     }
1154
1155     return gssInquireSecContextByOidNext(minor, context_handle,
1156                                          desired_object, data_set);
1157 }
1158
1159 OM_uint32
1160 gssStoreCred(OM_uint32 *minor,
1161              const gss_cred_id_t input_cred_handle,
1162              gss_cred_usage_t input_usage,
1163              const gss_OID desired_mech,
1164              OM_uint32 overwrite_cred,
1165              OM_uint32 default_cred,
1166              gss_OID_set *elements_stored,
1167              gss_cred_usage_t *cred_usage_stored)
1168 {
1169     if (gssStoreCredNext == NULL) {
1170         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1171         return GSS_S_UNAVAILABLE;
1172     }
1173
1174     return gssStoreCredNext(minor, input_cred_handle, input_usage,
1175                             desired_mech, overwrite_cred, default_cred,
1176                             elements_stored, cred_usage_stored);
1177 }
1178
1179 OM_uint32
1180 gssGetNameAttribute(OM_uint32 *minor,
1181                     gss_name_t name,
1182                     gss_buffer_t attr,
1183                     int *authenticated,
1184                     int *complete,
1185                     gss_buffer_t value,
1186                     gss_buffer_t display_value,
1187                     int *more)
1188 {
1189     if (gssGetNameAttributeNext == NULL) {
1190         *minor = GSSEAP_NO_MECHGLUE_SYMBOL;
1191         return GSS_S_UNAVAILABLE;
1192     }
1193
1194     return gssGetNameAttributeNext(minor, name, attr, authenticated, complete,
1195                                    value, display_value, more);
1196 }