rand_cpu_arm64.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * Copyright 2021 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License 2.0 (the "License"). You may not use
  5. * this file except in compliance with the License. You can obtain a copy
  6. * in the file LICENSE in the source distribution or at
  7. * https://www.openssl.org/source/license.html
  8. */
  9. #include "internal/cryptlib.h"
  10. #include <openssl/opensslconf.h>
  11. #include "crypto/rand_pool.h"
  12. #include "prov/seeding.h"
  13. #ifdef OPENSSL_RAND_SEED_RDCPU
  14. #include "crypto/arm_arch.h"
  15. size_t OPENSSL_rndrrs_bytes(unsigned char *buf, size_t len);
  16. static size_t get_hardware_random_value(unsigned char *buf, size_t len);
  17. /*
  18. * Acquire entropy using Arm-specific cpu instructions
  19. *
  20. * Uses the RNDRRS instruction. RNDR is never needed since
  21. * RNDRRS will always be available if RNDR is an available
  22. * instruction.
  23. *
  24. * Returns the total entropy count, if it exceeds the requested
  25. * entropy count. Otherwise, returns an entropy count of 0.
  26. */
  27. size_t ossl_prov_acquire_entropy_from_cpu(RAND_POOL *pool)
  28. {
  29. size_t bytes_needed;
  30. unsigned char *buffer;
  31. bytes_needed = ossl_rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
  32. if (bytes_needed > 0) {
  33. buffer = ossl_rand_pool_add_begin(pool, bytes_needed);
  34. if (buffer != NULL) {
  35. if (get_hardware_random_value(buffer, bytes_needed) == bytes_needed)
  36. ossl_rand_pool_add_end(pool, bytes_needed, 8 * bytes_needed);
  37. else
  38. ossl_rand_pool_add_end(pool, 0, 0);
  39. }
  40. }
  41. return ossl_rand_pool_entropy_available(pool);
  42. }
  43. static size_t get_hardware_random_value(unsigned char *buf, size_t len)
  44. {
  45. /* Always use RNDRRS or nothing */
  46. if (OPENSSL_armcap_P & ARMV8_RNG) {
  47. if (OPENSSL_rndrrs_bytes(buf, len) != len)
  48. return 0;
  49. } else {
  50. return 0;
  51. }
  52. return len;
  53. }
  54. #else
  55. NON_EMPTY_TRANSLATION_UNIT
  56. #endif /* OPENSSL_RAND_SEED_RDCPU */