eng_rdrand.c 2.2 KB

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