rsa-sign.c 10 KB

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