xref: /linux-6.15/include/linux/crypto.h (revision dfd28c89)
1 /* SPDX-License-Identifier: GPL-2.0-or-later */
2 /*
3  * Scatterlist Cryptographic API.
4  *
5  * Copyright (c) 2002 James Morris <[email protected]>
6  * Copyright (c) 2002 David S. Miller ([email protected])
7  * Copyright (c) 2005 Herbert Xu <[email protected]>
8  *
9  * Portions derived from Cryptoapi, by Alexander Kjeldaas <[email protected]>
10  * and Nettle, by Niels Möller.
11  */
12 #ifndef _LINUX_CRYPTO_H
13 #define _LINUX_CRYPTO_H
14 
15 #include <linux/completion.h>
16 #include <linux/errno.h>
17 #include <linux/list.h>
18 #include <linux/refcount.h>
19 #include <linux/slab.h>
20 #include <linux/types.h>
21 
22 /*
23  * Algorithm masks and types.
24  */
25 #define CRYPTO_ALG_TYPE_MASK		0x0000000f
26 #define CRYPTO_ALG_TYPE_CIPHER		0x00000001
27 #define CRYPTO_ALG_TYPE_COMPRESS	0x00000002
28 #define CRYPTO_ALG_TYPE_AEAD		0x00000003
29 #define CRYPTO_ALG_TYPE_LSKCIPHER	0x00000004
30 #define CRYPTO_ALG_TYPE_SKCIPHER	0x00000005
31 #define CRYPTO_ALG_TYPE_AKCIPHER	0x00000006
32 #define CRYPTO_ALG_TYPE_SIG		0x00000007
33 #define CRYPTO_ALG_TYPE_KPP		0x00000008
34 #define CRYPTO_ALG_TYPE_ACOMPRESS	0x0000000a
35 #define CRYPTO_ALG_TYPE_SCOMPRESS	0x0000000b
36 #define CRYPTO_ALG_TYPE_RNG		0x0000000c
37 #define CRYPTO_ALG_TYPE_HASH		0x0000000e
38 #define CRYPTO_ALG_TYPE_SHASH		0x0000000e
39 #define CRYPTO_ALG_TYPE_AHASH		0x0000000f
40 
41 #define CRYPTO_ALG_TYPE_ACOMPRESS_MASK	0x0000000e
42 
43 #define CRYPTO_ALG_LARVAL		0x00000010
44 #define CRYPTO_ALG_DEAD			0x00000020
45 #define CRYPTO_ALG_DYING		0x00000040
46 #define CRYPTO_ALG_ASYNC		0x00000080
47 
48 /*
49  * Set if the algorithm (or an algorithm which it uses) requires another
50  * algorithm of the same type to handle corner cases.
51  */
52 #define CRYPTO_ALG_NEED_FALLBACK	0x00000100
53 
54 /*
55  * Set if the algorithm has passed automated run-time testing.  Note that
56  * if there is no run-time testing for a given algorithm it is considered
57  * to have passed.
58  */
59 
60 #define CRYPTO_ALG_TESTED		0x00000400
61 
62 /*
63  * Set if the algorithm is an instance that is built from templates.
64  */
65 #define CRYPTO_ALG_INSTANCE		0x00000800
66 
67 /* Set this bit if the algorithm provided is hardware accelerated but
68  * not available to userspace via instruction set or so.
69  */
70 #define CRYPTO_ALG_KERN_DRIVER_ONLY	0x00001000
71 
72 /*
73  * Mark a cipher as a service implementation only usable by another
74  * cipher and never by a normal user of the kernel crypto API
75  */
76 #define CRYPTO_ALG_INTERNAL		0x00002000
77 
78 /*
79  * Set if the algorithm has a ->setkey() method but can be used without
80  * calling it first, i.e. there is a default key.
81  */
82 #define CRYPTO_ALG_OPTIONAL_KEY		0x00004000
83 
84 /*
85  * Don't trigger module loading
86  */
87 #define CRYPTO_NOLOAD			0x00008000
88 
89 /*
90  * The algorithm may allocate memory during request processing, i.e. during
91  * encryption, decryption, or hashing.  Users can request an algorithm with this
92  * flag unset if they can't handle memory allocation failures.
93  *
94  * This flag is currently only implemented for algorithms of type "skcipher",
95  * "aead", "ahash", "shash", and "cipher".  Algorithms of other types might not
96  * have this flag set even if they allocate memory.
97  *
98  * In some edge cases, algorithms can allocate memory regardless of this flag.
99  * To avoid these cases, users must obey the following usage constraints:
100  *    skcipher:
101  *	- The IV buffer and all scatterlist elements must be aligned to the
102  *	  algorithm's alignmask.
103  *	- If the data were to be divided into chunks of size
104  *	  crypto_skcipher_walksize() (with any remainder going at the end), no
105  *	  chunk can cross a page boundary or a scatterlist element boundary.
106  *    aead:
107  *	- The IV buffer and all scatterlist elements must be aligned to the
108  *	  algorithm's alignmask.
109  *	- The first scatterlist element must contain all the associated data,
110  *	  and its pages must be !PageHighMem.
111  *	- If the plaintext/ciphertext were to be divided into chunks of size
112  *	  crypto_aead_walksize() (with the remainder going at the end), no chunk
113  *	  can cross a page boundary or a scatterlist element boundary.
114  *    ahash:
115  *	- crypto_ahash_finup() must not be used unless the algorithm implements
116  *	  ->finup() natively.
117  */
118 #define CRYPTO_ALG_ALLOCATES_MEMORY	0x00010000
119 
120 /*
121  * Mark an algorithm as a service implementation only usable by a
122  * template and never by a normal user of the kernel crypto API.
123  * This is intended to be used by algorithms that are themselves
124  * not FIPS-approved but may instead be used to implement parts of
125  * a FIPS-approved algorithm (e.g., dh vs. ffdhe2048(dh)).
126  */
127 #define CRYPTO_ALG_FIPS_INTERNAL	0x00020000
128 
129 /* Set if the algorithm supports request chains and virtual addresses. */
130 #define CRYPTO_ALG_REQ_CHAIN		0x00040000
131 
132 /*
133  * Transform masks and values (for crt_flags).
134  */
135 #define CRYPTO_TFM_NEED_KEY		0x00000001
136 
137 #define CRYPTO_TFM_REQ_MASK		0x000fff00
138 #define CRYPTO_TFM_REQ_FORBID_WEAK_KEYS	0x00000100
139 #define CRYPTO_TFM_REQ_MAY_SLEEP	0x00000200
140 #define CRYPTO_TFM_REQ_MAY_BACKLOG	0x00000400
141 #define CRYPTO_TFM_REQ_ON_STACK		0x00000800
142 
143 /*
144  * Miscellaneous stuff.
145  */
146 #define CRYPTO_MAX_ALG_NAME		128
147 
148 /*
149  * The macro CRYPTO_MINALIGN_ATTR (along with the void * type in the actual
150  * declaration) is used to ensure that the crypto_tfm context structure is
151  * aligned correctly for the given architecture so that there are no alignment
152  * faults for C data types.  On architectures that support non-cache coherent
153  * DMA, such as ARM or arm64, it also takes into account the minimal alignment
154  * that is required to ensure that the context struct member does not share any
155  * cachelines with the rest of the struct. This is needed to ensure that cache
156  * maintenance for non-coherent DMA (cache invalidation in particular) does not
157  * affect data that may be accessed by the CPU concurrently.
158  */
159 #define CRYPTO_MINALIGN ARCH_KMALLOC_MINALIGN
160 
161 #define CRYPTO_MINALIGN_ATTR __attribute__ ((__aligned__(CRYPTO_MINALIGN)))
162 
163 struct crypto_tfm;
164 struct crypto_type;
165 struct module;
166 
167 typedef void (*crypto_completion_t)(void *req, int err);
168 
169 /**
170  * DOC: Block Cipher Context Data Structures
171  *
172  * These data structures define the operating context for each block cipher
173  * type.
174  */
175 
176 struct crypto_async_request {
177 	struct list_head list;
178 	crypto_completion_t complete;
179 	void *data;
180 	struct crypto_tfm *tfm;
181 
182 	u32 flags;
183 	int err;
184 };
185 
186 /**
187  * DOC: Block Cipher Algorithm Definitions
188  *
189  * These data structures define modular crypto algorithm implementations,
190  * managed via crypto_register_alg() and crypto_unregister_alg().
191  */
192 
193 /**
194  * struct cipher_alg - single-block symmetric ciphers definition
195  * @cia_min_keysize: Minimum key size supported by the transformation. This is
196  *		     the smallest key length supported by this transformation
197  *		     algorithm. This must be set to one of the pre-defined
198  *		     values as this is not hardware specific. Possible values
199  *		     for this field can be found via git grep "_MIN_KEY_SIZE"
200  *		     include/crypto/
201  * @cia_max_keysize: Maximum key size supported by the transformation. This is
202  *		    the largest key length supported by this transformation
203  *		    algorithm. This must be set to one of the pre-defined values
204  *		    as this is not hardware specific. Possible values for this
205  *		    field can be found via git grep "_MAX_KEY_SIZE"
206  *		    include/crypto/
207  * @cia_setkey: Set key for the transformation. This function is used to either
208  *	        program a supplied key into the hardware or store the key in the
209  *	        transformation context for programming it later. Note that this
210  *	        function does modify the transformation context. This function
211  *	        can be called multiple times during the existence of the
212  *	        transformation object, so one must make sure the key is properly
213  *	        reprogrammed into the hardware. This function is also
214  *	        responsible for checking the key length for validity.
215  * @cia_encrypt: Encrypt a single block. This function is used to encrypt a
216  *		 single block of data, which must be @cra_blocksize big. This
217  *		 always operates on a full @cra_blocksize and it is not possible
218  *		 to encrypt a block of smaller size. The supplied buffers must
219  *		 therefore also be at least of @cra_blocksize size. Both the
220  *		 input and output buffers are always aligned to @cra_alignmask.
221  *		 In case either of the input or output buffer supplied by user
222  *		 of the crypto API is not aligned to @cra_alignmask, the crypto
223  *		 API will re-align the buffers. The re-alignment means that a
224  *		 new buffer will be allocated, the data will be copied into the
225  *		 new buffer, then the processing will happen on the new buffer,
226  *		 then the data will be copied back into the original buffer and
227  *		 finally the new buffer will be freed. In case a software
228  *		 fallback was put in place in the @cra_init call, this function
229  *		 might need to use the fallback if the algorithm doesn't support
230  *		 all of the key sizes. In case the key was stored in
231  *		 transformation context, the key might need to be re-programmed
232  *		 into the hardware in this function. This function shall not
233  *		 modify the transformation context, as this function may be
234  *		 called in parallel with the same transformation object.
235  * @cia_decrypt: Decrypt a single block. This is a reverse counterpart to
236  *		 @cia_encrypt, and the conditions are exactly the same.
237  *
238  * All fields are mandatory and must be filled.
239  */
240 struct cipher_alg {
241 	unsigned int cia_min_keysize;
242 	unsigned int cia_max_keysize;
243 	int (*cia_setkey)(struct crypto_tfm *tfm, const u8 *key,
244 	                  unsigned int keylen);
245 	void (*cia_encrypt)(struct crypto_tfm *tfm, u8 *dst, const u8 *src);
246 	void (*cia_decrypt)(struct crypto_tfm *tfm, u8 *dst, const u8 *src);
247 };
248 
249 /**
250  * struct compress_alg - compression/decompression algorithm
251  * @coa_compress: Compress a buffer of specified length, storing the resulting
252  *		  data in the specified buffer. Return the length of the
253  *		  compressed data in dlen.
254  * @coa_decompress: Decompress the source buffer, storing the uncompressed
255  *		    data in the specified buffer. The length of the data is
256  *		    returned in dlen.
257  *
258  * All fields are mandatory.
259  */
260 struct compress_alg {
261 	int (*coa_compress)(struct crypto_tfm *tfm, const u8 *src,
262 			    unsigned int slen, u8 *dst, unsigned int *dlen);
263 	int (*coa_decompress)(struct crypto_tfm *tfm, const u8 *src,
264 			      unsigned int slen, u8 *dst, unsigned int *dlen);
265 };
266 
267 #define cra_cipher	cra_u.cipher
268 #define cra_compress	cra_u.compress
269 
270 /**
271  * struct crypto_alg - definition of a cryptograpic cipher algorithm
272  * @cra_flags: Flags describing this transformation. See include/linux/crypto.h
273  *	       CRYPTO_ALG_* flags for the flags which go in here. Those are
274  *	       used for fine-tuning the description of the transformation
275  *	       algorithm.
276  * @cra_blocksize: Minimum block size of this transformation. The size in bytes
277  *		   of the smallest possible unit which can be transformed with
278  *		   this algorithm. The users must respect this value.
279  *		   In case of HASH transformation, it is possible for a smaller
280  *		   block than @cra_blocksize to be passed to the crypto API for
281  *		   transformation, in case of any other transformation type, an
282  * 		   error will be returned upon any attempt to transform smaller
283  *		   than @cra_blocksize chunks.
284  * @cra_ctxsize: Size of the operational context of the transformation. This
285  *		 value informs the kernel crypto API about the memory size
286  *		 needed to be allocated for the transformation context.
287  * @cra_alignmask: For cipher, skcipher, lskcipher, and aead algorithms this is
288  *		   1 less than the alignment, in bytes, that the algorithm
289  *		   implementation requires for input and output buffers.  When
290  *		   the crypto API is invoked with buffers that are not aligned
291  *		   to this alignment, the crypto API automatically utilizes
292  *		   appropriately aligned temporary buffers to comply with what
293  *		   the algorithm needs.  (For scatterlists this happens only if
294  *		   the algorithm uses the skcipher_walk helper functions.)  This
295  *		   misalignment handling carries a performance penalty, so it is
296  *		   preferred that algorithms do not set a nonzero alignmask.
297  *		   Also, crypto API users may wish to allocate buffers aligned
298  *		   to the alignmask of the algorithm being used, in order to
299  *		   avoid the API having to realign them.  Note: the alignmask is
300  *		   not supported for hash algorithms and is always 0 for them.
301  * @cra_priority: Priority of this transformation implementation. In case
302  *		  multiple transformations with same @cra_name are available to
303  *		  the Crypto API, the kernel will use the one with highest
304  *		  @cra_priority.
305  * @cra_name: Generic name (usable by multiple implementations) of the
306  *	      transformation algorithm. This is the name of the transformation
307  *	      itself. This field is used by the kernel when looking up the
308  *	      providers of particular transformation.
309  * @cra_driver_name: Unique name of the transformation provider. This is the
310  *		     name of the provider of the transformation. This can be any
311  *		     arbitrary value, but in the usual case, this contains the
312  *		     name of the chip or provider and the name of the
313  *		     transformation algorithm.
314  * @cra_type: Type of the cryptographic transformation. This is a pointer to
315  *	      struct crypto_type, which implements callbacks common for all
316  *	      transformation types. There are multiple options, such as
317  *	      &crypto_skcipher_type, &crypto_ahash_type, &crypto_rng_type.
318  *	      This field might be empty. In that case, there are no common
319  *	      callbacks. This is the case for: cipher, compress, shash.
320  * @cra_u: Callbacks implementing the transformation. This is a union of
321  *	   multiple structures. Depending on the type of transformation selected
322  *	   by @cra_type and @cra_flags above, the associated structure must be
323  *	   filled with callbacks. This field might be empty. This is the case
324  *	   for ahash, shash.
325  * @cra_init: Initialize the cryptographic transformation object. This function
326  *	      is used to initialize the cryptographic transformation object.
327  *	      This function is called only once at the instantiation time, right
328  *	      after the transformation context was allocated. In case the
329  *	      cryptographic hardware has some special requirements which need to
330  *	      be handled by software, this function shall check for the precise
331  *	      requirement of the transformation and put any software fallbacks
332  *	      in place.
333  * @cra_exit: Deinitialize the cryptographic transformation object. This is a
334  *	      counterpart to @cra_init, used to remove various changes set in
335  *	      @cra_init.
336  * @cra_u.cipher: Union member which contains a single-block symmetric cipher
337  *		  definition. See @struct @cipher_alg.
338  * @cra_u.compress: Union member which contains a (de)compression algorithm.
339  *		    See @struct @compress_alg.
340  * @cra_module: Owner of this transformation implementation. Set to THIS_MODULE
341  * @cra_list: internally used
342  * @cra_users: internally used
343  * @cra_refcnt: internally used
344  * @cra_destroy: internally used
345  *
346  * The struct crypto_alg describes a generic Crypto API algorithm and is common
347  * for all of the transformations. Any variable not documented here shall not
348  * be used by a cipher implementation as it is internal to the Crypto API.
349  */
350 struct crypto_alg {
351 	struct list_head cra_list;
352 	struct list_head cra_users;
353 
354 	u32 cra_flags;
355 	unsigned int cra_blocksize;
356 	unsigned int cra_ctxsize;
357 	unsigned int cra_alignmask;
358 
359 	int cra_priority;
360 	refcount_t cra_refcnt;
361 
362 	char cra_name[CRYPTO_MAX_ALG_NAME];
363 	char cra_driver_name[CRYPTO_MAX_ALG_NAME];
364 
365 	const struct crypto_type *cra_type;
366 
367 	union {
368 		struct cipher_alg cipher;
369 		struct compress_alg compress;
370 	} cra_u;
371 
372 	int (*cra_init)(struct crypto_tfm *tfm);
373 	void (*cra_exit)(struct crypto_tfm *tfm);
374 	void (*cra_destroy)(struct crypto_alg *alg);
375 
376 	struct module *cra_module;
377 } CRYPTO_MINALIGN_ATTR;
378 
379 /*
380  * A helper struct for waiting for completion of async crypto ops
381  */
382 struct crypto_wait {
383 	struct completion completion;
384 	int err;
385 };
386 
387 /*
388  * Macro for declaring a crypto op async wait object on stack
389  */
390 #define DECLARE_CRYPTO_WAIT(_wait) \
391 	struct crypto_wait _wait = { \
392 		COMPLETION_INITIALIZER_ONSTACK((_wait).completion), 0 }
393 
394 /*
395  * Async ops completion helper functioons
396  */
397 void crypto_req_done(void *req, int err);
398 
399 static inline int crypto_wait_req(int err, struct crypto_wait *wait)
400 {
401 	switch (err) {
402 	case -EINPROGRESS:
403 	case -EBUSY:
404 		wait_for_completion(&wait->completion);
405 		reinit_completion(&wait->completion);
406 		err = wait->err;
407 		break;
408 	}
409 
410 	return err;
411 }
412 
413 static inline void crypto_init_wait(struct crypto_wait *wait)
414 {
415 	init_completion(&wait->completion);
416 }
417 
418 /*
419  * Algorithm query interface.
420  */
421 int crypto_has_alg(const char *name, u32 type, u32 mask);
422 
423 /*
424  * Transforms: user-instantiated objects which encapsulate algorithms
425  * and core processing logic.  Managed via crypto_alloc_*() and
426  * crypto_free_*(), as well as the various helpers below.
427  */
428 
429 struct crypto_tfm {
430 	refcount_t refcnt;
431 
432 	u32 crt_flags;
433 
434 	int node;
435 
436 	void (*exit)(struct crypto_tfm *tfm);
437 
438 	struct crypto_alg *__crt_alg;
439 
440 	void *__crt_ctx[] CRYPTO_MINALIGN_ATTR;
441 };
442 
443 struct crypto_comp {
444 	struct crypto_tfm base;
445 };
446 
447 /*
448  * Transform user interface.
449  */
450 
451 struct crypto_tfm *crypto_alloc_base(const char *alg_name, u32 type, u32 mask);
452 void crypto_destroy_tfm(void *mem, struct crypto_tfm *tfm);
453 
454 static inline void crypto_free_tfm(struct crypto_tfm *tfm)
455 {
456 	return crypto_destroy_tfm(tfm, tfm);
457 }
458 
459 /*
460  * Transform helpers which query the underlying algorithm.
461  */
462 static inline const char *crypto_tfm_alg_name(struct crypto_tfm *tfm)
463 {
464 	return tfm->__crt_alg->cra_name;
465 }
466 
467 static inline const char *crypto_tfm_alg_driver_name(struct crypto_tfm *tfm)
468 {
469 	return tfm->__crt_alg->cra_driver_name;
470 }
471 
472 static inline unsigned int crypto_tfm_alg_blocksize(struct crypto_tfm *tfm)
473 {
474 	return tfm->__crt_alg->cra_blocksize;
475 }
476 
477 static inline unsigned int crypto_tfm_alg_alignmask(struct crypto_tfm *tfm)
478 {
479 	return tfm->__crt_alg->cra_alignmask;
480 }
481 
482 static inline u32 crypto_tfm_get_flags(struct crypto_tfm *tfm)
483 {
484 	return tfm->crt_flags;
485 }
486 
487 static inline void crypto_tfm_set_flags(struct crypto_tfm *tfm, u32 flags)
488 {
489 	tfm->crt_flags |= flags;
490 }
491 
492 static inline void crypto_tfm_clear_flags(struct crypto_tfm *tfm, u32 flags)
493 {
494 	tfm->crt_flags &= ~flags;
495 }
496 
497 static inline unsigned int crypto_tfm_ctx_alignment(void)
498 {
499 	struct crypto_tfm *tfm;
500 	return __alignof__(tfm->__crt_ctx);
501 }
502 
503 static inline struct crypto_comp *__crypto_comp_cast(struct crypto_tfm *tfm)
504 {
505 	return (struct crypto_comp *)tfm;
506 }
507 
508 static inline struct crypto_comp *crypto_alloc_comp(const char *alg_name,
509 						    u32 type, u32 mask)
510 {
511 	type &= ~CRYPTO_ALG_TYPE_MASK;
512 	type |= CRYPTO_ALG_TYPE_COMPRESS;
513 	mask |= CRYPTO_ALG_TYPE_MASK;
514 
515 	return __crypto_comp_cast(crypto_alloc_base(alg_name, type, mask));
516 }
517 
518 static inline struct crypto_tfm *crypto_comp_tfm(struct crypto_comp *tfm)
519 {
520 	return &tfm->base;
521 }
522 
523 static inline void crypto_free_comp(struct crypto_comp *tfm)
524 {
525 	crypto_free_tfm(crypto_comp_tfm(tfm));
526 }
527 
528 static inline int crypto_has_comp(const char *alg_name, u32 type, u32 mask)
529 {
530 	type &= ~CRYPTO_ALG_TYPE_MASK;
531 	type |= CRYPTO_ALG_TYPE_COMPRESS;
532 	mask |= CRYPTO_ALG_TYPE_MASK;
533 
534 	return crypto_has_alg(alg_name, type, mask);
535 }
536 
537 static inline const char *crypto_comp_name(struct crypto_comp *tfm)
538 {
539 	return crypto_tfm_alg_name(crypto_comp_tfm(tfm));
540 }
541 
542 int crypto_comp_compress(struct crypto_comp *tfm,
543 			 const u8 *src, unsigned int slen,
544 			 u8 *dst, unsigned int *dlen);
545 
546 int crypto_comp_decompress(struct crypto_comp *tfm,
547 			   const u8 *src, unsigned int slen,
548 			   u8 *dst, unsigned int *dlen);
549 
550 static inline void crypto_reqchain_init(struct crypto_async_request *req)
551 {
552 	req->err = -EINPROGRESS;
553 	INIT_LIST_HEAD(&req->list);
554 }
555 
556 static inline void crypto_request_chain(struct crypto_async_request *req,
557 					struct crypto_async_request *head)
558 {
559 	req->err = -EINPROGRESS;
560 	list_add_tail(&req->list, &head->list);
561 }
562 
563 static inline bool crypto_tfm_is_async(struct crypto_tfm *tfm)
564 {
565 	return tfm->__crt_alg->cra_flags & CRYPTO_ALG_ASYNC;
566 }
567 
568 #endif	/* _LINUX_CRYPTO_H */
569 
570