Allow KDC to always return the salt in the PA-ETYPE-INFO[2]
[heimdal.git] / lib / krb5 / krcache.c
blobdbf81850ea34de31f1c7ce9d267eeed3e471c8f0
1 /*
2 * Copyright (c) 2006 The Regents of the University of Michigan.
3 * All rights reserved.
5 * Portions Copyright (c) 2018, AuriStor, Inc.
7 * Permission is granted to use, copy, create derivative works
8 * and redistribute this software and such derivative works
9 * for any purpose, so long as the name of The University of
10 * Michigan is not used in any advertising or publicity
11 * pertaining to the use of distribution of this software
12 * without specific, written prior authorization. If the
13 * above copyright notice or any other identification of the
14 * University of Michigan is included in any copy of any
15 * portion of this software, then the disclaimer below must
16 * also be included.
18 * THIS SOFTWARE IS PROVIDED AS IS, WITHOUT REPRESENTATION
19 * FROM THE UNIVERSITY OF MICHIGAN AS TO ITS FITNESS FOR ANY
20 * PURPOSE, AND WITHOUT WARRANTY BY THE UNIVERSITY OF
21 * MICHIGAN OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING
22 * WITHOUT LIMITATION THE IMPLIED WARRANTIES OF
23 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
24 * REGENTS OF THE UNIVERSITY OF MICHIGAN SHALL NOT BE LIABLE
25 * FOR ANY DAMAGES, INCLUDING SPECIAL, INDIRECT, INCIDENTAL, OR
26 * CONSEQUENTIAL DAMAGES, WITH RESPECT TO ANY CLAIM ARISING
27 * OUT OF OR IN CONNECTION WITH THE USE OF THE SOFTWARE, EVEN
28 * IF IT HAS BEEN OR IS HEREAFTER ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGES.
32 * Copyright 1990,1991,1992,1993,1994,2000,2004 Massachusetts Institute of
33 * Technology. All Rights Reserved.
35 * Original stdio support copyright 1995 by Cygnus Support.
37 * Export of this software from the United States of America may
38 * require a specific license from the United States Government.
39 * It is the responsibility of any person or organization contemplating
40 * export to obtain such a license before exporting.
42 * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
43 * distribute this software and its documentation for any purpose and
44 * without fee is hereby granted, provided that the above copyright
45 * notice appear in all copies and that both that copyright notice and
46 * this permission notice appear in supporting documentation, and that
47 * the name of M.I.T. not be used in advertising or publicity pertaining
48 * to distribution of the software without specific, written prior
49 * permission. Furthermore if you modify this software you must label
50 * your software as modified software and not distribute it in such a
51 * fashion that it might be confused with the original M.I.T. software.
52 * M.I.T. makes no representations about the suitability of
53 * this software for any purpose. It is provided "as is" without express
54 * or implied warranty.
58 * This file implements a collection-enabled credential cache type where the
59 * credentials are stored in the Linux keyring facility.
61 * A residual of this type can have three forms:
62 * anchor:collection:subsidiary
63 * anchor:collection
64 * collection
66 * The anchor name is "process", "thread", or "legacy" and determines where we
67 * search for keyring collections. In the third form, the anchor name is
68 * presumed to be "legacy". The anchor keyring for legacy caches is the
69 * session keyring.
71 * If the subsidiary name is present, the residual identifies a single cache
72 * within a collection. Otherwise, the residual identifies the collection
73 * itself. When a residual identifying a collection is resolved, the
74 * collection's primary key is looked up (or initialized, using the collection
75 * name as the subsidiary name), and the resulting cache's name will use the
76 * first name form and will identify the primary cache.
78 * Keyring collections are named "_krb_<collection>" and are linked from the
79 * anchor keyring. The keys within a keyring collection are links to cache
80 * keyrings, plus a link to one user key named "krb_ccache:primary" which
81 * contains a serialized representation of the collection version (currently 1)
82 * and the primary name of the collection.
84 * Cache keyrings contain one user key per credential which contains a
85 * serialized representation of the credential. There is also one user key
86 * named "__krb5_princ__" which contains a serialized representation of the
87 * cache's default principal.
89 * If the anchor name is "legacy", then the initial primary cache (the one
90 * named with the collection name) is also linked to the session keyring, and
91 * we look for a cache in that location when initializing the collection. This
92 * extra link allows that cache to be visible to old versions of the KEYRING
93 * cache type, and allows us to see caches created by that code.
96 #include "krb5_locl.h"
98 #ifdef HAVE_KEYUTILS_H
100 #include <keyutils.h>
103 * We try to use the big_key key type for credentials except in legacy caches.
104 * We fall back to the user key type if the kernel does not support big_key.
105 * If the library doesn't support keyctl_get_persistent(), we don't even try
106 * big_key since the two features were added at the same time.
108 #ifdef HAVE_KEYCTL_GET_PERSISTENT
109 #define KRCC_CRED_KEY_TYPE "big_key"
110 #else
111 #define KRCC_CRED_KEY_TYPE "user"
112 #endif
115 * We use the "user" key type for collection primary names, for cache principal
116 * names, and for credentials in legacy caches.
118 #define KRCC_KEY_TYPE_USER "user"
121 * We create ccaches as separate keyrings
123 #define KRCC_KEY_TYPE_KEYRING "keyring"
126 * Special name of the key within a ccache keyring
127 * holding principal information
129 #define KRCC_SPEC_PRINC_KEYNAME "__krb5_princ__"
132 * Special name for the key to communicate the name(s)
133 * of credentials caches to be used for requests.
134 * This should currently contain a single name, but
135 * in the future may contain a list that may be
136 * intelligently chosen from.
138 #define KRCC_SPEC_CCACHE_SET_KEYNAME "__krb5_cc_set__"
141 * This name identifies the key containing the name of the current primary
142 * cache within a collection.
144 #define KRCC_COLLECTION_PRIMARY "krb_ccache:primary"
147 * If the library context does not specify a keyring collection, unique ccaches
148 * will be created within this collection.
150 #define KRCC_DEFAULT_UNIQUE_COLLECTION "session:__krb5_unique__"
153 * Collection keyring names begin with this prefix. We use a prefix so that a
154 * cache keyring with the collection name itself can be linked directly into
155 * the anchor, for legacy session keyring compatibility.
157 #define KRCC_CCCOL_PREFIX "_krb_"
160 * For the "persistent" anchor type, we look up or create this fixed keyring
161 * name within the per-UID persistent keyring.
163 #define KRCC_PERSISTENT_KEYRING_NAME "_krb"
166 * Name of the key holding time offsets for the individual cache
168 #define KRCC_TIME_OFFSETS "__krb5_time_offsets__"
171 * Keyring name prefix and length of random name part
173 #define KRCC_NAME_PREFIX "krb_ccache_"
174 #define KRCC_NAME_RAND_CHARS 8
176 #define KRCC_COLLECTION_VERSION 1
178 #define KRCC_PERSISTENT_ANCHOR "persistent"
179 #define KRCC_PROCESS_ANCHOR "process"
180 #define KRCC_THREAD_ANCHOR "thread"
181 #define KRCC_SESSION_ANCHOR "session"
182 #define KRCC_USER_ANCHOR "user"
183 #define KRCC_LEGACY_ANCHOR "legacy"
185 #if SIZEOF_KEY_SERIAL_T != 4
186 /* lockless implementation assumes 32-bit key serials */
187 #error only 32-bit key serial numbers supported by this version of keyring ccache
188 #endif
190 typedef heim_base_atomic(key_serial_t) atomic_key_serial_t;
192 typedef union _krb5_krcache_and_princ_id {
193 heim_base_atomic(uint64_t) krcu_cache_and_princ_id;
194 struct {
195 atomic_key_serial_t cache_id; /* keyring ID representing ccache */
196 atomic_key_serial_t princ_id; /* key ID holding principal info */
197 } krcu_id;
198 #define krcu_cache_id krcu_id.cache_id
199 #define krcu_princ_id krcu_id.princ_id
200 } krb5_krcache_and_princ_id;
203 * This represents a credentials cache "file" where cache_id is the keyring
204 * serial number for this credentials cache "file". Each key in the keyring
205 * contains a separate key.
207 * Thread-safe as long as caches are not destroyed whilst other threads are
208 * using them.
210 typedef struct _krb5_krcache {
211 char *krc_name; /* Name for this credentials cache */
212 char *krc_collection;
213 char *krc_subsidiary;
214 heim_base_atomic(krb5_timestamp) krc_changetime; /* update time, does not decrease (mutable) */
215 krb5_krcache_and_princ_id krc_id; /* cache and principal IDs (mutable) */
216 #define krc_cache_and_principal_id krc_id.krcu_cache_and_princ_id
217 #define krc_cache_id krc_id.krcu_id.cache_id
218 #define krc_princ_id krc_id.krcu_id.princ_id
219 key_serial_t krc_coll_id; /* collection containing this cache keyring */
220 krb5_boolean krc_is_legacy; /* */
221 } krb5_krcache;
223 #define KRCACHE(X) ((krb5_krcache *)(X)->data.data)
225 static krb5_error_code KRB5_CALLCONV
226 krcc_get_first(krb5_context, krb5_ccache id, krb5_cc_cursor *cursor);
228 static krb5_error_code KRB5_CALLCONV
229 krcc_get_next(krb5_context context,
230 krb5_ccache id,
231 krb5_cc_cursor *cursor,
232 krb5_creds *creds);
234 static krb5_error_code KRB5_CALLCONV
235 krcc_end_get(krb5_context context,
236 krb5_ccache id,
237 krb5_cc_cursor *cursor);
239 static krb5_error_code KRB5_CALLCONV
240 krcc_end_cache_get(krb5_context context, krb5_cc_cursor cursor);
242 static krb5_error_code
243 clear_cache_keyring(krb5_context context, atomic_key_serial_t *pcache_id);
245 static krb5_error_code
246 alloc_cache(krb5_context context,
247 key_serial_t collection_id,
248 key_serial_t cache_id,
249 const char *anchor_name,
250 const char *collection_name,
251 const char *subsidiary_name,
252 krb5_krcache **data);
254 static krb5_error_code
255 save_principal(krb5_context context,
256 key_serial_t cache_id,
257 krb5_const_principal princ,
258 atomic_key_serial_t *pprinc_id);
260 static krb5_error_code
261 save_time_offsets(krb5_context context,
262 key_serial_t cache_id,
263 int32_t sec_offset,
264 int32_t usec_offset);
266 static void
267 update_change_time(krb5_context context,
268 krb5_timestamp now,
269 krb5_krcache *d);
272 * GET_PERSISTENT(uid) acquires the persistent keyring for uid, or falls back
273 * to the user keyring if uid matches the current effective uid.
276 static key_serial_t
277 get_persistent_fallback(uid_t uid)
279 return (uid == geteuid()) ? KEY_SPEC_USER_KEYRING : -1;
282 #ifdef HAVE_KEYCTL_GET_PERSISTENT
283 #define GET_PERSISTENT get_persistent_real
284 static key_serial_t
285 get_persistent_real(uid_t uid)
287 key_serial_t key;
289 key = keyctl_get_persistent(uid, KEY_SPEC_PROCESS_KEYRING);
291 return (key == -1 && errno == ENOTSUP) ? get_persistent_fallback(uid) : key;
293 #else
294 #define GET_PERSISTENT get_persistent_fallback
295 #endif
298 * If a process has no explicitly set session keyring, KEY_SPEC_SESSION_KEYRING
299 * will resolve to the user session keyring for ID lookup and reading, but in
300 * some kernel versions, writing to that special keyring will instead create a
301 * new empty session keyring for the process. We do not want that; the keys we
302 * create would be invisible to other processes. We can work around that
303 * behavior by explicitly writing to the user session keyring when it matches
304 * the session keyring. This function returns the keyring we should write to
305 * for the session anchor.
307 static key_serial_t
308 session_write_anchor(void)
310 key_serial_t s, u;
312 s = keyctl_get_keyring_ID(KEY_SPEC_SESSION_KEYRING, 0);
313 u = keyctl_get_keyring_ID(KEY_SPEC_USER_SESSION_KEYRING, 0);
315 return (s == u) ? KEY_SPEC_USER_SESSION_KEYRING : KEY_SPEC_SESSION_KEYRING;
319 * Find or create a keyring within parent with the given name. If possess is
320 * nonzero, also make sure the key is linked from possess. This is necessary
321 * to ensure that we have possession rights on the key when the parent is the
322 * user or persistent keyring.
324 static krb5_error_code
325 find_or_create_keyring(key_serial_t parent,
326 key_serial_t possess,
327 const char *name,
328 atomic_key_serial_t *pkey)
330 key_serial_t key;
332 key = keyctl_search(parent, KRCC_KEY_TYPE_KEYRING, name, possess);
333 if (key == -1) {
334 if (possess != 0) {
335 key = add_key(KRCC_KEY_TYPE_KEYRING, name, NULL, 0, possess);
336 if (key == -1 || keyctl_link(key, parent) == -1)
337 return errno;
338 } else {
339 key = add_key(KRCC_KEY_TYPE_KEYRING, name, NULL, 0, parent);
340 if (key == -1)
341 return errno;
345 heim_base_atomic_store(pkey, key);
347 return 0;
351 * Parse a residual name into an anchor name, a collection name, and possibly a
352 * subsidiary name.
354 static krb5_error_code
355 parse_residual(krb5_context context,
356 const char *residual,
357 char **panchor_name,
358 char **pcollection_name,
359 char **psubsidiary_name)
361 char *anchor_name = NULL;
362 char *collection_name = NULL;
363 char *subsidiary_name = NULL;
364 const char *sep;
366 *panchor_name = NULL;
367 *pcollection_name = NULL;
368 *psubsidiary_name = NULL;
370 /* Parse out the anchor name. Use the legacy anchor if not present. */
371 sep = strchr(residual, ':');
372 if (sep == NULL) {
373 anchor_name = strdup(KRCC_LEGACY_ANCHOR);
374 if (anchor_name == NULL)
375 goto nomem;
376 } else {
377 anchor_name = strndup(residual, sep - residual);
378 if (anchor_name == NULL)
379 goto nomem;
380 residual = sep + 1;
383 /* Parse out the collection and subsidiary name. */
384 sep = strchr(residual, ':');
385 if (sep == NULL) {
386 collection_name = strdup(residual);
387 if (collection_name == NULL)
388 goto nomem;
389 } else {
390 collection_name = strndup(residual, sep - residual);
391 if (collection_name == NULL)
392 goto nomem;
394 subsidiary_name = strdup(sep + 1);
395 if (subsidiary_name == NULL)
396 goto nomem;
399 *panchor_name = anchor_name;
400 *pcollection_name = collection_name;
401 *psubsidiary_name = subsidiary_name;
403 return 0;
405 nomem:
406 free(anchor_name);
407 free(collection_name);
408 free(subsidiary_name);
410 return krb5_enomem(context);
414 * Return TRUE if residual identifies a subsidiary cache which should be linked
415 * into the anchor so it can be visible to old code. This is the case if the
416 * residual has the legacy anchor and the subsidiary name matches the
417 * collection name.
419 static krb5_boolean
420 is_legacy_cache_name_p(const char *residual)
422 const char *sep, *aname, *cname, *sname;
423 size_t alen, clen, legacy_len = sizeof(KRCC_LEGACY_ANCHOR) - 1;
425 /* Get pointers to the anchor, collection, and subsidiary names. */
426 aname = residual;
427 sep = strchr(residual, ':');
428 if (sep == NULL)
429 return FALSE;
431 alen = sep - aname;
432 cname = sep + 1;
433 sep = strchr(cname, ':');
434 if (sep == NULL)
435 return FALSE;
437 clen = sep - cname;
438 sname = sep + 1;
440 return alen == legacy_len && clen == strlen(sname) &&
441 strncmp(aname, KRCC_LEGACY_ANCHOR, alen) == 0 &&
442 strncmp(cname, sname, clen) == 0;
446 * If the default cache name for context is a KEYRING cache, parse its residual
447 * string. Otherwise set all outputs to NULL.
449 static krb5_error_code
450 get_default(krb5_context context,
451 char **panchor_name,
452 char **pcollection_name,
453 char **psubsidiary_name)
455 const char *defname;
457 *panchor_name = *pcollection_name = *psubsidiary_name = NULL;
459 defname = krb5_cc_default_name(context);
460 if (defname == NULL || strncmp(defname, "KEYRING:", 8) != 0)
461 return 0;
463 return parse_residual(context, defname + 8,
464 panchor_name, pcollection_name, psubsidiary_name);
467 /* Create a residual identifying a subsidiary cache. */
468 static krb5_error_code
469 make_subsidiary_residual(krb5_context context,
470 const char *anchor_name,
471 const char *collection_name,
472 const char *subsidiary_name,
473 char **presidual)
475 if (asprintf(presidual, "%s:%s:%s", anchor_name, collection_name,
476 subsidiary_name) < 0) {
477 *presidual = NULL;
478 return krb5_enomem(context);
481 return 0;
485 * Retrieve or create a keyring for collection_name within the anchor, and set
486 * *collection_id to its serial number.
488 static krb5_error_code
489 get_collection(krb5_context context,
490 const char *anchor_name,
491 const char *collection_name,
492 atomic_key_serial_t *pcollection_id)
494 krb5_error_code ret;
495 key_serial_t persistent_id, anchor_id, possess_id = 0;
496 char *ckname, *cnend;
497 uid_t uidnum;
499 heim_base_atomic_init(pcollection_id, 0);
501 if (strcmp(anchor_name, KRCC_PERSISTENT_ANCHOR) == 0) {
503 * The collection name is a uid (or empty for the current effective
504 * uid), and we look up a fixed keyring name within the persistent
505 * keyring for that uid. We link it to the process keyring to ensure
506 * that we have possession rights on the collection key.
508 if (*collection_name != '\0') {
509 errno = 0;
510 uidnum = (uid_t)strtol(collection_name, &cnend, 10);
511 if (errno || *cnend != '\0')
512 return KRB5_KCC_INVALID_UID;
513 } else {
514 uidnum = geteuid();
517 persistent_id = GET_PERSISTENT(uidnum);
518 if (persistent_id == -1)
519 return KRB5_KCC_INVALID_UID;
521 return find_or_create_keyring(persistent_id, KEY_SPEC_PROCESS_KEYRING,
522 KRCC_PERSISTENT_KEYRING_NAME,
523 pcollection_id);
526 if (strcmp(anchor_name, KRCC_PROCESS_ANCHOR) == 0) {
527 anchor_id = KEY_SPEC_PROCESS_KEYRING;
528 } else if (strcmp(anchor_name, KRCC_THREAD_ANCHOR) == 0) {
529 anchor_id = KEY_SPEC_THREAD_KEYRING;
530 } else if (strcmp(anchor_name, KRCC_SESSION_ANCHOR) == 0) {
531 anchor_id = session_write_anchor();
532 } else if (strcmp(anchor_name, KRCC_USER_ANCHOR) == 0) {
534 * The user keyring does not confer possession, so we need to link the
535 * collection to the process keyring to maintain possession rights.
537 anchor_id = KEY_SPEC_USER_KEYRING;
538 possess_id = KEY_SPEC_PROCESS_KEYRING;
539 } else if (strcmp(anchor_name, KRCC_LEGACY_ANCHOR) == 0) {
540 anchor_id = session_write_anchor();
541 } else {
542 return KRB5_KCC_INVALID_ANCHOR;
545 /* Look up the collection keyring name within the anchor keyring. */
546 if (asprintf(&ckname, "%s%s", KRCC_CCCOL_PREFIX, collection_name) == -1)
547 return krb5_enomem(context);
549 ret = find_or_create_keyring(anchor_id, possess_id, ckname,
550 pcollection_id);
551 free(ckname);
553 return ret;
556 /* Store subsidiary_name into the primary index key for collection_id. */
557 static krb5_error_code
558 set_primary_name(krb5_context context,
559 key_serial_t collection_id,
560 const char *subsidiary_name)
562 krb5_error_code ret;
563 krb5_storage *sp;
564 krb5_data payload;
565 key_serial_t key;
567 sp = krb5_storage_emem();
568 if (sp == NULL) {
569 krb5_set_error_message(context, KRB5_CC_NOMEM, N_("malloc: out of memory", ""));
570 return KRB5_CC_NOMEM;
572 krb5_storage_set_byteorder(sp, KRB5_STORAGE_BYTEORDER_BE);
574 ret = krb5_store_int32(sp, KRCC_COLLECTION_VERSION);
575 if (ret)
576 goto cleanup;
578 ret = krb5_store_string(sp, subsidiary_name);
579 if (ret)
580 goto cleanup;
582 ret = krb5_storage_to_data(sp, &payload);
583 if (ret)
584 goto cleanup;
586 key = add_key(KRCC_KEY_TYPE_USER, KRCC_COLLECTION_PRIMARY,
587 payload.data, payload.length, collection_id);
588 ret = (key == -1) ? errno : 0;
589 krb5_data_free(&payload);
591 cleanup:
592 krb5_storage_free(sp);
594 return ret;
597 static krb5_error_code
598 parse_index(krb5_context context,
599 int32_t *version,
600 char **primary,
601 const unsigned char *payload,
602 size_t psize)
604 krb5_error_code ret;
605 krb5_data payload_data;
606 krb5_storage *sp;
608 payload_data.length = psize;
609 payload_data.data = rk_UNCONST(payload);
611 sp = krb5_storage_from_data(&payload_data);
612 if (sp == NULL)
613 return KRB5_CC_NOMEM;
615 krb5_storage_set_byteorder(sp, KRB5_STORAGE_BYTEORDER_BE);
617 ret = krb5_ret_int32(sp, version);
618 if (ret == 0)
619 ret = krb5_ret_string(sp, primary);
621 krb5_storage_free(sp);
623 return ret;
627 * Get or initialize the primary name within collection_id and set
628 * *subsidiary to its value. If initializing a legacy collection, look
629 * for a legacy cache and add it to the collection.
631 static krb5_error_code
632 get_primary_name(krb5_context context,
633 const char *anchor_name,
634 const char *collection_name,
635 key_serial_t collection_id,
636 char **psubsidiary)
638 krb5_error_code ret;
639 key_serial_t primary_id, legacy;
640 void *payload = NULL;
641 int payloadlen;
642 int32_t version;
643 char *subsidiary_name = NULL;
645 *psubsidiary = NULL;
647 primary_id = keyctl_search(collection_id, KRCC_KEY_TYPE_USER,
648 KRCC_COLLECTION_PRIMARY, 0);
649 if (primary_id == -1) {
651 * Initialize the primary key using the collection name. We can't name
652 * a key with the empty string, so map that to an arbitrary string.
654 subsidiary_name = strdup((*collection_name == '\0') ? "tkt" :
655 collection_name);
656 if (subsidiary_name == NULL) {
657 ret = krb5_enomem(context);
658 goto cleanup;
661 ret = set_primary_name(context, collection_id, subsidiary_name);
662 if (ret)
663 goto cleanup;
665 if (strcmp(anchor_name, KRCC_LEGACY_ANCHOR) == 0) {
667 * Look for a cache created by old code. If we find one, add it to
668 * the collection.
670 legacy = keyctl_search(KEY_SPEC_SESSION_KEYRING,
671 KRCC_KEY_TYPE_KEYRING, subsidiary_name, 0);
672 if (legacy != -1 && keyctl_link(legacy, collection_id) == -1) {
673 ret = errno;
674 goto cleanup;
677 } else {
678 /* Read, parse, and free the primary key's payload. */
679 payloadlen = keyctl_read_alloc(primary_id, &payload);
680 if (payloadlen == -1) {
681 ret = errno;
682 goto cleanup;
684 ret = parse_index(context, &version, &subsidiary_name, payload,
685 payloadlen);
686 if (ret)
687 goto cleanup;
689 if (version != KRCC_COLLECTION_VERSION) {
690 ret = KRB5_KCC_UNKNOWN_VERSION;
691 goto cleanup;
695 *psubsidiary = subsidiary_name;
696 subsidiary_name = NULL;
698 cleanup:
699 free(payload);
700 free(subsidiary_name);
702 return ret;
706 * Note: MIT keyring code uses krb5int_random_string() as if the second argument
707 * is a character count rather than a size. The function below takes a character
708 * count to match the usage in this file correctly.
710 static krb5_error_code
711 generate_random_string(krb5_context context, char *s, size_t slen)
713 static char chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
714 char *p;
715 size_t i;
717 p = malloc(slen);
718 if (p == NULL)
719 return krb5_enomem(context);
721 krb5_generate_random_block(p, slen);
723 for (i = 0; i < slen; i++)
724 s[i] = chars[p[i] % (sizeof(chars) - 1)];
726 s[i] = '\0';
727 free(p);
729 return 0;
733 * Create a keyring with a unique random name within collection_id. Set
734 * *subsidiary to its name and *cache_id to its key serial number.
736 static krb5_error_code
737 add_unique_keyring(krb5_context context,
738 key_serial_t collection_id,
739 char **psubsidiary,
740 key_serial_t *pcache_id)
742 key_serial_t key;
743 krb5_error_code ret;
744 char uniquename[sizeof(KRCC_NAME_PREFIX) + KRCC_NAME_RAND_CHARS];
745 int prefixlen = sizeof(KRCC_NAME_PREFIX) - 1;
746 int tries;
748 *psubsidiary = NULL;
749 *pcache_id = 0;
751 memcpy(uniquename, KRCC_NAME_PREFIX, sizeof(KRCC_NAME_PREFIX));
753 for (key = -1, tries = 0; tries < 5; tries++) {
754 ret = generate_random_string(context, uniquename + prefixlen,
755 KRCC_NAME_RAND_CHARS);
756 if (ret)
757 return ret;
759 key = keyctl_search(collection_id, KRCC_KEY_TYPE_KEYRING, uniquename, 0);
760 if (key == -1) {
761 /* Name does not already exist. Create it to reserve the name. */
762 key = add_key(KRCC_KEY_TYPE_KEYRING, uniquename, NULL, 0, collection_id);
763 if (key == -1)
764 return errno;
765 break;
769 *psubsidiary = strdup(uniquename);
770 if (*psubsidiary == NULL)
771 return krb5_enomem(context);
773 *pcache_id = key;
775 return 0;
778 static krb5_error_code
779 add_cred_key(const char *name,
780 const void *payload,
781 size_t plen,
782 key_serial_t cache_id,
783 krb5_boolean legacy_type,
784 key_serial_t *pkey)
786 key_serial_t key;
788 *pkey = -1;
790 if (!legacy_type) {
791 /* Try the preferred cred key type; fall back if no kernel support. */
792 key = add_key(KRCC_CRED_KEY_TYPE, name, payload, plen, cache_id);
793 if (key != -1) {
794 *pkey = key;
795 return 0;
796 } else if (errno != EINVAL && errno != ENODEV)
797 return errno;
800 /* Use the user key type. */
801 key = add_key(KRCC_KEY_TYPE_USER, name, payload, plen, cache_id);
802 if (key == -1)
803 return errno;
805 *pkey = key;
807 return 0;
810 static void
811 update_keyring_expiration(krb5_context context,
812 krb5_ccache id,
813 key_serial_t cache_id,
814 krb5_timestamp now)
816 krb5_cc_cursor cursor;
817 krb5_creds creds;
818 krb5_timestamp endtime = 0;
819 unsigned int timeout;
822 * We have no way to know what is the actual timeout set on the keyring.
823 * We also cannot keep track of it in a local variable as another process
824 * can always modify the keyring independently, so just always enumerate
825 * all start TGT keys and find out the highest endtime time.
827 if (krcc_get_first(context, id, &cursor) != 0)
828 return;
830 for (;;) {
831 if (krcc_get_next(context, id, &cursor, &creds) != 0)
832 break;
833 if (creds.times.endtime > endtime)
834 endtime = creds.times.endtime;
835 krb5_free_cred_contents(context, &creds);
837 (void) krcc_end_get(context, id, &cursor);
839 if (endtime == 0) /* No creds with end times */
840 return;
843 * Setting the timeout to zero would reset the timeout, so we set it to one
844 * second instead if creds are already expired.
846 timeout = endtime > now ? endtime - now : 1;
847 (void) keyctl_set_timeout(cache_id, timeout);
851 * Create or overwrite the cache keyring, and set the default principal.
853 static krb5_error_code
854 initialize_internal(krb5_context context,
855 krb5_ccache id,
856 krb5_const_principal princ)
858 krb5_krcache *data = KRCACHE(id);
859 krb5_error_code ret;
860 const char *cache_name, *p;
861 krb5_krcache_and_princ_id ids;
863 if (data == NULL)
864 return krb5_einval(context, 2);
866 memset(&ids, 0, sizeof(ids));
867 ids.krcu_cache_and_princ_id = heim_base_atomic_load(&data->krc_cache_and_principal_id);
869 ret = clear_cache_keyring(context, &ids.krcu_cache_id);
870 if (ret)
871 return ret;
873 if (ids.krcu_cache_id == 0) {
875 * The key didn't exist at resolve time, or was destroyed after resolving.
876 * Check again and create the key if it still isn't there.
878 p = strrchr(data->krc_name, ':');
879 cache_name = (p != NULL) ? p + 1 : data->krc_name;
880 ret = find_or_create_keyring(data->krc_coll_id, 0, cache_name, &ids.krcu_cache_id);
881 if (ret)
882 return ret;
886 * If this is the legacy cache in a legacy session collection, link it
887 * directly to the session keyring so that old code can see it.
889 if (is_legacy_cache_name_p(data->krc_name))
890 (void) keyctl_link(ids.krcu_cache_id, session_write_anchor());
892 if (princ != NULL) {
893 ret = save_principal(context, ids.krcu_cache_id, princ, &ids.krcu_princ_id);
894 if (ret)
895 return ret;
896 } else
897 ids.krcu_princ_id = 0;
900 * Save time offset if it is valid and this is not a legacy cache. Legacy
901 * applications would fail to parse the new key in the cache keyring.
903 if (context->kdc_sec_offset && !is_legacy_cache_name_p(data->krc_name)) {
904 ret = save_time_offsets(context,
905 ids.krcu_cache_id,
906 context->kdc_sec_offset,
907 context->kdc_usec_offset);
908 if (ret)
909 return ret;
912 /* update cache and principal IDs atomically */
913 heim_base_atomic_store(&data->krc_cache_and_principal_id, ids.krcu_cache_and_princ_id);
915 return 0;
918 static krb5_error_code KRB5_CALLCONV
919 krcc_initialize(krb5_context context, krb5_ccache id, krb5_principal princ)
921 krb5_krcache *data = KRCACHE(id);
922 krb5_error_code ret;
924 if (data == NULL)
925 return krb5_einval(context, 2);
927 if (princ == NULL)
928 return KRB5_CC_BADNAME;
930 ret = initialize_internal(context, id, princ);
931 if (ret == 0)
932 update_change_time(context, 0, data);
934 return ret;
937 /* Release the ccache handle. */
938 static krb5_error_code KRB5_CALLCONV
939 krcc_close(krb5_context context, krb5_ccache id)
941 krb5_krcache *data = KRCACHE(id);
943 if (data == NULL)
944 return krb5_einval(context, 2);
946 free(data->krc_subsidiary);
947 free(data->krc_collection);
948 free(data->krc_name);
949 krb5_data_free(&id->data);
951 return 0;
955 * Clear out a ccache keyring, unlinking all keys within it.
957 static krb5_error_code
958 clear_cache_keyring(krb5_context context,
959 atomic_key_serial_t *pcache_id)
961 int res;
962 key_serial_t cache_id = heim_base_atomic_load(pcache_id);
964 _krb5_debug(context, 10, "clear_cache_keyring: cache_id %d\n", cache_id);
966 if (cache_id != 0) {
967 res = keyctl_clear(cache_id);
968 if (res == -1 && (errno == EACCES || errno == ENOKEY)) {
970 * Possibly the keyring was destroyed between krcc_resolve() and now;
971 * if we really don't have permission, we will fail later.
973 res = 0;
974 heim_base_atomic_store(pcache_id, 0);
976 if (res == -1)
977 return errno;
980 return 0;
983 /* Destroy the cache keyring */
984 static krb5_error_code KRB5_CALLCONV
985 krcc_destroy(krb5_context context, krb5_ccache id)
987 krb5_error_code ret = 0;
988 krb5_krcache *data = KRCACHE(id);
989 int res;
991 if (data == NULL)
992 return krb5_einval(context, 2);
994 /* no atomics, destroy is not thread-safe */
995 (void) clear_cache_keyring(context, &data->krc_cache_id);
997 if (data->krc_cache_id != 0) {
998 res = keyctl_unlink(data->krc_cache_id, data->krc_coll_id);
999 if (res < 0) {
1000 ret = errno;
1001 _krb5_debug(context, 10, "unlinking key %d from ring %d: %s",
1002 data->krc_cache_id, data->krc_coll_id, error_message(errno));
1004 /* If this is a legacy cache, unlink it from the session anchor. */
1005 if (is_legacy_cache_name_p(data->krc_name))
1006 (void) keyctl_unlink(data->krc_cache_id, session_write_anchor());
1009 heim_base_atomic_store(&data->krc_princ_id, 0);
1011 /* krcc_close is called by libkrb5, do not double-free */
1012 return ret;
1015 /* Create a cache handle for a cache ID. */
1016 static krb5_error_code
1017 make_cache(krb5_context context,
1018 key_serial_t collection_id,
1019 key_serial_t cache_id,
1020 const char *anchor_name,
1021 const char *collection_name,
1022 const char *subsidiary_name,
1023 krb5_ccache *cache)
1025 krb5_error_code ret;
1026 krb5_krcache *data;
1027 key_serial_t princ_id = 0;
1029 /* Determine the key containing principal information, if present. */
1030 princ_id = keyctl_search(cache_id, KRCC_KEY_TYPE_USER, KRCC_SPEC_PRINC_KEYNAME, 0);
1031 if (princ_id == -1)
1032 princ_id = 0;
1034 ret = alloc_cache(context, collection_id, cache_id,
1035 anchor_name, collection_name, subsidiary_name, &data);
1036 if (ret)
1037 return ret;
1039 if (*cache == NULL) {
1040 ret = _krb5_cc_allocate(context, &krb5_krcc_ops, cache);
1041 if (ret) {
1042 free(data->krc_name);
1043 free(data);
1044 return ret;
1048 data->krc_princ_id = princ_id;
1050 (*cache)->data.data = data;
1051 (*cache)->data.length = sizeof(*data);
1053 return 0;
1056 /* Create a keyring ccache handle for the given residual string. */
1057 static krb5_error_code KRB5_CALLCONV
1058 krcc_resolve_2(krb5_context context,
1059 krb5_ccache *id,
1060 const char *residual,
1061 const char *sub)
1063 krb5_error_code ret;
1064 atomic_key_serial_t collection_id;
1065 key_serial_t cache_id;
1066 char *anchor_name = NULL, *collection_name = NULL, *subsidiary_name = NULL;
1068 ret = parse_residual(context, residual, &anchor_name, &collection_name,
1069 &subsidiary_name);
1070 if (ret)
1071 goto cleanup;
1072 if (sub) {
1073 free(subsidiary_name);
1074 if ((subsidiary_name = strdup(sub)) == NULL) {
1075 ret = krb5_enomem(context);
1076 goto cleanup;
1080 ret = get_collection(context, anchor_name, collection_name, &collection_id);
1081 if (ret)
1082 goto cleanup;
1084 if (subsidiary_name == NULL) {
1085 /* Retrieve or initialize the primary name for the collection. */
1086 ret = get_primary_name(context, anchor_name, collection_name,
1087 collection_id, &subsidiary_name);
1088 if (ret)
1089 goto cleanup;
1092 /* Look up the cache keyring ID, if the cache is already initialized. */
1093 cache_id = keyctl_search(collection_id, KRCC_KEY_TYPE_KEYRING,
1094 subsidiary_name, 0);
1095 if (cache_id < 0)
1096 cache_id = 0;
1098 ret = make_cache(context, collection_id, cache_id, anchor_name,
1099 collection_name, subsidiary_name, id);
1100 if (ret)
1101 goto cleanup;
1103 cleanup:
1104 free(anchor_name);
1105 free(collection_name);
1106 free(subsidiary_name);
1108 return ret;
1111 struct krcc_cursor {
1112 size_t numkeys;
1113 size_t currkey;
1114 key_serial_t princ_id;
1115 key_serial_t offsets_id;
1116 key_serial_t *keys;
1119 /* Prepare for a sequential iteration over the cache keyring. */
1120 static krb5_error_code
1121 krcc_get_first(krb5_context context,
1122 krb5_ccache id,
1123 krb5_cc_cursor *cursor)
1125 struct krcc_cursor *krcursor;
1126 krb5_krcache *data = KRCACHE(id);
1127 key_serial_t cache_id;
1128 void *keys;
1129 long size;
1131 if (data == NULL)
1132 return krb5_einval(context, 2);
1134 cache_id = heim_base_atomic_load(&data->krc_cache_id);
1135 if (cache_id == 0)
1136 return KRB5_FCC_NOFILE;
1138 size = keyctl_read_alloc(cache_id, &keys);
1139 if (size == -1) {
1140 _krb5_debug(context, 10, "Error getting from keyring: %s\n",
1141 strerror(errno));
1142 return KRB5_CC_IO;
1145 krcursor = calloc(1, sizeof(*krcursor));
1146 if (krcursor == NULL) {
1147 free(keys);
1148 return KRB5_CC_NOMEM;
1151 krcursor->princ_id = heim_base_atomic_load(&data->krc_princ_id);
1152 krcursor->offsets_id = keyctl_search(cache_id, KRCC_KEY_TYPE_USER,
1153 KRCC_TIME_OFFSETS, 0);
1154 krcursor->numkeys = size / sizeof(key_serial_t);
1155 krcursor->keys = keys;
1157 *cursor = krcursor;
1159 return 0;
1162 static krb5_error_code
1163 keyctl_read_krb5_data(key_serial_t keyid, krb5_data *payload)
1165 krb5_data_zero(payload);
1167 payload->length = keyctl_read_alloc(keyid, &payload->data);
1169 return (payload->length == -1) ? KRB5_FCC_NOFILE : 0;
1172 /* Get the next credential from the cache keyring. */
1173 static krb5_error_code KRB5_CALLCONV
1174 krcc_get_next(krb5_context context,
1175 krb5_ccache id,
1176 krb5_cc_cursor *cursor,
1177 krb5_creds *creds)
1179 struct krcc_cursor *krcursor;
1180 krb5_error_code ret;
1181 krb5_data payload;
1182 krb5_storage *sp;
1184 memset(creds, 0, sizeof(krb5_creds));
1186 krcursor = *cursor;
1187 if (krcursor == NULL)
1188 return KRB5_CC_END;
1190 if (krcursor->currkey >= krcursor->numkeys)
1191 return KRB5_CC_END;
1194 * If we're pointing at the entry with the principal, or at the key
1195 * with the time offsets, skip it.
1197 while (krcursor->keys[krcursor->currkey] == krcursor->princ_id ||
1198 krcursor->keys[krcursor->currkey] == krcursor->offsets_id) {
1199 krcursor->currkey++;
1200 if (krcursor->currkey >= krcursor->numkeys)
1201 return KRB5_CC_END;
1204 ret = keyctl_read_krb5_data(krcursor->keys[krcursor->currkey], &payload);
1205 if (ret) {
1206 _krb5_debug(context, 10, "Error reading key %d: %s\n",
1207 krcursor->keys[krcursor->currkey],
1208 strerror(errno));
1209 return ret;
1211 krcursor->currkey++;
1213 sp = krb5_storage_from_data(&payload);
1214 if (sp == NULL) {
1215 ret = KRB5_CC_IO;
1216 } else {
1217 ret = krb5_ret_creds(sp, creds);
1218 krb5_storage_free(sp);
1221 krb5_data_free(&payload);
1223 return ret;
1226 /* Release an iteration cursor. */
1227 static krb5_error_code KRB5_CALLCONV
1228 krcc_end_get(krb5_context context, krb5_ccache id, krb5_cc_cursor *cursor)
1230 struct krcc_cursor *krcursor = *cursor;
1232 if (krcursor != NULL) {
1233 free(krcursor->keys);
1234 free(krcursor);
1237 *cursor = NULL;
1239 return 0;
1242 /* Create keyring data for a credential cache. */
1243 static krb5_error_code
1244 alloc_cache(krb5_context context,
1245 key_serial_t collection_id,
1246 key_serial_t cache_id,
1247 const char *anchor_name,
1248 const char *collection_name,
1249 const char *subsidiary_name,
1250 krb5_krcache **pdata)
1252 krb5_error_code ret;
1253 krb5_krcache *data;
1255 *pdata = NULL;
1257 data = calloc(1, sizeof(*data));
1258 if (data == NULL)
1259 return KRB5_CC_NOMEM;
1261 ret = make_subsidiary_residual(context, anchor_name, collection_name,
1262 subsidiary_name, &data->krc_name);
1263 if (ret ||
1264 (data->krc_collection = strdup(collection_name)) == NULL ||
1265 (data->krc_subsidiary = strdup(subsidiary_name)) == NULL) {
1266 if (data) {
1267 free(data->krc_collection);
1268 free(data->krc_name);
1270 free(data);
1271 if (ret == 0)
1272 ret = krb5_enomem(context);
1273 return ret;
1276 heim_base_atomic_init(&data->krc_princ_id, 0);
1277 heim_base_atomic_init(&data->krc_cache_id, cache_id);
1278 data->krc_coll_id = collection_id;
1279 data->krc_changetime = 0;
1280 data->krc_is_legacy = (strcmp(anchor_name, KRCC_LEGACY_ANCHOR) == 0);
1282 update_change_time(context, 0, data);
1284 *pdata = data;
1286 return 0;
1289 /* Create a new keyring cache with a unique name. */
1290 static krb5_error_code KRB5_CALLCONV
1291 krcc_gen_new(krb5_context context, krb5_ccache *id)
1293 krb5_error_code ret;
1294 char *anchor_name, *collection_name, *subsidiary_name;
1295 char *new_subsidiary_name = NULL, *new_residual = NULL;
1296 krb5_krcache *data;
1297 atomic_key_serial_t collection_id;
1298 key_serial_t cache_id = 0;
1300 /* Determine the collection in which we will create the cache.*/
1301 ret = get_default(context, &anchor_name, &collection_name,
1302 &subsidiary_name);
1303 if (ret)
1304 return ret;
1306 if (anchor_name == NULL) {
1307 ret = parse_residual(context, KRCC_DEFAULT_UNIQUE_COLLECTION, &anchor_name,
1308 &collection_name, &subsidiary_name);
1309 if (ret)
1310 return ret;
1312 if (subsidiary_name != NULL) {
1313 krb5_set_error_message(context, KRB5_DCC_CANNOT_CREATE,
1314 N_("Can't create new subsidiary cache because default cache "
1315 "is already a subsidiary", ""));
1316 ret = KRB5_DCC_CANNOT_CREATE;
1317 goto cleanup;
1320 /* Make a unique keyring within the chosen collection. */
1321 ret = get_collection(context, anchor_name, collection_name, &collection_id);
1322 if (ret)
1323 goto cleanup;
1325 ret = add_unique_keyring(context, collection_id, &new_subsidiary_name, &cache_id);
1326 if (ret)
1327 goto cleanup;
1329 ret = alloc_cache(context, collection_id, cache_id,
1330 anchor_name, collection_name, new_subsidiary_name,
1331 &data);
1332 if (ret)
1333 goto cleanup;
1335 (*id)->data.data = data;
1336 (*id)->data.length = sizeof(*data);
1338 cleanup:
1339 free(anchor_name);
1340 free(collection_name);
1341 free(subsidiary_name);
1342 free(new_subsidiary_name);
1343 free(new_residual);
1345 return ret;
1348 /* Return an alias to the residual string of the cache. */
1349 static krb5_error_code KRB5_CALLCONV
1350 krcc_get_name_2(krb5_context context,
1351 krb5_ccache id,
1352 const char **name,
1353 const char **collection_name,
1354 const char **subsidiary_name)
1356 krb5_krcache *data = KRCACHE(id);
1358 if (data == NULL)
1359 return krb5_einval(context, 2);
1361 if (name)
1362 *name = data->krc_name;
1363 if (collection_name)
1364 *collection_name = data->krc_collection;
1365 if (subsidiary_name)
1366 *subsidiary_name = data->krc_subsidiary;
1367 return 0;
1370 /* Retrieve a copy of the default principal, if the cache is initialized. */
1371 static krb5_error_code KRB5_CALLCONV
1372 krcc_get_principal(krb5_context context,
1373 krb5_ccache id,
1374 krb5_principal *princ)
1376 krb5_krcache *data = KRCACHE(id);
1377 krb5_error_code ret;
1378 krb5_storage *sp = NULL;
1379 krb5_data payload;
1380 krb5_krcache_and_princ_id ids;
1382 krb5_data_zero(&payload);
1383 *princ = NULL;
1385 if (data == NULL)
1386 return krb5_einval(context, 2);
1388 memset(&ids, 0, sizeof(ids));
1389 ids.krcu_cache_and_princ_id = heim_base_atomic_load(&data->krc_cache_and_principal_id);
1390 if (ids.krcu_cache_id == 0 || ids.krcu_princ_id == 0) {
1391 ret = KRB5_FCC_NOFILE;
1392 krb5_set_error_message(context, ret,
1393 N_("Credentials cache keyring '%s' not found", ""),
1394 data->krc_name);
1395 goto cleanup;
1398 ret = keyctl_read_krb5_data(ids.krcu_princ_id, &payload);
1399 if (ret) {
1400 _krb5_debug(context, 10, "Reading principal key %d: %s\n",
1401 ids.krcu_princ_id, strerror(errno));
1402 goto cleanup;
1405 sp = krb5_storage_from_data(&payload);
1406 if (sp == NULL) {
1407 ret = KRB5_CC_IO;
1408 goto cleanup;
1411 ret = krb5_ret_principal(sp, princ);
1412 if (ret)
1413 goto cleanup;
1415 cleanup:
1416 krb5_storage_free(sp);
1417 krb5_data_free(&payload);
1419 return ret;
1422 /* Remove a cred from the cache keyring */
1423 static krb5_error_code KRB5_CALLCONV
1424 krcc_remove_cred(krb5_context context, krb5_ccache id,
1425 krb5_flags which, krb5_creds *mcred)
1427 krb5_krcache *data = KRCACHE(id);
1428 krb5_error_code ret, ret2;
1429 krb5_cc_cursor cursor;
1430 krb5_creds found_cred;
1431 krb5_krcache_and_princ_id ids;
1433 if (data == NULL)
1434 return krb5_einval(context, 2);
1436 ret = krcc_get_first(context, id, &cursor);
1437 if (ret)
1438 return ret;
1440 memset(&ids, 0, sizeof(ids));
1441 ids.krcu_cache_and_princ_id = heim_base_atomic_load(&data->krc_cache_and_principal_id);
1443 while ((ret = krcc_get_next(context, id, &cursor, &found_cred)) == 0) {
1444 struct krcc_cursor *krcursor = cursor;
1446 if (!krb5_compare_creds(context, which, mcred, &found_cred)) {
1447 krb5_free_cred_contents(context, &found_cred);
1448 continue;
1451 _krb5_debug(context, 10, "Removing cred %d from cache_id %d, princ_id %d\n",
1452 krcursor->keys[krcursor->currkey - 1],
1453 ids.krcu_cache_id, ids.krcu_princ_id);
1455 keyctl_invalidate(krcursor->keys[krcursor->currkey - 1]);
1456 krcursor->keys[krcursor->currkey - 1] = 0;
1457 krb5_free_cred_contents(context, &found_cred);
1460 ret2 = krcc_end_get(context, id, &cursor);
1461 if (ret == KRB5_CC_END)
1462 ret = ret2;
1464 return ret;
1467 /* Set flags on the cache. (We don't care about any flags.) */
1468 static krb5_error_code KRB5_CALLCONV
1469 krcc_set_flags(krb5_context context, krb5_ccache id, krb5_flags flags)
1471 return 0;
1474 static int KRB5_CALLCONV
1475 krcc_get_version(krb5_context context, krb5_ccache id)
1477 return 0;
1480 /* Store a credential in the cache keyring. */
1481 static krb5_error_code KRB5_CALLCONV
1482 krcc_store(krb5_context context, krb5_ccache id, krb5_creds *creds)
1484 krb5_error_code ret;
1485 krb5_krcache *data = KRCACHE(id);
1486 krb5_storage *sp = NULL;
1487 char *keyname = NULL;
1488 key_serial_t cred_key, cache_id;
1489 krb5_timestamp now;
1490 krb5_data payload;
1492 krb5_data_zero(&payload);
1494 if (data == NULL)
1495 return krb5_einval(context, 2);
1497 cache_id = heim_base_atomic_load(&data->krc_cache_id);
1498 if (cache_id == 0)
1499 return KRB5_FCC_NOFILE;
1501 ret = krb5_unparse_name(context, creds->server, &keyname);
1502 if (ret)
1503 goto cleanup;
1505 sp = krb5_storage_emem();
1506 if (sp == NULL) {
1507 krb5_set_error_message(context, KRB5_CC_NOMEM, N_("malloc: out of memory", ""));
1508 ret = KRB5_CC_NOMEM;
1509 goto cleanup;
1512 ret = krb5_store_creds(sp, creds);
1513 if (ret)
1514 goto cleanup;
1516 ret = krb5_storage_to_data(sp, &payload);
1517 if (ret)
1518 goto cleanup;
1520 _krb5_debug(context, 10, "krcc_store: adding new key '%s' to keyring %d\n",
1521 keyname, cache_id);
1522 ret = add_cred_key(keyname, payload.data, payload.length, cache_id,
1523 data->krc_is_legacy, &cred_key);
1524 if (ret)
1525 goto cleanup;
1527 ret = krb5_timeofday(context, &now);
1528 if (ret)
1529 goto cleanup;
1531 update_change_time(context, now, data);
1533 /* Set timeout on credential key */
1534 if (creds->times.endtime > now)
1535 (void) keyctl_set_timeout(cred_key, creds->times.endtime - now);
1537 /* Set timeout on credential cache keyring */
1538 update_keyring_expiration(context, id, cache_id, now);
1540 cleanup:
1541 krb5_data_free(&payload);
1542 krb5_storage_free(sp);
1543 krb5_xfree(keyname);
1545 return ret;
1549 * Get the cache's last modification time. (This is currently broken; it
1550 * returns only the last change made using this handle.)
1552 static krb5_error_code KRB5_CALLCONV
1553 krcc_lastchange(krb5_context context,
1554 krb5_ccache id,
1555 krb5_timestamp *change_time)
1557 krb5_krcache *data = KRCACHE(id);
1559 if (data == NULL)
1560 return krb5_einval(context, 2);
1562 *change_time = heim_base_atomic_load(&data->krc_changetime);
1564 return 0;
1567 static krb5_error_code
1568 save_principal(krb5_context context,
1569 key_serial_t cache_id,
1570 krb5_const_principal princ,
1571 atomic_key_serial_t *pprinc_id)
1573 krb5_error_code ret;
1574 krb5_storage *sp;
1575 key_serial_t newkey;
1576 krb5_data payload;
1578 krb5_data_zero(&payload);
1580 sp = krb5_storage_emem();
1581 if (sp == NULL) {
1582 krb5_set_error_message(context, KRB5_CC_NOMEM, N_("malloc: out of memory", ""));
1583 return KRB5_CC_NOMEM;
1586 ret = krb5_store_principal(sp, princ);
1587 if (ret) {
1588 krb5_storage_free(sp);
1589 return ret;
1592 ret = krb5_storage_to_data(sp, &payload);
1593 if (ret) {
1594 krb5_storage_free(sp);
1595 return ret;
1598 krb5_storage_free(sp);
1600 krb5_error_code tmp;
1601 char *princname = NULL;
1603 tmp = krb5_unparse_name(context, princ, &princname);
1604 _krb5_debug(context, 10, "save_principal: adding new key '%s' "
1605 "to keyring %d for principal '%s'\n",
1606 KRCC_SPEC_PRINC_KEYNAME, cache_id,
1607 tmp ? "<unknown>" : princname);
1608 if (tmp == 0)
1609 krb5_xfree(princname);
1612 /* Add new key into keyring */
1613 newkey = add_key(KRCC_KEY_TYPE_USER, KRCC_SPEC_PRINC_KEYNAME,
1614 payload.data, payload.length, cache_id);
1615 if (newkey == -1) {
1616 ret = errno;
1617 _krb5_debug(context, 10, "Error adding principal key: %s\n", strerror(ret));
1618 } else {
1619 ret = 0;
1620 heim_base_atomic_store(pprinc_id, newkey);
1623 krb5_data_free(&payload);
1625 return ret;
1628 /* Add a key to the cache keyring containing the given time offsets. */
1629 static krb5_error_code
1630 save_time_offsets(krb5_context context,
1631 key_serial_t cache_id,
1632 int32_t sec_offset,
1633 int32_t usec_offset)
1635 krb5_error_code ret;
1636 key_serial_t newkey;
1637 krb5_storage *sp;
1638 krb5_data payload;
1640 krb5_data_zero(&payload);
1642 sp = krb5_storage_emem();
1643 if (sp == NULL) {
1644 krb5_set_error_message(context, KRB5_CC_NOMEM, N_("malloc: out of memory", ""));
1645 return KRB5_CC_NOMEM;
1648 krb5_storage_set_byteorder(sp, KRB5_STORAGE_BYTEORDER_BE);
1650 ret = krb5_store_int32(sp, sec_offset);
1651 if (ret == 0)
1652 ret = krb5_store_int32(sp, usec_offset);
1653 if (ret) {
1654 krb5_storage_free(sp);
1655 return ret;
1658 ret = krb5_storage_to_data(sp, &payload);
1659 if (ret) {
1660 krb5_storage_free(sp);
1661 return ret;
1664 krb5_storage_free(sp);
1666 newkey = add_key(KRCC_KEY_TYPE_USER, KRCC_TIME_OFFSETS, payload.data,
1667 payload.length, cache_id);
1668 ret = newkey == -1 ? errno : 0;
1670 krb5_data_free(&payload);
1672 return ret;
1675 static krb5_error_code KRB5_CALLCONV
1676 krcc_set_kdc_offset(krb5_context context, krb5_ccache id, krb5_deltat offset)
1678 krb5_krcache *data = KRCACHE(id);
1679 key_serial_t cache_id;
1680 krb5_error_code ret;
1682 if (data == NULL)
1683 return krb5_einval(context, 2);
1685 cache_id = heim_base_atomic_load(&data->krc_cache_id);
1687 ret = save_time_offsets(context, cache_id, (int32_t)offset, 0);
1688 if (ret == 0)
1689 update_change_time(context, 0, data);
1691 return ret;
1694 /* Retrieve and parse the key in the cache keyring containing time offsets. */
1695 static krb5_error_code KRB5_CALLCONV
1696 krcc_get_kdc_offset(krb5_context context,
1697 krb5_ccache id,
1698 krb5_deltat *offset)
1700 krb5_krcache *data = KRCACHE(id);
1701 krb5_error_code ret = 0;
1702 key_serial_t key, cache_id;
1703 krb5_storage *sp = NULL;
1704 krb5_data payload;
1705 int32_t sec_offset, usec_offset;
1707 if (data == NULL)
1708 return krb5_einval(context, 2);
1710 krb5_data_zero(&payload);
1712 cache_id = heim_base_atomic_load(&data->krc_cache_id);
1713 if (cache_id == 0) {
1714 ret = KRB5_FCC_NOFILE;
1715 goto cleanup;
1718 key = keyctl_search(cache_id, KRCC_KEY_TYPE_USER, KRCC_TIME_OFFSETS, 0);
1719 if (key == -1) {
1720 ret = ENOENT;
1721 goto cleanup;
1724 ret = keyctl_read_krb5_data(key, &payload);
1725 if (ret) {
1726 _krb5_debug(context, 10, "Reading time offsets key %d: %s\n",
1727 key, strerror(errno));
1728 goto cleanup;
1731 sp = krb5_storage_from_data(&payload);
1732 if (sp == NULL) {
1733 ret = KRB5_CC_IO;
1734 goto cleanup;
1737 krb5_storage_set_byteorder(sp, KRB5_STORAGE_BYTEORDER_BE);
1739 ret = krb5_ret_int32(sp, &sec_offset);
1740 if (ret == 0)
1741 krb5_ret_int32(sp, &usec_offset);
1742 if (ret) {
1743 ret = KRB5_CC_END;
1744 goto cleanup;
1747 *offset = sec_offset;
1749 cleanup:
1750 krb5_storage_free(sp);
1751 krb5_data_free(&payload);
1753 return ret;
1756 struct krcc_iter {
1757 atomic_key_serial_t collection_id;
1758 char *anchor_name;
1759 char *collection_name;
1760 char *subsidiary_name;
1761 char *primary_name;
1762 krb5_boolean first;
1763 long num_keys;
1764 long next_key;
1765 key_serial_t *keys;
1768 static krb5_error_code KRB5_CALLCONV
1769 krcc_get_cache_first(krb5_context context, krb5_cc_cursor *cursor)
1771 struct krcc_iter *iter;
1772 krb5_error_code ret;
1773 void *keys;
1774 long size;
1776 *cursor = NULL;
1778 iter = calloc(1, sizeof(*iter));
1779 if (iter == NULL) {
1780 ret = krb5_enomem(context);
1781 goto error;
1783 iter->first = TRUE;
1785 ret = get_default(context, &iter->anchor_name, &iter->collection_name,
1786 &iter->subsidiary_name);
1787 if (ret)
1788 goto error;
1790 /* If there is no default collection, return an empty cursor. */
1791 if (iter->anchor_name == NULL) {
1792 *cursor = iter;
1793 return 0;
1796 ret = get_collection(context, iter->anchor_name, iter->collection_name,
1797 &iter->collection_id);
1798 if (ret)
1799 goto error;
1801 if (iter->subsidiary_name == NULL) {
1802 ret = get_primary_name(context, iter->anchor_name,
1803 iter->collection_name, iter->collection_id,
1804 &iter->primary_name);
1805 if (ret)
1806 goto error;
1808 size = keyctl_read_alloc(iter->collection_id, &keys);
1809 if (size == -1) {
1810 ret = errno;
1811 goto error;
1813 iter->keys = keys;
1814 iter->num_keys = size / sizeof(key_serial_t);
1817 *cursor = iter;
1819 return 0;
1821 error:
1822 krcc_end_cache_get(context, iter);
1824 return ret;
1827 static krb5_error_code KRB5_CALLCONV
1828 krcc_get_cache_next(krb5_context context,
1829 krb5_cc_cursor cursor,
1830 krb5_ccache *cache)
1832 krb5_error_code ret;
1833 struct krcc_iter *iter = cursor;
1834 key_serial_t key, cache_id = 0;
1835 const char *first_name, *keytype, *sep, *subsidiary_name;
1836 size_t keytypelen;
1837 char *description = NULL;
1839 *cache = NULL;
1841 /* No keyring available */
1842 if (iter->collection_id == 0)
1843 return KRB5_CC_END;
1845 if (iter->first) {
1847 * Look for the primary cache for a collection cursor, or the
1848 * subsidiary cache for a subsidiary cursor.
1850 iter->first = FALSE;
1851 first_name = (iter->primary_name != NULL) ? iter->primary_name :
1852 iter->subsidiary_name;
1853 cache_id = keyctl_search(iter->collection_id, KRCC_KEY_TYPE_KEYRING,
1854 first_name, 0);
1855 if (cache_id != -1) {
1856 return make_cache(context, iter->collection_id, cache_id,
1857 iter->anchor_name, iter->collection_name,
1858 first_name, cache);
1862 /* A subsidiary cursor yields at most the first cache. */
1863 if (iter->subsidiary_name != NULL)
1864 return KRB5_CC_END;
1866 keytype = KRCC_KEY_TYPE_KEYRING ";";
1867 keytypelen = strlen(keytype);
1869 for (ret = KRB5_CC_END; iter->next_key < iter->num_keys; iter->next_key++) {
1870 free(description);
1871 description = NULL;
1874 * Get the key description, which should have the form:
1875 * typename;UID;GID;permissions;description
1877 key = iter->keys[iter->next_key];
1878 if (keyctl_describe_alloc(key, &description) < 0)
1879 continue;
1880 sep = strrchr(description, ';');
1881 if (sep == NULL)
1882 continue;
1883 subsidiary_name = sep + 1;
1885 /* Skip this key if it isn't a keyring. */
1886 if (strncmp(description, keytype, keytypelen) != 0)
1887 continue;
1889 /* Don't repeat the primary cache. */
1890 if (strcmp(subsidiary_name, iter->primary_name) == 0)
1891 continue;
1893 /* We found a valid key */
1894 iter->next_key++;
1895 ret = make_cache(context, iter->collection_id, key, iter->anchor_name,
1896 iter->collection_name, subsidiary_name, cache);
1897 break;
1900 free(description);
1902 return ret;
1905 static krb5_error_code KRB5_CALLCONV
1906 krcc_end_cache_get(krb5_context context, krb5_cc_cursor cursor)
1908 struct krcc_iter *iter = cursor;
1910 if (iter != NULL) {
1911 free(iter->anchor_name);
1912 free(iter->collection_name);
1913 free(iter->subsidiary_name);
1914 free(iter->primary_name);
1915 free(iter->keys);
1917 memset(iter, 0, sizeof(*iter));
1918 free(iter);
1921 return 0;
1924 static krb5_error_code KRB5_CALLCONV
1925 krcc_set_default(krb5_context context, krb5_ccache id)
1927 krb5_krcache *data = KRCACHE(id);
1928 krb5_error_code ret;
1929 char *anchor_name, *collection_name, *subsidiary_name;
1930 atomic_key_serial_t collection_id;
1932 if (data == NULL)
1933 return krb5_einval(context, 2);
1935 ret = parse_residual(context, data->krc_name,
1936 &anchor_name, &collection_name, &subsidiary_name);
1937 if (ret)
1938 goto cleanup;
1940 ret = get_collection(context, anchor_name, collection_name, &collection_id);
1941 if (ret)
1942 goto cleanup;
1944 ret = set_primary_name(context, collection_id, subsidiary_name);
1945 if (ret)
1946 goto cleanup;
1948 cleanup:
1949 free(anchor_name);
1950 free(collection_name);
1951 free(subsidiary_name);
1953 return ret;
1957 * Utility routine: called by krcc_* functions to keep
1958 * result of krcc_last_change_time up to date.
1960 static void
1961 update_change_time(krb5_context context, krb5_timestamp now, krb5_krcache *data)
1963 krb5_timestamp old;
1965 if (now == 0)
1966 krb5_timeofday(context, &now);
1968 old = heim_base_exchange_time_t(&data->krc_changetime, now);
1969 if (old > now) /* don't go backwards */
1970 heim_base_atomic_store(&data->krc_changetime, old + 1);
1973 static int
1974 move_key_to_new_keyring(key_serial_t parent, key_serial_t key,
1975 char *desc, int desc_len, void *data)
1977 key_serial_t cache_id = *(key_serial_t *)data;
1979 if (parent) {
1980 if (keyctl_link(key, cache_id) == -1 ||
1981 keyctl_unlink(key, parent) == -1)
1982 return -1;
1985 return 0;
1988 /* Move contents of one ccache to another; destroys from cache */
1989 static krb5_error_code KRB5_CALLCONV
1990 krcc_move(krb5_context context, krb5_ccache from, krb5_ccache to)
1992 krb5_krcache *krfrom = KRCACHE(from);
1993 krb5_krcache *krto = KRCACHE(to);
1994 krb5_error_code ret;
1995 krb5_timestamp now;
1996 key_serial_t to_cache_id;
1998 if (krfrom == NULL || krto == NULL)
1999 return krb5_einval(context, 2);
2001 ret = initialize_internal(context, to, NULL);
2002 if (ret)
2003 return ret;
2005 krb5_timeofday(context, &now);
2006 to_cache_id = heim_base_atomic_load(&krto->krc_cache_id);
2008 if (krfrom->krc_cache_id != 0) {
2009 ret = recursive_key_scan(krfrom->krc_cache_id,
2010 move_key_to_new_keyring, &to_cache_id);
2011 if (ret)
2012 return KRB5_CC_IO;
2014 if (keyctl_unlink(krfrom->krc_cache_id, krfrom->krc_coll_id) == -1)
2015 return errno;
2017 heim_base_exchange_32(&krto->krc_princ_id, krfrom->krc_princ_id);
2020 update_change_time(context, now, krto);
2021 krb5_cc_destroy(context, from);
2022 return 0;
2025 static krb5_error_code KRB5_CALLCONV
2026 krcc_get_default_name(krb5_context context, char **str)
2028 *str = strdup("KEYRING:");
2029 if (*str == NULL)
2030 return krb5_enomem(context);
2032 return 0;
2036 * ccache implementation storing credentials in the Linux keyring facility
2037 * The default is to put them at the session keyring level.
2038 * If "KEYRING:process:" or "KEYRING:thread:" is specified, then they will
2039 * be stored at the process or thread level respectively.
2041 KRB5_LIB_VARIABLE const krb5_cc_ops krb5_krcc_ops = {
2042 KRB5_CC_OPS_VERSION_5,
2043 "KEYRING",
2044 NULL,
2045 NULL,
2046 krcc_gen_new,
2047 krcc_initialize,
2048 krcc_destroy,
2049 krcc_close,
2050 krcc_store,
2051 NULL, /* retrieve */
2052 krcc_get_principal,
2053 krcc_get_first,
2054 krcc_get_next,
2055 krcc_end_get,
2056 krcc_remove_cred,
2057 krcc_set_flags,
2058 krcc_get_version,
2059 krcc_get_cache_first,
2060 krcc_get_cache_next,
2061 krcc_end_cache_get,
2062 krcc_move,
2063 krcc_get_default_name,
2064 krcc_set_default,
2065 krcc_lastchange,
2066 krcc_set_kdc_offset,
2067 krcc_get_kdc_offset,
2068 krcc_get_name_2,
2069 krcc_resolve_2
2072 #endif /* HAVE_KEYUTILS_H */