rand_cpu_x86.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * Copyright 1995-2020 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 "prov/rand_pool.h"
  12. #include "prov/seeding.h"
  13. #ifdef OPENSSL_RAND_SEED_RDCPU
  14. size_t OPENSSL_ia32_rdseed_bytes(unsigned char *buf, size_t len);
  15. size_t OPENSSL_ia32_rdrand_bytes(unsigned char *buf, size_t len);
  16. /*
  17. * Acquire entropy using Intel-specific cpu instructions
  18. *
  19. * Uses the RDSEED instruction if available, otherwise uses
  20. * RDRAND if available.
  21. *
  22. * For the differences between RDSEED and RDRAND, and why RDSEED
  23. * is the preferred choice, see https://goo.gl/oK3KcN
  24. *
  25. * Returns the total entropy count, if it exceeds the requested
  26. * entropy count. Otherwise, returns an entropy count of 0.
  27. */
  28. size_t prov_acquire_entropy_from_cpu(RAND_POOL *pool)
  29. {
  30. size_t bytes_needed;
  31. unsigned char *buffer;
  32. bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
  33. if (bytes_needed > 0) {
  34. buffer = rand_pool_add_begin(pool, bytes_needed);
  35. if (buffer != NULL) {
  36. /* Whichever comes first, use RDSEED, RDRAND or nothing */
  37. if ((OPENSSL_ia32cap_P[2] & (1 << 18)) != 0) {
  38. if (OPENSSL_ia32_rdseed_bytes(buffer, bytes_needed)
  39. == bytes_needed) {
  40. rand_pool_add_end(pool, bytes_needed, 8 * bytes_needed);
  41. }
  42. } else if ((OPENSSL_ia32cap_P[1] & (1 << (62 - 32))) != 0) {
  43. if (OPENSSL_ia32_rdrand_bytes(buffer, bytes_needed)
  44. == bytes_needed) {
  45. rand_pool_add_end(pool, bytes_needed, 8 * bytes_needed);
  46. }
  47. } else {
  48. rand_pool_add_end(pool, 0, 0);
  49. }
  50. }
  51. }
  52. return rand_pool_entropy_available(pool);
  53. }
  54. #else
  55. NON_EMPTY_TRANSLATION_UNIT
  56. #endif