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