rsa-sign.c 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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, struct checksum_algo *checksum_algo,
  141. const struct image_region region[], int region_count,
  142. uint8_t **sigp, uint *sig_size)
  143. {
  144. EVP_PKEY *key;
  145. EVP_MD_CTX *context;
  146. int size, ret = 0;
  147. uint8_t *sig;
  148. int i;
  149. key = EVP_PKEY_new();
  150. if (!key)
  151. return rsa_err("EVP_PKEY object creation failed");
  152. if (!EVP_PKEY_set1_RSA(key, rsa)) {
  153. ret = rsa_err("EVP key setup failed");
  154. goto err_set;
  155. }
  156. size = EVP_PKEY_size(key);
  157. sig = malloc(size);
  158. if (!sig) {
  159. fprintf(stderr, "Out of memory for signature (%d bytes)\n",
  160. size);
  161. ret = -ENOMEM;
  162. goto err_alloc;
  163. }
  164. context = EVP_MD_CTX_create();
  165. if (!context) {
  166. ret = rsa_err("EVP context creation failed");
  167. goto err_create;
  168. }
  169. EVP_MD_CTX_init(context);
  170. if (!EVP_SignInit(context, checksum_algo->calculate_sign())) {
  171. ret = rsa_err("Signer setup failed");
  172. goto err_sign;
  173. }
  174. for (i = 0; i < region_count; i++) {
  175. if (!EVP_SignUpdate(context, region[i].data, region[i].size)) {
  176. ret = rsa_err("Signing data failed");
  177. goto err_sign;
  178. }
  179. }
  180. if (!EVP_SignFinal(context, sig, sig_size, key)) {
  181. ret = rsa_err("Could not obtain signature");
  182. goto err_sign;
  183. }
  184. EVP_MD_CTX_cleanup(context);
  185. EVP_MD_CTX_destroy(context);
  186. EVP_PKEY_free(key);
  187. debug("Got signature: %d bytes, expected %d\n", *sig_size, size);
  188. *sigp = sig;
  189. *sig_size = size;
  190. return 0;
  191. err_sign:
  192. EVP_MD_CTX_destroy(context);
  193. err_create:
  194. free(sig);
  195. err_alloc:
  196. err_set:
  197. EVP_PKEY_free(key);
  198. return ret;
  199. }
  200. int rsa_sign(struct image_sign_info *info,
  201. const struct image_region region[], int region_count,
  202. uint8_t **sigp, uint *sig_len)
  203. {
  204. RSA *rsa;
  205. int ret;
  206. ret = rsa_init();
  207. if (ret)
  208. return ret;
  209. ret = rsa_get_priv_key(info->keydir, info->keyname, &rsa);
  210. if (ret)
  211. goto err_priv;
  212. ret = rsa_sign_with_key(rsa, info->algo->checksum, region,
  213. region_count, sigp, sig_len);
  214. if (ret)
  215. goto err_sign;
  216. RSA_free(rsa);
  217. rsa_remove();
  218. return ret;
  219. err_sign:
  220. RSA_free(rsa);
  221. err_priv:
  222. rsa_remove();
  223. return ret;
  224. }
  225. /*
  226. * rsa_get_params(): - Get the important parameters of an RSA public key
  227. */
  228. int rsa_get_params(RSA *key, uint32_t *n0_invp, BIGNUM **modulusp,
  229. BIGNUM **r_squaredp)
  230. {
  231. BIGNUM *big1, *big2, *big32, *big2_32;
  232. BIGNUM *n, *r, *r_squared, *tmp;
  233. BN_CTX *bn_ctx = BN_CTX_new();
  234. int ret = 0;
  235. /* Initialize BIGNUMs */
  236. big1 = BN_new();
  237. big2 = BN_new();
  238. big32 = BN_new();
  239. r = BN_new();
  240. r_squared = BN_new();
  241. tmp = BN_new();
  242. big2_32 = BN_new();
  243. n = BN_new();
  244. if (!big1 || !big2 || !big32 || !r || !r_squared || !tmp || !big2_32 ||
  245. !n) {
  246. fprintf(stderr, "Out of memory (bignum)\n");
  247. return -ENOMEM;
  248. }
  249. if (!BN_copy(n, key->n) || !BN_set_word(big1, 1L) ||
  250. !BN_set_word(big2, 2L) || !BN_set_word(big32, 32L))
  251. ret = -1;
  252. /* big2_32 = 2^32 */
  253. if (!BN_exp(big2_32, big2, big32, bn_ctx))
  254. ret = -1;
  255. /* Calculate n0_inv = -1 / n[0] mod 2^32 */
  256. if (!BN_mod_inverse(tmp, n, big2_32, bn_ctx) ||
  257. !BN_sub(tmp, big2_32, tmp))
  258. ret = -1;
  259. *n0_invp = BN_get_word(tmp);
  260. /* Calculate R = 2^(# of key bits) */
  261. if (!BN_set_word(tmp, BN_num_bits(n)) ||
  262. !BN_exp(r, big2, tmp, bn_ctx))
  263. ret = -1;
  264. /* Calculate r_squared = R^2 mod n */
  265. if (!BN_copy(r_squared, r) ||
  266. !BN_mul(tmp, r_squared, r, bn_ctx) ||
  267. !BN_mod(r_squared, tmp, n, bn_ctx))
  268. ret = -1;
  269. *modulusp = n;
  270. *r_squaredp = r_squared;
  271. BN_free(big1);
  272. BN_free(big2);
  273. BN_free(big32);
  274. BN_free(r);
  275. BN_free(tmp);
  276. BN_free(big2_32);
  277. if (ret) {
  278. fprintf(stderr, "Bignum operations failed\n");
  279. return -ENOMEM;
  280. }
  281. return ret;
  282. }
  283. static int fdt_add_bignum(void *blob, int noffset, const char *prop_name,
  284. BIGNUM *num, int num_bits)
  285. {
  286. int nwords = num_bits / 32;
  287. int size;
  288. uint32_t *buf, *ptr;
  289. BIGNUM *tmp, *big2, *big32, *big2_32;
  290. BN_CTX *ctx;
  291. int ret;
  292. tmp = BN_new();
  293. big2 = BN_new();
  294. big32 = BN_new();
  295. big2_32 = BN_new();
  296. if (!tmp || !big2 || !big32 || !big2_32) {
  297. fprintf(stderr, "Out of memory (bignum)\n");
  298. return -ENOMEM;
  299. }
  300. ctx = BN_CTX_new();
  301. if (!tmp) {
  302. fprintf(stderr, "Out of memory (bignum context)\n");
  303. return -ENOMEM;
  304. }
  305. BN_set_word(big2, 2L);
  306. BN_set_word(big32, 32L);
  307. BN_exp(big2_32, big2, big32, ctx); /* B = 2^32 */
  308. size = nwords * sizeof(uint32_t);
  309. buf = malloc(size);
  310. if (!buf) {
  311. fprintf(stderr, "Out of memory (%d bytes)\n", size);
  312. return -ENOMEM;
  313. }
  314. /* Write out modulus as big endian array of integers */
  315. for (ptr = buf + nwords - 1; ptr >= buf; ptr--) {
  316. BN_mod(tmp, num, big2_32, ctx); /* n = N mod B */
  317. *ptr = cpu_to_fdt32(BN_get_word(tmp));
  318. BN_rshift(num, num, 32); /* N = N/B */
  319. }
  320. ret = fdt_setprop(blob, noffset, prop_name, buf, size);
  321. if (ret) {
  322. fprintf(stderr, "Failed to write public key to FIT\n");
  323. return -ENOSPC;
  324. }
  325. free(buf);
  326. BN_free(tmp);
  327. BN_free(big2);
  328. BN_free(big32);
  329. BN_free(big2_32);
  330. return ret;
  331. }
  332. int rsa_add_verify_data(struct image_sign_info *info, void *keydest)
  333. {
  334. BIGNUM *modulus, *r_squared;
  335. uint32_t n0_inv;
  336. int parent, node;
  337. char name[100];
  338. int ret;
  339. int bits;
  340. RSA *rsa;
  341. debug("%s: Getting verification data\n", __func__);
  342. ret = rsa_get_pub_key(info->keydir, info->keyname, &rsa);
  343. if (ret)
  344. return ret;
  345. ret = rsa_get_params(rsa, &n0_inv, &modulus, &r_squared);
  346. if (ret)
  347. return ret;
  348. bits = BN_num_bits(modulus);
  349. parent = fdt_subnode_offset(keydest, 0, FIT_SIG_NODENAME);
  350. if (parent == -FDT_ERR_NOTFOUND) {
  351. parent = fdt_add_subnode(keydest, 0, FIT_SIG_NODENAME);
  352. if (parent < 0) {
  353. ret = parent;
  354. if (ret != -FDT_ERR_NOSPACE) {
  355. fprintf(stderr, "Couldn't create signature node: %s\n",
  356. fdt_strerror(parent));
  357. }
  358. }
  359. }
  360. if (ret)
  361. goto done;
  362. /* Either create or overwrite the named key node */
  363. snprintf(name, sizeof(name), "key-%s", info->keyname);
  364. node = fdt_subnode_offset(keydest, parent, name);
  365. if (node == -FDT_ERR_NOTFOUND) {
  366. node = fdt_add_subnode(keydest, parent, name);
  367. if (node < 0) {
  368. ret = node;
  369. if (ret != -FDT_ERR_NOSPACE) {
  370. fprintf(stderr, "Could not create key subnode: %s\n",
  371. fdt_strerror(node));
  372. }
  373. }
  374. } else if (node < 0) {
  375. fprintf(stderr, "Cannot select keys parent: %s\n",
  376. fdt_strerror(node));
  377. ret = node;
  378. }
  379. if (!ret) {
  380. ret = fdt_setprop_string(keydest, node, "key-name-hint",
  381. info->keyname);
  382. }
  383. if (!ret)
  384. ret = fdt_setprop_u32(keydest, node, "rsa,num-bits", bits);
  385. if (!ret)
  386. ret = fdt_setprop_u32(keydest, node, "rsa,n0-inverse", n0_inv);
  387. if (!ret) {
  388. ret = fdt_add_bignum(keydest, node, "rsa,modulus", modulus,
  389. bits);
  390. }
  391. if (!ret) {
  392. ret = fdt_add_bignum(keydest, node, "rsa,r-squared", r_squared,
  393. bits);
  394. }
  395. if (!ret) {
  396. ret = fdt_setprop_string(keydest, node, FIT_ALGO_PROP,
  397. info->algo->name);
  398. }
  399. if (info->require_keys) {
  400. ret = fdt_setprop_string(keydest, node, "required",
  401. info->require_keys);
  402. }
  403. done:
  404. BN_free(modulus);
  405. BN_free(r_squared);
  406. if (ret)
  407. return ret == -FDT_ERR_NOSPACE ? -ENOSPC : -EIO;
  408. return 0;
  409. }