2
0

eng_rdrand.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /*
  2. * Copyright 2011-2018 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the OpenSSL license (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 <openssl/opensslconf.h>
  10. #include <stdio.h>
  11. #include <string.h>
  12. #include "internal/engine.h"
  13. #include <openssl/rand.h>
  14. #include <openssl/err.h>
  15. #include <openssl/crypto.h>
  16. #if (defined(__i386) || defined(__i386__) || defined(_M_IX86) || \
  17. defined(__x86_64) || defined(__x86_64__) || \
  18. defined(_M_AMD64) || defined (_M_X64)) && defined(OPENSSL_CPUID_OBJ)
  19. size_t OPENSSL_ia32_rdrand_bytes(unsigned char *buf, size_t len);
  20. static int get_random_bytes(unsigned char *buf, int num)
  21. {
  22. if (num < 0) {
  23. return 0;
  24. }
  25. return (size_t)num == OPENSSL_ia32_rdrand_bytes(buf, (size_t)num);
  26. }
  27. static int random_status(void)
  28. {
  29. return 1;
  30. }
  31. static RAND_METHOD rdrand_meth = {
  32. NULL, /* seed */
  33. get_random_bytes,
  34. NULL, /* cleanup */
  35. NULL, /* add */
  36. get_random_bytes,
  37. random_status,
  38. };
  39. static int rdrand_init(ENGINE *e)
  40. {
  41. return 1;
  42. }
  43. static const char *engine_e_rdrand_id = "rdrand";
  44. static const char *engine_e_rdrand_name = "Intel RDRAND engine";
  45. static int bind_helper(ENGINE *e)
  46. {
  47. if (!ENGINE_set_id(e, engine_e_rdrand_id) ||
  48. !ENGINE_set_name(e, engine_e_rdrand_name) ||
  49. !ENGINE_set_flags(e, ENGINE_FLAGS_NO_REGISTER_ALL) ||
  50. !ENGINE_set_init_function(e, rdrand_init) ||
  51. !ENGINE_set_RAND(e, &rdrand_meth))
  52. return 0;
  53. return 1;
  54. }
  55. static ENGINE *ENGINE_rdrand(void)
  56. {
  57. ENGINE *ret = ENGINE_new();
  58. if (ret == NULL)
  59. return NULL;
  60. if (!bind_helper(ret)) {
  61. ENGINE_free(ret);
  62. return NULL;
  63. }
  64. return ret;
  65. }
  66. void engine_load_rdrand_int(void)
  67. {
  68. extern unsigned int OPENSSL_ia32cap_P[];
  69. if (OPENSSL_ia32cap_P[1] & (1 << (62 - 32))) {
  70. ENGINE *toadd = ENGINE_rdrand();
  71. if (!toadd)
  72. return;
  73. ENGINE_add(toadd);
  74. ENGINE_free(toadd);
  75. ERR_clear_error();
  76. }
  77. }
  78. #else
  79. void engine_load_rdrand_int(void)
  80. {
  81. }
  82. #endif