| 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 | |
| 10 | #include <openssl/opensslconf.h> |
| 11 | |
| 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 | |
| 20 | #if (defined(__i386) || defined(__i386__) || defined(_M_IX86) || \ |
| 21 | defined(__x86_64) || defined(__x86_64__) || \ |
| 22 | defined(_M_AMD64) || defined (_M_X64)) && defined(OPENSSL_CPUID_OBJ) |
| 23 | |
| 24 | size_t OPENSSL_ia32_rdrand_bytes(unsigned char *buf, size_t len); |
| 25 | |
| 26 | static int get_random_bytes(unsigned char *buf, int num) |
| 27 | { |
| 28 | if (num < 0) { |
| 29 | return 0; |
| 30 | } |
| 31 | |
| 32 | return (size_t)num == OPENSSL_ia32_rdrand_bytes(buf, (size_t)num); |
| 33 | } |
| 34 | |
| 35 | static int random_status(void) |
| 36 | { |
| 37 | return 1; |
| 38 | } |
| 39 | |
| 40 | static RAND_METHOD rdrand_meth = { |
| 41 | NULL, /* seed */ |
| 42 | get_random_bytes, |
| 43 | NULL, /* cleanup */ |
| 44 | NULL, /* add */ |
| 45 | get_random_bytes, |
| 46 | random_status, |
| 47 | }; |
| 48 | |
| 49 | static int rdrand_init(ENGINE *e) |
| 50 | { |
| 51 | return 1; |
| 52 | } |
| 53 | |
| 54 | static const char *engine_e_rdrand_id = "rdrand" ; |
| 55 | static const char *engine_e_rdrand_name = "Intel RDRAND engine" ; |
| 56 | |
| 57 | static int bind_helper(ENGINE *e) |
| 58 | { |
| 59 | if (!ENGINE_set_id(e, engine_e_rdrand_id) || |
| 60 | !ENGINE_set_name(e, engine_e_rdrand_name) || |
| 61 | !ENGINE_set_flags(e, ENGINE_FLAGS_NO_REGISTER_ALL) || |
| 62 | !ENGINE_set_init_function(e, rdrand_init) || |
| 63 | !ENGINE_set_RAND(e, &rdrand_meth)) |
| 64 | return 0; |
| 65 | |
| 66 | return 1; |
| 67 | } |
| 68 | |
| 69 | static ENGINE *ENGINE_rdrand(void) |
| 70 | { |
| 71 | ENGINE *ret = ENGINE_new(); |
| 72 | if (ret == NULL) |
| 73 | return NULL; |
| 74 | if (!bind_helper(ret)) { |
| 75 | ENGINE_free(ret); |
| 76 | return NULL; |
| 77 | } |
| 78 | return ret; |
| 79 | } |
| 80 | |
| 81 | void engine_load_rdrand_int(void) |
| 82 | { |
| 83 | if (OPENSSL_ia32cap_P[1] & (1 << (62 - 32))) { |
| 84 | ENGINE *toadd = ENGINE_rdrand(); |
| 85 | if (!toadd) |
| 86 | return; |
| 87 | ENGINE_add(toadd); |
| 88 | ENGINE_free(toadd); |
| 89 | ERR_clear_error(); |
| 90 | } |
| 91 | } |
| 92 | #else |
| 93 | void engine_load_rdrand_int(void) |
| 94 | { |
| 95 | } |
| 96 | #endif |
| 97 | |