keys: Cache the hash value to avoid lots of recalculation
[linux-block.git] / security / keys / keyring.c
CommitLineData
69664cf1 1/* Keyring handling
1da177e4 2 *
b2a4df20 3 * Copyright (C) 2004-2005, 2008, 2013 Red Hat, Inc. All Rights Reserved.
1da177e4
LT
4 * Written by David Howells (dhowells@redhat.com)
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 */
11
876979c9 12#include <linux/export.h>
1da177e4
LT
13#include <linux/init.h>
14#include <linux/sched.h>
15#include <linux/slab.h>
29db9190 16#include <linux/security.h>
1da177e4
LT
17#include <linux/seq_file.h>
18#include <linux/err.h>
e9e349b0 19#include <keys/keyring-type.h>
b2a4df20
DH
20#include <keys/user-type.h>
21#include <linux/assoc_array_priv.h>
512ea3bc 22#include <linux/uaccess.h>
1da177e4
LT
23#include "internal.h"
24
25/*
973c9f4f
DH
26 * When plumbing the depths of the key tree, this sets a hard limit
27 * set on how deep we're willing to go.
1da177e4
LT
28 */
29#define KEYRING_SEARCH_MAX_DEPTH 6
30
31/*
973c9f4f 32 * We keep all named keyrings in a hash to speed looking them up.
1da177e4
LT
33 */
34#define KEYRING_NAME_HASH_SIZE (1 << 5)
35
b2a4df20
DH
36/*
37 * We mark pointers we pass to the associative array with bit 1 set if
38 * they're keyrings and clear otherwise.
39 */
40#define KEYRING_PTR_SUBTYPE 0x2UL
41
42static inline bool keyring_ptr_is_keyring(const struct assoc_array_ptr *x)
43{
44 return (unsigned long)x & KEYRING_PTR_SUBTYPE;
45}
46static inline struct key *keyring_ptr_to_key(const struct assoc_array_ptr *x)
47{
48 void *object = assoc_array_ptr_to_leaf(x);
49 return (struct key *)((unsigned long)object & ~KEYRING_PTR_SUBTYPE);
50}
51static inline void *keyring_key_to_ptr(struct key *key)
52{
53 if (key->type == &key_type_keyring)
54 return (void *)((unsigned long)key | KEYRING_PTR_SUBTYPE);
55 return key;
56}
57
1da177e4
LT
58static struct list_head keyring_name_hash[KEYRING_NAME_HASH_SIZE];
59static DEFINE_RWLOCK(keyring_name_lock);
60
61static inline unsigned keyring_hash(const char *desc)
62{
63 unsigned bucket = 0;
64
65 for (; *desc; desc++)
c5b60b5e 66 bucket += (unsigned char)*desc;
1da177e4
LT
67
68 return bucket & (KEYRING_NAME_HASH_SIZE - 1);
69}
70
71/*
973c9f4f
DH
72 * The keyring key type definition. Keyrings are simply keys of this type and
73 * can be treated as ordinary keys in addition to having their own special
74 * operations.
1da177e4 75 */
5d19e20b
DH
76static int keyring_preparse(struct key_preparsed_payload *prep);
77static void keyring_free_preparse(struct key_preparsed_payload *prep);
1da177e4 78static int keyring_instantiate(struct key *keyring,
cf7f601c 79 struct key_preparsed_payload *prep);
31204ed9 80static void keyring_revoke(struct key *keyring);
1da177e4
LT
81static void keyring_destroy(struct key *keyring);
82static void keyring_describe(const struct key *keyring, struct seq_file *m);
83static long keyring_read(const struct key *keyring,
84 char __user *buffer, size_t buflen);
85
86struct key_type key_type_keyring = {
87 .name = "keyring",
b2a4df20 88 .def_datalen = 0,
5d19e20b
DH
89 .preparse = keyring_preparse,
90 .free_preparse = keyring_free_preparse,
1da177e4 91 .instantiate = keyring_instantiate,
31204ed9 92 .revoke = keyring_revoke,
1da177e4
LT
93 .destroy = keyring_destroy,
94 .describe = keyring_describe,
95 .read = keyring_read,
96};
7318226e
DH
97EXPORT_SYMBOL(key_type_keyring);
98
1da177e4 99/*
973c9f4f
DH
100 * Semaphore to serialise link/link calls to prevent two link calls in parallel
101 * introducing a cycle.
1da177e4 102 */
3be59f74 103static DEFINE_MUTEX(keyring_serialise_link_lock);
1da177e4 104
1da177e4 105/*
973c9f4f
DH
106 * Publish the name of a keyring so that it can be found by name (if it has
107 * one).
1da177e4 108 */
69664cf1 109static void keyring_publish_name(struct key *keyring)
1da177e4
LT
110{
111 int bucket;
112
113 if (keyring->description) {
114 bucket = keyring_hash(keyring->description);
115
116 write_lock(&keyring_name_lock);
117
118 if (!keyring_name_hash[bucket].next)
119 INIT_LIST_HEAD(&keyring_name_hash[bucket]);
120
146aa8b1 121 list_add_tail(&keyring->name_link,
1da177e4
LT
122 &keyring_name_hash[bucket]);
123
124 write_unlock(&keyring_name_lock);
125 }
a8b17ed0 126}
1da177e4 127
5d19e20b
DH
128/*
129 * Preparse a keyring payload
130 */
131static int keyring_preparse(struct key_preparsed_payload *prep)
132{
133 return prep->datalen != 0 ? -EINVAL : 0;
134}
135
136/*
137 * Free a preparse of a user defined key payload
138 */
139static void keyring_free_preparse(struct key_preparsed_payload *prep)
140{
141}
142
1da177e4 143/*
973c9f4f
DH
144 * Initialise a keyring.
145 *
146 * Returns 0 on success, -EINVAL if given any data.
1da177e4
LT
147 */
148static int keyring_instantiate(struct key *keyring,
cf7f601c 149 struct key_preparsed_payload *prep)
1da177e4 150{
5d19e20b
DH
151 assoc_array_init(&keyring->keys);
152 /* make the keyring available by name if it has one */
153 keyring_publish_name(keyring);
154 return 0;
a8b17ed0 155}
1da177e4 156
1da177e4 157/*
b2a4df20
DH
158 * Multiply 64-bits by 32-bits to 96-bits and fold back to 64-bit. Ideally we'd
159 * fold the carry back too, but that requires inline asm.
160 */
161static u64 mult_64x32_and_fold(u64 x, u32 y)
162{
163 u64 hi = (u64)(u32)(x >> 32) * y;
164 u64 lo = (u64)(u32)(x) * y;
165 return lo + ((u64)(u32)hi << 32) + (u32)(hi >> 32);
166}
167
168/*
169 * Hash a key type and description.
170 */
355ef8e1 171static void hash_key_type_and_desc(struct keyring_index_key *index_key)
b2a4df20
DH
172{
173 const unsigned level_shift = ASSOC_ARRAY_LEVEL_STEP;
d54e58b7 174 const unsigned long fan_mask = ASSOC_ARRAY_FAN_MASK;
b2a4df20
DH
175 const char *description = index_key->description;
176 unsigned long hash, type;
177 u32 piece;
178 u64 acc;
179 int n, desc_len = index_key->desc_len;
180
181 type = (unsigned long)index_key->type;
b2a4df20
DH
182 acc = mult_64x32_and_fold(type, desc_len + 13);
183 acc = mult_64x32_and_fold(acc, 9207);
f771fde8 184
b2a4df20
DH
185 for (;;) {
186 n = desc_len;
187 if (n <= 0)
188 break;
189 if (n > 4)
190 n = 4;
191 piece = 0;
192 memcpy(&piece, description, n);
193 description += n;
194 desc_len -= n;
195 acc = mult_64x32_and_fold(acc, piece);
196 acc = mult_64x32_and_fold(acc, 9207);
197 }
198
199 /* Fold the hash down to 32 bits if need be. */
200 hash = acc;
201 if (ASSOC_ARRAY_KEY_CHUNK_SIZE == 32)
202 hash ^= acc >> 32;
203
204 /* Squidge all the keyrings into a separate part of the tree to
205 * ordinary keys by making sure the lowest level segment in the hash is
206 * zero for keyrings and non-zero otherwise.
207 */
d54e58b7 208 if (index_key->type != &key_type_keyring && (hash & fan_mask) == 0)
355ef8e1
DH
209 hash |= (hash >> (ASSOC_ARRAY_KEY_CHUNK_SIZE - level_shift)) | 1;
210 else if (index_key->type == &key_type_keyring && (hash & fan_mask) != 0)
211 hash = (hash + (hash << level_shift)) & ~fan_mask;
212 index_key->hash = hash;
213}
214
215/*
216 * Finalise an index key to include a part of the description actually in the
217 * index key and to add in the hash too.
218 */
219void key_set_index_key(struct keyring_index_key *index_key)
220{
221 size_t n = min_t(size_t, index_key->desc_len, sizeof(index_key->desc));
222 memcpy(index_key->desc, index_key->description, n);
223
224 hash_key_type_and_desc(index_key);
b2a4df20
DH
225}
226
227/*
228 * Build the next index key chunk.
229 *
b2a4df20 230 * We return it one word-sized chunk at a time.
1da177e4 231 */
b2a4df20
DH
232static unsigned long keyring_get_key_chunk(const void *data, int level)
233{
234 const struct keyring_index_key *index_key = data;
235 unsigned long chunk = 0;
f771fde8 236 const u8 *d;
b2a4df20
DH
237 int desc_len = index_key->desc_len, n = sizeof(chunk);
238
239 level /= ASSOC_ARRAY_KEY_CHUNK_SIZE;
240 switch (level) {
241 case 0:
355ef8e1 242 return index_key->hash;
b2a4df20 243 case 1:
f771fde8 244 return index_key->x;
b2a4df20 245 case 2:
f771fde8 246 return (unsigned long)index_key->type;
b2a4df20 247 default:
f771fde8
DH
248 level -= 3;
249 if (desc_len <= sizeof(index_key->desc))
b2a4df20 250 return 0;
f771fde8
DH
251
252 d = index_key->description + sizeof(index_key->desc);
253 d += level * sizeof(long);
254 desc_len -= sizeof(index_key->desc);
b2a4df20
DH
255 if (desc_len > n)
256 desc_len = n;
b2a4df20
DH
257 do {
258 chunk <<= 8;
f771fde8 259 chunk |= *d++;
b2a4df20 260 } while (--desc_len > 0);
b2a4df20
DH
261 return chunk;
262 }
263}
264
265static unsigned long keyring_get_object_key_chunk(const void *object, int level)
266{
267 const struct key *key = keyring_ptr_to_key(object);
268 return keyring_get_key_chunk(&key->index_key, level);
269}
270
271static bool keyring_compare_object(const void *object, const void *data)
1da177e4 272{
b2a4df20
DH
273 const struct keyring_index_key *index_key = data;
274 const struct key *key = keyring_ptr_to_key(object);
275
276 return key->index_key.type == index_key->type &&
277 key->index_key.desc_len == index_key->desc_len &&
278 memcmp(key->index_key.description, index_key->description,
279 index_key->desc_len) == 0;
a8b17ed0 280}
1da177e4 281
b2a4df20
DH
282/*
283 * Compare the index keys of a pair of objects and determine the bit position
284 * at which they differ - if they differ.
285 */
23fd78d7 286static int keyring_diff_objects(const void *object, const void *data)
b2a4df20 287{
23fd78d7 288 const struct key *key_a = keyring_ptr_to_key(object);
b2a4df20 289 const struct keyring_index_key *a = &key_a->index_key;
23fd78d7 290 const struct keyring_index_key *b = data;
b2a4df20
DH
291 unsigned long seg_a, seg_b;
292 int level, i;
293
294 level = 0;
355ef8e1
DH
295 seg_a = a->hash;
296 seg_b = b->hash;
b2a4df20
DH
297 if ((seg_a ^ seg_b) != 0)
298 goto differ;
f771fde8 299 level += ASSOC_ARRAY_KEY_CHUNK_SIZE / 8;
b2a4df20
DH
300
301 /* The number of bits contributed by the hash is controlled by a
302 * constant in the assoc_array headers. Everything else thereafter we
303 * can deal with as being machine word-size dependent.
304 */
f771fde8
DH
305 seg_a = a->x;
306 seg_b = b->x;
b2a4df20
DH
307 if ((seg_a ^ seg_b) != 0)
308 goto differ;
f771fde8 309 level += sizeof(unsigned long);
b2a4df20
DH
310
311 /* The next bit may not work on big endian */
b2a4df20
DH
312 seg_a = (unsigned long)a->type;
313 seg_b = (unsigned long)b->type;
314 if ((seg_a ^ seg_b) != 0)
315 goto differ;
b2a4df20 316 level += sizeof(unsigned long);
b2a4df20 317
f771fde8
DH
318 i = sizeof(a->desc);
319 if (a->desc_len <= i)
320 goto same;
b2a4df20
DH
321
322 for (; i < a->desc_len; i++) {
323 seg_a = *(unsigned char *)(a->description + i);
324 seg_b = *(unsigned char *)(b->description + i);
325 if ((seg_a ^ seg_b) != 0)
326 goto differ_plus_i;
327 }
328
329same:
330 return -1;
331
332differ_plus_i:
333 level += i;
334differ:
335 i = level * 8 + __ffs(seg_a ^ seg_b);
336 return i;
337}
338
339/*
340 * Free an object after stripping the keyring flag off of the pointer.
341 */
342static void keyring_free_object(void *object)
343{
344 key_put(keyring_ptr_to_key(object));
345}
346
347/*
348 * Operations for keyring management by the index-tree routines.
349 */
350static const struct assoc_array_ops keyring_assoc_array_ops = {
351 .get_key_chunk = keyring_get_key_chunk,
352 .get_object_key_chunk = keyring_get_object_key_chunk,
353 .compare_object = keyring_compare_object,
354 .diff_objects = keyring_diff_objects,
355 .free_object = keyring_free_object,
356};
357
1da177e4 358/*
973c9f4f
DH
359 * Clean up a keyring when it is destroyed. Unpublish its name if it had one
360 * and dispose of its data.
233e4735
DH
361 *
362 * The garbage collector detects the final key_put(), removes the keyring from
363 * the serial number tree and then does RCU synchronisation before coming here,
364 * so we shouldn't need to worry about code poking around here with the RCU
365 * readlock held by this time.
1da177e4
LT
366 */
367static void keyring_destroy(struct key *keyring)
368{
1da177e4
LT
369 if (keyring->description) {
370 write_lock(&keyring_name_lock);
94efe72f 371
146aa8b1
DH
372 if (keyring->name_link.next != NULL &&
373 !list_empty(&keyring->name_link))
374 list_del(&keyring->name_link);
94efe72f 375
1da177e4
LT
376 write_unlock(&keyring_name_lock);
377 }
378
2b6aa412
MM
379 if (keyring->restrict_link) {
380 struct key_restriction *keyres = keyring->restrict_link;
381
382 key_put(keyres->key);
383 kfree(keyres);
384 }
385
b2a4df20 386 assoc_array_destroy(&keyring->keys, &keyring_assoc_array_ops);
a8b17ed0 387}
1da177e4 388
1da177e4 389/*
973c9f4f 390 * Describe a keyring for /proc.
1da177e4
LT
391 */
392static void keyring_describe(const struct key *keyring, struct seq_file *m)
393{
c8563473 394 if (keyring->description)
1da177e4 395 seq_puts(m, keyring->description);
c8563473 396 else
1da177e4 397 seq_puts(m, "[anon]");
1da177e4 398
363b02da 399 if (key_is_positive(keyring)) {
b2a4df20
DH
400 if (keyring->keys.nr_leaves_on_tree != 0)
401 seq_printf(m, ": %lu", keyring->keys.nr_leaves_on_tree);
78b7280c
DH
402 else
403 seq_puts(m, ": empty");
78b7280c 404 }
a8b17ed0 405}
1da177e4 406
b2a4df20 407struct keyring_read_iterator_context {
e645016a 408 size_t buflen;
b2a4df20
DH
409 size_t count;
410 key_serial_t __user *buffer;
411};
412
413static int keyring_read_iterator(const void *object, void *data)
414{
415 struct keyring_read_iterator_context *ctx = data;
416 const struct key *key = keyring_ptr_to_key(object);
417 int ret;
418
419 kenter("{%s,%d},,{%zu/%zu}",
e645016a 420 key->type->name, key->serial, ctx->count, ctx->buflen);
b2a4df20 421
e645016a 422 if (ctx->count >= ctx->buflen)
b2a4df20
DH
423 return 1;
424
425 ret = put_user(key->serial, ctx->buffer);
426 if (ret < 0)
427 return ret;
428 ctx->buffer++;
429 ctx->count += sizeof(key->serial);
430 return 0;
431}
432
1da177e4 433/*
973c9f4f
DH
434 * Read a list of key IDs from the keyring's contents in binary form
435 *
b2a4df20
DH
436 * The keyring's semaphore is read-locked by the caller. This prevents someone
437 * from modifying it under us - which could cause us to read key IDs multiple
438 * times.
1da177e4
LT
439 */
440static long keyring_read(const struct key *keyring,
441 char __user *buffer, size_t buflen)
442{
b2a4df20 443 struct keyring_read_iterator_context ctx;
3239b6f2 444 long ret;
1da177e4 445
b2a4df20
DH
446 kenter("{%d},,%zu", key_serial(keyring), buflen);
447
448 if (buflen & (sizeof(key_serial_t) - 1))
449 return -EINVAL;
450
3239b6f2
EB
451 /* Copy as many key IDs as fit into the buffer */
452 if (buffer && buflen) {
453 ctx.buffer = (key_serial_t __user *)buffer;
454 ctx.buflen = buflen;
455 ctx.count = 0;
456 ret = assoc_array_iterate(&keyring->keys,
457 keyring_read_iterator, &ctx);
458 if (ret < 0) {
459 kleave(" = %ld [iterate]", ret);
460 return ret;
461 }
1da177e4
LT
462 }
463
3239b6f2
EB
464 /* Return the size of the buffer needed */
465 ret = keyring->keys.nr_leaves_on_tree * sizeof(key_serial_t);
466 if (ret <= buflen)
467 kleave("= %ld [ok]", ret);
468 else
469 kleave("= %ld [buffer too small]", ret);
470 return ret;
a8b17ed0 471}
1da177e4 472
1da177e4 473/*
973c9f4f 474 * Allocate a keyring and link into the destination keyring.
1da177e4 475 */
9a56c2db 476struct key *keyring_alloc(const char *description, kuid_t uid, kgid_t gid,
96b5c8fe 477 const struct cred *cred, key_perm_t perm,
5ac7eace 478 unsigned long flags,
2b6aa412 479 struct key_restriction *restrict_link,
5ac7eace 480 struct key *dest)
1da177e4
LT
481{
482 struct key *keyring;
483 int ret;
484
485 keyring = key_alloc(&key_type_keyring, description,
5ac7eace 486 uid, gid, cred, perm, flags, restrict_link);
1da177e4 487 if (!IS_ERR(keyring)) {
3e30148c 488 ret = key_instantiate_and_link(keyring, NULL, 0, dest, NULL);
1da177e4
LT
489 if (ret < 0) {
490 key_put(keyring);
491 keyring = ERR_PTR(ret);
492 }
493 }
494
495 return keyring;
a8b17ed0 496}
f8aa23a5 497EXPORT_SYMBOL(keyring_alloc);
1da177e4 498
5ac7eace
DH
499/**
500 * restrict_link_reject - Give -EPERM to restrict link
501 * @keyring: The keyring being added to.
502 * @type: The type of key being added.
5ac7eace 503 * @payload: The payload of the key intended to be added.
9fd16537 504 * @restriction_key: Keys providing additional data for evaluating restriction.
5ac7eace
DH
505 *
506 * Reject the addition of any links to a keyring. It can be overridden by
507 * passing KEY_ALLOC_BYPASS_RESTRICTION to key_instantiate_and_link() when
508 * adding a key to a keyring.
509 *
2b6aa412
MM
510 * This is meant to be stored in a key_restriction structure which is passed
511 * in the restrict_link parameter to keyring_alloc().
5ac7eace
DH
512 */
513int restrict_link_reject(struct key *keyring,
514 const struct key_type *type,
aaf66c88
MM
515 const union key_payload *payload,
516 struct key *restriction_key)
5ac7eace
DH
517{
518 return -EPERM;
519}
520
c06cfb08
DH
521/*
522 * By default, we keys found by getting an exact match on their descriptions.
523 */
0c903ab6
DH
524bool key_default_cmp(const struct key *key,
525 const struct key_match_data *match_data)
c06cfb08
DH
526{
527 return strcmp(key->description, match_data->raw_data) == 0;
528}
529
b2a4df20
DH
530/*
531 * Iteration function to consider each key found.
1da177e4 532 */
b2a4df20 533static int keyring_search_iterator(const void *object, void *iterator_data)
1da177e4 534{
b2a4df20
DH
535 struct keyring_search_context *ctx = iterator_data;
536 const struct key *key = keyring_ptr_to_key(object);
363b02da
DH
537 unsigned long kflags = READ_ONCE(key->flags);
538 short state = READ_ONCE(key->state);
1da177e4 539
b2a4df20 540 kenter("{%d}", key->serial);
1da177e4 541
b2a4df20
DH
542 /* ignore keys not of this type */
543 if (key->type != ctx->index_key.type) {
544 kleave(" = 0 [!type]");
545 return 0;
29db9190 546 }
1da177e4 547
b2a4df20
DH
548 /* skip invalidated, revoked and expired keys */
549 if (ctx->flags & KEYRING_SEARCH_DO_STATE_CHECK) {
074d5898 550 time64_t expiry = READ_ONCE(key->expiry);
9d6c8711 551
b2a4df20
DH
552 if (kflags & ((1 << KEY_FLAG_INVALIDATED) |
553 (1 << KEY_FLAG_REVOKED))) {
554 ctx->result = ERR_PTR(-EKEYREVOKED);
555 kleave(" = %d [invrev]", ctx->skipped_ret);
556 goto skipped;
557 }
1da177e4 558
074d5898 559 if (expiry && ctx->now >= expiry) {
0b0a8415
DH
560 if (!(ctx->flags & KEYRING_SEARCH_SKIP_EXPIRED))
561 ctx->result = ERR_PTR(-EKEYEXPIRED);
b2a4df20
DH
562 kleave(" = %d [expire]", ctx->skipped_ret);
563 goto skipped;
564 }
565 }
664cceb0 566
b2a4df20 567 /* keys that don't match */
46291959 568 if (!ctx->match_data.cmp(key, &ctx->match_data)) {
b2a4df20
DH
569 kleave(" = 0 [!match]");
570 return 0;
571 }
dceba994 572
b2a4df20
DH
573 /* key must have search permissions */
574 if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM) &&
575 key_task_permission(make_key_ref(key, ctx->possessed),
f5895943 576 ctx->cred, KEY_NEED_SEARCH) < 0) {
b2a4df20
DH
577 ctx->result = ERR_PTR(-EACCES);
578 kleave(" = %d [!perm]", ctx->skipped_ret);
579 goto skipped;
dceba994
KC
580 }
581
b2a4df20
DH
582 if (ctx->flags & KEYRING_SEARCH_DO_STATE_CHECK) {
583 /* we set a different error code if we pass a negative key */
363b02da
DH
584 if (state < 0) {
585 ctx->result = ERR_PTR(state);
b2a4df20
DH
586 kleave(" = %d [neg]", ctx->skipped_ret);
587 goto skipped;
588 }
589 }
1da177e4 590
b2a4df20
DH
591 /* Found */
592 ctx->result = make_key_ref(key, ctx->possessed);
593 kleave(" = 1 [found]");
594 return 1;
1da177e4 595
b2a4df20
DH
596skipped:
597 return ctx->skipped_ret;
598}
1da177e4 599
b2a4df20
DH
600/*
601 * Search inside a keyring for a key. We can search by walking to it
602 * directly based on its index-key or we can iterate over the entire
603 * tree looking for it, based on the match function.
604 */
605static int search_keyring(struct key *keyring, struct keyring_search_context *ctx)
606{
46291959 607 if (ctx->match_data.lookup_type == KEYRING_SEARCH_LOOKUP_DIRECT) {
b2a4df20
DH
608 const void *object;
609
610 object = assoc_array_find(&keyring->keys,
611 &keyring_assoc_array_ops,
612 &ctx->index_key);
613 return object ? ctx->iterator(object, ctx) : 0;
614 }
615 return assoc_array_iterate(&keyring->keys, ctx->iterator, ctx);
616}
1da177e4 617
b2a4df20
DH
618/*
619 * Search a tree of keyrings that point to other keyrings up to the maximum
620 * depth.
621 */
622static bool search_nested_keyrings(struct key *keyring,
623 struct keyring_search_context *ctx)
624{
625 struct {
626 struct key *keyring;
627 struct assoc_array_node *node;
628 int slot;
629 } stack[KEYRING_SEARCH_MAX_DEPTH];
1da177e4 630
b2a4df20
DH
631 struct assoc_array_shortcut *shortcut;
632 struct assoc_array_node *node;
633 struct assoc_array_ptr *ptr;
634 struct key *key;
635 int sp = 0, slot;
1da177e4 636
b2a4df20
DH
637 kenter("{%d},{%s,%s}",
638 keyring->serial,
639 ctx->index_key.type->name,
640 ctx->index_key.description);
1da177e4 641
054f6180
DH
642#define STATE_CHECKS (KEYRING_SEARCH_NO_STATE_CHECK | KEYRING_SEARCH_DO_STATE_CHECK)
643 BUG_ON((ctx->flags & STATE_CHECKS) == 0 ||
644 (ctx->flags & STATE_CHECKS) == STATE_CHECKS);
645
f771fde8
DH
646 if (ctx->index_key.description)
647 key_set_index_key(&ctx->index_key);
648
b2a4df20
DH
649 /* Check to see if this top-level keyring is what we are looking for
650 * and whether it is valid or not.
651 */
46291959 652 if (ctx->match_data.lookup_type == KEYRING_SEARCH_LOOKUP_ITERATE ||
b2a4df20
DH
653 keyring_compare_object(keyring, &ctx->index_key)) {
654 ctx->skipped_ret = 2;
b2a4df20
DH
655 switch (ctx->iterator(keyring_key_to_ptr(keyring), ctx)) {
656 case 1:
78b7280c 657 goto found;
b2a4df20
DH
658 case 2:
659 return false;
660 default:
661 break;
1da177e4 662 }
b2a4df20 663 }
1da177e4 664
b2a4df20 665 ctx->skipped_ret = 0;
b2a4df20
DH
666
667 /* Start processing a new keyring */
668descend_to_keyring:
669 kdebug("descend to %d", keyring->serial);
670 if (keyring->flags & ((1 << KEY_FLAG_INVALIDATED) |
671 (1 << KEY_FLAG_REVOKED)))
672 goto not_this_keyring;
673
674 /* Search through the keys in this keyring before its searching its
675 * subtrees.
676 */
677 if (search_keyring(keyring, ctx))
1da177e4 678 goto found;
1da177e4 679
b2a4df20
DH
680 /* Then manually iterate through the keyrings nested in this one.
681 *
682 * Start from the root node of the index tree. Because of the way the
683 * hash function has been set up, keyrings cluster on the leftmost
684 * branch of the root node (root slot 0) or in the root node itself.
685 * Non-keyrings avoid the leftmost branch of the root entirely (root
686 * slots 1-15).
687 */
381f20fc 688 ptr = READ_ONCE(keyring->keys.root);
b2a4df20
DH
689 if (!ptr)
690 goto not_this_keyring;
1da177e4 691
b2a4df20
DH
692 if (assoc_array_ptr_is_shortcut(ptr)) {
693 /* If the root is a shortcut, either the keyring only contains
694 * keyring pointers (everything clusters behind root slot 0) or
695 * doesn't contain any keyring pointers.
1da177e4 696 */
b2a4df20 697 shortcut = assoc_array_ptr_to_shortcut(ptr);
b2a4df20
DH
698 if ((shortcut->index_key[0] & ASSOC_ARRAY_FAN_MASK) != 0)
699 goto not_this_keyring;
700
381f20fc 701 ptr = READ_ONCE(shortcut->next_node);
b2a4df20
DH
702 node = assoc_array_ptr_to_node(ptr);
703 goto begin_node;
704 }
705
706 node = assoc_array_ptr_to_node(ptr);
b2a4df20
DH
707 ptr = node->slots[0];
708 if (!assoc_array_ptr_is_meta(ptr))
709 goto begin_node;
710
711descend_to_node:
712 /* Descend to a more distal node in this keyring's content tree and go
713 * through that.
714 */
715 kdebug("descend");
716 if (assoc_array_ptr_is_shortcut(ptr)) {
717 shortcut = assoc_array_ptr_to_shortcut(ptr);
381f20fc 718 ptr = READ_ONCE(shortcut->next_node);
b2a4df20 719 BUG_ON(!assoc_array_ptr_is_node(ptr));
b2a4df20 720 }
9c5e45df 721 node = assoc_array_ptr_to_node(ptr);
b2a4df20
DH
722
723begin_node:
724 kdebug("begin_node");
b2a4df20
DH
725 slot = 0;
726ascend_to_node:
727 /* Go through the slots in a node */
728 for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
381f20fc 729 ptr = READ_ONCE(node->slots[slot]);
b2a4df20
DH
730
731 if (assoc_array_ptr_is_meta(ptr) && node->back_pointer)
732 goto descend_to_node;
733
734 if (!keyring_ptr_is_keyring(ptr))
76d8aeab 735 continue;
1da177e4 736
b2a4df20
DH
737 key = keyring_ptr_to_key(ptr);
738
739 if (sp >= KEYRING_SEARCH_MAX_DEPTH) {
740 if (ctx->flags & KEYRING_SEARCH_DETECT_TOO_DEEP) {
741 ctx->result = ERR_PTR(-ELOOP);
742 return false;
743 }
744 goto not_this_keyring;
745 }
746
747 /* Search a nested keyring */
748 if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM) &&
749 key_task_permission(make_key_ref(key, ctx->possessed),
f5895943 750 ctx->cred, KEY_NEED_SEARCH) < 0)
76d8aeab 751 continue;
1da177e4
LT
752
753 /* stack the current position */
31d5a79d 754 stack[sp].keyring = keyring;
b2a4df20
DH
755 stack[sp].node = node;
756 stack[sp].slot = slot;
1da177e4
LT
757 sp++;
758
759 /* begin again with the new keyring */
760 keyring = key;
b2a4df20
DH
761 goto descend_to_keyring;
762 }
763
764 /* We've dealt with all the slots in the current node, so now we need
765 * to ascend to the parent and continue processing there.
766 */
381f20fc 767 ptr = READ_ONCE(node->back_pointer);
b2a4df20
DH
768 slot = node->parent_slot;
769
770 if (ptr && assoc_array_ptr_is_shortcut(ptr)) {
771 shortcut = assoc_array_ptr_to_shortcut(ptr);
381f20fc 772 ptr = READ_ONCE(shortcut->back_pointer);
b2a4df20
DH
773 slot = shortcut->parent_slot;
774 }
775 if (!ptr)
776 goto not_this_keyring;
777 node = assoc_array_ptr_to_node(ptr);
b2a4df20
DH
778 slot++;
779
780 /* If we've ascended to the root (zero backpointer), we must have just
781 * finished processing the leftmost branch rather than the root slots -
782 * so there can't be any more keyrings for us to find.
783 */
784 if (node->back_pointer) {
785 kdebug("ascend %d", slot);
786 goto ascend_to_node;
1da177e4
LT
787 }
788
b2a4df20
DH
789 /* The keyring we're looking at was disqualified or didn't contain a
790 * matching key.
791 */
664cceb0 792not_this_keyring:
b2a4df20
DH
793 kdebug("not_this_keyring %d", sp);
794 if (sp <= 0) {
795 kleave(" = false");
796 return false;
1da177e4
LT
797 }
798
b2a4df20
DH
799 /* Resume the processing of a keyring higher up in the tree */
800 sp--;
801 keyring = stack[sp].keyring;
802 node = stack[sp].node;
803 slot = stack[sp].slot + 1;
804 kdebug("ascend to %d [%d]", keyring->serial, slot);
805 goto ascend_to_node;
1da177e4 806
b2a4df20 807 /* We found a viable match */
664cceb0 808found:
b2a4df20 809 key = key_ref_to_ptr(ctx->result);
1da177e4 810 key_check(key);
b2a4df20 811 if (!(ctx->flags & KEYRING_SEARCH_NO_UPDATE_TIME)) {
074d5898
BW
812 key->last_used_at = ctx->now;
813 keyring->last_used_at = ctx->now;
b2a4df20 814 while (sp > 0)
074d5898 815 stack[--sp].keyring->last_used_at = ctx->now;
b2a4df20
DH
816 }
817 kleave(" = true");
818 return true;
819}
820
821/**
e59428f7 822 * keyring_search_rcu - Search a keyring tree for a matching key under RCU
b2a4df20
DH
823 * @keyring_ref: A pointer to the keyring with possession indicator.
824 * @ctx: The keyring search context.
825 *
826 * Search the supplied keyring tree for a key that matches the criteria given.
827 * The root keyring and any linked keyrings must grant Search permission to the
828 * caller to be searchable and keys can only be found if they too grant Search
829 * to the caller. The possession flag on the root keyring pointer controls use
830 * of the possessor bits in permissions checking of the entire tree. In
831 * addition, the LSM gets to forbid keyring searches and key matches.
832 *
833 * The search is performed as a breadth-then-depth search up to the prescribed
e59428f7
DH
834 * limit (KEYRING_SEARCH_MAX_DEPTH). The caller must hold the RCU read lock to
835 * prevent keyrings from being destroyed or rearranged whilst they are being
836 * searched.
b2a4df20
DH
837 *
838 * Keys are matched to the type provided and are then filtered by the match
839 * function, which is given the description to use in any way it sees fit. The
840 * match function may use any attributes of a key that it wishes to to
841 * determine the match. Normally the match function from the key type would be
842 * used.
843 *
844 * RCU can be used to prevent the keyring key lists from disappearing without
845 * the need to take lots of locks.
846 *
847 * Returns a pointer to the found key and increments the key usage count if
848 * successful; -EAGAIN if no matching keys were found, or if expired or revoked
849 * keys were found; -ENOKEY if only negative keys were found; -ENOTDIR if the
850 * specified keyring wasn't a keyring.
851 *
852 * In the case of a successful return, the possession attribute from
853 * @keyring_ref is propagated to the returned key reference.
854 */
e59428f7 855key_ref_t keyring_search_rcu(key_ref_t keyring_ref,
b2a4df20
DH
856 struct keyring_search_context *ctx)
857{
858 struct key *keyring;
859 long err;
860
861 ctx->iterator = keyring_search_iterator;
862 ctx->possessed = is_key_possessed(keyring_ref);
863 ctx->result = ERR_PTR(-EAGAIN);
864
865 keyring = key_ref_to_ptr(keyring_ref);
866 key_check(keyring);
867
868 if (keyring->type != &key_type_keyring)
869 return ERR_PTR(-ENOTDIR);
870
871 if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM)) {
f5895943 872 err = key_task_permission(keyring_ref, ctx->cred, KEY_NEED_SEARCH);
b2a4df20
DH
873 if (err < 0)
874 return ERR_PTR(err);
875 }
876
074d5898 877 ctx->now = ktime_get_real_seconds();
b2a4df20
DH
878 if (search_nested_keyrings(keyring, ctx))
879 __key_get(key_ref_to_ptr(ctx->result));
b2a4df20 880 return ctx->result;
a8b17ed0 881}
1da177e4 882
973c9f4f
DH
883/**
884 * keyring_search - Search the supplied keyring tree for a matching key
885 * @keyring: The root of the keyring tree to be searched.
886 * @type: The type of keyring we want to find.
887 * @description: The name of the keyring we want to find.
888 *
e59428f7 889 * As keyring_search_rcu() above, but using the current task's credentials and
b2a4df20 890 * type's default matching function and preferred search method.
1da177e4 891 */
664cceb0
DH
892key_ref_t keyring_search(key_ref_t keyring,
893 struct key_type *type,
894 const char *description)
1da177e4 895{
4bdf0bc3
DH
896 struct keyring_search_context ctx = {
897 .index_key.type = type,
898 .index_key.description = description,
ede0fa98 899 .index_key.desc_len = strlen(description),
4bdf0bc3 900 .cred = current_cred(),
c06cfb08 901 .match_data.cmp = key_default_cmp,
46291959
DH
902 .match_data.raw_data = description,
903 .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT,
904 .flags = KEYRING_SEARCH_DO_STATE_CHECK,
4bdf0bc3 905 };
46291959
DH
906 key_ref_t key;
907 int ret;
4bdf0bc3 908
46291959
DH
909 if (type->match_preparse) {
910 ret = type->match_preparse(&ctx.match_data);
911 if (ret < 0)
912 return ERR_PTR(ret);
913 }
914
e59428f7
DH
915 rcu_read_lock();
916 key = keyring_search_rcu(keyring, &ctx);
917 rcu_read_unlock();
46291959
DH
918
919 if (type->match_free)
920 type->match_free(&ctx.match_data);
921 return key;
a8b17ed0 922}
1da177e4
LT
923EXPORT_SYMBOL(keyring_search);
924
6563c91f
MM
925static struct key_restriction *keyring_restriction_alloc(
926 key_restrict_link_func_t check)
927{
928 struct key_restriction *keyres =
929 kzalloc(sizeof(struct key_restriction), GFP_KERNEL);
930
931 if (!keyres)
932 return ERR_PTR(-ENOMEM);
933
934 keyres->check = check;
935
936 return keyres;
937}
938
939/*
940 * Semaphore to serialise restriction setup to prevent reference count
941 * cycles through restriction key pointers.
942 */
943static DECLARE_RWSEM(keyring_serialise_restrict_sem);
944
945/*
946 * Check for restriction cycles that would prevent keyring garbage collection.
947 * keyring_serialise_restrict_sem must be held.
948 */
949static bool keyring_detect_restriction_cycle(const struct key *dest_keyring,
950 struct key_restriction *keyres)
951{
952 while (keyres && keyres->key &&
953 keyres->key->type == &key_type_keyring) {
954 if (keyres->key == dest_keyring)
955 return true;
956
957 keyres = keyres->key->restrict_link;
958 }
959
960 return false;
961}
962
963/**
964 * keyring_restrict - Look up and apply a restriction to a keyring
9fd16537
DH
965 * @keyring_ref: The keyring to be restricted
966 * @type: The key type that will provide the restriction checker.
6563c91f 967 * @restriction: The restriction options to apply to the keyring
9fd16537
DH
968 *
969 * Look up a keyring and apply a restriction to it. The restriction is managed
970 * by the specific key type, but can be configured by the options specified in
971 * the restriction string.
6563c91f
MM
972 */
973int keyring_restrict(key_ref_t keyring_ref, const char *type,
974 const char *restriction)
975{
976 struct key *keyring;
977 struct key_type *restrict_type = NULL;
978 struct key_restriction *restrict_link;
979 int ret = 0;
980
981 keyring = key_ref_to_ptr(keyring_ref);
982 key_check(keyring);
983
984 if (keyring->type != &key_type_keyring)
985 return -ENOTDIR;
986
987 if (!type) {
988 restrict_link = keyring_restriction_alloc(restrict_link_reject);
989 } else {
990 restrict_type = key_type_lookup(type);
991
992 if (IS_ERR(restrict_type))
993 return PTR_ERR(restrict_type);
994
995 if (!restrict_type->lookup_restriction) {
996 ret = -ENOENT;
997 goto error;
998 }
999
1000 restrict_link = restrict_type->lookup_restriction(restriction);
1001 }
1002
1003 if (IS_ERR(restrict_link)) {
1004 ret = PTR_ERR(restrict_link);
1005 goto error;
1006 }
1007
1008 down_write(&keyring->sem);
1009 down_write(&keyring_serialise_restrict_sem);
1010
1011 if (keyring->restrict_link)
1012 ret = -EEXIST;
1013 else if (keyring_detect_restriction_cycle(keyring, restrict_link))
1014 ret = -EDEADLK;
1015 else
1016 keyring->restrict_link = restrict_link;
1017
1018 up_write(&keyring_serialise_restrict_sem);
1019 up_write(&keyring->sem);
1020
1021 if (ret < 0) {
1022 key_put(restrict_link->key);
1023 kfree(restrict_link);
1024 }
1025
1026error:
1027 if (restrict_type)
1028 key_type_put(restrict_type);
1029
1030 return ret;
1031}
1032EXPORT_SYMBOL(keyring_restrict);
1033
1da177e4 1034/*
b2a4df20 1035 * Search the given keyring for a key that might be updated.
973c9f4f
DH
1036 *
1037 * The caller must guarantee that the keyring is a keyring and that the
b2a4df20
DH
1038 * permission is granted to modify the keyring as no check is made here. The
1039 * caller must also hold a lock on the keyring semaphore.
973c9f4f
DH
1040 *
1041 * Returns a pointer to the found key with usage count incremented if
b2a4df20
DH
1042 * successful and returns NULL if not found. Revoked and invalidated keys are
1043 * skipped over.
973c9f4f
DH
1044 *
1045 * If successful, the possession indicator is propagated from the keyring ref
1046 * to the returned key reference.
1da177e4 1047 */
b2a4df20
DH
1048key_ref_t find_key_to_update(key_ref_t keyring_ref,
1049 const struct keyring_index_key *index_key)
1da177e4 1050{
664cceb0 1051 struct key *keyring, *key;
b2a4df20 1052 const void *object;
1da177e4 1053
664cceb0 1054 keyring = key_ref_to_ptr(keyring_ref);
664cceb0 1055
b2a4df20
DH
1056 kenter("{%d},{%s,%s}",
1057 keyring->serial, index_key->type->name, index_key->description);
76d8aeab 1058
b2a4df20
DH
1059 object = assoc_array_find(&keyring->keys, &keyring_assoc_array_ops,
1060 index_key);
1da177e4 1061
b2a4df20
DH
1062 if (object)
1063 goto found;
1064
1065 kleave(" = NULL");
1066 return NULL;
1da177e4 1067
c5b60b5e 1068found:
b2a4df20
DH
1069 key = keyring_ptr_to_key(object);
1070 if (key->flags & ((1 << KEY_FLAG_INVALIDATED) |
1071 (1 << KEY_FLAG_REVOKED))) {
1072 kleave(" = NULL [x]");
1073 return NULL;
1074 }
ccc3e6d9 1075 __key_get(key);
b2a4df20
DH
1076 kleave(" = {%d}", key->serial);
1077 return make_key_ref(key, is_key_possessed(keyring_ref));
a8b17ed0 1078}
1da177e4 1079
1da177e4 1080/*
973c9f4f
DH
1081 * Find a keyring with the specified name.
1082 *
237bbd29
EB
1083 * Only keyrings that have nonzero refcount, are not revoked, and are owned by a
1084 * user in the current user namespace are considered. If @uid_keyring is %true,
1085 * the keyring additionally must have been allocated as a user or user session
1086 * keyring; otherwise, it must grant Search permission directly to the caller.
973c9f4f
DH
1087 *
1088 * Returns a pointer to the keyring with the keyring's refcount having being
1089 * incremented on success. -ENOKEY is returned if a key could not be found.
1da177e4 1090 */
237bbd29 1091struct key *find_keyring_by_name(const char *name, bool uid_keyring)
1da177e4
LT
1092{
1093 struct key *keyring;
1094 int bucket;
1095
1da177e4 1096 if (!name)
cea7daa3 1097 return ERR_PTR(-EINVAL);
1da177e4
LT
1098
1099 bucket = keyring_hash(name);
1100
1101 read_lock(&keyring_name_lock);
1102
1103 if (keyring_name_hash[bucket].next) {
1104 /* search this hash bucket for a keyring with a matching name
1105 * that's readable and that hasn't been revoked */
1106 list_for_each_entry(keyring,
1107 &keyring_name_hash[bucket],
146aa8b1 1108 name_link
1da177e4 1109 ) {
9a56c2db 1110 if (!kuid_has_mapping(current_user_ns(), keyring->user->uid))
2ea190d0
SH
1111 continue;
1112
76d8aeab 1113 if (test_bit(KEY_FLAG_REVOKED, &keyring->flags))
1da177e4
LT
1114 continue;
1115
1116 if (strcmp(keyring->description, name) != 0)
1117 continue;
1118
237bbd29
EB
1119 if (uid_keyring) {
1120 if (!test_bit(KEY_FLAG_UID_KEYRING,
1121 &keyring->flags))
1122 continue;
1123 } else {
1124 if (key_permission(make_key_ref(keyring, 0),
1125 KEY_NEED_SEARCH) < 0)
1126 continue;
1127 }
1da177e4 1128
cea7daa3
TO
1129 /* we've got a match but we might end up racing with
1130 * key_cleanup() if the keyring is currently 'dead'
1131 * (ie. it has a zero usage count) */
fff29291 1132 if (!refcount_inc_not_zero(&keyring->usage))
cea7daa3 1133 continue;
074d5898 1134 keyring->last_used_at = ktime_get_real_seconds();
cea7daa3 1135 goto out;
1da177e4
LT
1136 }
1137 }
1138
1da177e4 1139 keyring = ERR_PTR(-ENOKEY);
cea7daa3
TO
1140out:
1141 read_unlock(&keyring_name_lock);
1da177e4 1142 return keyring;
a8b17ed0 1143}
1da177e4 1144
b2a4df20
DH
1145static int keyring_detect_cycle_iterator(const void *object,
1146 void *iterator_data)
1147{
1148 struct keyring_search_context *ctx = iterator_data;
1149 const struct key *key = keyring_ptr_to_key(object);
1150
1151 kenter("{%d}", key->serial);
1152
979e0d74
DH
1153 /* We might get a keyring with matching index-key that is nonetheless a
1154 * different keyring. */
46291959 1155 if (key != ctx->match_data.raw_data)
979e0d74
DH
1156 return 0;
1157
b2a4df20
DH
1158 ctx->result = ERR_PTR(-EDEADLK);
1159 return 1;
1160}
1161
1da177e4 1162/*
973c9f4f
DH
1163 * See if a cycle will will be created by inserting acyclic tree B in acyclic
1164 * tree A at the topmost level (ie: as a direct child of A).
1165 *
1166 * Since we are adding B to A at the top level, checking for cycles should just
1167 * be a matter of seeing if node A is somewhere in tree B.
1da177e4
LT
1168 */
1169static int keyring_detect_cycle(struct key *A, struct key *B)
1170{
b2a4df20 1171 struct keyring_search_context ctx = {
46291959
DH
1172 .index_key = A->index_key,
1173 .match_data.raw_data = A,
1174 .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT,
1175 .iterator = keyring_detect_cycle_iterator,
1176 .flags = (KEYRING_SEARCH_NO_STATE_CHECK |
1177 KEYRING_SEARCH_NO_UPDATE_TIME |
1178 KEYRING_SEARCH_NO_CHECK_PERM |
1179 KEYRING_SEARCH_DETECT_TOO_DEEP),
b2a4df20 1180 };
1da177e4 1181
76d8aeab 1182 rcu_read_lock();
b2a4df20 1183 search_nested_keyrings(B, &ctx);
76d8aeab 1184 rcu_read_unlock();
b2a4df20 1185 return PTR_ERR(ctx.result) == -EAGAIN ? 0 : PTR_ERR(ctx.result);
f70e2e06 1186}
cab8eb59 1187
df593ee2
DH
1188/*
1189 * Lock keyring for link.
1190 */
1191int __key_link_lock(struct key *keyring,
1192 const struct keyring_index_key *index_key)
1193 __acquires(&keyring->sem)
1194 __acquires(&keyring_serialise_link_lock)
1195{
1196 if (keyring->type != &key_type_keyring)
1197 return -ENOTDIR;
1198
1199 down_write(&keyring->sem);
1200
1201 /* Serialise link/link calls to prevent parallel calls causing a cycle
1202 * when linking two keyring in opposite orders.
1203 */
1204 if (index_key->type == &key_type_keyring)
1205 mutex_lock(&keyring_serialise_link_lock);
1206
1207 return 0;
1208}
1209
ed0ac5c7
DH
1210/*
1211 * Lock keyrings for move (link/unlink combination).
1212 */
1213int __key_move_lock(struct key *l_keyring, struct key *u_keyring,
1214 const struct keyring_index_key *index_key)
1215 __acquires(&l_keyring->sem)
1216 __acquires(&u_keyring->sem)
1217 __acquires(&keyring_serialise_link_lock)
1218{
1219 if (l_keyring->type != &key_type_keyring ||
1220 u_keyring->type != &key_type_keyring)
1221 return -ENOTDIR;
1222
1223 /* We have to be very careful here to take the keyring locks in the
1224 * right order, lest we open ourselves to deadlocking against another
1225 * move operation.
1226 */
1227 if (l_keyring < u_keyring) {
1228 down_write(&l_keyring->sem);
1229 down_write_nested(&u_keyring->sem, 1);
1230 } else {
1231 down_write(&u_keyring->sem);
1232 down_write_nested(&l_keyring->sem, 1);
1233 }
1234
1235 /* Serialise link/link calls to prevent parallel calls causing a cycle
1236 * when linking two keyring in opposite orders.
1237 */
1238 if (index_key->type == &key_type_keyring)
1239 mutex_lock(&keyring_serialise_link_lock);
1240
1241 return 0;
1242}
1243
1da177e4 1244/*
973c9f4f 1245 * Preallocate memory so that a key can be linked into to a keyring.
1da177e4 1246 */
b2a4df20
DH
1247int __key_link_begin(struct key *keyring,
1248 const struct keyring_index_key *index_key,
1249 struct assoc_array_edit **_edit)
1da177e4 1250{
b2a4df20
DH
1251 struct assoc_array_edit *edit;
1252 int ret;
1da177e4 1253
16feef43 1254 kenter("%d,%s,%s,",
b2a4df20
DH
1255 keyring->serial, index_key->type->name, index_key->description);
1256
1257 BUG_ON(index_key->desc_len == 0);
df593ee2 1258 BUG_ON(*_edit != NULL);
1da177e4 1259
df593ee2 1260 *_edit = NULL;
f70e2e06
DH
1261
1262 ret = -EKEYREVOKED;
1263 if (test_bit(KEY_FLAG_REVOKED, &keyring->flags))
df593ee2 1264 goto error;
553d603c 1265
b2a4df20
DH
1266 /* Create an edit script that will insert/replace the key in the
1267 * keyring tree.
1268 */
1269 edit = assoc_array_insert(&keyring->keys,
1270 &keyring_assoc_array_ops,
1271 index_key,
1272 NULL);
1273 if (IS_ERR(edit)) {
1274 ret = PTR_ERR(edit);
df593ee2 1275 goto error;
034faeb9
DH
1276 }
1277
1278 /* If we're not replacing a link in-place then we're going to need some
1279 * extra quota.
1280 */
1281 if (!edit->dead_leaf) {
1282 ret = key_payload_reserve(keyring,
1283 keyring->datalen + KEYQUOTA_LINK_BYTES);
1284 if (ret < 0)
1285 goto error_cancel;
1da177e4
LT
1286 }
1287
b2a4df20 1288 *_edit = edit;
f70e2e06
DH
1289 kleave(" = 0");
1290 return 0;
1da177e4 1291
034faeb9
DH
1292error_cancel:
1293 assoc_array_cancel_edit(edit);
df593ee2 1294error:
f70e2e06
DH
1295 kleave(" = %d", ret);
1296 return ret;
1297}
1da177e4 1298
f70e2e06 1299/*
973c9f4f
DH
1300 * Check already instantiated keys aren't going to be a problem.
1301 *
1302 * The caller must have called __key_link_begin(). Don't need to call this for
1303 * keys that were created since __key_link_begin() was called.
f70e2e06
DH
1304 */
1305int __key_link_check_live_key(struct key *keyring, struct key *key)
1306{
1307 if (key->type == &key_type_keyring)
1308 /* check that we aren't going to create a cycle by linking one
1309 * keyring to another */
1310 return keyring_detect_cycle(keyring, key);
1311 return 0;
1312}
1313
1314/*
973c9f4f
DH
1315 * Link a key into to a keyring.
1316 *
1317 * Must be called with __key_link_begin() having being called. Discards any
1318 * already extant link to matching key if there is one, so that each keyring
1319 * holds at most one link to any given key of a particular type+description
1320 * combination.
f70e2e06 1321 */
b2a4df20 1322void __key_link(struct key *key, struct assoc_array_edit **_edit)
f70e2e06 1323{
ccc3e6d9 1324 __key_get(key);
b2a4df20
DH
1325 assoc_array_insert_set_object(*_edit, keyring_key_to_ptr(key));
1326 assoc_array_apply_edit(*_edit);
1327 *_edit = NULL;
f70e2e06
DH
1328}
1329
1330/*
973c9f4f
DH
1331 * Finish linking a key into to a keyring.
1332 *
1333 * Must be called with __key_link_begin() having being called.
f70e2e06 1334 */
16feef43
DH
1335void __key_link_end(struct key *keyring,
1336 const struct keyring_index_key *index_key,
b2a4df20 1337 struct assoc_array_edit *edit)
f70e2e06 1338 __releases(&keyring->sem)
3be59f74 1339 __releases(&keyring_serialise_link_lock)
f70e2e06 1340{
16feef43 1341 BUG_ON(index_key->type == NULL);
b2a4df20 1342 kenter("%d,%s,", keyring->serial, index_key->type->name);
f70e2e06 1343
ca4da5dd
CIK
1344 if (edit) {
1345 if (!edit->dead_leaf) {
1346 key_payload_reserve(keyring,
1347 keyring->datalen - KEYQUOTA_LINK_BYTES);
1348 }
b2a4df20 1349 assoc_array_cancel_edit(edit);
f70e2e06
DH
1350 }
1351 up_write(&keyring->sem);
df593ee2
DH
1352
1353 if (index_key->type == &key_type_keyring)
1354 mutex_unlock(&keyring_serialise_link_lock);
f70e2e06 1355}
1da177e4 1356
5ac7eace
DH
1357/*
1358 * Check addition of keys to restricted keyrings.
1359 */
1360static int __key_link_check_restriction(struct key *keyring, struct key *key)
1361{
2b6aa412 1362 if (!keyring->restrict_link || !keyring->restrict_link->check)
5ac7eace 1363 return 0;
2b6aa412
MM
1364 return keyring->restrict_link->check(keyring, key->type, &key->payload,
1365 keyring->restrict_link->key);
5ac7eace
DH
1366}
1367
973c9f4f
DH
1368/**
1369 * key_link - Link a key to a keyring
1370 * @keyring: The keyring to make the link in.
1371 * @key: The key to link to.
1372 *
1373 * Make a link in a keyring to a key, such that the keyring holds a reference
1374 * on that key and the key can potentially be found by searching that keyring.
1375 *
1376 * This function will write-lock the keyring's semaphore and will consume some
1377 * of the user's key data quota to hold the link.
1378 *
1379 * Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring,
1380 * -EKEYREVOKED if the keyring has been revoked, -ENFILE if the keyring is
1381 * full, -EDQUOT if there is insufficient key data quota remaining to add
1382 * another link or -ENOMEM if there's insufficient memory.
1383 *
1384 * It is assumed that the caller has checked that it is permitted for a link to
1385 * be made (the keyring should have Write permission and the key Link
1386 * permission).
1da177e4
LT
1387 */
1388int key_link(struct key *keyring, struct key *key)
1389{
df593ee2 1390 struct assoc_array_edit *edit = NULL;
1da177e4
LT
1391 int ret;
1392
fff29291 1393 kenter("{%d,%d}", keyring->serial, refcount_read(&keyring->usage));
b2a4df20 1394
1da177e4
LT
1395 key_check(keyring);
1396 key_check(key);
1397
df593ee2
DH
1398 ret = __key_link_lock(keyring, &key->index_key);
1399 if (ret < 0)
1400 goto error;
1401
b2a4df20 1402 ret = __key_link_begin(keyring, &key->index_key, &edit);
df593ee2
DH
1403 if (ret < 0)
1404 goto error_end;
1da177e4 1405
df593ee2
DH
1406 kdebug("begun {%d,%d}", keyring->serial, refcount_read(&keyring->usage));
1407 ret = __key_link_check_restriction(keyring, key);
1408 if (ret == 0)
1409 ret = __key_link_check_live_key(keyring, key);
1410 if (ret == 0)
1411 __key_link(key, &edit);
1412
1413error_end:
1414 __key_link_end(keyring, &key->index_key, edit);
1415error:
fff29291 1416 kleave(" = %d {%d,%d}", ret, keyring->serial, refcount_read(&keyring->usage));
1da177e4 1417 return ret;
f70e2e06 1418}
1da177e4
LT
1419EXPORT_SYMBOL(key_link);
1420
eb0f68cb
DH
1421/*
1422 * Lock a keyring for unlink.
1423 */
1424static int __key_unlink_lock(struct key *keyring)
1425 __acquires(&keyring->sem)
1426{
1427 if (keyring->type != &key_type_keyring)
1428 return -ENOTDIR;
1429
1430 down_write(&keyring->sem);
1431 return 0;
1432}
1433
1434/*
1435 * Begin the process of unlinking a key from a keyring.
1436 */
1437static int __key_unlink_begin(struct key *keyring, struct key *key,
1438 struct assoc_array_edit **_edit)
1439{
1440 struct assoc_array_edit *edit;
1441
1442 BUG_ON(*_edit != NULL);
1443
1444 edit = assoc_array_delete(&keyring->keys, &keyring_assoc_array_ops,
1445 &key->index_key);
1446 if (IS_ERR(edit))
1447 return PTR_ERR(edit);
1448
1449 if (!edit)
1450 return -ENOENT;
1451
1452 *_edit = edit;
1453 return 0;
1454}
1455
1456/*
1457 * Apply an unlink change.
1458 */
1459static void __key_unlink(struct key *keyring, struct key *key,
1460 struct assoc_array_edit **_edit)
1461{
1462 assoc_array_apply_edit(*_edit);
1463 *_edit = NULL;
1464 key_payload_reserve(keyring, keyring->datalen - KEYQUOTA_LINK_BYTES);
1465}
1466
1467/*
1468 * Finish unlinking a key from to a keyring.
1469 */
1470static void __key_unlink_end(struct key *keyring,
1471 struct key *key,
1472 struct assoc_array_edit *edit)
1473 __releases(&keyring->sem)
1474{
1475 if (edit)
1476 assoc_array_cancel_edit(edit);
1477 up_write(&keyring->sem);
1478}
1479
973c9f4f
DH
1480/**
1481 * key_unlink - Unlink the first link to a key from a keyring.
1482 * @keyring: The keyring to remove the link from.
1483 * @key: The key the link is to.
1484 *
1485 * Remove a link from a keyring to a key.
1486 *
1487 * This function will write-lock the keyring's semaphore.
1488 *
1489 * Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring, -ENOENT if
1490 * the key isn't linked to by the keyring or -ENOMEM if there's insufficient
1491 * memory.
1492 *
1493 * It is assumed that the caller has checked that it is permitted for a link to
1494 * be removed (the keyring should have Write permission; no permissions are
1495 * required on the key).
1da177e4
LT
1496 */
1497int key_unlink(struct key *keyring, struct key *key)
1498{
eb0f68cb 1499 struct assoc_array_edit *edit = NULL;
b2a4df20 1500 int ret;
1da177e4
LT
1501
1502 key_check(keyring);
1503 key_check(key);
1504
eb0f68cb
DH
1505 ret = __key_unlink_lock(keyring);
1506 if (ret < 0)
1507 return ret;
1da177e4 1508
eb0f68cb
DH
1509 ret = __key_unlink_begin(keyring, key, &edit);
1510 if (ret == 0)
1511 __key_unlink(keyring, key, &edit);
1512 __key_unlink_end(keyring, key, edit);
b2a4df20 1513 return ret;
a8b17ed0 1514}
1da177e4
LT
1515EXPORT_SYMBOL(key_unlink);
1516
ed0ac5c7
DH
1517/**
1518 * key_move - Move a key from one keyring to another
1519 * @key: The key to move
1520 * @from_keyring: The keyring to remove the link from.
1521 * @to_keyring: The keyring to make the link in.
1522 * @flags: Qualifying flags, such as KEYCTL_MOVE_EXCL.
1523 *
1524 * Make a link in @to_keyring to a key, such that the keyring holds a reference
1525 * on that key and the key can potentially be found by searching that keyring
1526 * whilst simultaneously removing a link to the key from @from_keyring.
1527 *
1528 * This function will write-lock both keyring's semaphores and will consume
1529 * some of the user's key data quota to hold the link on @to_keyring.
1530 *
1531 * Returns 0 if successful, -ENOTDIR if either keyring isn't a keyring,
1532 * -EKEYREVOKED if either keyring has been revoked, -ENFILE if the second
1533 * keyring is full, -EDQUOT if there is insufficient key data quota remaining
1534 * to add another link or -ENOMEM if there's insufficient memory. If
1535 * KEYCTL_MOVE_EXCL is set, then -EEXIST will be returned if there's already a
1536 * matching key in @to_keyring.
1537 *
1538 * It is assumed that the caller has checked that it is permitted for a link to
1539 * be made (the keyring should have Write permission and the key Link
1540 * permission).
1541 */
1542int key_move(struct key *key,
1543 struct key *from_keyring,
1544 struct key *to_keyring,
1545 unsigned int flags)
1546{
1547 struct assoc_array_edit *from_edit = NULL, *to_edit = NULL;
1548 int ret;
1549
1550 kenter("%d,%d,%d", key->serial, from_keyring->serial, to_keyring->serial);
1551
1552 if (from_keyring == to_keyring)
1553 return 0;
1554
1555 key_check(key);
1556 key_check(from_keyring);
1557 key_check(to_keyring);
1558
1559 ret = __key_move_lock(from_keyring, to_keyring, &key->index_key);
1560 if (ret < 0)
1561 goto out;
1562 ret = __key_unlink_begin(from_keyring, key, &from_edit);
1563 if (ret < 0)
1564 goto error;
1565 ret = __key_link_begin(to_keyring, &key->index_key, &to_edit);
1566 if (ret < 0)
1567 goto error;
1568
1569 ret = -EEXIST;
1570 if (to_edit->dead_leaf && (flags & KEYCTL_MOVE_EXCL))
1571 goto error;
1572
1573 ret = __key_link_check_restriction(to_keyring, key);
1574 if (ret < 0)
1575 goto error;
1576 ret = __key_link_check_live_key(to_keyring, key);
1577 if (ret < 0)
1578 goto error;
1579
1580 __key_unlink(from_keyring, key, &from_edit);
1581 __key_link(key, &to_edit);
1582error:
1583 __key_link_end(to_keyring, &key->index_key, to_edit);
1584 __key_unlink_end(from_keyring, key, from_edit);
1585out:
1586 kleave(" = %d", ret);
1587 return ret;
1588}
1589EXPORT_SYMBOL(key_move);
1590
973c9f4f
DH
1591/**
1592 * keyring_clear - Clear a keyring
1593 * @keyring: The keyring to clear.
1594 *
1595 * Clear the contents of the specified keyring.
1596 *
1597 * Returns 0 if successful or -ENOTDIR if the keyring isn't a keyring.
1da177e4
LT
1598 */
1599int keyring_clear(struct key *keyring)
1600{
b2a4df20 1601 struct assoc_array_edit *edit;
76d8aeab 1602 int ret;
1da177e4 1603
b2a4df20
DH
1604 if (keyring->type != &key_type_keyring)
1605 return -ENOTDIR;
1da177e4 1606
b2a4df20 1607 down_write(&keyring->sem);
1da177e4 1608
b2a4df20
DH
1609 edit = assoc_array_clear(&keyring->keys, &keyring_assoc_array_ops);
1610 if (IS_ERR(edit)) {
1611 ret = PTR_ERR(edit);
1612 } else {
1613 if (edit)
1614 assoc_array_apply_edit(edit);
1615 key_payload_reserve(keyring, 0);
1da177e4
LT
1616 ret = 0;
1617 }
1618
b2a4df20 1619 up_write(&keyring->sem);
1da177e4 1620 return ret;
a8b17ed0 1621}
1da177e4 1622EXPORT_SYMBOL(keyring_clear);
31204ed9 1623
31204ed9 1624/*
973c9f4f
DH
1625 * Dispose of the links from a revoked keyring.
1626 *
1627 * This is called with the key sem write-locked.
31204ed9
DH
1628 */
1629static void keyring_revoke(struct key *keyring)
1630{
b2a4df20 1631 struct assoc_array_edit *edit;
f0641cba 1632
b2a4df20
DH
1633 edit = assoc_array_clear(&keyring->keys, &keyring_assoc_array_ops);
1634 if (!IS_ERR(edit)) {
1635 if (edit)
1636 assoc_array_apply_edit(edit);
1637 key_payload_reserve(keyring, 0);
1638 }
1639}
31204ed9 1640
62fe3182 1641static bool keyring_gc_select_iterator(void *object, void *iterator_data)
b2a4df20
DH
1642{
1643 struct key *key = keyring_ptr_to_key(object);
074d5898 1644 time64_t *limit = iterator_data;
31204ed9 1645
b2a4df20
DH
1646 if (key_is_dead(key, *limit))
1647 return false;
1648 key_get(key);
1649 return true;
a8b17ed0 1650}
5d135440 1651
62fe3182
DH
1652static int keyring_gc_check_iterator(const void *object, void *iterator_data)
1653{
1654 const struct key *key = keyring_ptr_to_key(object);
074d5898 1655 time64_t *limit = iterator_data;
62fe3182
DH
1656
1657 key_check(key);
1658 return key_is_dead(key, *limit);
1659}
1660
5d135440 1661/*
62fe3182 1662 * Garbage collect pointers from a keyring.
973c9f4f 1663 *
62fe3182
DH
1664 * Not called with any locks held. The keyring's key struct will not be
1665 * deallocated under us as only our caller may deallocate it.
5d135440 1666 */
074d5898 1667void keyring_gc(struct key *keyring, time64_t limit)
5d135440 1668{
62fe3182
DH
1669 int result;
1670
1671 kenter("%x{%s}", keyring->serial, keyring->description ?: "");
5d135440 1672
62fe3182
DH
1673 if (keyring->flags & ((1 << KEY_FLAG_INVALIDATED) |
1674 (1 << KEY_FLAG_REVOKED)))
1675 goto dont_gc;
1676
1677 /* scan the keyring looking for dead keys */
1678 rcu_read_lock();
1679 result = assoc_array_iterate(&keyring->keys,
1680 keyring_gc_check_iterator, &limit);
1681 rcu_read_unlock();
1682 if (result == true)
1683 goto do_gc;
1684
1685dont_gc:
1686 kleave(" [no gc]");
1687 return;
1688
1689do_gc:
5d135440 1690 down_write(&keyring->sem);
b2a4df20 1691 assoc_array_gc(&keyring->keys, &keyring_assoc_array_ops,
62fe3182 1692 keyring_gc_select_iterator, &limit);
c08ef808 1693 up_write(&keyring->sem);
62fe3182 1694 kleave(" [gc]");
5d135440 1695}
2b6aa412
MM
1696
1697/*
1698 * Garbage collect restriction pointers from a keyring.
1699 *
1700 * Keyring restrictions are associated with a key type, and must be cleaned
1701 * up if the key type is unregistered. The restriction is altered to always
1702 * reject additional keys so a keyring cannot be opened up by unregistering
1703 * a key type.
1704 *
1705 * Not called with any keyring locks held. The keyring's key struct will not
1706 * be deallocated under us as only our caller may deallocate it.
1707 *
1708 * The caller is required to hold key_types_sem and dead_type->sem. This is
1709 * fulfilled by key_gc_keytype() holding the locks on behalf of
1710 * key_garbage_collector(), which it invokes on a workqueue.
1711 */
1712void keyring_restriction_gc(struct key *keyring, struct key_type *dead_type)
1713{
1714 struct key_restriction *keyres;
1715
1716 kenter("%x{%s}", keyring->serial, keyring->description ?: "");
1717
1718 /*
1719 * keyring->restrict_link is only assigned at key allocation time
1720 * or with the key type locked, so the only values that could be
1721 * concurrently assigned to keyring->restrict_link are for key
1722 * types other than dead_type. Given this, it's ok to check
1723 * the key type before acquiring keyring->sem.
1724 */
1725 if (!dead_type || !keyring->restrict_link ||
1726 keyring->restrict_link->keytype != dead_type) {
1727 kleave(" [no restriction gc]");
1728 return;
1729 }
1730
1731 /* Lock the keyring to ensure that a link is not in progress */
1732 down_write(&keyring->sem);
1733
1734 keyres = keyring->restrict_link;
1735
1736 keyres->check = restrict_link_reject;
1737
1738 key_put(keyres->key);
1739 keyres->key = NULL;
1740 keyres->keytype = NULL;
1741
1742 up_write(&keyring->sem);
1743
1744 kleave(" [restriction gc]");
1745}