rsa-sign.c 10 KB

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