eng_rdrand.c 2.3 KB

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