key.c 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106
  1. /* Basic authentication token and access key management
  2. *
  3. * Copyright (C) 2004-2008 Red Hat, Inc. All Rights Reserved.
  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. #include <linux/module.h>
  12. #include <linux/init.h>
  13. #include <linux/poison.h>
  14. #include <linux/sched.h>
  15. #include <linux/slab.h>
  16. #include <linux/security.h>
  17. #include <linux/workqueue.h>
  18. #include <linux/random.h>
  19. #include <linux/err.h>
  20. #include <linux/user_namespace.h>
  21. #include "internal.h"
  22. struct kmem_cache *key_jar;
  23. struct rb_root key_serial_tree; /* tree of keys indexed by serial */
  24. DEFINE_SPINLOCK(key_serial_lock);
  25. struct rb_root key_user_tree; /* tree of quota records indexed by UID */
  26. DEFINE_SPINLOCK(key_user_lock);
  27. unsigned int key_quota_root_maxkeys = 200; /* root's key count quota */
  28. unsigned int key_quota_root_maxbytes = 20000; /* root's key space quota */
  29. unsigned int key_quota_maxkeys = 200; /* general key count quota */
  30. unsigned int key_quota_maxbytes = 20000; /* general key space quota */
  31. static LIST_HEAD(key_types_list);
  32. static DECLARE_RWSEM(key_types_sem);
  33. /* We serialise key instantiation and link */
  34. DEFINE_MUTEX(key_construction_mutex);
  35. #ifdef KEY_DEBUGGING
  36. void __key_check(const struct key *key)
  37. {
  38. printk("__key_check: key %p {%08x} should be {%08x}\n",
  39. key, key->magic, KEY_DEBUG_MAGIC);
  40. BUG();
  41. }
  42. #endif
  43. /*
  44. * Get the key quota record for a user, allocating a new record if one doesn't
  45. * already exist.
  46. */
  47. struct key_user *key_user_lookup(uid_t uid, struct user_namespace *user_ns)
  48. {
  49. struct key_user *candidate = NULL, *user;
  50. struct rb_node *parent = NULL;
  51. struct rb_node **p;
  52. try_again:
  53. p = &key_user_tree.rb_node;
  54. spin_lock(&key_user_lock);
  55. /* search the tree for a user record with a matching UID */
  56. while (*p) {
  57. parent = *p;
  58. user = rb_entry(parent, struct key_user, node);
  59. if (uid < user->uid)
  60. p = &(*p)->rb_left;
  61. else if (uid > user->uid)
  62. p = &(*p)->rb_right;
  63. else if (user_ns < user->user_ns)
  64. p = &(*p)->rb_left;
  65. else if (user_ns > user->user_ns)
  66. p = &(*p)->rb_right;
  67. else
  68. goto found;
  69. }
  70. /* if we get here, we failed to find a match in the tree */
  71. if (!candidate) {
  72. /* allocate a candidate user record if we don't already have
  73. * one */
  74. spin_unlock(&key_user_lock);
  75. user = NULL;
  76. candidate = kmalloc(sizeof(struct key_user), GFP_KERNEL);
  77. if (unlikely(!candidate))
  78. goto out;
  79. /* the allocation may have scheduled, so we need to repeat the
  80. * search lest someone else added the record whilst we were
  81. * asleep */
  82. goto try_again;
  83. }
  84. /* if we get here, then the user record still hadn't appeared on the
  85. * second pass - so we use the candidate record */
  86. atomic_set(&candidate->usage, 1);
  87. atomic_set(&candidate->nkeys, 0);
  88. atomic_set(&candidate->nikeys, 0);
  89. candidate->uid = uid;
  90. candidate->user_ns = get_user_ns(user_ns);
  91. candidate->qnkeys = 0;
  92. candidate->qnbytes = 0;
  93. spin_lock_init(&candidate->lock);
  94. mutex_init(&candidate->cons_lock);
  95. rb_link_node(&candidate->node, parent, p);
  96. rb_insert_color(&candidate->node, &key_user_tree);
  97. spin_unlock(&key_user_lock);
  98. user = candidate;
  99. goto out;
  100. /* okay - we found a user record for this UID */
  101. found:
  102. atomic_inc(&user->usage);
  103. spin_unlock(&key_user_lock);
  104. kfree(candidate);
  105. out:
  106. return user;
  107. }
  108. /*
  109. * Dispose of a user structure
  110. */
  111. void key_user_put(struct key_user *user)
  112. {
  113. if (atomic_dec_and_lock(&user->usage, &key_user_lock)) {
  114. rb_erase(&user->node, &key_user_tree);
  115. spin_unlock(&key_user_lock);
  116. put_user_ns(user->user_ns);
  117. kfree(user);
  118. }
  119. }
  120. /*
  121. * Allocate a serial number for a key. These are assigned randomly to avoid
  122. * security issues through covert channel problems.
  123. */
  124. static inline void key_alloc_serial(struct key *key)
  125. {
  126. struct rb_node *parent, **p;
  127. struct key *xkey;
  128. /* propose a random serial number and look for a hole for it in the
  129. * serial number tree */
  130. do {
  131. get_random_bytes(&key->serial, sizeof(key->serial));
  132. key->serial >>= 1; /* negative numbers are not permitted */
  133. } while (key->serial < 3);
  134. spin_lock(&key_serial_lock);
  135. attempt_insertion:
  136. parent = NULL;
  137. p = &key_serial_tree.rb_node;
  138. while (*p) {
  139. parent = *p;
  140. xkey = rb_entry(parent, struct key, serial_node);
  141. if (key->serial < xkey->serial)
  142. p = &(*p)->rb_left;
  143. else if (key->serial > xkey->serial)
  144. p = &(*p)->rb_right;
  145. else
  146. goto serial_exists;
  147. }
  148. /* we've found a suitable hole - arrange for this key to occupy it */
  149. rb_link_node(&key->serial_node, parent, p);
  150. rb_insert_color(&key->serial_node, &key_serial_tree);
  151. spin_unlock(&key_serial_lock);
  152. return;
  153. /* we found a key with the proposed serial number - walk the tree from
  154. * that point looking for the next unused serial number */
  155. serial_exists:
  156. for (;;) {
  157. key->serial++;
  158. if (key->serial < 3) {
  159. key->serial = 3;
  160. goto attempt_insertion;
  161. }
  162. parent = rb_next(parent);
  163. if (!parent)
  164. goto attempt_insertion;
  165. xkey = rb_entry(parent, struct key, serial_node);
  166. if (key->serial < xkey->serial)
  167. goto attempt_insertion;
  168. }
  169. }
  170. /**
  171. * key_alloc - Allocate a key of the specified type.
  172. * @type: The type of key to allocate.
  173. * @desc: The key description to allow the key to be searched out.
  174. * @uid: The owner of the new key.
  175. * @gid: The group ID for the new key's group permissions.
  176. * @cred: The credentials specifying UID namespace.
  177. * @perm: The permissions mask of the new key.
  178. * @flags: Flags specifying quota properties.
  179. *
  180. * Allocate a key of the specified type with the attributes given. The key is
  181. * returned in an uninstantiated state and the caller needs to instantiate the
  182. * key before returning.
  183. *
  184. * The user's key count quota is updated to reflect the creation of the key and
  185. * the user's key data quota has the default for the key type reserved. The
  186. * instantiation function should amend this as necessary. If insufficient
  187. * quota is available, -EDQUOT will be returned.
  188. *
  189. * The LSM security modules can prevent a key being created, in which case
  190. * -EACCES will be returned.
  191. *
  192. * Returns a pointer to the new key if successful and an error code otherwise.
  193. *
  194. * Note that the caller needs to ensure the key type isn't uninstantiated.
  195. * Internally this can be done by locking key_types_sem. Externally, this can
  196. * be done by either never unregistering the key type, or making sure
  197. * key_alloc() calls don't race with module unloading.
  198. */
  199. struct key *key_alloc(struct key_type *type, const char *desc,
  200. uid_t uid, gid_t gid, const struct cred *cred,
  201. key_perm_t perm, unsigned long flags)
  202. {
  203. struct key_user *user = NULL;
  204. struct key *key;
  205. size_t desclen, quotalen;
  206. int ret;
  207. key = ERR_PTR(-EINVAL);
  208. if (!desc || !*desc)
  209. goto error;
  210. if (type->vet_description) {
  211. ret = type->vet_description(desc);
  212. if (ret < 0) {
  213. key = ERR_PTR(ret);
  214. goto error;
  215. }
  216. }
  217. desclen = strlen(desc) + 1;
  218. quotalen = desclen + type->def_datalen;
  219. /* get hold of the key tracking for this user */
  220. user = key_user_lookup(uid, cred->user_ns);
  221. if (!user)
  222. goto no_memory_1;
  223. /* check that the user's quota permits allocation of another key and
  224. * its description */
  225. if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) {
  226. unsigned maxkeys = (uid == 0) ?
  227. key_quota_root_maxkeys : key_quota_maxkeys;
  228. unsigned maxbytes = (uid == 0) ?
  229. key_quota_root_maxbytes : key_quota_maxbytes;
  230. spin_lock(&user->lock);
  231. if (!(flags & KEY_ALLOC_QUOTA_OVERRUN)) {
  232. if (user->qnkeys + 1 >= maxkeys ||
  233. user->qnbytes + quotalen >= maxbytes ||
  234. user->qnbytes + quotalen < user->qnbytes)
  235. goto no_quota;
  236. }
  237. user->qnkeys++;
  238. user->qnbytes += quotalen;
  239. spin_unlock(&user->lock);
  240. }
  241. /* allocate and initialise the key and its description */
  242. key = kmem_cache_alloc(key_jar, GFP_KERNEL);
  243. if (!key)
  244. goto no_memory_2;
  245. if (desc) {
  246. key->description = kmemdup(desc, desclen, GFP_KERNEL);
  247. if (!key->description)
  248. goto no_memory_3;
  249. }
  250. atomic_set(&key->usage, 1);
  251. init_rwsem(&key->sem);
  252. lockdep_set_class(&key->sem, &type->lock_class);
  253. key->type = type;
  254. key->user = user;
  255. key->quotalen = quotalen;
  256. key->datalen = type->def_datalen;
  257. key->uid = uid;
  258. key->gid = gid;
  259. key->perm = perm;
  260. key->flags = 0;
  261. key->expiry = 0;
  262. key->payload.data = NULL;
  263. key->security = NULL;
  264. if (!(flags & KEY_ALLOC_NOT_IN_QUOTA))
  265. key->flags |= 1 << KEY_FLAG_IN_QUOTA;
  266. memset(&key->type_data, 0, sizeof(key->type_data));
  267. #ifdef KEY_DEBUGGING
  268. key->magic = KEY_DEBUG_MAGIC;
  269. #endif
  270. /* let the security module know about the key */
  271. ret = security_key_alloc(key, cred, flags);
  272. if (ret < 0)
  273. goto security_error;
  274. /* publish the key by giving it a serial number */
  275. atomic_inc(&user->nkeys);
  276. key_alloc_serial(key);
  277. error:
  278. return key;
  279. security_error:
  280. kfree(key->description);
  281. kmem_cache_free(key_jar, key);
  282. if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) {
  283. spin_lock(&user->lock);
  284. user->qnkeys--;
  285. user->qnbytes -= quotalen;
  286. spin_unlock(&user->lock);
  287. }
  288. key_user_put(user);
  289. key = ERR_PTR(ret);
  290. goto error;
  291. no_memory_3:
  292. kmem_cache_free(key_jar, key);
  293. no_memory_2:
  294. if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) {
  295. spin_lock(&user->lock);
  296. user->qnkeys--;
  297. user->qnbytes -= quotalen;
  298. spin_unlock(&user->lock);
  299. }
  300. key_user_put(user);
  301. no_memory_1:
  302. key = ERR_PTR(-ENOMEM);
  303. goto error;
  304. no_quota:
  305. spin_unlock(&user->lock);
  306. key_user_put(user);
  307. key = ERR_PTR(-EDQUOT);
  308. goto error;
  309. }
  310. EXPORT_SYMBOL(key_alloc);
  311. /**
  312. * key_payload_reserve - Adjust data quota reservation for the key's payload
  313. * @key: The key to make the reservation for.
  314. * @datalen: The amount of data payload the caller now wants.
  315. *
  316. * Adjust the amount of the owning user's key data quota that a key reserves.
  317. * If the amount is increased, then -EDQUOT may be returned if there isn't
  318. * enough free quota available.
  319. *
  320. * If successful, 0 is returned.
  321. */
  322. int key_payload_reserve(struct key *key, size_t datalen)
  323. {
  324. int delta = (int)datalen - key->datalen;
  325. int ret = 0;
  326. key_check(key);
  327. /* contemplate the quota adjustment */
  328. if (delta != 0 && test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) {
  329. unsigned maxbytes = (key->user->uid == 0) ?
  330. key_quota_root_maxbytes : key_quota_maxbytes;
  331. spin_lock(&key->user->lock);
  332. if (delta > 0 &&
  333. (key->user->qnbytes + delta >= maxbytes ||
  334. key->user->qnbytes + delta < key->user->qnbytes)) {
  335. ret = -EDQUOT;
  336. }
  337. else {
  338. key->user->qnbytes += delta;
  339. key->quotalen += delta;
  340. }
  341. spin_unlock(&key->user->lock);
  342. }
  343. /* change the recorded data length if that didn't generate an error */
  344. if (ret == 0)
  345. key->datalen = datalen;
  346. return ret;
  347. }
  348. EXPORT_SYMBOL(key_payload_reserve);
  349. /*
  350. * Instantiate a key and link it into the target keyring atomically. Must be
  351. * called with the target keyring's semaphore writelocked. The target key's
  352. * semaphore need not be locked as instantiation is serialised by
  353. * key_construction_mutex.
  354. */
  355. static int __key_instantiate_and_link(struct key *key,
  356. struct key_preparsed_payload *prep,
  357. struct key *keyring,
  358. struct key *authkey,
  359. unsigned long *_prealloc)
  360. {
  361. int ret, awaken;
  362. key_check(key);
  363. key_check(keyring);
  364. awaken = 0;
  365. ret = -EBUSY;
  366. mutex_lock(&key_construction_mutex);
  367. /* can't instantiate twice */
  368. if (!test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) {
  369. /* instantiate the key */
  370. ret = key->type->instantiate(key, prep);
  371. if (ret == 0) {
  372. /* mark the key as being instantiated */
  373. atomic_inc(&key->user->nikeys);
  374. set_bit(KEY_FLAG_INSTANTIATED, &key->flags);
  375. if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))
  376. awaken = 1;
  377. /* and link it into the destination keyring */
  378. if (keyring)
  379. __key_link(keyring, key, _prealloc);
  380. /* disable the authorisation key */
  381. if (authkey)
  382. key_revoke(authkey);
  383. }
  384. }
  385. mutex_unlock(&key_construction_mutex);
  386. /* wake up anyone waiting for a key to be constructed */
  387. if (awaken)
  388. wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);
  389. return ret;
  390. }
  391. /**
  392. * key_instantiate_and_link - Instantiate a key and link it into the keyring.
  393. * @key: The key to instantiate.
  394. * @data: The data to use to instantiate the keyring.
  395. * @datalen: The length of @data.
  396. * @keyring: Keyring to create a link in on success (or NULL).
  397. * @authkey: The authorisation token permitting instantiation.
  398. *
  399. * Instantiate a key that's in the uninstantiated state using the provided data
  400. * and, if successful, link it in to the destination keyring if one is
  401. * supplied.
  402. *
  403. * If successful, 0 is returned, the authorisation token is revoked and anyone
  404. * waiting for the key is woken up. If the key was already instantiated,
  405. * -EBUSY will be returned.
  406. */
  407. int key_instantiate_and_link(struct key *key,
  408. const void *data,
  409. size_t datalen,
  410. struct key *keyring,
  411. struct key *authkey)
  412. {
  413. struct key_preparsed_payload prep;
  414. unsigned long prealloc;
  415. int ret;
  416. memset(&prep, 0, sizeof(prep));
  417. prep.data = data;
  418. prep.datalen = datalen;
  419. prep.quotalen = key->type->def_datalen;
  420. if (key->type->preparse) {
  421. ret = key->type->preparse(&prep);
  422. if (ret < 0)
  423. goto error;
  424. }
  425. if (keyring) {
  426. ret = __key_link_begin(keyring, key->type, key->description,
  427. &prealloc);
  428. if (ret < 0)
  429. goto error_free_preparse;
  430. }
  431. ret = __key_instantiate_and_link(key, &prep, keyring, authkey,
  432. &prealloc);
  433. if (keyring)
  434. __key_link_end(keyring, key->type, prealloc);
  435. error_free_preparse:
  436. if (key->type->preparse)
  437. key->type->free_preparse(&prep);
  438. error:
  439. return ret;
  440. }
  441. EXPORT_SYMBOL(key_instantiate_and_link);
  442. /**
  443. * key_reject_and_link - Negatively instantiate a key and link it into the keyring.
  444. * @key: The key to instantiate.
  445. * @timeout: The timeout on the negative key.
  446. * @error: The error to return when the key is hit.
  447. * @keyring: Keyring to create a link in on success (or NULL).
  448. * @authkey: The authorisation token permitting instantiation.
  449. *
  450. * Negatively instantiate a key that's in the uninstantiated state and, if
  451. * successful, set its timeout and stored error and link it in to the
  452. * destination keyring if one is supplied. The key and any links to the key
  453. * will be automatically garbage collected after the timeout expires.
  454. *
  455. * Negative keys are used to rate limit repeated request_key() calls by causing
  456. * them to return the stored error code (typically ENOKEY) until the negative
  457. * key expires.
  458. *
  459. * If successful, 0 is returned, the authorisation token is revoked and anyone
  460. * waiting for the key is woken up. If the key was already instantiated,
  461. * -EBUSY will be returned.
  462. */
  463. int key_reject_and_link(struct key *key,
  464. unsigned timeout,
  465. unsigned error,
  466. struct key *keyring,
  467. struct key *authkey)
  468. {
  469. unsigned long prealloc;
  470. struct timespec now;
  471. int ret, awaken, link_ret = 0;
  472. key_check(key);
  473. key_check(keyring);
  474. awaken = 0;
  475. ret = -EBUSY;
  476. if (keyring)
  477. link_ret = __key_link_begin(keyring, key->type,
  478. key->description, &prealloc);
  479. mutex_lock(&key_construction_mutex);
  480. /* can't instantiate twice */
  481. if (!test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) {
  482. /* mark the key as being negatively instantiated */
  483. atomic_inc(&key->user->nikeys);
  484. set_bit(KEY_FLAG_NEGATIVE, &key->flags);
  485. set_bit(KEY_FLAG_INSTANTIATED, &key->flags);
  486. key->type_data.reject_error = -error;
  487. now = current_kernel_time();
  488. key->expiry = now.tv_sec + timeout;
  489. key_schedule_gc(key->expiry + key_gc_delay);
  490. if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))
  491. awaken = 1;
  492. ret = 0;
  493. /* and link it into the destination keyring */
  494. if (keyring && link_ret == 0)
  495. __key_link(keyring, key, &prealloc);
  496. /* disable the authorisation key */
  497. if (authkey)
  498. key_revoke(authkey);
  499. }
  500. mutex_unlock(&key_construction_mutex);
  501. if (keyring)
  502. __key_link_end(keyring, key->type, prealloc);
  503. /* wake up anyone waiting for a key to be constructed */
  504. if (awaken)
  505. wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);
  506. return ret == 0 ? link_ret : ret;
  507. }
  508. EXPORT_SYMBOL(key_reject_and_link);
  509. /**
  510. * key_put - Discard a reference to a key.
  511. * @key: The key to discard a reference from.
  512. *
  513. * Discard a reference to a key, and when all the references are gone, we
  514. * schedule the cleanup task to come and pull it out of the tree in process
  515. * context at some later time.
  516. */
  517. void key_put(struct key *key)
  518. {
  519. if (key) {
  520. key_check(key);
  521. if (atomic_dec_and_test(&key->usage))
  522. queue_work(system_nrt_wq, &key_gc_work);
  523. }
  524. }
  525. EXPORT_SYMBOL(key_put);
  526. /*
  527. * Find a key by its serial number.
  528. */
  529. struct key *key_lookup(key_serial_t id)
  530. {
  531. struct rb_node *n;
  532. struct key *key;
  533. spin_lock(&key_serial_lock);
  534. /* search the tree for the specified key */
  535. n = key_serial_tree.rb_node;
  536. while (n) {
  537. key = rb_entry(n, struct key, serial_node);
  538. if (id < key->serial)
  539. n = n->rb_left;
  540. else if (id > key->serial)
  541. n = n->rb_right;
  542. else
  543. goto found;
  544. }
  545. not_found:
  546. key = ERR_PTR(-ENOKEY);
  547. goto error;
  548. found:
  549. /* pretend it doesn't exist if it is awaiting deletion */
  550. if (atomic_read(&key->usage) == 0)
  551. goto not_found;
  552. /* this races with key_put(), but that doesn't matter since key_put()
  553. * doesn't actually change the key
  554. */
  555. atomic_inc(&key->usage);
  556. error:
  557. spin_unlock(&key_serial_lock);
  558. return key;
  559. }
  560. /*
  561. * Find and lock the specified key type against removal.
  562. *
  563. * We return with the sem read-locked if successful. If the type wasn't
  564. * available -ENOKEY is returned instead.
  565. */
  566. struct key_type *key_type_lookup(const char *type)
  567. {
  568. struct key_type *ktype;
  569. down_read(&key_types_sem);
  570. /* look up the key type to see if it's one of the registered kernel
  571. * types */
  572. list_for_each_entry(ktype, &key_types_list, link) {
  573. if (strcmp(ktype->name, type) == 0)
  574. goto found_kernel_type;
  575. }
  576. up_read(&key_types_sem);
  577. ktype = ERR_PTR(-ENOKEY);
  578. found_kernel_type:
  579. return ktype;
  580. }
  581. void key_set_timeout(struct key *key, unsigned timeout)
  582. {
  583. struct timespec now;
  584. time_t expiry = 0;
  585. /* make the changes with the locks held to prevent races */
  586. down_write(&key->sem);
  587. if (timeout > 0) {
  588. now = current_kernel_time();
  589. expiry = now.tv_sec + timeout;
  590. }
  591. key->expiry = expiry;
  592. key_schedule_gc(key->expiry + key_gc_delay);
  593. up_write(&key->sem);
  594. }
  595. EXPORT_SYMBOL_GPL(key_set_timeout);
  596. /*
  597. * Unlock a key type locked by key_type_lookup().
  598. */
  599. void key_type_put(struct key_type *ktype)
  600. {
  601. up_read(&key_types_sem);
  602. }
  603. /*
  604. * Attempt to update an existing key.
  605. *
  606. * The key is given to us with an incremented refcount that we need to discard
  607. * if we get an error.
  608. */
  609. static inline key_ref_t __key_update(key_ref_t key_ref,
  610. struct key_preparsed_payload *prep)
  611. {
  612. struct key *key = key_ref_to_ptr(key_ref);
  613. int ret;
  614. /* need write permission on the key to update it */
  615. ret = key_permission(key_ref, KEY_WRITE);
  616. if (ret < 0)
  617. goto error;
  618. ret = -EEXIST;
  619. if (!key->type->update)
  620. goto error;
  621. down_write(&key->sem);
  622. ret = key->type->update(key, prep);
  623. if (ret == 0)
  624. /* updating a negative key instantiates it */
  625. clear_bit(KEY_FLAG_NEGATIVE, &key->flags);
  626. up_write(&key->sem);
  627. if (ret < 0)
  628. goto error;
  629. out:
  630. return key_ref;
  631. error:
  632. key_put(key);
  633. key_ref = ERR_PTR(ret);
  634. goto out;
  635. }
  636. /**
  637. * key_create_or_update - Update or create and instantiate a key.
  638. * @keyring_ref: A pointer to the destination keyring with possession flag.
  639. * @type: The type of key.
  640. * @description: The searchable description for the key.
  641. * @payload: The data to use to instantiate or update the key.
  642. * @plen: The length of @payload.
  643. * @perm: The permissions mask for a new key.
  644. * @flags: The quota flags for a new key.
  645. *
  646. * Search the destination keyring for a key of the same description and if one
  647. * is found, update it, otherwise create and instantiate a new one and create a
  648. * link to it from that keyring.
  649. *
  650. * If perm is KEY_PERM_UNDEF then an appropriate key permissions mask will be
  651. * concocted.
  652. *
  653. * Returns a pointer to the new key if successful, -ENODEV if the key type
  654. * wasn't available, -ENOTDIR if the keyring wasn't a keyring, -EACCES if the
  655. * caller isn't permitted to modify the keyring or the LSM did not permit
  656. * creation of the key.
  657. *
  658. * On success, the possession flag from the keyring ref will be tacked on to
  659. * the key ref before it is returned.
  660. */
  661. key_ref_t key_create_or_update(key_ref_t keyring_ref,
  662. const char *type,
  663. const char *description,
  664. const void *payload,
  665. size_t plen,
  666. key_perm_t perm,
  667. unsigned long flags)
  668. {
  669. unsigned long prealloc;
  670. struct key_preparsed_payload prep;
  671. const struct cred *cred = current_cred();
  672. struct key_type *ktype;
  673. struct key *keyring, *key = NULL;
  674. key_ref_t key_ref;
  675. int ret;
  676. /* look up the key type to see if it's one of the registered kernel
  677. * types */
  678. ktype = key_type_lookup(type);
  679. if (IS_ERR(ktype)) {
  680. key_ref = ERR_PTR(-ENODEV);
  681. goto error;
  682. }
  683. key_ref = ERR_PTR(-EINVAL);
  684. if (!ktype->match || !ktype->instantiate ||
  685. (!description && !ktype->preparse))
  686. goto error_put_type;
  687. keyring = key_ref_to_ptr(keyring_ref);
  688. key_check(keyring);
  689. key_ref = ERR_PTR(-ENOTDIR);
  690. if (keyring->type != &key_type_keyring)
  691. goto error_put_type;
  692. memset(&prep, 0, sizeof(prep));
  693. prep.data = payload;
  694. prep.datalen = plen;
  695. prep.quotalen = ktype->def_datalen;
  696. if (ktype->preparse) {
  697. ret = ktype->preparse(&prep);
  698. if (ret < 0) {
  699. key_ref = ERR_PTR(ret);
  700. goto error_put_type;
  701. }
  702. if (!description)
  703. description = prep.description;
  704. key_ref = ERR_PTR(-EINVAL);
  705. if (!description)
  706. goto error_free_prep;
  707. }
  708. ret = __key_link_begin(keyring, ktype, description, &prealloc);
  709. if (ret < 0) {
  710. key_ref = ERR_PTR(ret);
  711. goto error_free_prep;
  712. }
  713. /* if we're going to allocate a new key, we're going to have
  714. * to modify the keyring */
  715. ret = key_permission(keyring_ref, KEY_WRITE);
  716. if (ret < 0) {
  717. key_ref = ERR_PTR(ret);
  718. goto error_link_end;
  719. }
  720. /* if it's possible to update this type of key, search for an existing
  721. * key of the same type and description in the destination keyring and
  722. * update that instead if possible
  723. */
  724. if (ktype->update) {
  725. key_ref = __keyring_search_one(keyring_ref, ktype, description,
  726. 0);
  727. if (!IS_ERR(key_ref))
  728. goto found_matching_key;
  729. }
  730. /* if the client doesn't provide, decide on the permissions we want */
  731. if (perm == KEY_PERM_UNDEF) {
  732. perm = KEY_POS_VIEW | KEY_POS_SEARCH | KEY_POS_LINK | KEY_POS_SETATTR;
  733. perm |= KEY_USR_VIEW | KEY_USR_SEARCH | KEY_USR_LINK | KEY_USR_SETATTR;
  734. if (ktype->read)
  735. perm |= KEY_POS_READ | KEY_USR_READ;
  736. if (ktype == &key_type_keyring || ktype->update)
  737. perm |= KEY_USR_WRITE;
  738. }
  739. /* allocate a new key */
  740. key = key_alloc(ktype, description, cred->fsuid, cred->fsgid, cred,
  741. perm, flags);
  742. if (IS_ERR(key)) {
  743. key_ref = ERR_CAST(key);
  744. goto error_link_end;
  745. }
  746. /* instantiate it and link it into the target keyring */
  747. ret = __key_instantiate_and_link(key, &prep, keyring, NULL, &prealloc);
  748. if (ret < 0) {
  749. key_put(key);
  750. key_ref = ERR_PTR(ret);
  751. goto error_link_end;
  752. }
  753. key_ref = make_key_ref(key, is_key_possessed(keyring_ref));
  754. error_link_end:
  755. __key_link_end(keyring, ktype, prealloc);
  756. error_free_prep:
  757. if (ktype->preparse)
  758. ktype->free_preparse(&prep);
  759. error_put_type:
  760. key_type_put(ktype);
  761. error:
  762. return key_ref;
  763. found_matching_key:
  764. /* we found a matching key, so we're going to try to update it
  765. * - we can drop the locks first as we have the key pinned
  766. */
  767. __key_link_end(keyring, ktype, prealloc);
  768. key_ref = __key_update(key_ref, &prep);
  769. goto error_free_prep;
  770. }
  771. EXPORT_SYMBOL(key_create_or_update);
  772. /**
  773. * key_update - Update a key's contents.
  774. * @key_ref: The pointer (plus possession flag) to the key.
  775. * @payload: The data to be used to update the key.
  776. * @plen: The length of @payload.
  777. *
  778. * Attempt to update the contents of a key with the given payload data. The
  779. * caller must be granted Write permission on the key. Negative keys can be
  780. * instantiated by this method.
  781. *
  782. * Returns 0 on success, -EACCES if not permitted and -EOPNOTSUPP if the key
  783. * type does not support updating. The key type may return other errors.
  784. */
  785. int key_update(key_ref_t key_ref, const void *payload, size_t plen)
  786. {
  787. struct key_preparsed_payload prep;
  788. struct key *key = key_ref_to_ptr(key_ref);
  789. int ret;
  790. key_check(key);
  791. /* the key must be writable */
  792. ret = key_permission(key_ref, KEY_WRITE);
  793. if (ret < 0)
  794. goto error;
  795. /* attempt to update it if supported */
  796. ret = -EOPNOTSUPP;
  797. if (!key->type->update)
  798. goto error;
  799. memset(&prep, 0, sizeof(prep));
  800. prep.data = payload;
  801. prep.datalen = plen;
  802. prep.quotalen = key->type->def_datalen;
  803. if (key->type->preparse) {
  804. ret = key->type->preparse(&prep);
  805. if (ret < 0)
  806. goto error;
  807. }
  808. down_write(&key->sem);
  809. ret = key->type->update(key, &prep);
  810. if (ret == 0)
  811. /* updating a negative key instantiates it */
  812. clear_bit(KEY_FLAG_NEGATIVE, &key->flags);
  813. up_write(&key->sem);
  814. if (key->type->preparse)
  815. key->type->free_preparse(&prep);
  816. error:
  817. return ret;
  818. }
  819. EXPORT_SYMBOL(key_update);
  820. /**
  821. * key_revoke - Revoke a key.
  822. * @key: The key to be revoked.
  823. *
  824. * Mark a key as being revoked and ask the type to free up its resources. The
  825. * revocation timeout is set and the key and all its links will be
  826. * automatically garbage collected after key_gc_delay amount of time if they
  827. * are not manually dealt with first.
  828. */
  829. void key_revoke(struct key *key)
  830. {
  831. struct timespec now;
  832. time_t time;
  833. key_check(key);
  834. /* make sure no one's trying to change or use the key when we mark it
  835. * - we tell lockdep that we might nest because we might be revoking an
  836. * authorisation key whilst holding the sem on a key we've just
  837. * instantiated
  838. */
  839. down_write_nested(&key->sem, 1);
  840. if (!test_and_set_bit(KEY_FLAG_REVOKED, &key->flags) &&
  841. key->type->revoke)
  842. key->type->revoke(key);
  843. /* set the death time to no more than the expiry time */
  844. now = current_kernel_time();
  845. time = now.tv_sec;
  846. if (key->revoked_at == 0 || key->revoked_at > time) {
  847. key->revoked_at = time;
  848. key_schedule_gc(key->revoked_at + key_gc_delay);
  849. }
  850. up_write(&key->sem);
  851. }
  852. EXPORT_SYMBOL(key_revoke);
  853. /**
  854. * key_invalidate - Invalidate a key.
  855. * @key: The key to be invalidated.
  856. *
  857. * Mark a key as being invalidated and have it cleaned up immediately. The key
  858. * is ignored by all searches and other operations from this point.
  859. */
  860. void key_invalidate(struct key *key)
  861. {
  862. kenter("%d", key_serial(key));
  863. key_check(key);
  864. if (!test_bit(KEY_FLAG_INVALIDATED, &key->flags)) {
  865. down_write_nested(&key->sem, 1);
  866. if (!test_and_set_bit(KEY_FLAG_INVALIDATED, &key->flags))
  867. key_schedule_gc_links();
  868. up_write(&key->sem);
  869. }
  870. }
  871. EXPORT_SYMBOL(key_invalidate);
  872. /**
  873. * register_key_type - Register a type of key.
  874. * @ktype: The new key type.
  875. *
  876. * Register a new key type.
  877. *
  878. * Returns 0 on success or -EEXIST if a type of this name already exists.
  879. */
  880. int register_key_type(struct key_type *ktype)
  881. {
  882. struct key_type *p;
  883. int ret;
  884. memset(&ktype->lock_class, 0, sizeof(ktype->lock_class));
  885. ret = -EEXIST;
  886. down_write(&key_types_sem);
  887. /* disallow key types with the same name */
  888. list_for_each_entry(p, &key_types_list, link) {
  889. if (strcmp(p->name, ktype->name) == 0)
  890. goto out;
  891. }
  892. /* store the type */
  893. list_add(&ktype->link, &key_types_list);
  894. pr_notice("Key type %s registered\n", ktype->name);
  895. ret = 0;
  896. out:
  897. up_write(&key_types_sem);
  898. return ret;
  899. }
  900. EXPORT_SYMBOL(register_key_type);
  901. /**
  902. * unregister_key_type - Unregister a type of key.
  903. * @ktype: The key type.
  904. *
  905. * Unregister a key type and mark all the extant keys of this type as dead.
  906. * Those keys of this type are then destroyed to get rid of their payloads and
  907. * they and their links will be garbage collected as soon as possible.
  908. */
  909. void unregister_key_type(struct key_type *ktype)
  910. {
  911. down_write(&key_types_sem);
  912. list_del_init(&ktype->link);
  913. downgrade_write(&key_types_sem);
  914. key_gc_keytype(ktype);
  915. pr_notice("Key type %s unregistered\n", ktype->name);
  916. up_read(&key_types_sem);
  917. }
  918. EXPORT_SYMBOL(unregister_key_type);
  919. /*
  920. * Initialise the key management state.
  921. */
  922. void __init key_init(void)
  923. {
  924. /* allocate a slab in which we can store keys */
  925. key_jar = kmem_cache_create("key_jar", sizeof(struct key),
  926. 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL);
  927. /* add the special key types */
  928. list_add_tail(&key_type_keyring.link, &key_types_list);
  929. list_add_tail(&key_type_dead.link, &key_types_list);
  930. list_add_tail(&key_type_user.link, &key_types_list);
  931. list_add_tail(&key_type_logon.link, &key_types_list);
  932. /* record the root user tracking */
  933. rb_link_node(&root_key_user.node,
  934. NULL,
  935. &key_user_tree.rb_node);
  936. rb_insert_color(&root_key_user.node,
  937. &key_user_tree);
  938. }