rsa-sign.c 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. /*
  2. * Copyright (c) 2013, Google Inc.
  3. *
  4. * SPDX-License-Identifier: GPL-2.0+
  5. */
  6. #include "mkimage.h"
  7. #include <stdio.h>
  8. #include <string.h>
  9. #include <image.h>
  10. #include <time.h>
  11. #include <openssl/rsa.h>
  12. #include <openssl/pem.h>
  13. #include <openssl/err.h>
  14. #include <openssl/ssl.h>
  15. #include <openssl/evp.h>
  16. #if OPENSSL_VERSION_NUMBER >= 0x10000000L
  17. #define HAVE_ERR_REMOVE_THREAD_STATE
  18. #endif
  19. static int rsa_err(const char *msg)
  20. {
  21. unsigned long sslErr = ERR_get_error();
  22. fprintf(stderr, "%s", msg);
  23. fprintf(stderr, ": %s\n",
  24. ERR_error_string(sslErr, 0));
  25. return -1;
  26. }
  27. /**
  28. * rsa_get_pub_key() - read a public key from a .crt file
  29. *
  30. * @keydir: Directory containins the key
  31. * @name Name of key file (will have a .crt extension)
  32. * @rsap Returns RSA object, or NULL on failure
  33. * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
  34. */
  35. static int rsa_get_pub_key(const char *keydir, const char *name, RSA **rsap)
  36. {
  37. char path[1024];
  38. EVP_PKEY *key;
  39. X509 *cert;
  40. RSA *rsa;
  41. FILE *f;
  42. int ret;
  43. *rsap = NULL;
  44. snprintf(path, sizeof(path), "%s/%s.crt", keydir, name);
  45. f = fopen(path, "r");
  46. if (!f) {
  47. fprintf(stderr, "Couldn't open RSA certificate: '%s': %s\n",
  48. path, strerror(errno));
  49. return -EACCES;
  50. }
  51. /* Read the certificate */
  52. cert = NULL;
  53. if (!PEM_read_X509(f, &cert, NULL, NULL)) {
  54. rsa_err("Couldn't read certificate");
  55. ret = -EINVAL;
  56. goto err_cert;
  57. }
  58. /* Get the public key from the certificate. */
  59. key = X509_get_pubkey(cert);
  60. if (!key) {
  61. rsa_err("Couldn't read public key\n");
  62. ret = -EINVAL;
  63. goto err_pubkey;
  64. }
  65. /* Convert to a RSA_style key. */
  66. rsa = EVP_PKEY_get1_RSA(key);
  67. if (!rsa) {
  68. rsa_err("Couldn't convert to a RSA style key");
  69. goto err_rsa;
  70. }
  71. fclose(f);
  72. EVP_PKEY_free(key);
  73. X509_free(cert);
  74. *rsap = rsa;
  75. return 0;
  76. err_rsa:
  77. EVP_PKEY_free(key);
  78. err_pubkey:
  79. X509_free(cert);
  80. err_cert:
  81. fclose(f);
  82. return ret;
  83. }
  84. /**
  85. * rsa_get_priv_key() - read a private key from a .key file
  86. *
  87. * @keydir: Directory containins the key
  88. * @name Name of key file (will have a .key extension)
  89. * @rsap Returns RSA object, or NULL on failure
  90. * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
  91. */
  92. static int rsa_get_priv_key(const char *keydir, const char *name, RSA **rsap)
  93. {
  94. char path[1024];
  95. RSA *rsa;
  96. FILE *f;
  97. *rsap = NULL;
  98. snprintf(path, sizeof(path), "%s/%s.key", keydir, name);
  99. f = fopen(path, "r");
  100. if (!f) {
  101. fprintf(stderr, "Couldn't open RSA private key: '%s': %s\n",
  102. path, strerror(errno));
  103. return -ENOENT;
  104. }
  105. rsa = PEM_read_RSAPrivateKey(f, 0, NULL, path);
  106. if (!rsa) {
  107. rsa_err("Failure reading private key");
  108. fclose(f);
  109. return -EPROTO;
  110. }
  111. fclose(f);
  112. *rsap = rsa;
  113. return 0;
  114. }
  115. static int rsa_init(void)
  116. {
  117. int ret;
  118. ret = SSL_library_init();
  119. if (!ret) {
  120. fprintf(stderr, "Failure to init SSL library\n");
  121. return -1;
  122. }
  123. SSL_load_error_strings();
  124. OpenSSL_add_all_algorithms();
  125. OpenSSL_add_all_digests();
  126. OpenSSL_add_all_ciphers();
  127. return 0;
  128. }
  129. static void rsa_remove(void)
  130. {
  131. CRYPTO_cleanup_all_ex_data();
  132. ERR_free_strings();
  133. #ifdef HAVE_ERR_REMOVE_THREAD_STATE
  134. ERR_remove_thread_state(NULL);
  135. #else
  136. ERR_remove_state(0);
  137. #endif
  138. EVP_cleanup();
  139. }
  140. static int rsa_sign_with_key(RSA *rsa, const struct image_region region[],
  141. int region_count, uint8_t **sigp, uint *sig_size)
  142. {
  143. EVP_PKEY *key;
  144. EVP_MD_CTX *context;
  145. int size, ret = 0;
  146. uint8_t *sig;
  147. int i;
  148. key = EVP_PKEY_new();
  149. if (!key)
  150. return rsa_err("EVP_PKEY object creation failed");
  151. if (!EVP_PKEY_set1_RSA(key, rsa)) {
  152. ret = rsa_err("EVP key setup failed");
  153. goto err_set;
  154. }
  155. size = EVP_PKEY_size(key);
  156. sig = malloc(size);
  157. if (!sig) {
  158. fprintf(stderr, "Out of memory for signature (%d bytes)\n",
  159. size);
  160. ret = -ENOMEM;
  161. goto err_alloc;
  162. }
  163. context = EVP_MD_CTX_create();
  164. if (!context) {
  165. ret = rsa_err("EVP context creation failed");
  166. goto err_create;
  167. }
  168. EVP_MD_CTX_init(context);
  169. if (!EVP_SignInit(context, EVP_sha1())) {
  170. ret = rsa_err("Signer setup failed");
  171. goto err_sign;
  172. }
  173. for (i = 0; i < region_count; i++) {
  174. if (!EVP_SignUpdate(context, region[i].data, region[i].size)) {
  175. ret = rsa_err("Signing data failed");
  176. goto err_sign;
  177. }
  178. }
  179. if (!EVP_SignFinal(context, sig, sig_size, key)) {
  180. ret = rsa_err("Could not obtain signature");
  181. goto err_sign;
  182. }
  183. EVP_MD_CTX_cleanup(context);
  184. EVP_MD_CTX_destroy(context);
  185. EVP_PKEY_free(key);
  186. debug("Got signature: %d bytes, expected %d\n", *sig_size, size);
  187. *sigp = sig;
  188. *sig_size = size;
  189. return 0;
  190. err_sign:
  191. EVP_MD_CTX_destroy(context);
  192. err_create:
  193. free(sig);
  194. err_alloc:
  195. err_set:
  196. EVP_PKEY_free(key);
  197. return ret;
  198. }
  199. int rsa_sign(struct image_sign_info *info,
  200. const struct image_region region[], int region_count,
  201. uint8_t **sigp, uint *sig_len)
  202. {
  203. RSA *rsa;
  204. int ret;
  205. ret = rsa_init();
  206. if (ret)
  207. return ret;
  208. ret = rsa_get_priv_key(info->keydir, info->keyname, &rsa);
  209. if (ret)
  210. goto err_priv;
  211. ret = rsa_sign_with_key(rsa, region, region_count, sigp, sig_len);
  212. if (ret)
  213. goto err_sign;
  214. RSA_free(rsa);
  215. rsa_remove();
  216. return ret;
  217. err_sign:
  218. RSA_free(rsa);
  219. err_priv:
  220. rsa_remove();
  221. return ret;
  222. }
  223. /*
  224. * rsa_get_params(): - Get the important parameters of an RSA public key
  225. */
  226. int rsa_get_params(RSA *key, uint32_t *n0_invp, BIGNUM **modulusp,
  227. BIGNUM **r_squaredp)
  228. {
  229. BIGNUM *big1, *big2, *big32, *big2_32;
  230. BIGNUM *n, *r, *r_squared, *tmp;
  231. BN_CTX *bn_ctx = BN_CTX_new();
  232. int ret = 0;
  233. /* Initialize BIGNUMs */
  234. big1 = BN_new();
  235. big2 = BN_new();
  236. big32 = BN_new();
  237. r = BN_new();
  238. r_squared = BN_new();
  239. tmp = BN_new();
  240. big2_32 = BN_new();
  241. n = BN_new();
  242. if (!big1 || !big2 || !big32 || !r || !r_squared || !tmp || !big2_32 ||
  243. !n) {
  244. fprintf(stderr, "Out of memory (bignum)\n");
  245. return -ENOMEM;
  246. }
  247. if (!BN_copy(n, key->n) || !BN_set_word(big1, 1L) ||
  248. !BN_set_word(big2, 2L) || !BN_set_word(big32, 32L))
  249. ret = -1;
  250. /* big2_32 = 2^32 */
  251. if (!BN_exp(big2_32, big2, big32, bn_ctx))
  252. ret = -1;
  253. /* Calculate n0_inv = -1 / n[0] mod 2^32 */
  254. if (!BN_mod_inverse(tmp, n, big2_32, bn_ctx) ||
  255. !BN_sub(tmp, big2_32, tmp))
  256. ret = -1;
  257. *n0_invp = BN_get_word(tmp);
  258. /* Calculate R = 2^(# of key bits) */
  259. if (!BN_set_word(tmp, BN_num_bits(n)) ||
  260. !BN_exp(r, big2, tmp, bn_ctx))
  261. ret = -1;
  262. /* Calculate r_squared = R^2 mod n */
  263. if (!BN_copy(r_squared, r) ||
  264. !BN_mul(tmp, r_squared, r, bn_ctx) ||
  265. !BN_mod(r_squared, tmp, n, bn_ctx))
  266. ret = -1;
  267. *modulusp = n;
  268. *r_squaredp = r_squared;
  269. BN_free(big1);
  270. BN_free(big2);
  271. BN_free(big32);
  272. BN_free(r);
  273. BN_free(tmp);
  274. BN_free(big2_32);
  275. if (ret) {
  276. fprintf(stderr, "Bignum operations failed\n");
  277. return -ENOMEM;
  278. }
  279. return ret;
  280. }
  281. static int fdt_add_bignum(void *blob, int noffset, const char *prop_name,
  282. BIGNUM *num, int num_bits)
  283. {
  284. int nwords = num_bits / 32;
  285. int size;
  286. uint32_t *buf, *ptr;
  287. BIGNUM *tmp, *big2, *big32, *big2_32;
  288. BN_CTX *ctx;
  289. int ret;
  290. tmp = BN_new();
  291. big2 = BN_new();
  292. big32 = BN_new();
  293. big2_32 = BN_new();
  294. if (!tmp || !big2 || !big32 || !big2_32) {
  295. fprintf(stderr, "Out of memory (bignum)\n");
  296. return -ENOMEM;
  297. }
  298. ctx = BN_CTX_new();
  299. if (!tmp) {
  300. fprintf(stderr, "Out of memory (bignum context)\n");
  301. return -ENOMEM;
  302. }
  303. BN_set_word(big2, 2L);
  304. BN_set_word(big32, 32L);
  305. BN_exp(big2_32, big2, big32, ctx); /* B = 2^32 */
  306. size = nwords * sizeof(uint32_t);
  307. buf = malloc(size);
  308. if (!buf) {
  309. fprintf(stderr, "Out of memory (%d bytes)\n", size);
  310. return -ENOMEM;
  311. }
  312. /* Write out modulus as big endian array of integers */
  313. for (ptr = buf + nwords - 1; ptr >= buf; ptr--) {
  314. BN_mod(tmp, num, big2_32, ctx); /* n = N mod B */
  315. *ptr = cpu_to_fdt32(BN_get_word(tmp));
  316. BN_rshift(num, num, 32); /* N = N/B */
  317. }
  318. ret = fdt_setprop(blob, noffset, prop_name, buf, size);
  319. if (ret) {
  320. fprintf(stderr, "Failed to write public key to FIT\n");
  321. return -ENOSPC;
  322. }
  323. free(buf);
  324. BN_free(tmp);
  325. BN_free(big2);
  326. BN_free(big32);
  327. BN_free(big2_32);
  328. return ret;
  329. }
  330. int rsa_add_verify_data(struct image_sign_info *info, void *keydest)
  331. {
  332. BIGNUM *modulus, *r_squared;
  333. uint32_t n0_inv;
  334. int parent, node;
  335. char name[100];
  336. int ret;
  337. int bits;
  338. RSA *rsa;
  339. debug("%s: Getting verification data\n", __func__);
  340. ret = rsa_get_pub_key(info->keydir, info->keyname, &rsa);
  341. if (ret)
  342. return ret;
  343. ret = rsa_get_params(rsa, &n0_inv, &modulus, &r_squared);
  344. if (ret)
  345. return ret;
  346. bits = BN_num_bits(modulus);
  347. parent = fdt_subnode_offset(keydest, 0, FIT_SIG_NODENAME);
  348. if (parent == -FDT_ERR_NOTFOUND) {
  349. parent = fdt_add_subnode(keydest, 0, FIT_SIG_NODENAME);
  350. if (parent < 0) {
  351. fprintf(stderr, "Couldn't create signature node: %s\n",
  352. fdt_strerror(parent));
  353. return -EINVAL;
  354. }
  355. }
  356. /* Either create or overwrite the named key node */
  357. snprintf(name, sizeof(name), "key-%s", info->keyname);
  358. node = fdt_subnode_offset(keydest, parent, name);
  359. if (node == -FDT_ERR_NOTFOUND) {
  360. node = fdt_add_subnode(keydest, parent, name);
  361. if (node < 0) {
  362. fprintf(stderr, "Could not create key subnode: %s\n",
  363. fdt_strerror(node));
  364. return -EINVAL;
  365. }
  366. } else if (node < 0) {
  367. fprintf(stderr, "Cannot select keys parent: %s\n",
  368. fdt_strerror(node));
  369. return -ENOSPC;
  370. }
  371. ret = fdt_setprop_string(keydest, node, "key-name-hint",
  372. info->keyname);
  373. ret |= fdt_setprop_u32(keydest, node, "rsa,num-bits", bits);
  374. ret |= fdt_setprop_u32(keydest, node, "rsa,n0-inverse", n0_inv);
  375. ret |= fdt_add_bignum(keydest, node, "rsa,modulus", modulus, bits);
  376. ret |= fdt_add_bignum(keydest, node, "rsa,r-squared", r_squared, bits);
  377. ret |= fdt_setprop_string(keydest, node, FIT_ALGO_PROP,
  378. info->algo->name);
  379. if (info->require_keys) {
  380. fdt_setprop_string(keydest, node, "required",
  381. info->require_keys);
  382. }
  383. BN_free(modulus);
  384. BN_free(r_squared);
  385. if (ret)
  386. return -EIO;
  387. return 0;
  388. }