rsa-sign.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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_exponent(): - Get the public exponent from an RSA key
  227. */
  228. static int rsa_get_exponent(RSA *key, uint64_t *e)
  229. {
  230. int ret;
  231. BIGNUM *bn_te;
  232. uint64_t te;
  233. ret = -EINVAL;
  234. bn_te = NULL;
  235. if (!e)
  236. goto cleanup;
  237. if (BN_num_bits(key->e) > 64)
  238. goto cleanup;
  239. *e = BN_get_word(key->e);
  240. if (BN_num_bits(key->e) < 33) {
  241. ret = 0;
  242. goto cleanup;
  243. }
  244. bn_te = BN_dup(key->e);
  245. if (!bn_te)
  246. goto cleanup;
  247. if (!BN_rshift(bn_te, bn_te, 32))
  248. goto cleanup;
  249. if (!BN_mask_bits(bn_te, 32))
  250. goto cleanup;
  251. te = BN_get_word(bn_te);
  252. te <<= 32;
  253. *e |= te;
  254. ret = 0;
  255. cleanup:
  256. if (bn_te)
  257. BN_free(bn_te);
  258. return ret;
  259. }
  260. /*
  261. * rsa_get_params(): - Get the important parameters of an RSA public key
  262. */
  263. int rsa_get_params(RSA *key, uint64_t *exponent, uint32_t *n0_invp,
  264. BIGNUM **modulusp, BIGNUM **r_squaredp)
  265. {
  266. BIGNUM *big1, *big2, *big32, *big2_32;
  267. BIGNUM *n, *r, *r_squared, *tmp;
  268. BN_CTX *bn_ctx = BN_CTX_new();
  269. int ret = 0;
  270. /* Initialize BIGNUMs */
  271. big1 = BN_new();
  272. big2 = BN_new();
  273. big32 = BN_new();
  274. r = BN_new();
  275. r_squared = BN_new();
  276. tmp = BN_new();
  277. big2_32 = BN_new();
  278. n = BN_new();
  279. if (!big1 || !big2 || !big32 || !r || !r_squared || !tmp || !big2_32 ||
  280. !n) {
  281. fprintf(stderr, "Out of memory (bignum)\n");
  282. return -ENOMEM;
  283. }
  284. if (0 != rsa_get_exponent(key, exponent))
  285. ret = -1;
  286. if (!BN_copy(n, key->n) || !BN_set_word(big1, 1L) ||
  287. !BN_set_word(big2, 2L) || !BN_set_word(big32, 32L))
  288. ret = -1;
  289. /* big2_32 = 2^32 */
  290. if (!BN_exp(big2_32, big2, big32, bn_ctx))
  291. ret = -1;
  292. /* Calculate n0_inv = -1 / n[0] mod 2^32 */
  293. if (!BN_mod_inverse(tmp, n, big2_32, bn_ctx) ||
  294. !BN_sub(tmp, big2_32, tmp))
  295. ret = -1;
  296. *n0_invp = BN_get_word(tmp);
  297. /* Calculate R = 2^(# of key bits) */
  298. if (!BN_set_word(tmp, BN_num_bits(n)) ||
  299. !BN_exp(r, big2, tmp, bn_ctx))
  300. ret = -1;
  301. /* Calculate r_squared = R^2 mod n */
  302. if (!BN_copy(r_squared, r) ||
  303. !BN_mul(tmp, r_squared, r, bn_ctx) ||
  304. !BN_mod(r_squared, tmp, n, bn_ctx))
  305. ret = -1;
  306. *modulusp = n;
  307. *r_squaredp = r_squared;
  308. BN_free(big1);
  309. BN_free(big2);
  310. BN_free(big32);
  311. BN_free(r);
  312. BN_free(tmp);
  313. BN_free(big2_32);
  314. if (ret) {
  315. fprintf(stderr, "Bignum operations failed\n");
  316. return -ENOMEM;
  317. }
  318. return ret;
  319. }
  320. static int fdt_add_bignum(void *blob, int noffset, const char *prop_name,
  321. BIGNUM *num, int num_bits)
  322. {
  323. int nwords = num_bits / 32;
  324. int size;
  325. uint32_t *buf, *ptr;
  326. BIGNUM *tmp, *big2, *big32, *big2_32;
  327. BN_CTX *ctx;
  328. int ret;
  329. tmp = BN_new();
  330. big2 = BN_new();
  331. big32 = BN_new();
  332. big2_32 = BN_new();
  333. if (!tmp || !big2 || !big32 || !big2_32) {
  334. fprintf(stderr, "Out of memory (bignum)\n");
  335. return -ENOMEM;
  336. }
  337. ctx = BN_CTX_new();
  338. if (!tmp) {
  339. fprintf(stderr, "Out of memory (bignum context)\n");
  340. return -ENOMEM;
  341. }
  342. BN_set_word(big2, 2L);
  343. BN_set_word(big32, 32L);
  344. BN_exp(big2_32, big2, big32, ctx); /* B = 2^32 */
  345. size = nwords * sizeof(uint32_t);
  346. buf = malloc(size);
  347. if (!buf) {
  348. fprintf(stderr, "Out of memory (%d bytes)\n", size);
  349. return -ENOMEM;
  350. }
  351. /* Write out modulus as big endian array of integers */
  352. for (ptr = buf + nwords - 1; ptr >= buf; ptr--) {
  353. BN_mod(tmp, num, big2_32, ctx); /* n = N mod B */
  354. *ptr = cpu_to_fdt32(BN_get_word(tmp));
  355. BN_rshift(num, num, 32); /* N = N/B */
  356. }
  357. ret = fdt_setprop(blob, noffset, prop_name, buf, size);
  358. if (ret) {
  359. fprintf(stderr, "Failed to write public key to FIT\n");
  360. return -ENOSPC;
  361. }
  362. free(buf);
  363. BN_free(tmp);
  364. BN_free(big2);
  365. BN_free(big32);
  366. BN_free(big2_32);
  367. return ret;
  368. }
  369. int rsa_add_verify_data(struct image_sign_info *info, void *keydest)
  370. {
  371. BIGNUM *modulus, *r_squared;
  372. uint64_t exponent;
  373. uint32_t n0_inv;
  374. int parent, node;
  375. char name[100];
  376. int ret;
  377. int bits;
  378. RSA *rsa;
  379. debug("%s: Getting verification data\n", __func__);
  380. ret = rsa_get_pub_key(info->keydir, info->keyname, &rsa);
  381. if (ret)
  382. return ret;
  383. ret = rsa_get_params(rsa, &exponent, &n0_inv, &modulus, &r_squared);
  384. if (ret)
  385. return ret;
  386. bits = BN_num_bits(modulus);
  387. parent = fdt_subnode_offset(keydest, 0, FIT_SIG_NODENAME);
  388. if (parent == -FDT_ERR_NOTFOUND) {
  389. parent = fdt_add_subnode(keydest, 0, FIT_SIG_NODENAME);
  390. if (parent < 0) {
  391. ret = parent;
  392. if (ret != -FDT_ERR_NOSPACE) {
  393. fprintf(stderr, "Couldn't create signature node: %s\n",
  394. fdt_strerror(parent));
  395. }
  396. }
  397. }
  398. if (ret)
  399. goto done;
  400. /* Either create or overwrite the named key node */
  401. snprintf(name, sizeof(name), "key-%s", info->keyname);
  402. node = fdt_subnode_offset(keydest, parent, name);
  403. if (node == -FDT_ERR_NOTFOUND) {
  404. node = fdt_add_subnode(keydest, parent, name);
  405. if (node < 0) {
  406. ret = node;
  407. if (ret != -FDT_ERR_NOSPACE) {
  408. fprintf(stderr, "Could not create key subnode: %s\n",
  409. fdt_strerror(node));
  410. }
  411. }
  412. } else if (node < 0) {
  413. fprintf(stderr, "Cannot select keys parent: %s\n",
  414. fdt_strerror(node));
  415. ret = node;
  416. }
  417. if (!ret) {
  418. ret = fdt_setprop_string(keydest, node, "key-name-hint",
  419. info->keyname);
  420. }
  421. if (!ret)
  422. ret = fdt_setprop_u32(keydest, node, "rsa,num-bits", bits);
  423. if (!ret)
  424. ret = fdt_setprop_u32(keydest, node, "rsa,n0-inverse", n0_inv);
  425. if (!ret) {
  426. ret = fdt_setprop_u64(keydest, node, "rsa,exponent", exponent);
  427. }
  428. if (!ret) {
  429. ret = fdt_add_bignum(keydest, node, "rsa,modulus", modulus,
  430. bits);
  431. }
  432. if (!ret) {
  433. ret = fdt_add_bignum(keydest, node, "rsa,r-squared", r_squared,
  434. bits);
  435. }
  436. if (!ret) {
  437. ret = fdt_setprop_string(keydest, node, FIT_ALGO_PROP,
  438. info->algo->name);
  439. }
  440. if (info->require_keys) {
  441. ret = fdt_setprop_string(keydest, node, "required",
  442. info->require_keys);
  443. }
  444. done:
  445. BN_free(modulus);
  446. BN_free(r_squared);
  447. if (ret)
  448. return ret == -FDT_ERR_NOSPACE ? -ENOSPC : -EIO;
  449. return 0;
  450. }