core.rst 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849
  1. ============================
  2. Kernel Key Retention Service
  3. ============================
  4. This service allows cryptographic keys, authentication tokens, cross-domain
  5. user mappings, and similar to be cached in the kernel for the use of
  6. filesystems and other kernel services.
  7. Keyrings are permitted; these are a special type of key that can hold links to
  8. other keys. Processes each have three standard keyring subscriptions that a
  9. kernel service can search for relevant keys.
  10. The key service can be configured on by enabling:
  11. "Security options"/"Enable access key retention support" (CONFIG_KEYS)
  12. This document has the following sections:
  13. .. contents:: :local:
  14. Key Overview
  15. ============
  16. In this context, keys represent units of cryptographic data, authentication
  17. tokens, keyrings, etc.. These are represented in the kernel by struct key.
  18. Each key has a number of attributes:
  19. - A serial number.
  20. - A type.
  21. - A description (for matching a key in a search).
  22. - Access control information.
  23. - An expiry time.
  24. - A payload.
  25. - State.
  26. * Each key is issued a serial number of type key_serial_t that is unique for
  27. the lifetime of that key. All serial numbers are positive non-zero 32-bit
  28. integers.
  29. Userspace programs can use a key's serial numbers as a way to gain access
  30. to it, subject to permission checking.
  31. * Each key is of a defined "type". Types must be registered inside the
  32. kernel by a kernel service (such as a filesystem) before keys of that type
  33. can be added or used. Userspace programs cannot define new types directly.
  34. Key types are represented in the kernel by struct key_type. This defines a
  35. number of operations that can be performed on a key of that type.
  36. Should a type be removed from the system, all the keys of that type will
  37. be invalidated.
  38. * Each key has a description. This should be a printable string. The key
  39. type provides an operation to perform a match between the description on a
  40. key and a criterion string.
  41. * Each key has an owner user ID, a group ID and a permissions mask. These
  42. are used to control what a process may do to a key from userspace, and
  43. whether a kernel service will be able to find the key.
  44. * Each key can be set to expire at a specific time by the key type's
  45. instantiation function. Keys can also be immortal.
  46. * Each key can have a payload. This is a quantity of data that represent the
  47. actual "key". In the case of a keyring, this is a list of keys to which
  48. the keyring links; in the case of a user-defined key, it's an arbitrary
  49. blob of data.
  50. Having a payload is not required; and the payload can, in fact, just be a
  51. value stored in the struct key itself.
  52. When a key is instantiated, the key type's instantiation function is
  53. called with a blob of data, and that then creates the key's payload in
  54. some way.
  55. Similarly, when userspace wants to read back the contents of the key, if
  56. permitted, another key type operation will be called to convert the key's
  57. attached payload back into a blob of data.
  58. * Each key can be in one of a number of basic states:
  59. * Uninstantiated. The key exists, but does not have any data attached.
  60. Keys being requested from userspace will be in this state.
  61. * Instantiated. This is the normal state. The key is fully formed, and
  62. has data attached.
  63. * Negative. This is a relatively short-lived state. The key acts as a
  64. note saying that a previous call out to userspace failed, and acts as
  65. a throttle on key lookups. A negative key can be updated to a normal
  66. state.
  67. * Expired. Keys can have lifetimes set. If their lifetime is exceeded,
  68. they traverse to this state. An expired key can be updated back to a
  69. normal state.
  70. * Revoked. A key is put in this state by userspace action. It can't be
  71. found or operated upon (apart from by unlinking it).
  72. * Dead. The key's type was unregistered, and so the key is now useless.
  73. Keys in the last three states are subject to garbage collection. See the
  74. section on "Garbage collection".
  75. Key Service Overview
  76. ====================
  77. The key service provides a number of features besides keys:
  78. * The key service defines three special key types:
  79. (+) "keyring"
  80. Keyrings are special keys that contain a list of other keys. Keyring
  81. lists can be modified using various system calls. Keyrings should not
  82. be given a payload when created.
  83. (+) "user"
  84. A key of this type has a description and a payload that are arbitrary
  85. blobs of data. These can be created, updated and read by userspace,
  86. and aren't intended for use by kernel services.
  87. (+) "logon"
  88. Like a "user" key, a "logon" key has a payload that is an arbitrary
  89. blob of data. It is intended as a place to store secrets which are
  90. accessible to the kernel but not to userspace programs.
  91. The description can be arbitrary, but must be prefixed with a non-zero
  92. length string that describes the key "subclass". The subclass is
  93. separated from the rest of the description by a ':'. "logon" keys can
  94. be created and updated from userspace, but the payload is only
  95. readable from kernel space.
  96. * Each process subscribes to three keyrings: a thread-specific keyring, a
  97. process-specific keyring, and a session-specific keyring.
  98. The thread-specific keyring is discarded from the child when any sort of
  99. clone, fork, vfork or execve occurs. A new keyring is created only when
  100. required.
  101. The process-specific keyring is replaced with an empty one in the child on
  102. clone, fork, vfork unless CLONE_THREAD is supplied, in which case it is
  103. shared. execve also discards the process's process keyring and creates a
  104. new one.
  105. The session-specific keyring is persistent across clone, fork, vfork and
  106. execve, even when the latter executes a set-UID or set-GID binary. A
  107. process can, however, replace its current session keyring with a new one
  108. by using PR_JOIN_SESSION_KEYRING. It is permitted to request an anonymous
  109. new one, or to attempt to create or join one of a specific name.
  110. The ownership of the thread keyring changes when the real UID and GID of
  111. the thread changes.
  112. * Each user ID resident in the system holds two special keyrings: a user
  113. specific keyring and a default user session keyring. The default session
  114. keyring is initialised with a link to the user-specific keyring.
  115. When a process changes its real UID, if it used to have no session key, it
  116. will be subscribed to the default session key for the new UID.
  117. If a process attempts to access its session key when it doesn't have one,
  118. it will be subscribed to the default for its current UID.
  119. * Each user has two quotas against which the keys they own are tracked. One
  120. limits the total number of keys and keyrings, the other limits the total
  121. amount of description and payload space that can be consumed.
  122. The user can view information on this and other statistics through procfs
  123. files. The root user may also alter the quota limits through sysctl files
  124. (see the section "New procfs files").
  125. Process-specific and thread-specific keyrings are not counted towards a
  126. user's quota.
  127. If a system call that modifies a key or keyring in some way would put the
  128. user over quota, the operation is refused and error EDQUOT is returned.
  129. * There's a system call interface by which userspace programs can create and
  130. manipulate keys and keyrings.
  131. * There's a kernel interface by which services can register types and search
  132. for keys.
  133. * There's a way for the a search done from the kernel to call back to
  134. userspace to request a key that can't be found in a process's keyrings.
  135. * An optional filesystem is available through which the key database can be
  136. viewed and manipulated.
  137. Key Access Permissions
  138. ======================
  139. Keys have an owner user ID, a group access ID, and a permissions mask. The mask
  140. has up to eight bits each for possessor, user, group and other access. Only
  141. six of each set of eight bits are defined. These permissions granted are:
  142. * View
  143. This permits a key or keyring's attributes to be viewed - including key
  144. type and description.
  145. * Read
  146. This permits a key's payload to be viewed or a keyring's list of linked
  147. keys.
  148. * Write
  149. This permits a key's payload to be instantiated or updated, or it allows a
  150. link to be added to or removed from a keyring.
  151. * Search
  152. This permits keyrings to be searched and keys to be found. Searches can
  153. only recurse into nested keyrings that have search permission set.
  154. * Link
  155. This permits a key or keyring to be linked to. To create a link from a
  156. keyring to a key, a process must have Write permission on the keyring and
  157. Link permission on the key.
  158. * Set Attribute
  159. This permits a key's UID, GID and permissions mask to be changed.
  160. For changing the ownership, group ID or permissions mask, being the owner of
  161. the key or having the sysadmin capability is sufficient.
  162. SELinux Support
  163. ===============
  164. The security class "key" has been added to SELinux so that mandatory access
  165. controls can be applied to keys created within various contexts. This support
  166. is preliminary, and is likely to change quite significantly in the near future.
  167. Currently, all of the basic permissions explained above are provided in SELinux
  168. as well; SELinux is simply invoked after all basic permission checks have been
  169. performed.
  170. The value of the file /proc/self/attr/keycreate influences the labeling of
  171. newly-created keys. If the contents of that file correspond to an SELinux
  172. security context, then the key will be assigned that context. Otherwise, the
  173. key will be assigned the current context of the task that invoked the key
  174. creation request. Tasks must be granted explicit permission to assign a
  175. particular context to newly-created keys, using the "create" permission in the
  176. key security class.
  177. The default keyrings associated with users will be labeled with the default
  178. context of the user if and only if the login programs have been instrumented to
  179. properly initialize keycreate during the login process. Otherwise, they will
  180. be labeled with the context of the login program itself.
  181. Note, however, that the default keyrings associated with the root user are
  182. labeled with the default kernel context, since they are created early in the
  183. boot process, before root has a chance to log in.
  184. The keyrings associated with new threads are each labeled with the context of
  185. their associated thread, and both session and process keyrings are handled
  186. similarly.
  187. New ProcFS Files
  188. ================
  189. Two files have been added to procfs by which an administrator can find out
  190. about the status of the key service:
  191. * /proc/keys
  192. This lists the keys that are currently viewable by the task reading the
  193. file, giving information about their type, description and permissions.
  194. It is not possible to view the payload of the key this way, though some
  195. information about it may be given.
  196. The only keys included in the list are those that grant View permission to
  197. the reading process whether or not it possesses them. Note that LSM
  198. security checks are still performed, and may further filter out keys that
  199. the current process is not authorised to view.
  200. The contents of the file look like this::
  201. SERIAL FLAGS USAGE EXPY PERM UID GID TYPE DESCRIPTION: SUMMARY
  202. 00000001 I----- 39 perm 1f3f0000 0 0 keyring _uid_ses.0: 1/4
  203. 00000002 I----- 2 perm 1f3f0000 0 0 keyring _uid.0: empty
  204. 00000007 I----- 1 perm 1f3f0000 0 0 keyring _pid.1: empty
  205. 0000018d I----- 1 perm 1f3f0000 0 0 keyring _pid.412: empty
  206. 000004d2 I--Q-- 1 perm 1f3f0000 32 -1 keyring _uid.32: 1/4
  207. 000004d3 I--Q-- 3 perm 1f3f0000 32 -1 keyring _uid_ses.32: empty
  208. 00000892 I--QU- 1 perm 1f000000 0 0 user metal:copper: 0
  209. 00000893 I--Q-N 1 35s 1f3f0000 0 0 user metal:silver: 0
  210. 00000894 I--Q-- 1 10h 003f0000 0 0 user metal:gold: 0
  211. The flags are::
  212. I Instantiated
  213. R Revoked
  214. D Dead
  215. Q Contributes to user's quota
  216. U Under construction by callback to userspace
  217. N Negative key
  218. * /proc/key-users
  219. This file lists the tracking data for each user that has at least one key
  220. on the system. Such data includes quota information and statistics::
  221. [root@andromeda root]# cat /proc/key-users
  222. 0: 46 45/45 1/100 13/10000
  223. 29: 2 2/2 2/100 40/10000
  224. 32: 2 2/2 2/100 40/10000
  225. 38: 2 2/2 2/100 40/10000
  226. The format of each line is::
  227. <UID>: User ID to which this applies
  228. <usage> Structure refcount
  229. <inst>/<keys> Total number of keys and number instantiated
  230. <keys>/<max> Key count quota
  231. <bytes>/<max> Key size quota
  232. Four new sysctl files have been added also for the purpose of controlling the
  233. quota limits on keys:
  234. * /proc/sys/kernel/keys/root_maxkeys
  235. /proc/sys/kernel/keys/root_maxbytes
  236. These files hold the maximum number of keys that root may have and the
  237. maximum total number of bytes of data that root may have stored in those
  238. keys.
  239. * /proc/sys/kernel/keys/maxkeys
  240. /proc/sys/kernel/keys/maxbytes
  241. These files hold the maximum number of keys that each non-root user may
  242. have and the maximum total number of bytes of data that each of those
  243. users may have stored in their keys.
  244. Root may alter these by writing each new limit as a decimal number string to
  245. the appropriate file.
  246. Userspace System Call Interface
  247. ===============================
  248. Userspace can manipulate keys directly through three new syscalls: add_key,
  249. request_key and keyctl. The latter provides a number of functions for
  250. manipulating keys.
  251. When referring to a key directly, userspace programs should use the key's
  252. serial number (a positive 32-bit integer). However, there are some special
  253. values available for referring to special keys and keyrings that relate to the
  254. process making the call::
  255. CONSTANT VALUE KEY REFERENCED
  256. ============================== ====== ===========================
  257. KEY_SPEC_THREAD_KEYRING -1 thread-specific keyring
  258. KEY_SPEC_PROCESS_KEYRING -2 process-specific keyring
  259. KEY_SPEC_SESSION_KEYRING -3 session-specific keyring
  260. KEY_SPEC_USER_KEYRING -4 UID-specific keyring
  261. KEY_SPEC_USER_SESSION_KEYRING -5 UID-session keyring
  262. KEY_SPEC_GROUP_KEYRING -6 GID-specific keyring
  263. KEY_SPEC_REQKEY_AUTH_KEY -7 assumed request_key()
  264. authorisation key
  265. The main syscalls are:
  266. * Create a new key of given type, description and payload and add it to the
  267. nominated keyring::
  268. key_serial_t add_key(const char *type, const char *desc,
  269. const void *payload, size_t plen,
  270. key_serial_t keyring);
  271. If a key of the same type and description as that proposed already exists
  272. in the keyring, this will try to update it with the given payload, or it
  273. will return error EEXIST if that function is not supported by the key
  274. type. The process must also have permission to write to the key to be able
  275. to update it. The new key will have all user permissions granted and no
  276. group or third party permissions.
  277. Otherwise, this will attempt to create a new key of the specified type and
  278. description, and to instantiate it with the supplied payload and attach it
  279. to the keyring. In this case, an error will be generated if the process
  280. does not have permission to write to the keyring.
  281. If the key type supports it, if the description is NULL or an empty
  282. string, the key type will try and generate a description from the content
  283. of the payload.
  284. The payload is optional, and the pointer can be NULL if not required by
  285. the type. The payload is plen in size, and plen can be zero for an empty
  286. payload.
  287. A new keyring can be generated by setting type "keyring", the keyring name
  288. as the description (or NULL) and setting the payload to NULL.
  289. User defined keys can be created by specifying type "user". It is
  290. recommended that a user defined key's description by prefixed with a type
  291. ID and a colon, such as "krb5tgt:" for a Kerberos 5 ticket granting
  292. ticket.
  293. Any other type must have been registered with the kernel in advance by a
  294. kernel service such as a filesystem.
  295. The ID of the new or updated key is returned if successful.
  296. * Search the process's keyrings for a key, potentially calling out to
  297. userspace to create it::
  298. key_serial_t request_key(const char *type, const char *description,
  299. const char *callout_info,
  300. key_serial_t dest_keyring);
  301. This function searches all the process's keyrings in the order thread,
  302. process, session for a matching key. This works very much like
  303. KEYCTL_SEARCH, including the optional attachment of the discovered key to
  304. a keyring.
  305. If a key cannot be found, and if callout_info is not NULL, then
  306. /sbin/request-key will be invoked in an attempt to obtain a key. The
  307. callout_info string will be passed as an argument to the program.
  308. To link a key into the destination keyring the key must grant link
  309. permission on the key to the caller and the keyring must grant write
  310. permission.
  311. See also Documentation/security/keys/request-key.rst.
  312. The keyctl syscall functions are:
  313. * Map a special key ID to a real key ID for this process::
  314. key_serial_t keyctl(KEYCTL_GET_KEYRING_ID, key_serial_t id,
  315. int create);
  316. The special key specified by "id" is looked up (with the key being created
  317. if necessary) and the ID of the key or keyring thus found is returned if
  318. it exists.
  319. If the key does not yet exist, the key will be created if "create" is
  320. non-zero; and the error ENOKEY will be returned if "create" is zero.
  321. * Replace the session keyring this process subscribes to with a new one::
  322. key_serial_t keyctl(KEYCTL_JOIN_SESSION_KEYRING, const char *name);
  323. If name is NULL, an anonymous keyring is created attached to the process
  324. as its session keyring, displacing the old session keyring.
  325. If name is not NULL, if a keyring of that name exists, the process
  326. attempts to attach it as the session keyring, returning an error if that
  327. is not permitted; otherwise a new keyring of that name is created and
  328. attached as the session keyring.
  329. To attach to a named keyring, the keyring must have search permission for
  330. the process's ownership.
  331. The ID of the new session keyring is returned if successful.
  332. * Update the specified key::
  333. long keyctl(KEYCTL_UPDATE, key_serial_t key, const void *payload,
  334. size_t plen);
  335. This will try to update the specified key with the given payload, or it
  336. will return error EOPNOTSUPP if that function is not supported by the key
  337. type. The process must also have permission to write to the key to be able
  338. to update it.
  339. The payload is of length plen, and may be absent or empty as for
  340. add_key().
  341. * Revoke a key::
  342. long keyctl(KEYCTL_REVOKE, key_serial_t key);
  343. This makes a key unavailable for further operations. Further attempts to
  344. use the key will be met with error EKEYREVOKED, and the key will no longer
  345. be findable.
  346. * Change the ownership of a key::
  347. long keyctl(KEYCTL_CHOWN, key_serial_t key, uid_t uid, gid_t gid);
  348. This function permits a key's owner and group ID to be changed. Either one
  349. of uid or gid can be set to -1 to suppress that change.
  350. Only the superuser can change a key's owner to something other than the
  351. key's current owner. Similarly, only the superuser can change a key's
  352. group ID to something other than the calling process's group ID or one of
  353. its group list members.
  354. * Change the permissions mask on a key::
  355. long keyctl(KEYCTL_SETPERM, key_serial_t key, key_perm_t perm);
  356. This function permits the owner of a key or the superuser to change the
  357. permissions mask on a key.
  358. Only bits the available bits are permitted; if any other bits are set,
  359. error EINVAL will be returned.
  360. * Describe a key::
  361. long keyctl(KEYCTL_DESCRIBE, key_serial_t key, char *buffer,
  362. size_t buflen);
  363. This function returns a summary of the key's attributes (but not its
  364. payload data) as a string in the buffer provided.
  365. Unless there's an error, it always returns the amount of data it could
  366. produce, even if that's too big for the buffer, but it won't copy more
  367. than requested to userspace. If the buffer pointer is NULL then no copy
  368. will take place.
  369. A process must have view permission on the key for this function to be
  370. successful.
  371. If successful, a string is placed in the buffer in the following format::
  372. <type>;<uid>;<gid>;<perm>;<description>
  373. Where type and description are strings, uid and gid are decimal, and perm
  374. is hexadecimal. A NUL character is included at the end of the string if
  375. the buffer is sufficiently big.
  376. This can be parsed with::
  377. sscanf(buffer, "%[^;];%d;%d;%o;%s", type, &uid, &gid, &mode, desc);
  378. * Clear out a keyring::
  379. long keyctl(KEYCTL_CLEAR, key_serial_t keyring);
  380. This function clears the list of keys attached to a keyring. The calling
  381. process must have write permission on the keyring, and it must be a
  382. keyring (or else error ENOTDIR will result).
  383. This function can also be used to clear special kernel keyrings if they
  384. are appropriately marked if the user has CAP_SYS_ADMIN capability. The
  385. DNS resolver cache keyring is an example of this.
  386. * Link a key into a keyring::
  387. long keyctl(KEYCTL_LINK, key_serial_t keyring, key_serial_t key);
  388. This function creates a link from the keyring to the key. The process must
  389. have write permission on the keyring and must have link permission on the
  390. key.
  391. Should the keyring not be a keyring, error ENOTDIR will result; and if the
  392. keyring is full, error ENFILE will result.
  393. The link procedure checks the nesting of the keyrings, returning ELOOP if
  394. it appears too deep or EDEADLK if the link would introduce a cycle.
  395. Any links within the keyring to keys that match the new key in terms of
  396. type and description will be discarded from the keyring as the new one is
  397. added.
  398. * Move a key from one keyring to another::
  399. long keyctl(KEYCTL_MOVE,
  400. key_serial_t id,
  401. key_serial_t from_ring_id,
  402. key_serial_t to_ring_id,
  403. unsigned int flags);
  404. Move the key specified by "id" from the keyring specified by
  405. "from_ring_id" to the keyring specified by "to_ring_id". If the two
  406. keyrings are the same, nothing is done.
  407. "flags" can have KEYCTL_MOVE_EXCL set in it to cause the operation to fail
  408. with EEXIST if a matching key exists in the destination keyring, otherwise
  409. such a key will be replaced.
  410. A process must have link permission on the key for this function to be
  411. successful and write permission on both keyrings. Any errors that can
  412. occur from KEYCTL_LINK also apply on the destination keyring here.
  413. * Unlink a key or keyring from another keyring::
  414. long keyctl(KEYCTL_UNLINK, key_serial_t keyring, key_serial_t key);
  415. This function looks through the keyring for the first link to the
  416. specified key, and removes it if found. Subsequent links to that key are
  417. ignored. The process must have write permission on the keyring.
  418. If the keyring is not a keyring, error ENOTDIR will result; and if the key
  419. is not present, error ENOENT will be the result.
  420. * Search a keyring tree for a key::
  421. key_serial_t keyctl(KEYCTL_SEARCH, key_serial_t keyring,
  422. const char *type, const char *description,
  423. key_serial_t dest_keyring);
  424. This searches the keyring tree headed by the specified keyring until a key
  425. is found that matches the type and description criteria. Each keyring is
  426. checked for keys before recursion into its children occurs.
  427. The process must have search permission on the top level keyring, or else
  428. error EACCES will result. Only keyrings that the process has search
  429. permission on will be recursed into, and only keys and keyrings for which
  430. a process has search permission can be matched. If the specified keyring
  431. is not a keyring, ENOTDIR will result.
  432. If the search succeeds, the function will attempt to link the found key
  433. into the destination keyring if one is supplied (non-zero ID). All the
  434. constraints applicable to KEYCTL_LINK apply in this case too.
  435. Error ENOKEY, EKEYREVOKED or EKEYEXPIRED will be returned if the search
  436. fails. On success, the resulting key ID will be returned.
  437. * Read the payload data from a key::
  438. long keyctl(KEYCTL_READ, key_serial_t keyring, char *buffer,
  439. size_t buflen);
  440. This function attempts to read the payload data from the specified key
  441. into the buffer. The process must have read permission on the key to
  442. succeed.
  443. The returned data will be processed for presentation by the key type. For
  444. instance, a keyring will return an array of key_serial_t entries
  445. representing the IDs of all the keys to which it is subscribed. The user
  446. defined key type will return its data as is. If a key type does not
  447. implement this function, error EOPNOTSUPP will result.
  448. If the specified buffer is too small, then the size of the buffer required
  449. will be returned. Note that in this case, the contents of the buffer may
  450. have been overwritten in some undefined way.
  451. Otherwise, on success, the function will return the amount of data copied
  452. into the buffer.
  453. * Instantiate a partially constructed key::
  454. long keyctl(KEYCTL_INSTANTIATE, key_serial_t key,
  455. const void *payload, size_t plen,
  456. key_serial_t keyring);
  457. long keyctl(KEYCTL_INSTANTIATE_IOV, key_serial_t key,
  458. const struct iovec *payload_iov, unsigned ioc,
  459. key_serial_t keyring);
  460. If the kernel calls back to userspace to complete the instantiation of a
  461. key, userspace should use this call to supply data for the key before the
  462. invoked process returns, or else the key will be marked negative
  463. automatically.
  464. The process must have write access on the key to be able to instantiate
  465. it, and the key must be uninstantiated.
  466. If a keyring is specified (non-zero), the key will also be linked into
  467. that keyring, however all the constraints applying in KEYCTL_LINK apply in
  468. this case too.
  469. The payload and plen arguments describe the payload data as for add_key().
  470. The payload_iov and ioc arguments describe the payload data in an iovec
  471. array instead of a single buffer.
  472. * Negatively instantiate a partially constructed key::
  473. long keyctl(KEYCTL_NEGATE, key_serial_t key,
  474. unsigned timeout, key_serial_t keyring);
  475. long keyctl(KEYCTL_REJECT, key_serial_t key,
  476. unsigned timeout, unsigned error, key_serial_t keyring);
  477. If the kernel calls back to userspace to complete the instantiation of a
  478. key, userspace should use this call mark the key as negative before the
  479. invoked process returns if it is unable to fulfill the request.
  480. The process must have write access on the key to be able to instantiate
  481. it, and the key must be uninstantiated.
  482. If a keyring is specified (non-zero), the key will also be linked into
  483. that keyring, however all the constraints applying in KEYCTL_LINK apply in
  484. this case too.
  485. If the key is rejected, future searches for it will return the specified
  486. error code until the rejected key expires. Negating the key is the same
  487. as rejecting the key with ENOKEY as the error code.
  488. * Set the default request-key destination keyring::
  489. long keyctl(KEYCTL_SET_REQKEY_KEYRING, int reqkey_defl);
  490. This sets the default keyring to which implicitly requested keys will be
  491. attached for this thread. reqkey_defl should be one of these constants::
  492. CONSTANT VALUE NEW DEFAULT KEYRING
  493. ====================================== ====== =======================
  494. KEY_REQKEY_DEFL_NO_CHANGE -1 No change
  495. KEY_REQKEY_DEFL_DEFAULT 0 Default[1]
  496. KEY_REQKEY_DEFL_THREAD_KEYRING 1 Thread keyring
  497. KEY_REQKEY_DEFL_PROCESS_KEYRING 2 Process keyring
  498. KEY_REQKEY_DEFL_SESSION_KEYRING 3 Session keyring
  499. KEY_REQKEY_DEFL_USER_KEYRING 4 User keyring
  500. KEY_REQKEY_DEFL_USER_SESSION_KEYRING 5 User session keyring
  501. KEY_REQKEY_DEFL_GROUP_KEYRING 6 Group keyring
  502. The old default will be returned if successful and error EINVAL will be
  503. returned if reqkey_defl is not one of the above values.
  504. The default keyring can be overridden by the keyring indicated to the
  505. request_key() system call.
  506. Note that this setting is inherited across fork/exec.
  507. [1] The default is: the thread keyring if there is one, otherwise
  508. the process keyring if there is one, otherwise the session keyring if
  509. there is one, otherwise the user default session keyring.
  510. * Set the timeout on a key::
  511. long keyctl(KEYCTL_SET_TIMEOUT, key_serial_t key, unsigned timeout);
  512. This sets or clears the timeout on a key. The timeout can be 0 to clear
  513. the timeout or a number of seconds to set the expiry time that far into
  514. the future.
  515. The process must have attribute modification access on a key to set its
  516. timeout. Timeouts may not be set with this function on negative, revoked
  517. or expired keys.
  518. * Assume the authority granted to instantiate a key::
  519. long keyctl(KEYCTL_ASSUME_AUTHORITY, key_serial_t key);
  520. This assumes or divests the authority required to instantiate the
  521. specified key. Authority can only be assumed if the thread has the
  522. authorisation key associated with the specified key in its keyrings
  523. somewhere.
  524. Once authority is assumed, searches for keys will also search the
  525. requester's keyrings using the requester's security label, UID, GID and
  526. groups.
  527. If the requested authority is unavailable, error EPERM will be returned,
  528. likewise if the authority has been revoked because the target key is
  529. already instantiated.
  530. If the specified key is 0, then any assumed authority will be divested.
  531. The assumed authoritative key is inherited across fork and exec.
  532. * Get the LSM security context attached to a key::
  533. long keyctl(KEYCTL_GET_SECURITY, key_serial_t key, char *buffer,
  534. size_t buflen)
  535. This function returns a string that represents the LSM security context
  536. attached to a key in the buffer provided.
  537. Unless there's an error, it always returns the amount of data it could
  538. produce, even if that's too big for the buffer, but it won't copy more
  539. than requested to userspace. If the buffer pointer is NULL then no copy
  540. will take place.
  541. A NUL character is included at the end of the string if the buffer is
  542. sufficiently big. This is included in the returned count. If no LSM is
  543. in force then an empty string will be returned.
  544. A process must have view permission on the key for this function to be
  545. successful.
  546. * Install the calling process's session keyring on its parent::
  547. long keyctl(KEYCTL_SESSION_TO_PARENT);
  548. This functions attempts to install the calling process's session keyring
  549. on to the calling process's parent, replacing the parent's current session
  550. keyring.
  551. The calling process must have the same ownership as its parent, the
  552. keyring must have the same ownership as the calling process, the calling
  553. process must have LINK permission on the keyring and the active LSM module
  554. mustn't deny permission, otherwise error EPERM will be returned.
  555. Error ENOMEM will be returned if there was insufficient memory to complete
  556. the operation, otherwise 0 will be returned to indicate success.
  557. The keyring will be replaced next time the parent process leaves the
  558. kernel and resumes executing userspace.
  559. * Invalidate a key::
  560. long keyctl(KEYCTL_INVALIDATE, key_serial_t key);
  561. This function marks a key as being invalidated and then wakes up the
  562. garbage collector. The garbage collector immediately removes invalidated
  563. keys from all keyrings and deletes the key when its reference count
  564. reaches zero.
  565. Keys that are marked invalidated become invisible to normal key operations
  566. immediately, though they are still visible in /proc/keys until deleted
  567. (they're marked with an 'i' flag).
  568. A process must have search permission on the key for this function to be
  569. successful.
  570. * Compute a Diffie-Hellman shared secret or public key::
  571. long keyctl(KEYCTL_DH_COMPUTE, struct keyctl_dh_params *params,
  572. char *buffer, size_t buflen, struct keyctl_kdf_params *kdf);
  573. The params struct contains serial numbers for three keys::
  574. - The prime, p, known to both parties
  575. - The local private key
  576. - The base integer, which is either a shared generator or the
  577. remote public key
  578. The value computed is::
  579. result = base ^ private (mod prime)
  580. If the base is the shared generator, the result is the local
  581. public key. If the base is the remote public key, the result is
  582. the shared secret.
  583. If the parameter kdf is NULL, the following applies:
  584. - The buffer length must be at least the length of the prime, or zero.
  585. - If the buffer length is nonzero, the length of the result is
  586. returned when it is successfully calculated and copied in to the
  587. buffer. When the buffer length is zero, the minimum required
  588. buffer length is returned.
  589. The kdf parameter allows the caller to apply a key derivation function
  590. (KDF) on the Diffie-Hellman computation where only the result
  591. of the KDF is returned to the caller. The KDF is characterized with
  592. struct keyctl_kdf_params as follows:
  593. - ``char *hashname`` specifies the NUL terminated string identifying
  594. the hash used from the kernel crypto API and applied for the KDF
  595. operation. The KDF implemenation complies with SP800-56A as well
  596. as with SP800-108 (the counter KDF).
  597. - ``char *otherinfo`` specifies the OtherInfo data as documented in
  598. SP800-56A section 5.8.1.2. The length of the buffer is given with
  599. otherinfolen. The format of OtherInfo is defined by the caller.
  600. The otherinfo pointer may be NULL if no OtherInfo shall be used.
  601. This function will return error EOPNOTSUPP if the key type is not
  602. supported, error ENOKEY if the key could not be found, or error
  603. EACCES if the key is not readable by the caller. In addition, the
  604. function will return EMSGSIZE when the parameter kdf is non-NULL
  605. and either the buffer length or the OtherInfo length exceeds the
  606. allowed length.
  607. * Restrict keyring linkage::
  608. long keyctl(KEYCTL_RESTRICT_KEYRING, key_serial_t keyring,
  609. const char *type, const char *restriction);
  610. An existing keyring can restrict linkage of additional keys by evaluating
  611. the contents of the key according to a restriction scheme.
  612. "keyring" is the key ID for an existing keyring to apply a restriction
  613. to. It may be empty or may already have keys linked. Existing linked keys
  614. will remain in the keyring even if the new restriction would reject them.
  615. "type" is a registered key type.
  616. "restriction" is a string describing how key linkage is to be restricted.
  617. The format varies depending on the key type, and the string is passed to
  618. the lookup_restriction() function for the requested type. It may specify
  619. a method and relevant data for the restriction such as signature
  620. verification or constraints on key payload. If the requested key type is
  621. later unregistered, no keys may be added to the keyring after the key type
  622. is removed.
  623. To apply a keyring restriction the process must have Set Attribute
  624. permission and the keyring must not be previously restricted.
  625. One application of restricted keyrings is to verify X.509 certificate
  626. chains or individual certificate signatures using the asymmetric key type.
  627. See Documentation/crypto/asymmetric-keys.rst for specific restrictions
  628. applicable to the asymmetric key type.
  629. * Query an asymmetric key::
  630. long keyctl(KEYCTL_PKEY_QUERY,
  631. key_serial_t key_id, unsigned long reserved,
  632. const char *params,
  633. struct keyctl_pkey_query *info);
  634. Get information about an asymmetric key. Specific algorithms and
  635. encodings may be queried by using the ``params`` argument. This is a
  636. string containing a space- or tab-separated string of key-value pairs.
  637. Currently supported keys include ``enc`` and ``hash``. The information
  638. is returned in the keyctl_pkey_query struct::
  639. __u32 supported_ops;
  640. __u32 key_size;
  641. __u16 max_data_size;
  642. __u16 max_sig_size;
  643. __u16 max_enc_size;
  644. __u16 max_dec_size;
  645. __u32 __spare[10];
  646. ``supported_ops`` contains a bit mask of flags indicating which ops are
  647. supported. This is constructed from a bitwise-OR of::
  648. KEYCTL_SUPPORTS_{ENCRYPT,DECRYPT,SIGN,VERIFY}
  649. ``key_size`` indicated the size of the key in bits.
  650. ``max_*_size`` indicate the maximum sizes in bytes of a blob of data to be
  651. signed, a signature blob, a blob to be encrypted and a blob to be
  652. decrypted.
  653. ``__spare[]`` must be set to 0. This is intended for future use to hand
  654. over one or more passphrases needed unlock a key.
  655. If successful, 0 is returned. If the key is not an asymmetric key,
  656. EOPNOTSUPP is returned.
  657. * Encrypt, decrypt, sign or verify a blob using an asymmetric key::
  658. long keyctl(KEYCTL_PKEY_ENCRYPT,
  659. const struct keyctl_pkey_params *params,
  660. const char *info,
  661. const void *in,
  662. void *out);
  663. long keyctl(KEYCTL_PKEY_DECRYPT,
  664. const struct keyctl_pkey_params *params,
  665. const char *info,
  666. const void *in,
  667. void *out);
  668. long keyctl(KEYCTL_PKEY_SIGN,
  669. const struct keyctl_pkey_params *params,
  670. const char *info,
  671. const void *in,
  672. void *out);
  673. long keyctl(KEYCTL_PKEY_VERIFY,
  674. const struct keyctl_pkey_params *params,
  675. const char *info,
  676. const void *in,
  677. const void *in2);
  678. Use an asymmetric key to perform a public-key cryptographic operation a
  679. blob of data. For encryption and verification, the asymmetric key may
  680. only need the public parts to be available, but for decryption and signing
  681. the private parts are required also.
  682. The parameter block pointed to by params contains a number of integer
  683. values::
  684. __s32 key_id;
  685. __u32 in_len;
  686. __u32 out_len;
  687. __u32 in2_len;
  688. ``key_id`` is the ID of the asymmetric key to be used. ``in_len`` and
  689. ``in2_len`` indicate the amount of data in the in and in2 buffers and
  690. ``out_len`` indicates the size of the out buffer as appropriate for the
  691. above operations.
  692. For a given operation, the in and out buffers are used as follows::
  693. Operation ID in,in_len out,out_len in2,in2_len
  694. ======================= =============== =============== ===============
  695. KEYCTL_PKEY_ENCRYPT Raw data Encrypted data -
  696. KEYCTL_PKEY_DECRYPT Encrypted data Raw data -
  697. KEYCTL_PKEY_SIGN Raw data Signature -
  698. KEYCTL_PKEY_VERIFY Raw data - Signature
  699. ``info`` is a string of key=value pairs that supply supplementary
  700. information. These include:
  701. ``enc=<encoding>`` The encoding of the encrypted/signature blob. This
  702. can be "pkcs1" for RSASSA-PKCS1-v1.5 or
  703. RSAES-PKCS1-v1.5; "pss" for "RSASSA-PSS"; "oaep" for
  704. "RSAES-OAEP". If omitted or is "raw", the raw output
  705. of the encryption function is specified.
  706. ``hash=<algo>`` If the data buffer contains the output of a hash
  707. function and the encoding includes some indication of
  708. which hash function was used, the hash function can be
  709. specified with this, eg. "hash=sha256".
  710. The ``__spare[]`` space in the parameter block must be set to 0. This is
  711. intended, amongst other things, to allow the passing of passphrases
  712. required to unlock a key.
  713. If successful, encrypt, decrypt and sign all return the amount of data
  714. written into the output buffer. Verification returns 0 on success.
  715. * Watch a key or keyring for changes::
  716. long keyctl(KEYCTL_WATCH_KEY, key_serial_t key, int queue_fd,
  717. const struct watch_notification_filter *filter);
  718. This will set or remove a watch for changes on the specified key or
  719. keyring.
  720. "key" is the ID of the key to be watched.
  721. "queue_fd" is a file descriptor referring to an open pipe which
  722. manages the buffer into which notifications will be delivered.
  723. "filter" is either NULL to remove a watch or a filter specification to
  724. indicate what events are required from the key.
  725. See Documentation/watch_queue.rst for more information.
  726. Note that only one watch may be emplaced for any particular { key,
  727. queue_fd } combination.
  728. Notification records look like::
  729. struct key_notification {
  730. struct watch_notification watch;
  731. __u32 key_id;
  732. __u32 aux;
  733. };
  734. In this, watch::type will be "WATCH_TYPE_KEY_NOTIFY" and subtype will be
  735. one of::
  736. NOTIFY_KEY_INSTANTIATED
  737. NOTIFY_KEY_UPDATED
  738. NOTIFY_KEY_LINKED
  739. NOTIFY_KEY_UNLINKED
  740. NOTIFY_KEY_CLEARED
  741. NOTIFY_KEY_REVOKED
  742. NOTIFY_KEY_INVALIDATED
  743. NOTIFY_KEY_SETATTR
  744. Where these indicate a key being instantiated/rejected, updated, a link
  745. being made in a keyring, a link being removed from a keyring, a keyring
  746. being cleared, a key being revoked, a key being invalidated or a key
  747. having one of its attributes changed (user, group, perm, timeout,
  748. restriction).
  749. If a watched key is deleted, a basic watch_notification will be issued
  750. with "type" set to WATCH_TYPE_META and "subtype" set to
  751. watch_meta_removal_notification. The watchpoint ID will be set in the
  752. "info" field.
  753. This needs to be configured by enabling:
  754. "Provide key/keyring change notifications" (KEY_NOTIFICATIONS)
  755. Kernel Services
  756. ===============
  757. The kernel services for key management are fairly simple to deal with. They can
  758. be broken down into two areas: keys and key types.
  759. Dealing with keys is fairly straightforward. Firstly, the kernel service
  760. registers its type, then it searches for a key of that type. It should retain
  761. the key as long as it has need of it, and then it should release it. For a
  762. filesystem or device file, a search would probably be performed during the open
  763. call, and the key released upon close. How to deal with conflicting keys due to
  764. two different users opening the same file is left to the filesystem author to
  765. solve.
  766. To access the key manager, the following header must be #included::
  767. <linux/key.h>
  768. Specific key types should have a header file under include/keys/ that should be
  769. used to access that type. For keys of type "user", for example, that would be::
  770. <keys/user-type.h>
  771. Note that there are two different types of pointers to keys that may be
  772. encountered:
  773. * struct key *
  774. This simply points to the key structure itself. Key structures will be at
  775. least four-byte aligned.
  776. * key_ref_t
  777. This is equivalent to a ``struct key *``, but the least significant bit is set
  778. if the caller "possesses" the key. By "possession" it is meant that the
  779. calling processes has a searchable link to the key from one of its
  780. keyrings. There are three functions for dealing with these::
  781. key_ref_t make_key_ref(const struct key *key, bool possession);
  782. struct key *key_ref_to_ptr(const key_ref_t key_ref);
  783. bool is_key_possessed(const key_ref_t key_ref);
  784. The first function constructs a key reference from a key pointer and
  785. possession information (which must be true or false).
  786. The second function retrieves the key pointer from a reference and the
  787. third retrieves the possession flag.
  788. When accessing a key's payload contents, certain precautions must be taken to
  789. prevent access vs modification races. See the section "Notes on accessing
  790. payload contents" for more information.
  791. * To search for a key, call::
  792. struct key *request_key(const struct key_type *type,
  793. const char *description,
  794. const char *callout_info);
  795. This is used to request a key or keyring with a description that matches
  796. the description specified according to the key type's match_preparse()
  797. method. This permits approximate matching to occur. If callout_string is
  798. not NULL, then /sbin/request-key will be invoked in an attempt to obtain
  799. the key from userspace. In that case, callout_string will be passed as an
  800. argument to the program.
  801. Should the function fail error ENOKEY, EKEYEXPIRED or EKEYREVOKED will be
  802. returned.
  803. If successful, the key will have been attached to the default keyring for
  804. implicitly obtained request-key keys, as set by KEYCTL_SET_REQKEY_KEYRING.
  805. See also Documentation/security/keys/request-key.rst.
  806. * To search for a key in a specific domain, call::
  807. struct key *request_key_tag(const struct key_type *type,
  808. const char *description,
  809. struct key_tag *domain_tag,
  810. const char *callout_info);
  811. This is identical to request_key(), except that a domain tag may be
  812. specifies that causes search algorithm to only match keys matching that
  813. tag. The domain_tag may be NULL, specifying a global domain that is
  814. separate from any nominated domain.
  815. * To search for a key, passing auxiliary data to the upcaller, call::
  816. struct key *request_key_with_auxdata(const struct key_type *type,
  817. const char *description,
  818. struct key_tag *domain_tag,
  819. const void *callout_info,
  820. size_t callout_len,
  821. void *aux);
  822. This is identical to request_key_tag(), except that the auxiliary data is
  823. passed to the key_type->request_key() op if it exists, and the
  824. callout_info is a blob of length callout_len, if given (the length may be
  825. 0).
  826. * To search for a key under RCU conditions, call::
  827. struct key *request_key_rcu(const struct key_type *type,
  828. const char *description,
  829. struct key_tag *domain_tag);
  830. which is similar to request_key_tag() except that it does not check for
  831. keys that are under construction and it will not call out to userspace to
  832. construct a key if it can't find a match.
  833. * When it is no longer required, the key should be released using::
  834. void key_put(struct key *key);
  835. Or::
  836. void key_ref_put(key_ref_t key_ref);
  837. These can be called from interrupt context. If CONFIG_KEYS is not set then
  838. the argument will not be parsed.
  839. * Extra references can be made to a key by calling one of the following
  840. functions::
  841. struct key *__key_get(struct key *key);
  842. struct key *key_get(struct key *key);
  843. Keys so references will need to be disposed of by calling key_put() when
  844. they've been finished with. The key pointer passed in will be returned.
  845. In the case of key_get(), if the pointer is NULL or CONFIG_KEYS is not set
  846. then the key will not be dereferenced and no increment will take place.
  847. * A key's serial number can be obtained by calling::
  848. key_serial_t key_serial(struct key *key);
  849. If key is NULL or if CONFIG_KEYS is not set then 0 will be returned (in the
  850. latter case without parsing the argument).
  851. * If a keyring was found in the search, this can be further searched by::
  852. key_ref_t keyring_search(key_ref_t keyring_ref,
  853. const struct key_type *type,
  854. const char *description,
  855. bool recurse)
  856. This searches the specified keyring only (recurse == false) or keyring tree
  857. (recurse == true) specified for a matching key. Error ENOKEY is returned
  858. upon failure (use IS_ERR/PTR_ERR to determine). If successful, the returned
  859. key will need to be released.
  860. The possession attribute from the keyring reference is used to control
  861. access through the permissions mask and is propagated to the returned key
  862. reference pointer if successful.
  863. * A keyring can be created by::
  864. struct key *keyring_alloc(const char *description, uid_t uid, gid_t gid,
  865. const struct cred *cred,
  866. key_perm_t perm,
  867. struct key_restriction *restrict_link,
  868. unsigned long flags,
  869. struct key *dest);
  870. This creates a keyring with the given attributes and returns it. If dest
  871. is not NULL, the new keyring will be linked into the keyring to which it
  872. points. No permission checks are made upon the destination keyring.
  873. Error EDQUOT can be returned if the keyring would overload the quota (pass
  874. KEY_ALLOC_NOT_IN_QUOTA in flags if the keyring shouldn't be accounted
  875. towards the user's quota). Error ENOMEM can also be returned.
  876. If restrict_link is not NULL, it should point to a structure that contains
  877. the function that will be called each time an attempt is made to link a
  878. key into the new keyring. The structure may also contain a key pointer
  879. and an associated key type. The function is called to check whether a key
  880. may be added into the keyring or not. The key type is used by the garbage
  881. collector to clean up function or data pointers in this structure if the
  882. given key type is unregistered. Callers of key_create_or_update() within
  883. the kernel can pass KEY_ALLOC_BYPASS_RESTRICTION to suppress the check.
  884. An example of using this is to manage rings of cryptographic keys that are
  885. set up when the kernel boots where userspace is also permitted to add keys
  886. - provided they can be verified by a key the kernel already has.
  887. When called, the restriction function will be passed the keyring being
  888. added to, the key type, the payload of the key being added, and data to be
  889. used in the restriction check. Note that when a new key is being created,
  890. this is called between payload preparsing and actual key creation. The
  891. function should return 0 to allow the link or an error to reject it.
  892. A convenience function, restrict_link_reject, exists to always return
  893. -EPERM to in this case.
  894. * To check the validity of a key, this function can be called::
  895. int validate_key(struct key *key);
  896. This checks that the key in question hasn't expired or and hasn't been
  897. revoked. Should the key be invalid, error EKEYEXPIRED or EKEYREVOKED will
  898. be returned. If the key is NULL or if CONFIG_KEYS is not set then 0 will be
  899. returned (in the latter case without parsing the argument).
  900. * To register a key type, the following function should be called::
  901. int register_key_type(struct key_type *type);
  902. This will return error EEXIST if a type of the same name is already
  903. present.
  904. * To unregister a key type, call::
  905. void unregister_key_type(struct key_type *type);
  906. Under some circumstances, it may be desirable to deal with a bundle of keys.
  907. The facility provides access to the keyring type for managing such a bundle::
  908. struct key_type key_type_keyring;
  909. This can be used with a function such as request_key() to find a specific
  910. keyring in a process's keyrings. A keyring thus found can then be searched
  911. with keyring_search(). Note that it is not possible to use request_key() to
  912. search a specific keyring, so using keyrings in this way is of limited utility.
  913. Notes On Accessing Payload Contents
  914. ===================================
  915. The simplest payload is just data stored in key->payload directly. In this
  916. case, there's no need to indulge in RCU or locking when accessing the payload.
  917. More complex payload contents must be allocated and pointers to them set in the
  918. key->payload.data[] array. One of the following ways must be selected to
  919. access the data:
  920. 1) Unmodifiable key type.
  921. If the key type does not have a modify method, then the key's payload can
  922. be accessed without any form of locking, provided that it's known to be
  923. instantiated (uninstantiated keys cannot be "found").
  924. 2) The key's semaphore.
  925. The semaphore could be used to govern access to the payload and to control
  926. the payload pointer. It must be write-locked for modifications and would
  927. have to be read-locked for general access. The disadvantage of doing this
  928. is that the accessor may be required to sleep.
  929. 3) RCU.
  930. RCU must be used when the semaphore isn't already held; if the semaphore
  931. is held then the contents can't change under you unexpectedly as the
  932. semaphore must still be used to serialise modifications to the key. The
  933. key management code takes care of this for the key type.
  934. However, this means using::
  935. rcu_read_lock() ... rcu_dereference() ... rcu_read_unlock()
  936. to read the pointer, and::
  937. rcu_dereference() ... rcu_assign_pointer() ... call_rcu()
  938. to set the pointer and dispose of the old contents after a grace period.
  939. Note that only the key type should ever modify a key's payload.
  940. Furthermore, an RCU controlled payload must hold a struct rcu_head for the
  941. use of call_rcu() and, if the payload is of variable size, the length of
  942. the payload. key->datalen cannot be relied upon to be consistent with the
  943. payload just dereferenced if the key's semaphore is not held.
  944. Note that key->payload.data[0] has a shadow that is marked for __rcu
  945. usage. This is called key->payload.rcu_data0. The following accessors
  946. wrap the RCU calls to this element:
  947. a) Set or change the first payload pointer::
  948. rcu_assign_keypointer(struct key *key, void *data);
  949. b) Read the first payload pointer with the key semaphore held::
  950. [const] void *dereference_key_locked([const] struct key *key);
  951. Note that the return value will inherit its constness from the key
  952. parameter. Static analysis will give an error if it things the lock
  953. isn't held.
  954. c) Read the first payload pointer with the RCU read lock held::
  955. const void *dereference_key_rcu(const struct key *key);
  956. Defining a Key Type
  957. ===================
  958. A kernel service may want to define its own key type. For instance, an AFS
  959. filesystem might want to define a Kerberos 5 ticket key type. To do this, it
  960. author fills in a key_type struct and registers it with the system.
  961. Source files that implement key types should include the following header file::
  962. <linux/key-type.h>
  963. The structure has a number of fields, some of which are mandatory:
  964. * ``const char *name``
  965. The name of the key type. This is used to translate a key type name
  966. supplied by userspace into a pointer to the structure.
  967. * ``size_t def_datalen``
  968. This is optional - it supplies the default payload data length as
  969. contributed to the quota. If the key type's payload is always or almost
  970. always the same size, then this is a more efficient way to do things.
  971. The data length (and quota) on a particular key can always be changed
  972. during instantiation or update by calling::
  973. int key_payload_reserve(struct key *key, size_t datalen);
  974. With the revised data length. Error EDQUOT will be returned if this is not
  975. viable.
  976. * ``int (*vet_description)(const char *description);``
  977. This optional method is called to vet a key description. If the key type
  978. doesn't approve of the key description, it may return an error, otherwise
  979. it should return 0.
  980. * ``int (*preparse)(struct key_preparsed_payload *prep);``
  981. This optional method permits the key type to attempt to parse payload
  982. before a key is created (add key) or the key semaphore is taken (update or
  983. instantiate key). The structure pointed to by prep looks like::
  984. struct key_preparsed_payload {
  985. char *description;
  986. union key_payload payload;
  987. const void *data;
  988. size_t datalen;
  989. size_t quotalen;
  990. time_t expiry;
  991. };
  992. Before calling the method, the caller will fill in data and datalen with
  993. the payload blob parameters; quotalen will be filled in with the default
  994. quota size from the key type; expiry will be set to TIME_T_MAX and the
  995. rest will be cleared.
  996. If a description can be proposed from the payload contents, that should be
  997. attached as a string to the description field. This will be used for the
  998. key description if the caller of add_key() passes NULL or "".
  999. The method can attach anything it likes to payload. This is merely passed
  1000. along to the instantiate() or update() operations. If set, the expiry
  1001. time will be applied to the key if it is instantiated from this data.
  1002. The method should return 0 if successful or a negative error code
  1003. otherwise.
  1004. * ``void (*free_preparse)(struct key_preparsed_payload *prep);``
  1005. This method is only required if the preparse() method is provided,
  1006. otherwise it is unused. It cleans up anything attached to the description
  1007. and payload fields of the key_preparsed_payload struct as filled in by the
  1008. preparse() method. It will always be called after preparse() returns
  1009. successfully, even if instantiate() or update() succeed.
  1010. * ``int (*instantiate)(struct key *key, struct key_preparsed_payload *prep);``
  1011. This method is called to attach a payload to a key during construction.
  1012. The payload attached need not bear any relation to the data passed to this
  1013. function.
  1014. The prep->data and prep->datalen fields will define the original payload
  1015. blob. If preparse() was supplied then other fields may be filled in also.
  1016. If the amount of data attached to the key differs from the size in
  1017. keytype->def_datalen, then key_payload_reserve() should be called.
  1018. This method does not have to lock the key in order to attach a payload.
  1019. The fact that KEY_FLAG_INSTANTIATED is not set in key->flags prevents
  1020. anything else from gaining access to the key.
  1021. It is safe to sleep in this method.
  1022. generic_key_instantiate() is provided to simply copy the data from
  1023. prep->payload.data[] to key->payload.data[], with RCU-safe assignment on
  1024. the first element. It will then clear prep->payload.data[] so that the
  1025. free_preparse method doesn't release the data.
  1026. * ``int (*update)(struct key *key, const void *data, size_t datalen);``
  1027. If this type of key can be updated, then this method should be provided.
  1028. It is called to update a key's payload from the blob of data provided.
  1029. The prep->data and prep->datalen fields will define the original payload
  1030. blob. If preparse() was supplied then other fields may be filled in also.
  1031. key_payload_reserve() should be called if the data length might change
  1032. before any changes are actually made. Note that if this succeeds, the type
  1033. is committed to changing the key because it's already been altered, so all
  1034. memory allocation must be done first.
  1035. The key will have its semaphore write-locked before this method is called,
  1036. but this only deters other writers; any changes to the key's payload must
  1037. be made under RCU conditions, and call_rcu() must be used to dispose of
  1038. the old payload.
  1039. key_payload_reserve() should be called before the changes are made, but
  1040. after all allocations and other potentially failing function calls are
  1041. made.
  1042. It is safe to sleep in this method.
  1043. * ``int (*match_preparse)(struct key_match_data *match_data);``
  1044. This method is optional. It is called when a key search is about to be
  1045. performed. It is given the following structure::
  1046. struct key_match_data {
  1047. bool (*cmp)(const struct key *key,
  1048. const struct key_match_data *match_data);
  1049. const void *raw_data;
  1050. void *preparsed;
  1051. unsigned lookup_type;
  1052. };
  1053. On entry, raw_data will be pointing to the criteria to be used in matching
  1054. a key by the caller and should not be modified. ``(*cmp)()`` will be pointing
  1055. to the default matcher function (which does an exact description match
  1056. against raw_data) and lookup_type will be set to indicate a direct lookup.
  1057. The following lookup_type values are available:
  1058. * KEYRING_SEARCH_LOOKUP_DIRECT - A direct lookup hashes the type and
  1059. description to narrow down the search to a small number of keys.
  1060. * KEYRING_SEARCH_LOOKUP_ITERATE - An iterative lookup walks all the
  1061. keys in the keyring until one is matched. This must be used for any
  1062. search that's not doing a simple direct match on the key description.
  1063. The method may set cmp to point to a function of its choice that does some
  1064. other form of match, may set lookup_type to KEYRING_SEARCH_LOOKUP_ITERATE
  1065. and may attach something to the preparsed pointer for use by ``(*cmp)()``.
  1066. ``(*cmp)()`` should return true if a key matches and false otherwise.
  1067. If preparsed is set, it may be necessary to use the match_free() method to
  1068. clean it up.
  1069. The method should return 0 if successful or a negative error code
  1070. otherwise.
  1071. It is permitted to sleep in this method, but ``(*cmp)()`` may not sleep as
  1072. locks will be held over it.
  1073. If match_preparse() is not provided, keys of this type will be matched
  1074. exactly by their description.
  1075. * ``void (*match_free)(struct key_match_data *match_data);``
  1076. This method is optional. If given, it called to clean up
  1077. match_data->preparsed after a successful call to match_preparse().
  1078. * ``void (*revoke)(struct key *key);``
  1079. This method is optional. It is called to discard part of the payload
  1080. data upon a key being revoked. The caller will have the key semaphore
  1081. write-locked.
  1082. It is safe to sleep in this method, though care should be taken to avoid
  1083. a deadlock against the key semaphore.
  1084. * ``void (*destroy)(struct key *key);``
  1085. This method is optional. It is called to discard the payload data on a key
  1086. when it is being destroyed.
  1087. This method does not need to lock the key to access the payload; it can
  1088. consider the key as being inaccessible at this time. Note that the key's
  1089. type may have been changed before this function is called.
  1090. It is not safe to sleep in this method; the caller may hold spinlocks.
  1091. * ``void (*describe)(const struct key *key, struct seq_file *p);``
  1092. This method is optional. It is called during /proc/keys reading to
  1093. summarise a key's description and payload in text form.
  1094. This method will be called with the RCU read lock held. rcu_dereference()
  1095. should be used to read the payload pointer if the payload is to be
  1096. accessed. key->datalen cannot be trusted to stay consistent with the
  1097. contents of the payload.
  1098. The description will not change, though the key's state may.
  1099. It is not safe to sleep in this method; the RCU read lock is held by the
  1100. caller.
  1101. * ``long (*read)(const struct key *key, char __user *buffer, size_t buflen);``
  1102. This method is optional. It is called by KEYCTL_READ to translate the
  1103. key's payload into something a blob of data for userspace to deal with.
  1104. Ideally, the blob should be in the same format as that passed in to the
  1105. instantiate and update methods.
  1106. If successful, the blob size that could be produced should be returned
  1107. rather than the size copied.
  1108. This method will be called with the key's semaphore read-locked. This will
  1109. prevent the key's payload changing. It is not necessary to use RCU locking
  1110. when accessing the key's payload. It is safe to sleep in this method, such
  1111. as might happen when the userspace buffer is accessed.
  1112. * ``int (*request_key)(struct key_construction *cons, const char *op, void *aux);``
  1113. This method is optional. If provided, request_key() and friends will
  1114. invoke this function rather than upcalling to /sbin/request-key to operate
  1115. upon a key of this type.
  1116. The aux parameter is as passed to request_key_async_with_auxdata() and
  1117. similar or is NULL otherwise. Also passed are the construction record for
  1118. the key to be operated upon and the operation type (currently only
  1119. "create").
  1120. This method is permitted to return before the upcall is complete, but the
  1121. following function must be called under all circumstances to complete the
  1122. instantiation process, whether or not it succeeds, whether or not there's
  1123. an error::
  1124. void complete_request_key(struct key_construction *cons, int error);
  1125. The error parameter should be 0 on success, -ve on error. The
  1126. construction record is destroyed by this action and the authorisation key
  1127. will be revoked. If an error is indicated, the key under construction
  1128. will be negatively instantiated if it wasn't already instantiated.
  1129. If this method returns an error, that error will be returned to the
  1130. caller of request_key*(). complete_request_key() must be called prior to
  1131. returning.
  1132. The key under construction and the authorisation key can be found in the
  1133. key_construction struct pointed to by cons:
  1134. * ``struct key *key;``
  1135. The key under construction.
  1136. * ``struct key *authkey;``
  1137. The authorisation key.
  1138. * ``struct key_restriction *(*lookup_restriction)(const char *params);``
  1139. This optional method is used to enable userspace configuration of keyring
  1140. restrictions. The restriction parameter string (not including the key type
  1141. name) is passed in, and this method returns a pointer to a key_restriction
  1142. structure containing the relevant functions and data to evaluate each
  1143. attempted key link operation. If there is no match, -EINVAL is returned.
  1144. * ``asym_eds_op`` and ``asym_verify_signature``::
  1145. int (*asym_eds_op)(struct kernel_pkey_params *params,
  1146. const void *in, void *out);
  1147. int (*asym_verify_signature)(struct kernel_pkey_params *params,
  1148. const void *in, const void *in2);
  1149. These methods are optional. If provided the first allows a key to be
  1150. used to encrypt, decrypt or sign a blob of data, and the second allows a
  1151. key to verify a signature.
  1152. In all cases, the following information is provided in the params block::
  1153. struct kernel_pkey_params {
  1154. struct key *key;
  1155. const char *encoding;
  1156. const char *hash_algo;
  1157. char *info;
  1158. __u32 in_len;
  1159. union {
  1160. __u32 out_len;
  1161. __u32 in2_len;
  1162. };
  1163. enum kernel_pkey_operation op : 8;
  1164. };
  1165. This includes the key to be used; a string indicating the encoding to use
  1166. (for instance, "pkcs1" may be used with an RSA key to indicate
  1167. RSASSA-PKCS1-v1.5 or RSAES-PKCS1-v1.5 encoding or "raw" if no encoding);
  1168. the name of the hash algorithm used to generate the data for a signature
  1169. (if appropriate); the sizes of the input and output (or second input)
  1170. buffers; and the ID of the operation to be performed.
  1171. For a given operation ID, the input and output buffers are used as
  1172. follows::
  1173. Operation ID in,in_len out,out_len in2,in2_len
  1174. ======================= =============== =============== ===============
  1175. kernel_pkey_encrypt Raw data Encrypted data -
  1176. kernel_pkey_decrypt Encrypted data Raw data -
  1177. kernel_pkey_sign Raw data Signature -
  1178. kernel_pkey_verify Raw data - Signature
  1179. asym_eds_op() deals with encryption, decryption and signature creation as
  1180. specified by params->op. Note that params->op is also set for
  1181. asym_verify_signature().
  1182. Encrypting and signature creation both take raw data in the input buffer
  1183. and return the encrypted result in the output buffer. Padding may have
  1184. been added if an encoding was set. In the case of signature creation,
  1185. depending on the encoding, the padding created may need to indicate the
  1186. digest algorithm - the name of which should be supplied in hash_algo.
  1187. Decryption takes encrypted data in the input buffer and returns the raw
  1188. data in the output buffer. Padding will get checked and stripped off if
  1189. an encoding was set.
  1190. Verification takes raw data in the input buffer and the signature in the
  1191. second input buffer and checks that the one matches the other. Padding
  1192. will be validated. Depending on the encoding, the digest algorithm used
  1193. to generate the raw data may need to be indicated in hash_algo.
  1194. If successful, asym_eds_op() should return the number of bytes written
  1195. into the output buffer. asym_verify_signature() should return 0.
  1196. A variety of errors may be returned, including EOPNOTSUPP if the operation
  1197. is not supported; EKEYREJECTED if verification fails; ENOPKG if the
  1198. required crypto isn't available.
  1199. * ``asym_query``::
  1200. int (*asym_query)(const struct kernel_pkey_params *params,
  1201. struct kernel_pkey_query *info);
  1202. This method is optional. If provided it allows information about the
  1203. public or asymmetric key held in the key to be determined.
  1204. The parameter block is as for asym_eds_op() and co. but in_len and out_len
  1205. are unused. The encoding and hash_algo fields should be used to reduce
  1206. the returned buffer/data sizes as appropriate.
  1207. If successful, the following information is filled in::
  1208. struct kernel_pkey_query {
  1209. __u32 supported_ops;
  1210. __u32 key_size;
  1211. __u16 max_data_size;
  1212. __u16 max_sig_size;
  1213. __u16 max_enc_size;
  1214. __u16 max_dec_size;
  1215. };
  1216. The supported_ops field will contain a bitmask indicating what operations
  1217. are supported by the key, including encryption of a blob, decryption of a
  1218. blob, signing a blob and verifying the signature on a blob. The following
  1219. constants are defined for this::
  1220. KEYCTL_SUPPORTS_{ENCRYPT,DECRYPT,SIGN,VERIFY}
  1221. The key_size field is the size of the key in bits. max_data_size and
  1222. max_sig_size are the maximum raw data and signature sizes for creation and
  1223. verification of a signature; max_enc_size and max_dec_size are the maximum
  1224. raw data and signature sizes for encryption and decryption. The
  1225. max_*_size fields are measured in bytes.
  1226. If successful, 0 will be returned. If the key doesn't support this,
  1227. EOPNOTSUPP will be returned.
  1228. Request-Key Callback Service
  1229. ============================
  1230. To create a new key, the kernel will attempt to execute the following command
  1231. line::
  1232. /sbin/request-key create <key> <uid> <gid> \
  1233. <threadring> <processring> <sessionring> <callout_info>
  1234. <key> is the key being constructed, and the three keyrings are the process
  1235. keyrings from the process that caused the search to be issued. These are
  1236. included for two reasons:
  1237. 1 There may be an authentication token in one of the keyrings that is
  1238. required to obtain the key, eg: a Kerberos Ticket-Granting Ticket.
  1239. 2 The new key should probably be cached in one of these rings.
  1240. This program should set it UID and GID to those specified before attempting to
  1241. access any more keys. It may then look around for a user specific process to
  1242. hand the request off to (perhaps a path held in placed in another key by, for
  1243. example, the KDE desktop manager).
  1244. The program (or whatever it calls) should finish construction of the key by
  1245. calling KEYCTL_INSTANTIATE or KEYCTL_INSTANTIATE_IOV, which also permits it to
  1246. cache the key in one of the keyrings (probably the session ring) before
  1247. returning. Alternatively, the key can be marked as negative with KEYCTL_NEGATE
  1248. or KEYCTL_REJECT; this also permits the key to be cached in one of the
  1249. keyrings.
  1250. If it returns with the key remaining in the unconstructed state, the key will
  1251. be marked as being negative, it will be added to the session keyring, and an
  1252. error will be returned to the key requestor.
  1253. Supplementary information may be provided from whoever or whatever invoked this
  1254. service. This will be passed as the <callout_info> parameter. If no such
  1255. information was made available, then "-" will be passed as this parameter
  1256. instead.
  1257. Similarly, the kernel may attempt to update an expired or a soon to expire key
  1258. by executing::
  1259. /sbin/request-key update <key> <uid> <gid> \
  1260. <threadring> <processring> <sessionring>
  1261. In this case, the program isn't required to actually attach the key to a ring;
  1262. the rings are provided for reference.
  1263. Garbage Collection
  1264. ==================
  1265. Dead keys (for which the type has been removed) will be automatically unlinked
  1266. from those keyrings that point to them and deleted as soon as possible by a
  1267. background garbage collector.
  1268. Similarly, revoked and expired keys will be garbage collected, but only after a
  1269. certain amount of time has passed. This time is set as a number of seconds in::
  1270. /proc/sys/kernel/keys/gc_delay