rsa-sign.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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. ret = -EINVAL;
  70. goto err_rsa;
  71. }
  72. fclose(f);
  73. EVP_PKEY_free(key);
  74. X509_free(cert);
  75. *rsap = rsa;
  76. return 0;
  77. err_rsa:
  78. EVP_PKEY_free(key);
  79. err_pubkey:
  80. X509_free(cert);
  81. err_cert:
  82. fclose(f);
  83. return ret;
  84. }
  85. /**
  86. * rsa_get_priv_key() - read a private key from a .key file
  87. *
  88. * @keydir: Directory containins the key
  89. * @name Name of key file (will have a .key extension)
  90. * @rsap Returns RSA object, or NULL on failure
  91. * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
  92. */
  93. static int rsa_get_priv_key(const char *keydir, const char *name, RSA **rsap)
  94. {
  95. char path[1024];
  96. RSA *rsa;
  97. FILE *f;
  98. *rsap = NULL;
  99. snprintf(path, sizeof(path), "%s/%s.key", keydir, name);
  100. f = fopen(path, "r");
  101. if (!f) {
  102. fprintf(stderr, "Couldn't open RSA private key: '%s': %s\n",
  103. path, strerror(errno));
  104. return -ENOENT;
  105. }
  106. rsa = PEM_read_RSAPrivateKey(f, 0, NULL, path);
  107. if (!rsa) {
  108. rsa_err("Failure reading private key");
  109. fclose(f);
  110. return -EPROTO;
  111. }
  112. fclose(f);
  113. *rsap = rsa;
  114. return 0;
  115. }
  116. static int rsa_init(void)
  117. {
  118. int ret;
  119. ret = SSL_library_init();
  120. if (!ret) {
  121. fprintf(stderr, "Failure to init SSL library\n");
  122. return -1;
  123. }
  124. SSL_load_error_strings();
  125. OpenSSL_add_all_algorithms();
  126. OpenSSL_add_all_digests();
  127. OpenSSL_add_all_ciphers();
  128. return 0;
  129. }
  130. static void rsa_remove(void)
  131. {
  132. CRYPTO_cleanup_all_ex_data();
  133. ERR_free_strings();
  134. #ifdef HAVE_ERR_REMOVE_THREAD_STATE
  135. ERR_remove_thread_state(NULL);
  136. #else
  137. ERR_remove_state(0);
  138. #endif
  139. EVP_cleanup();
  140. }
  141. static int rsa_sign_with_key(RSA *rsa, struct checksum_algo *checksum_algo,
  142. const struct image_region region[], int region_count,
  143. uint8_t **sigp, uint *sig_size)
  144. {
  145. EVP_PKEY *key;
  146. EVP_MD_CTX *context;
  147. int size, ret = 0;
  148. uint8_t *sig;
  149. int i;
  150. key = EVP_PKEY_new();
  151. if (!key)
  152. return rsa_err("EVP_PKEY object creation failed");
  153. if (!EVP_PKEY_set1_RSA(key, rsa)) {
  154. ret = rsa_err("EVP key setup failed");
  155. goto err_set;
  156. }
  157. size = EVP_PKEY_size(key);
  158. sig = malloc(size);
  159. if (!sig) {
  160. fprintf(stderr, "Out of memory for signature (%d bytes)\n",
  161. size);
  162. ret = -ENOMEM;
  163. goto err_alloc;
  164. }
  165. context = EVP_MD_CTX_create();
  166. if (!context) {
  167. ret = rsa_err("EVP context creation failed");
  168. goto err_create;
  169. }
  170. EVP_MD_CTX_init(context);
  171. if (!EVP_SignInit(context, checksum_algo->calculate_sign())) {
  172. ret = rsa_err("Signer setup failed");
  173. goto err_sign;
  174. }
  175. for (i = 0; i < region_count; i++) {
  176. if (!EVP_SignUpdate(context, region[i].data, region[i].size)) {
  177. ret = rsa_err("Signing data failed");
  178. goto err_sign;
  179. }
  180. }
  181. if (!EVP_SignFinal(context, sig, sig_size, key)) {
  182. ret = rsa_err("Could not obtain signature");
  183. goto err_sign;
  184. }
  185. EVP_MD_CTX_cleanup(context);
  186. EVP_MD_CTX_destroy(context);
  187. EVP_PKEY_free(key);
  188. debug("Got signature: %d bytes, expected %d\n", *sig_size, size);
  189. *sigp = sig;
  190. *sig_size = size;
  191. return 0;
  192. err_sign:
  193. EVP_MD_CTX_destroy(context);
  194. err_create:
  195. free(sig);
  196. err_alloc:
  197. err_set:
  198. EVP_PKEY_free(key);
  199. return ret;
  200. }
  201. int rsa_sign(struct image_sign_info *info,
  202. const struct image_region region[], int region_count,
  203. uint8_t **sigp, uint *sig_len)
  204. {
  205. RSA *rsa;
  206. int ret;
  207. ret = rsa_init();
  208. if (ret)
  209. return ret;
  210. ret = rsa_get_priv_key(info->keydir, info->keyname, &rsa);
  211. if (ret)
  212. goto err_priv;
  213. ret = rsa_sign_with_key(rsa, info->checksum, region,
  214. region_count, sigp, sig_len);
  215. if (ret)
  216. goto err_sign;
  217. RSA_free(rsa);
  218. rsa_remove();
  219. return ret;
  220. err_sign:
  221. RSA_free(rsa);
  222. err_priv:
  223. rsa_remove();
  224. return ret;
  225. }
  226. /*
  227. * rsa_get_exponent(): - Get the public exponent from an RSA key
  228. */
  229. static int rsa_get_exponent(RSA *key, uint64_t *e)
  230. {
  231. int ret;
  232. BIGNUM *bn_te;
  233. uint64_t te;
  234. ret = -EINVAL;
  235. bn_te = NULL;
  236. if (!e)
  237. goto cleanup;
  238. if (BN_num_bits(key->e) > 64)
  239. goto cleanup;
  240. *e = BN_get_word(key->e);
  241. if (BN_num_bits(key->e) < 33) {
  242. ret = 0;
  243. goto cleanup;
  244. }
  245. bn_te = BN_dup(key->e);
  246. if (!bn_te)
  247. goto cleanup;
  248. if (!BN_rshift(bn_te, bn_te, 32))
  249. goto cleanup;
  250. if (!BN_mask_bits(bn_te, 32))
  251. goto cleanup;
  252. te = BN_get_word(bn_te);
  253. te <<= 32;
  254. *e |= te;
  255. ret = 0;
  256. cleanup:
  257. if (bn_te)
  258. BN_free(bn_te);
  259. return ret;
  260. }
  261. /*
  262. * rsa_get_params(): - Get the important parameters of an RSA public key
  263. */
  264. int rsa_get_params(RSA *key, uint64_t *exponent, uint32_t *n0_invp,
  265. BIGNUM **modulusp, BIGNUM **r_squaredp)
  266. {
  267. BIGNUM *big1, *big2, *big32, *big2_32;
  268. BIGNUM *n, *r, *r_squared, *tmp;
  269. BN_CTX *bn_ctx = BN_CTX_new();
  270. int ret = 0;
  271. /* Initialize BIGNUMs */
  272. big1 = BN_new();
  273. big2 = BN_new();
  274. big32 = BN_new();
  275. r = BN_new();
  276. r_squared = BN_new();
  277. tmp = BN_new();
  278. big2_32 = BN_new();
  279. n = BN_new();
  280. if (!big1 || !big2 || !big32 || !r || !r_squared || !tmp || !big2_32 ||
  281. !n) {
  282. fprintf(stderr, "Out of memory (bignum)\n");
  283. return -ENOMEM;
  284. }
  285. if (0 != rsa_get_exponent(key, exponent))
  286. ret = -1;
  287. if (!BN_copy(n, key->n) || !BN_set_word(big1, 1L) ||
  288. !BN_set_word(big2, 2L) || !BN_set_word(big32, 32L))
  289. ret = -1;
  290. /* big2_32 = 2^32 */
  291. if (!BN_exp(big2_32, big2, big32, bn_ctx))
  292. ret = -1;
  293. /* Calculate n0_inv = -1 / n[0] mod 2^32 */
  294. if (!BN_mod_inverse(tmp, n, big2_32, bn_ctx) ||
  295. !BN_sub(tmp, big2_32, tmp))
  296. ret = -1;
  297. *n0_invp = BN_get_word(tmp);
  298. /* Calculate R = 2^(# of key bits) */
  299. if (!BN_set_word(tmp, BN_num_bits(n)) ||
  300. !BN_exp(r, big2, tmp, bn_ctx))
  301. ret = -1;
  302. /* Calculate r_squared = R^2 mod n */
  303. if (!BN_copy(r_squared, r) ||
  304. !BN_mul(tmp, r_squared, r, bn_ctx) ||
  305. !BN_mod(r_squared, tmp, n, bn_ctx))
  306. ret = -1;
  307. *modulusp = n;
  308. *r_squaredp = r_squared;
  309. BN_free(big1);
  310. BN_free(big2);
  311. BN_free(big32);
  312. BN_free(r);
  313. BN_free(tmp);
  314. BN_free(big2_32);
  315. if (ret) {
  316. fprintf(stderr, "Bignum operations failed\n");
  317. return -ENOMEM;
  318. }
  319. return ret;
  320. }
  321. static int fdt_add_bignum(void *blob, int noffset, const char *prop_name,
  322. BIGNUM *num, int num_bits)
  323. {
  324. int nwords = num_bits / 32;
  325. int size;
  326. uint32_t *buf, *ptr;
  327. BIGNUM *tmp, *big2, *big32, *big2_32;
  328. BN_CTX *ctx;
  329. int ret;
  330. tmp = BN_new();
  331. big2 = BN_new();
  332. big32 = BN_new();
  333. big2_32 = BN_new();
  334. if (!tmp || !big2 || !big32 || !big2_32) {
  335. fprintf(stderr, "Out of memory (bignum)\n");
  336. return -ENOMEM;
  337. }
  338. ctx = BN_CTX_new();
  339. if (!tmp) {
  340. fprintf(stderr, "Out of memory (bignum context)\n");
  341. return -ENOMEM;
  342. }
  343. BN_set_word(big2, 2L);
  344. BN_set_word(big32, 32L);
  345. BN_exp(big2_32, big2, big32, ctx); /* B = 2^32 */
  346. size = nwords * sizeof(uint32_t);
  347. buf = malloc(size);
  348. if (!buf) {
  349. fprintf(stderr, "Out of memory (%d bytes)\n", size);
  350. return -ENOMEM;
  351. }
  352. /* Write out modulus as big endian array of integers */
  353. for (ptr = buf + nwords - 1; ptr >= buf; ptr--) {
  354. BN_mod(tmp, num, big2_32, ctx); /* n = N mod B */
  355. *ptr = cpu_to_fdt32(BN_get_word(tmp));
  356. BN_rshift(num, num, 32); /* N = N/B */
  357. }
  358. /*
  359. * We try signing with successively increasing size values, so this
  360. * might fail several times
  361. */
  362. ret = fdt_setprop(blob, noffset, prop_name, buf, size);
  363. if (ret)
  364. return -FDT_ERR_NOSPACE;
  365. free(buf);
  366. BN_free(tmp);
  367. BN_free(big2);
  368. BN_free(big32);
  369. BN_free(big2_32);
  370. return ret;
  371. }
  372. int rsa_add_verify_data(struct image_sign_info *info, void *keydest)
  373. {
  374. BIGNUM *modulus, *r_squared;
  375. uint64_t exponent;
  376. uint32_t n0_inv;
  377. int parent, node;
  378. char name[100];
  379. int ret;
  380. int bits;
  381. RSA *rsa;
  382. debug("%s: Getting verification data\n", __func__);
  383. ret = rsa_get_pub_key(info->keydir, info->keyname, &rsa);
  384. if (ret)
  385. return ret;
  386. ret = rsa_get_params(rsa, &exponent, &n0_inv, &modulus, &r_squared);
  387. if (ret)
  388. return ret;
  389. bits = BN_num_bits(modulus);
  390. parent = fdt_subnode_offset(keydest, 0, FIT_SIG_NODENAME);
  391. if (parent == -FDT_ERR_NOTFOUND) {
  392. parent = fdt_add_subnode(keydest, 0, FIT_SIG_NODENAME);
  393. if (parent < 0) {
  394. ret = parent;
  395. if (ret != -FDT_ERR_NOSPACE) {
  396. fprintf(stderr, "Couldn't create signature node: %s\n",
  397. fdt_strerror(parent));
  398. }
  399. }
  400. }
  401. if (ret)
  402. goto done;
  403. /* Either create or overwrite the named key node */
  404. snprintf(name, sizeof(name), "key-%s", info->keyname);
  405. node = fdt_subnode_offset(keydest, parent, name);
  406. if (node == -FDT_ERR_NOTFOUND) {
  407. node = fdt_add_subnode(keydest, parent, name);
  408. if (node < 0) {
  409. ret = node;
  410. if (ret != -FDT_ERR_NOSPACE) {
  411. fprintf(stderr, "Could not create key subnode: %s\n",
  412. fdt_strerror(node));
  413. }
  414. }
  415. } else if (node < 0) {
  416. fprintf(stderr, "Cannot select keys parent: %s\n",
  417. fdt_strerror(node));
  418. ret = node;
  419. }
  420. if (!ret) {
  421. ret = fdt_setprop_string(keydest, node, "key-name-hint",
  422. info->keyname);
  423. }
  424. if (!ret)
  425. ret = fdt_setprop_u32(keydest, node, "rsa,num-bits", bits);
  426. if (!ret)
  427. ret = fdt_setprop_u32(keydest, node, "rsa,n0-inverse", n0_inv);
  428. if (!ret) {
  429. ret = fdt_setprop_u64(keydest, node, "rsa,exponent", exponent);
  430. }
  431. if (!ret) {
  432. ret = fdt_add_bignum(keydest, node, "rsa,modulus", modulus,
  433. bits);
  434. }
  435. if (!ret) {
  436. ret = fdt_add_bignum(keydest, node, "rsa,r-squared", r_squared,
  437. bits);
  438. }
  439. if (!ret) {
  440. ret = fdt_setprop_string(keydest, node, FIT_ALGO_PROP,
  441. info->name);
  442. }
  443. if (!ret && info->require_keys) {
  444. ret = fdt_setprop_string(keydest, node, "required",
  445. info->require_keys);
  446. }
  447. done:
  448. BN_free(modulus);
  449. BN_free(r_squared);
  450. if (ret)
  451. return ret == -FDT_ERR_NOSPACE ? -ENOSPC : -EIO;
  452. return 0;
  453. }