xref: /linux/crypto/asymmetric_keys/public_key.c (revision 0526b56cbc3c489642bd6a5fe4b718dea7ef0ee8)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* In-software asymmetric public-key crypto subtype
3  *
4  * See Documentation/crypto/asymmetric-keys.rst
5  *
6  * Copyright (C) 2012 Red Hat, Inc. All Rights Reserved.
7  * Written by David Howells (dhowells@redhat.com)
8  */
9 
10 #define pr_fmt(fmt) "PKEY: "fmt
11 #include <linux/module.h>
12 #include <linux/export.h>
13 #include <linux/kernel.h>
14 #include <linux/slab.h>
15 #include <linux/seq_file.h>
16 #include <linux/scatterlist.h>
17 #include <linux/asn1.h>
18 #include <keys/asymmetric-subtype.h>
19 #include <crypto/public_key.h>
20 #include <crypto/akcipher.h>
21 #include <crypto/sm2.h>
22 #include <crypto/sm3_base.h>
23 
24 MODULE_DESCRIPTION("In-software asymmetric public-key subtype");
25 MODULE_AUTHOR("Red Hat, Inc.");
26 MODULE_LICENSE("GPL");
27 
28 /*
29  * Provide a part of a description of the key for /proc/keys.
30  */
31 static void public_key_describe(const struct key *asymmetric_key,
32 				struct seq_file *m)
33 {
34 	struct public_key *key = asymmetric_key->payload.data[asym_crypto];
35 
36 	if (key)
37 		seq_printf(m, "%s.%s", key->id_type, key->pkey_algo);
38 }
39 
40 /*
41  * Destroy a public key algorithm key.
42  */
43 void public_key_free(struct public_key *key)
44 {
45 	if (key) {
46 		kfree(key->key);
47 		kfree(key->params);
48 		kfree(key);
49 	}
50 }
51 EXPORT_SYMBOL_GPL(public_key_free);
52 
53 /*
54  * Destroy a public key algorithm key.
55  */
56 static void public_key_destroy(void *payload0, void *payload3)
57 {
58 	public_key_free(payload0);
59 	public_key_signature_free(payload3);
60 }
61 
62 /*
63  * Given a public_key, and an encoding and hash_algo to be used for signing
64  * and/or verification with that key, determine the name of the corresponding
65  * akcipher algorithm.  Also check that encoding and hash_algo are allowed.
66  */
67 static int
68 software_key_determine_akcipher(const struct public_key *pkey,
69 				const char *encoding, const char *hash_algo,
70 				char alg_name[CRYPTO_MAX_ALG_NAME])
71 {
72 	int n;
73 
74 	if (!encoding)
75 		return -EINVAL;
76 
77 	if (strcmp(pkey->pkey_algo, "rsa") == 0) {
78 		/*
79 		 * RSA signatures usually use EMSA-PKCS1-1_5 [RFC3447 sec 8.2].
80 		 */
81 		if (strcmp(encoding, "pkcs1") == 0) {
82 			if (!hash_algo)
83 				n = snprintf(alg_name, CRYPTO_MAX_ALG_NAME,
84 					     "pkcs1pad(%s)",
85 					     pkey->pkey_algo);
86 			else
87 				n = snprintf(alg_name, CRYPTO_MAX_ALG_NAME,
88 					     "pkcs1pad(%s,%s)",
89 					     pkey->pkey_algo, hash_algo);
90 			return n >= CRYPTO_MAX_ALG_NAME ? -EINVAL : 0;
91 		}
92 		if (strcmp(encoding, "raw") != 0)
93 			return -EINVAL;
94 		/*
95 		 * Raw RSA cannot differentiate between different hash
96 		 * algorithms.
97 		 */
98 		if (hash_algo)
99 			return -EINVAL;
100 	} else if (strncmp(pkey->pkey_algo, "ecdsa", 5) == 0) {
101 		if (strcmp(encoding, "x962") != 0)
102 			return -EINVAL;
103 		/*
104 		 * ECDSA signatures are taken over a raw hash, so they don't
105 		 * differentiate between different hash algorithms.  That means
106 		 * that the verifier should hard-code a specific hash algorithm.
107 		 * Unfortunately, in practice ECDSA is used with multiple SHAs,
108 		 * so we have to allow all of them and not just one.
109 		 */
110 		if (!hash_algo)
111 			return -EINVAL;
112 		if (strcmp(hash_algo, "sha1") != 0 &&
113 		    strcmp(hash_algo, "sha224") != 0 &&
114 		    strcmp(hash_algo, "sha256") != 0 &&
115 		    strcmp(hash_algo, "sha384") != 0 &&
116 		    strcmp(hash_algo, "sha512") != 0)
117 			return -EINVAL;
118 	} else if (strcmp(pkey->pkey_algo, "sm2") == 0) {
119 		if (strcmp(encoding, "raw") != 0)
120 			return -EINVAL;
121 		if (!hash_algo)
122 			return -EINVAL;
123 		if (strcmp(hash_algo, "sm3") != 0)
124 			return -EINVAL;
125 	} else if (strcmp(pkey->pkey_algo, "ecrdsa") == 0) {
126 		if (strcmp(encoding, "raw") != 0)
127 			return -EINVAL;
128 		if (!hash_algo)
129 			return -EINVAL;
130 		if (strcmp(hash_algo, "streebog256") != 0 &&
131 		    strcmp(hash_algo, "streebog512") != 0)
132 			return -EINVAL;
133 	} else {
134 		/* Unknown public key algorithm */
135 		return -ENOPKG;
136 	}
137 	if (strscpy(alg_name, pkey->pkey_algo, CRYPTO_MAX_ALG_NAME) < 0)
138 		return -EINVAL;
139 	return 0;
140 }
141 
142 static u8 *pkey_pack_u32(u8 *dst, u32 val)
143 {
144 	memcpy(dst, &val, sizeof(val));
145 	return dst + sizeof(val);
146 }
147 
148 /*
149  * Query information about a key.
150  */
151 static int software_key_query(const struct kernel_pkey_params *params,
152 			      struct kernel_pkey_query *info)
153 {
154 	struct crypto_akcipher *tfm;
155 	struct public_key *pkey = params->key->payload.data[asym_crypto];
156 	char alg_name[CRYPTO_MAX_ALG_NAME];
157 	u8 *key, *ptr;
158 	int ret, len;
159 
160 	ret = software_key_determine_akcipher(pkey, params->encoding,
161 					      params->hash_algo, alg_name);
162 	if (ret < 0)
163 		return ret;
164 
165 	tfm = crypto_alloc_akcipher(alg_name, 0, 0);
166 	if (IS_ERR(tfm))
167 		return PTR_ERR(tfm);
168 
169 	ret = -ENOMEM;
170 	key = kmalloc(pkey->keylen + sizeof(u32) * 2 + pkey->paramlen,
171 		      GFP_KERNEL);
172 	if (!key)
173 		goto error_free_tfm;
174 	memcpy(key, pkey->key, pkey->keylen);
175 	ptr = key + pkey->keylen;
176 	ptr = pkey_pack_u32(ptr, pkey->algo);
177 	ptr = pkey_pack_u32(ptr, pkey->paramlen);
178 	memcpy(ptr, pkey->params, pkey->paramlen);
179 
180 	if (pkey->key_is_private)
181 		ret = crypto_akcipher_set_priv_key(tfm, key, pkey->keylen);
182 	else
183 		ret = crypto_akcipher_set_pub_key(tfm, key, pkey->keylen);
184 	if (ret < 0)
185 		goto error_free_key;
186 
187 	len = crypto_akcipher_maxsize(tfm);
188 	info->key_size = len * 8;
189 
190 	if (strncmp(pkey->pkey_algo, "ecdsa", 5) == 0) {
191 		/*
192 		 * ECDSA key sizes are much smaller than RSA, and thus could
193 		 * operate on (hashed) inputs that are larger than key size.
194 		 * For example SHA384-hashed input used with secp256r1
195 		 * based keys.  Set max_data_size to be at least as large as
196 		 * the largest supported hash size (SHA512)
197 		 */
198 		info->max_data_size = 64;
199 
200 		/*
201 		 * Verify takes ECDSA-Sig (described in RFC 5480) as input,
202 		 * which is actually 2 'key_size'-bit integers encoded in
203 		 * ASN.1.  Account for the ASN.1 encoding overhead here.
204 		 */
205 		info->max_sig_size = 2 * (len + 3) + 2;
206 	} else {
207 		info->max_data_size = len;
208 		info->max_sig_size = len;
209 	}
210 
211 	info->max_enc_size = len;
212 	info->max_dec_size = len;
213 	info->supported_ops = (KEYCTL_SUPPORTS_ENCRYPT |
214 			       KEYCTL_SUPPORTS_VERIFY);
215 	if (pkey->key_is_private)
216 		info->supported_ops |= (KEYCTL_SUPPORTS_DECRYPT |
217 					KEYCTL_SUPPORTS_SIGN);
218 	ret = 0;
219 
220 error_free_key:
221 	kfree(key);
222 error_free_tfm:
223 	crypto_free_akcipher(tfm);
224 	pr_devel("<==%s() = %d\n", __func__, ret);
225 	return ret;
226 }
227 
228 /*
229  * Do encryption, decryption and signing ops.
230  */
231 static int software_key_eds_op(struct kernel_pkey_params *params,
232 			       const void *in, void *out)
233 {
234 	const struct public_key *pkey = params->key->payload.data[asym_crypto];
235 	struct akcipher_request *req;
236 	struct crypto_akcipher *tfm;
237 	struct crypto_wait cwait;
238 	struct scatterlist in_sg, out_sg;
239 	char alg_name[CRYPTO_MAX_ALG_NAME];
240 	char *key, *ptr;
241 	int ret;
242 
243 	pr_devel("==>%s()\n", __func__);
244 
245 	ret = software_key_determine_akcipher(pkey, params->encoding,
246 					      params->hash_algo, alg_name);
247 	if (ret < 0)
248 		return ret;
249 
250 	tfm = crypto_alloc_akcipher(alg_name, 0, 0);
251 	if (IS_ERR(tfm))
252 		return PTR_ERR(tfm);
253 
254 	ret = -ENOMEM;
255 	req = akcipher_request_alloc(tfm, GFP_KERNEL);
256 	if (!req)
257 		goto error_free_tfm;
258 
259 	key = kmalloc(pkey->keylen + sizeof(u32) * 2 + pkey->paramlen,
260 		      GFP_KERNEL);
261 	if (!key)
262 		goto error_free_req;
263 
264 	memcpy(key, pkey->key, pkey->keylen);
265 	ptr = key + pkey->keylen;
266 	ptr = pkey_pack_u32(ptr, pkey->algo);
267 	ptr = pkey_pack_u32(ptr, pkey->paramlen);
268 	memcpy(ptr, pkey->params, pkey->paramlen);
269 
270 	if (pkey->key_is_private)
271 		ret = crypto_akcipher_set_priv_key(tfm, key, pkey->keylen);
272 	else
273 		ret = crypto_akcipher_set_pub_key(tfm, key, pkey->keylen);
274 	if (ret)
275 		goto error_free_key;
276 
277 	sg_init_one(&in_sg, in, params->in_len);
278 	sg_init_one(&out_sg, out, params->out_len);
279 	akcipher_request_set_crypt(req, &in_sg, &out_sg, params->in_len,
280 				   params->out_len);
281 	crypto_init_wait(&cwait);
282 	akcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG |
283 				      CRYPTO_TFM_REQ_MAY_SLEEP,
284 				      crypto_req_done, &cwait);
285 
286 	/* Perform the encryption calculation. */
287 	switch (params->op) {
288 	case kernel_pkey_encrypt:
289 		ret = crypto_akcipher_encrypt(req);
290 		break;
291 	case kernel_pkey_decrypt:
292 		ret = crypto_akcipher_decrypt(req);
293 		break;
294 	case kernel_pkey_sign:
295 		ret = crypto_akcipher_sign(req);
296 		break;
297 	default:
298 		BUG();
299 	}
300 
301 	ret = crypto_wait_req(ret, &cwait);
302 	if (ret == 0)
303 		ret = req->dst_len;
304 
305 error_free_key:
306 	kfree(key);
307 error_free_req:
308 	akcipher_request_free(req);
309 error_free_tfm:
310 	crypto_free_akcipher(tfm);
311 	pr_devel("<==%s() = %d\n", __func__, ret);
312 	return ret;
313 }
314 
315 #if IS_REACHABLE(CONFIG_CRYPTO_SM2)
316 static int cert_sig_digest_update(const struct public_key_signature *sig,
317 				  struct crypto_akcipher *tfm_pkey)
318 {
319 	struct crypto_shash *tfm;
320 	struct shash_desc *desc;
321 	size_t desc_size;
322 	unsigned char dgst[SM3_DIGEST_SIZE];
323 	int ret;
324 
325 	BUG_ON(!sig->data);
326 
327 	/* SM2 signatures always use the SM3 hash algorithm */
328 	if (!sig->hash_algo || strcmp(sig->hash_algo, "sm3") != 0)
329 		return -EINVAL;
330 
331 	ret = sm2_compute_z_digest(tfm_pkey, SM2_DEFAULT_USERID,
332 					SM2_DEFAULT_USERID_LEN, dgst);
333 	if (ret)
334 		return ret;
335 
336 	tfm = crypto_alloc_shash(sig->hash_algo, 0, 0);
337 	if (IS_ERR(tfm))
338 		return PTR_ERR(tfm);
339 
340 	desc_size = crypto_shash_descsize(tfm) + sizeof(*desc);
341 	desc = kzalloc(desc_size, GFP_KERNEL);
342 	if (!desc) {
343 		ret = -ENOMEM;
344 		goto error_free_tfm;
345 	}
346 
347 	desc->tfm = tfm;
348 
349 	ret = crypto_shash_init(desc);
350 	if (ret < 0)
351 		goto error_free_desc;
352 
353 	ret = crypto_shash_update(desc, dgst, SM3_DIGEST_SIZE);
354 	if (ret < 0)
355 		goto error_free_desc;
356 
357 	ret = crypto_shash_finup(desc, sig->data, sig->data_size, sig->digest);
358 
359 error_free_desc:
360 	kfree(desc);
361 error_free_tfm:
362 	crypto_free_shash(tfm);
363 	return ret;
364 }
365 #else
366 static inline int cert_sig_digest_update(
367 	const struct public_key_signature *sig,
368 	struct crypto_akcipher *tfm_pkey)
369 {
370 	return -ENOTSUPP;
371 }
372 #endif /* ! IS_REACHABLE(CONFIG_CRYPTO_SM2) */
373 
374 /*
375  * Verify a signature using a public key.
376  */
377 int public_key_verify_signature(const struct public_key *pkey,
378 				const struct public_key_signature *sig)
379 {
380 	struct crypto_wait cwait;
381 	struct crypto_akcipher *tfm;
382 	struct akcipher_request *req;
383 	struct scatterlist src_sg[2];
384 	char alg_name[CRYPTO_MAX_ALG_NAME];
385 	char *key, *ptr;
386 	int ret;
387 
388 	pr_devel("==>%s()\n", __func__);
389 
390 	BUG_ON(!pkey);
391 	BUG_ON(!sig);
392 	BUG_ON(!sig->s);
393 
394 	/*
395 	 * If the signature specifies a public key algorithm, it *must* match
396 	 * the key's actual public key algorithm.
397 	 *
398 	 * Small exception: ECDSA signatures don't specify the curve, but ECDSA
399 	 * keys do.  So the strings can mismatch slightly in that case:
400 	 * "ecdsa-nist-*" for the key, but "ecdsa" for the signature.
401 	 */
402 	if (sig->pkey_algo) {
403 		if (strcmp(pkey->pkey_algo, sig->pkey_algo) != 0 &&
404 		    (strncmp(pkey->pkey_algo, "ecdsa-", 6) != 0 ||
405 		     strcmp(sig->pkey_algo, "ecdsa") != 0))
406 			return -EKEYREJECTED;
407 	}
408 
409 	ret = software_key_determine_akcipher(pkey, sig->encoding,
410 					      sig->hash_algo, alg_name);
411 	if (ret < 0)
412 		return ret;
413 
414 	tfm = crypto_alloc_akcipher(alg_name, 0, 0);
415 	if (IS_ERR(tfm))
416 		return PTR_ERR(tfm);
417 
418 	ret = -ENOMEM;
419 	req = akcipher_request_alloc(tfm, GFP_KERNEL);
420 	if (!req)
421 		goto error_free_tfm;
422 
423 	key = kmalloc(pkey->keylen + sizeof(u32) * 2 + pkey->paramlen,
424 		      GFP_KERNEL);
425 	if (!key)
426 		goto error_free_req;
427 
428 	memcpy(key, pkey->key, pkey->keylen);
429 	ptr = key + pkey->keylen;
430 	ptr = pkey_pack_u32(ptr, pkey->algo);
431 	ptr = pkey_pack_u32(ptr, pkey->paramlen);
432 	memcpy(ptr, pkey->params, pkey->paramlen);
433 
434 	if (pkey->key_is_private)
435 		ret = crypto_akcipher_set_priv_key(tfm, key, pkey->keylen);
436 	else
437 		ret = crypto_akcipher_set_pub_key(tfm, key, pkey->keylen);
438 	if (ret)
439 		goto error_free_key;
440 
441 	if (strcmp(pkey->pkey_algo, "sm2") == 0 && sig->data_size) {
442 		ret = cert_sig_digest_update(sig, tfm);
443 		if (ret)
444 			goto error_free_key;
445 	}
446 
447 	sg_init_table(src_sg, 2);
448 	sg_set_buf(&src_sg[0], sig->s, sig->s_size);
449 	sg_set_buf(&src_sg[1], sig->digest, sig->digest_size);
450 	akcipher_request_set_crypt(req, src_sg, NULL, sig->s_size,
451 				   sig->digest_size);
452 	crypto_init_wait(&cwait);
453 	akcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG |
454 				      CRYPTO_TFM_REQ_MAY_SLEEP,
455 				      crypto_req_done, &cwait);
456 	ret = crypto_wait_req(crypto_akcipher_verify(req), &cwait);
457 
458 error_free_key:
459 	kfree(key);
460 error_free_req:
461 	akcipher_request_free(req);
462 error_free_tfm:
463 	crypto_free_akcipher(tfm);
464 	pr_devel("<==%s() = %d\n", __func__, ret);
465 	if (WARN_ON_ONCE(ret > 0))
466 		ret = -EINVAL;
467 	return ret;
468 }
469 EXPORT_SYMBOL_GPL(public_key_verify_signature);
470 
471 static int public_key_verify_signature_2(const struct key *key,
472 					 const struct public_key_signature *sig)
473 {
474 	const struct public_key *pk = key->payload.data[asym_crypto];
475 	return public_key_verify_signature(pk, sig);
476 }
477 
478 /*
479  * Public key algorithm asymmetric key subtype
480  */
481 struct asymmetric_key_subtype public_key_subtype = {
482 	.owner			= THIS_MODULE,
483 	.name			= "public_key",
484 	.name_len		= sizeof("public_key") - 1,
485 	.describe		= public_key_describe,
486 	.destroy		= public_key_destroy,
487 	.query			= software_key_query,
488 	.eds_op			= software_key_eds_op,
489 	.verify_signature	= public_key_verify_signature_2,
490 };
491 EXPORT_SYMBOL_GPL(public_key_subtype);
492