1// SPDX-License-Identifier: GPL-2.0+
2/*
3 * Copyright (c) 2013, Google Inc.
4 */
5
6#define OPENSSL_API_COMPAT 0x10101000L
7
8#include "mkimage.h"
9#include <stdlib.h>
10#include <stdio.h>
11#include <string.h>
12#include <image.h>
13#include <time.h>
14#include <u-boot/fdt-libcrypto.h>
15#include <openssl/bn.h>
16#include <openssl/ec.h>
17#include <openssl/rsa.h>
18#include <openssl/pem.h>
19#include <openssl/err.h>
20#include <openssl/ssl.h>
21#include <openssl/evp.h>
22#include <openssl/engine.h>
23
24static int rsa_err(const char *msg)
25{
26	unsigned long sslErr = ERR_get_error();
27
28	fprintf(stderr, "%s", msg);
29	fprintf(stderr, ": %s\n",
30		ERR_error_string(sslErr, 0));
31
32	return -1;
33}
34
35/**
36 * rsa_pem_get_pub_key() - read a public key from a .crt file
37 *
38 * @keydir:	Directory containins the key
39 * @name	Name of key file (will have a .crt extension)
40 * @evpp	Returns EVP_PKEY object, or NULL on failure
41 * Return: 0 if ok, -ve on error (in which case *evpp will be set to NULL)
42 */
43static int rsa_pem_get_pub_key(const char *keydir, const char *name, EVP_PKEY **evpp)
44{
45	char path[1024];
46	EVP_PKEY *key = NULL;
47	X509 *cert;
48	FILE *f;
49	int ret;
50
51	if (!evpp)
52		return -EINVAL;
53
54	*evpp = NULL;
55	snprintf(path, sizeof(path), "%s/%s.crt", keydir, name);
56	f = fopen(path, "r");
57	if (!f) {
58		fprintf(stderr, "Couldn't open RSA certificate: '%s': %s\n",
59			path, strerror(errno));
60		return -EACCES;
61	}
62
63	/* Read the certificate */
64	cert = NULL;
65	if (!PEM_read_X509(f, &cert, NULL, NULL)) {
66		rsa_err("Couldn't read certificate");
67		ret = -EINVAL;
68		goto err_cert;
69	}
70
71	/* Get the public key from the certificate. */
72	key = X509_get_pubkey(cert);
73	if (!key) {
74		rsa_err("Couldn't read public key\n");
75		ret = -EINVAL;
76		goto err_pubkey;
77	}
78
79	fclose(f);
80	*evpp = key;
81	X509_free(cert);
82
83	return 0;
84
85err_pubkey:
86	X509_free(cert);
87err_cert:
88	fclose(f);
89	return ret;
90}
91
92/**
93 * rsa_engine_get_pub_key() - read a public key from given engine
94 *
95 * @keydir:	Key prefix
96 * @name	Name of key
97 * @engine	Engine to use
98 * @evpp	Returns EVP_PKEY object, or NULL on failure
99 * Return: 0 if ok, -ve on error (in which case *evpp will be set to NULL)
100 */
101static int rsa_engine_get_pub_key(const char *keydir, const char *name,
102				  ENGINE *engine, EVP_PKEY **evpp)
103{
104	const char *engine_id;
105	char key_id[1024];
106	EVP_PKEY *key = NULL;
107	const char *const pkcs11_schema = "pkcs11:";
108	const char *pkcs11_uri_prepend = "";
109
110	if (!evpp)
111		return -EINVAL;
112
113	*evpp = NULL;
114
115	engine_id = ENGINE_get_id(engine);
116
117	if (engine_id && !strcmp(engine_id, "pkcs11")) {
118		if (keydir) {
119			// Check for legacy keydir spec and prepend
120			if (strncmp(pkcs11_schema, keydir, strlen(pkcs11_schema))) {
121				pkcs11_uri_prepend = pkcs11_schema;
122				fprintf(stderr, "WARNING: Legacy URI specified. Please add '%s'.\n", pkcs11_schema);
123			}
124
125			if (strstr(keydir, "object="))
126				snprintf(key_id, sizeof(key_id),
127					 "%s%s;type=public",
128					 pkcs11_uri_prepend, keydir);
129			else
130				snprintf(key_id, sizeof(key_id),
131					 "%s%s;object=%s;type=public",
132					 pkcs11_uri_prepend, keydir, name);
133		} else {
134			snprintf(key_id, sizeof(key_id),
135				 "pkcs11:object=%s;type=public",
136				 name);
137		}
138	} else if (engine_id) {
139		if (keydir)
140			snprintf(key_id, sizeof(key_id),
141				 "%s%s",
142				 keydir, name);
143		else
144			snprintf(key_id, sizeof(key_id),
145				 "%s",
146				 name);
147	} else {
148		fprintf(stderr, "Engine not supported\n");
149		return -ENOTSUP;
150	}
151
152	key = ENGINE_load_public_key(engine, key_id, NULL, NULL);
153	if (!key)
154		return rsa_err("Failure loading public key from engine");
155
156	*evpp = key;
157
158	return 0;
159}
160
161/**
162 * rsa_get_pub_key() - read a public key
163 *
164 * @keydir:	Directory containing the key (PEM file) or key prefix (engine)
165 * @name	Name of key file (will have a .crt extension)
166 * @engine	Engine to use
167 * @evpp	Returns EVP_PKEY object, or NULL on failure
168 * Return: 0 if ok, -ve on error (in which case *evpp will be set to NULL)
169 */
170static int rsa_get_pub_key(const char *keydir, const char *name,
171			   ENGINE *engine, EVP_PKEY **evpp)
172{
173	if (engine)
174		return rsa_engine_get_pub_key(keydir, name, engine, evpp);
175	return rsa_pem_get_pub_key(keydir, name, evpp);
176}
177
178/**
179 * rsa_pem_get_priv_key() - read a private key from a .key file
180 *
181 * @keydir:	Directory containing the key
182 * @name	Name of key file (will have a .key extension)
183 * @evpp	Returns EVP_PKEY object, or NULL on failure
184 * Return: 0 if ok, -ve on error (in which case *evpp will be set to NULL)
185 */
186static int rsa_pem_get_priv_key(const char *keydir, const char *name,
187				const char *keyfile, EVP_PKEY **evpp)
188{
189	char path[1024] = {0};
190	FILE *f = NULL;
191
192	if (!evpp)
193		return -EINVAL;
194
195	*evpp = NULL;
196	if (keydir && name)
197		snprintf(path, sizeof(path), "%s/%s.key", keydir, name);
198	else if (keyfile)
199		snprintf(path, sizeof(path), "%s", keyfile);
200	else
201		return -EINVAL;
202
203	f = fopen(path, "r");
204	if (!f) {
205		fprintf(stderr, "Couldn't open RSA private key: '%s': %s\n",
206			path, strerror(errno));
207		return -ENOENT;
208	}
209
210	if (!PEM_read_PrivateKey(f, evpp, NULL, path)) {
211		rsa_err("Failure reading private key");
212		fclose(f);
213		return -EPROTO;
214	}
215	fclose(f);
216
217	return 0;
218}
219
220/**
221 * rsa_engine_get_priv_key() - read a private key from given engine
222 *
223 * @keydir:	Key prefix
224 * @name	Name of key
225 * @engine	Engine to use
226 * @evpp	Returns EVP_PKEY object, or NULL on failure
227 * Return: 0 if ok, -ve on error (in which case *evpp will be set to NULL)
228 */
229static int rsa_engine_get_priv_key(const char *keydir, const char *name,
230				   const char *keyfile,
231				   ENGINE *engine, EVP_PKEY **evpp)
232{
233	const char *engine_id;
234	char key_id[1024];
235	EVP_PKEY *key = NULL;
236	const char *const pkcs11_schema = "pkcs11:";
237	const char *pkcs11_uri_prepend = "";
238
239	if (!evpp)
240		return -EINVAL;
241
242	engine_id = ENGINE_get_id(engine);
243
244	if (engine_id && !strcmp(engine_id, "pkcs11")) {
245		if (!keydir && !name) {
246			fprintf(stderr, "Please use 'keydir' with PKCS11\n");
247			return -EINVAL;
248		}
249		if (keydir) {
250			// Check for legacy keydir spec and prepend
251			if (strncmp(pkcs11_schema, keydir, strlen(pkcs11_schema))) {
252				pkcs11_uri_prepend = pkcs11_schema;
253				fprintf(stderr, "WARNING: Legacy URI specified. Please add '%s'.\n", pkcs11_schema);
254			}
255
256			if (strstr(keydir, "object="))
257				snprintf(key_id, sizeof(key_id),
258					 "%s%s;type=private",
259					 pkcs11_uri_prepend, keydir);
260			else
261				snprintf(key_id, sizeof(key_id),
262					 "%s%s;object=%s;type=private",
263					 pkcs11_uri_prepend, keydir, name);
264		} else {
265			snprintf(key_id, sizeof(key_id),
266				 "pkcs11:object=%s;type=private",
267				 name);
268		}
269	} else if (engine_id) {
270		if (keydir && name)
271			snprintf(key_id, sizeof(key_id),
272				 "%s%s",
273				 keydir, name);
274		else if (name)
275			snprintf(key_id, sizeof(key_id),
276				 "%s",
277				 name ? name : "");
278		else if (keyfile)
279			snprintf(key_id, sizeof(key_id), "%s", keyfile);
280		else
281			return -EINVAL;
282
283	} else {
284		fprintf(stderr, "Engine not supported\n");
285		return -ENOTSUP;
286	}
287
288	key = ENGINE_load_private_key(engine, key_id, NULL, NULL);
289	if (!key)
290		return rsa_err("Failure loading private key from engine");
291
292	*evpp = key;
293
294	return 0;
295}
296
297/**
298 * rsa_get_priv_key() - read a private key
299 *
300 * @keydir:	Directory containing the key (PEM file) or key prefix (engine)
301 * @name	Name of key
302 * @engine	Engine to use for signing
303 * @evpp	Returns EVP_PKEY object, or NULL on failure
304 * Return: 0 if ok, -ve on error (in which case *evpp will be set to NULL)
305 */
306static int rsa_get_priv_key(const char *keydir, const char *name,
307			    const char *keyfile, ENGINE *engine, EVP_PKEY **evpp)
308{
309	if (engine)
310		return rsa_engine_get_priv_key(keydir, name, keyfile, engine,
311					       evpp);
312	return rsa_pem_get_priv_key(keydir, name, keyfile, evpp);
313}
314
315static int rsa_init(void)
316{
317	int ret;
318
319	ret = OPENSSL_init_ssl(0, NULL);
320	if (!ret) {
321		fprintf(stderr, "Failure to init SSL library\n");
322		return -1;
323	}
324
325	return 0;
326}
327
328static int rsa_engine_init(const char *engine_id, ENGINE **pe)
329{
330	const char *key_pass;
331	ENGINE *e;
332	int ret;
333
334	ENGINE_load_builtin_engines();
335
336	e = ENGINE_by_id(engine_id);
337	if (!e) {
338		fprintf(stderr, "Engine '%s' isn't available\n", engine_id);
339		ERR_print_errors_fp(stderr);
340		return -1;
341	}
342
343	if (!ENGINE_init(e)) {
344		fprintf(stderr, "Couldn't initialize engine\n");
345		ret = -1;
346		goto err_engine_init;
347	}
348
349	if (!ENGINE_set_default_RSA(e)) {
350		fprintf(stderr, "Couldn't set engine as default for RSA\n");
351		ret = -1;
352		goto err_set_rsa;
353	}
354
355	key_pass = getenv("MKIMAGE_SIGN_PIN");
356	if (key_pass) {
357		if (!ENGINE_ctrl_cmd_string(e, "PIN", key_pass, 0)) {
358			fprintf(stderr, "Couldn't set PIN\n");
359			ret = -1;
360			goto err_set_pin;
361		}
362	}
363
364	*pe = e;
365
366	return 0;
367
368err_set_pin:
369err_set_rsa:
370	ENGINE_finish(e);
371err_engine_init:
372	ENGINE_free(e);
373	return ret;
374}
375
376static void rsa_engine_remove(ENGINE *e)
377{
378	if (e) {
379		ENGINE_finish(e);
380		ENGINE_free(e);
381	}
382}
383
384static int rsa_sign_with_key(EVP_PKEY *pkey, struct padding_algo *padding_algo,
385			     struct checksum_algo *checksum_algo,
386		const struct image_region region[], int region_count,
387		uint8_t **sigp, uint *sig_size)
388{
389	EVP_PKEY_CTX *ckey;
390	EVP_MD_CTX *context;
391	int ret = 0;
392	size_t size;
393	uint8_t *sig;
394	int i;
395
396	size = EVP_PKEY_size(pkey);
397	sig = malloc(size);
398	if (!sig) {
399		fprintf(stderr, "Out of memory for signature (%zu bytes)\n",
400			size);
401		ret = -ENOMEM;
402		goto err_alloc;
403	}
404
405	context = EVP_MD_CTX_new();
406	if (!context) {
407		ret = rsa_err("EVP context creation failed");
408		goto err_create;
409	}
410
411	ckey = EVP_PKEY_CTX_new(pkey, NULL);
412	if (!ckey) {
413		ret = rsa_err("EVP key context creation failed");
414		goto err_create;
415	}
416
417	if (EVP_DigestSignInit(context, &ckey,
418			       checksum_algo->calculate_sign(),
419			       NULL, pkey) <= 0) {
420		ret = rsa_err("Signer setup failed");
421		goto err_sign;
422	}
423
424	if (CONFIG_IS_ENABLED(FIT_RSASSA_PSS) && padding_algo &&
425	    !strcmp(padding_algo->name, "pss")) {
426		if (EVP_PKEY_CTX_set_rsa_padding(ckey,
427						 RSA_PKCS1_PSS_PADDING) <= 0) {
428			ret = rsa_err("Signer padding setup failed");
429			goto err_sign;
430		}
431	}
432
433	for (i = 0; i < region_count; i++) {
434		if (!EVP_DigestSignUpdate(context, region[i].data,
435					  region[i].size)) {
436			ret = rsa_err("Signing data failed");
437			goto err_sign;
438		}
439	}
440
441	if (!EVP_DigestSignFinal(context, sig, &size)) {
442		ret = rsa_err("Could not obtain signature");
443		goto err_sign;
444	}
445
446	EVP_MD_CTX_free(context);
447
448	debug("Got signature: %zu bytes, expected %d\n", size, EVP_PKEY_size(pkey));
449	*sigp = sig;
450	*sig_size = size;
451
452	return 0;
453
454err_sign:
455	EVP_MD_CTX_free(context);
456err_create:
457	free(sig);
458err_alloc:
459	return ret;
460}
461
462int rsa_sign(struct image_sign_info *info,
463	     const struct image_region region[], int region_count,
464	     uint8_t **sigp, uint *sig_len)
465{
466	EVP_PKEY *pkey = NULL;
467	ENGINE *e = NULL;
468	int ret;
469
470	ret = rsa_init();
471	if (ret)
472		return ret;
473
474	if (info->engine_id) {
475		ret = rsa_engine_init(info->engine_id, &e);
476		if (ret)
477			return ret;
478	}
479
480	ret = rsa_get_priv_key(info->keydir, info->keyname, info->keyfile,
481			       e, &pkey);
482	if (ret)
483		goto err_priv;
484	ret = rsa_sign_with_key(pkey, info->padding, info->checksum, region,
485				region_count, sigp, sig_len);
486	if (ret)
487		goto err_sign;
488
489	EVP_PKEY_free(pkey);
490	if (info->engine_id)
491		rsa_engine_remove(e);
492
493	return ret;
494
495err_sign:
496	EVP_PKEY_free(pkey);
497err_priv:
498	if (info->engine_id)
499		rsa_engine_remove(e);
500	return ret;
501}
502
503/*
504 * rsa_get_exponent(): - Get the public exponent from an RSA key
505 */
506static int rsa_get_exponent(RSA *key, uint64_t *e)
507{
508	int ret;
509	BIGNUM *bn_te;
510	const BIGNUM *key_e;
511	uint64_t te;
512
513	ret = -EINVAL;
514	bn_te = NULL;
515
516	if (!e)
517		goto cleanup;
518
519	RSA_get0_key(key, NULL, &key_e, NULL);
520	if (BN_num_bits(key_e) > 64)
521		goto cleanup;
522
523	*e = BN_get_word(key_e);
524
525	if (BN_num_bits(key_e) < 33) {
526		ret = 0;
527		goto cleanup;
528	}
529
530	bn_te = BN_dup(key_e);
531	if (!bn_te)
532		goto cleanup;
533
534	if (!BN_rshift(bn_te, bn_te, 32))
535		goto cleanup;
536
537	if (!BN_mask_bits(bn_te, 32))
538		goto cleanup;
539
540	te = BN_get_word(bn_te);
541	te <<= 32;
542	*e |= te;
543	ret = 0;
544
545cleanup:
546	if (bn_te)
547		BN_free(bn_te);
548
549	return ret;
550}
551
552/*
553 * rsa_get_params(): - Get the important parameters of an RSA public key
554 */
555int rsa_get_params(RSA *key, uint64_t *exponent, uint32_t *n0_invp,
556		   BIGNUM **modulusp, BIGNUM **r_squaredp)
557{
558	BIGNUM *big1, *big2, *big32, *big2_32;
559	BIGNUM *n, *r, *r_squared, *tmp;
560	const BIGNUM *key_n;
561	BN_CTX *bn_ctx = BN_CTX_new();
562	int ret = 0;
563
564	/* Initialize BIGNUMs */
565	big1 = BN_new();
566	big2 = BN_new();
567	big32 = BN_new();
568	r = BN_new();
569	r_squared = BN_new();
570	tmp = BN_new();
571	big2_32 = BN_new();
572	n = BN_new();
573	if (!big1 || !big2 || !big32 || !r || !r_squared || !tmp || !big2_32 ||
574	    !n) {
575		fprintf(stderr, "Out of memory (bignum)\n");
576		return -ENOMEM;
577	}
578
579	if (0 != rsa_get_exponent(key, exponent))
580		ret = -1;
581
582	RSA_get0_key(key, &key_n, NULL, NULL);
583	if (!BN_copy(n, key_n) || !BN_set_word(big1, 1L) ||
584	    !BN_set_word(big2, 2L) || !BN_set_word(big32, 32L))
585		ret = -1;
586
587	/* big2_32 = 2^32 */
588	if (!BN_exp(big2_32, big2, big32, bn_ctx))
589		ret = -1;
590
591	/* Calculate n0_inv = -1 / n[0] mod 2^32 */
592	if (!BN_mod_inverse(tmp, n, big2_32, bn_ctx) ||
593	    !BN_sub(tmp, big2_32, tmp))
594		ret = -1;
595	*n0_invp = BN_get_word(tmp);
596
597	/* Calculate R = 2^(# of key bits) */
598	if (!BN_set_word(tmp, BN_num_bits(n)) ||
599	    !BN_exp(r, big2, tmp, bn_ctx))
600		ret = -1;
601
602	/* Calculate r_squared = R^2 mod n */
603	if (!BN_copy(r_squared, r) ||
604	    !BN_mul(tmp, r_squared, r, bn_ctx) ||
605	    !BN_mod(r_squared, tmp, n, bn_ctx))
606		ret = -1;
607
608	*modulusp = n;
609	*r_squaredp = r_squared;
610
611	BN_free(big1);
612	BN_free(big2);
613	BN_free(big32);
614	BN_free(r);
615	BN_free(tmp);
616	BN_free(big2_32);
617	if (ret) {
618		fprintf(stderr, "Bignum operations failed\n");
619		return -ENOMEM;
620	}
621
622	return ret;
623}
624
625int rsa_add_verify_data(struct image_sign_info *info, void *keydest)
626{
627	BIGNUM *modulus, *r_squared;
628	uint64_t exponent;
629	uint32_t n0_inv;
630	int parent, node = -FDT_ERR_NOTFOUND;
631	char name[100];
632	int ret;
633	int bits;
634	RSA *rsa;
635	EVP_PKEY *pkey = NULL;
636	ENGINE *e = NULL;
637
638	debug("%s: Getting verification data\n", __func__);
639	if (info->engine_id) {
640		ret = rsa_engine_init(info->engine_id, &e);
641		if (ret)
642			return ret;
643	}
644	ret = rsa_get_pub_key(info->keydir, info->keyname, e, &pkey);
645	if (ret)
646		goto err_get_pub_key;
647
648	rsa = (RSA *)EVP_PKEY_get0_RSA(pkey);
649	ret = rsa_get_params(rsa, &exponent, &n0_inv, &modulus, &r_squared);
650	if (ret)
651		goto err_get_params;
652	bits = BN_num_bits(modulus);
653	parent = fdt_subnode_offset(keydest, 0, FIT_SIG_NODENAME);
654	if (parent == -FDT_ERR_NOTFOUND) {
655		parent = fdt_add_subnode(keydest, 0, FIT_SIG_NODENAME);
656		if (parent < 0) {
657			ret = parent;
658			if (ret != -FDT_ERR_NOSPACE) {
659				fprintf(stderr, "Couldn't create signature node: %s\n",
660					fdt_strerror(parent));
661			}
662		}
663	}
664	if (ret)
665		goto done;
666
667	/* Either create or overwrite the named key node */
668	snprintf(name, sizeof(name), "key-%s", info->keyname);
669	node = fdt_subnode_offset(keydest, parent, name);
670	if (node == -FDT_ERR_NOTFOUND) {
671		node = fdt_add_subnode(keydest, parent, name);
672		if (node < 0) {
673			ret = node;
674			if (ret != -FDT_ERR_NOSPACE) {
675				fprintf(stderr, "Could not create key subnode: %s\n",
676					fdt_strerror(node));
677			}
678		}
679	} else if (node < 0) {
680		fprintf(stderr, "Cannot select keys parent: %s\n",
681			fdt_strerror(node));
682		ret = node;
683	}
684
685	if (!ret) {
686		ret = fdt_setprop_string(keydest, node, FIT_KEY_HINT,
687					 info->keyname);
688	}
689	if (!ret)
690		ret = fdt_setprop_u32(keydest, node, "rsa,num-bits", bits);
691	if (!ret)
692		ret = fdt_setprop_u32(keydest, node, "rsa,n0-inverse", n0_inv);
693	if (!ret) {
694		ret = fdt_setprop_u64(keydest, node, "rsa,exponent", exponent);
695	}
696	if (!ret) {
697		ret = fdt_add_bignum(keydest, node, "rsa,modulus", modulus,
698				     bits);
699	}
700	if (!ret) {
701		ret = fdt_add_bignum(keydest, node, "rsa,r-squared", r_squared,
702				     bits);
703	}
704	if (!ret) {
705		ret = fdt_setprop_string(keydest, node, FIT_ALGO_PROP,
706					 info->name);
707	}
708	if (!ret && info->require_keys) {
709		ret = fdt_setprop_string(keydest, node, FIT_KEY_REQUIRED,
710					 info->require_keys);
711	}
712done:
713	BN_free(modulus);
714	BN_free(r_squared);
715	if (ret)
716		ret = ret == -FDT_ERR_NOSPACE ? -ENOSPC : -EIO;
717err_get_params:
718	EVP_PKEY_free(pkey);
719err_get_pub_key:
720	if (info->engine_id)
721		rsa_engine_remove(e);
722
723	if (ret)
724		return ret;
725
726	return node;
727}
728