fdt-libcrypto.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // SPDX-License-Identifier: GPL-2.0+
  2. /*
  3. * Copyright (c) 2020, Alexandru Gagniuc <mr.nuke.me@gmail.com>
  4. * Copyright (c) 2013, Google Inc.
  5. */
  6. #include <libfdt.h>
  7. #include <u-boot/fdt-libcrypto.h>
  8. int fdt_add_bignum(void *blob, int noffset, const char *prop_name,
  9. BIGNUM *num, int num_bits)
  10. {
  11. int nwords = num_bits / 32;
  12. int size;
  13. uint32_t *buf, *ptr;
  14. BIGNUM *tmp, *big2, *big32, *big2_32;
  15. BN_CTX *ctx;
  16. int ret;
  17. tmp = BN_new();
  18. big2 = BN_new();
  19. big32 = BN_new();
  20. big2_32 = BN_new();
  21. /*
  22. * Note: This code assumes that all of the above succeed, or all fail.
  23. * In practice memory allocations generally do not fail (unless the
  24. * process is killed), so it does not seem worth handling each of these
  25. * as a separate case. Technicaly this could leak memory on failure,
  26. * but a) it won't happen in practice, and b) it doesn't matter as we
  27. * will immediately exit with a failure code.
  28. */
  29. if (!tmp || !big2 || !big32 || !big2_32) {
  30. fprintf(stderr, "Out of memory (bignum)\n");
  31. return -ENOMEM;
  32. }
  33. ctx = BN_CTX_new();
  34. if (!ctx) {
  35. fprintf(stderr, "Out of memory (bignum context)\n");
  36. return -ENOMEM;
  37. }
  38. BN_set_word(big2, 2L);
  39. BN_set_word(big32, 32L);
  40. BN_exp(big2_32, big2, big32, ctx); /* B = 2^32 */
  41. size = nwords * sizeof(uint32_t);
  42. buf = malloc(size);
  43. if (!buf) {
  44. fprintf(stderr, "Out of memory (%d bytes)\n", size);
  45. return -ENOMEM;
  46. }
  47. /* Write out modulus as big endian array of integers */
  48. for (ptr = buf + nwords - 1; ptr >= buf; ptr--) {
  49. BN_mod(tmp, num, big2_32, ctx); /* n = N mod B */
  50. *ptr = cpu_to_fdt32(BN_get_word(tmp));
  51. BN_rshift(num, num, 32); /* N = N/B */
  52. }
  53. /*
  54. * We try signing with successively increasing size values, so this
  55. * might fail several times
  56. */
  57. ret = fdt_setprop(blob, noffset, prop_name, buf, size);
  58. free(buf);
  59. BN_free(tmp);
  60. BN_free(big2);
  61. BN_free(big32);
  62. BN_free(big2_32);
  63. return ret ? -FDT_ERR_NOSPACE : 0;
  64. }