Botan 3.7.1
Crypto and TLS for C&
rdseed.cpp
Go to the documentation of this file.
1/*
2* Entropy Source Using Intel's rdseed instruction
3* (C) 2015 Daniel Neus
4* (C) 2015,2019 Jack Lloyd
5*
6* Botan is released under the Simplified BSD License (see license.txt)
7*/
8
9#include <botan/internal/rdseed.h>
10
11#include <botan/compiler.h>
12#include <botan/internal/cpuid.h>
13
14#include <immintrin.h>
15
16namespace Botan {
17
18namespace {
19
20BOTAN_FUNC_ISA("rdseed") bool read_rdseed(secure_vector<uint32_t>& seed) {
21 /*
22 * RDSEED is not guaranteed to generate an output within any specific number
23 * of attempts. However in testing on a Skylake system, with all hyperthreads
24 * occupied in tight RDSEED loops, RDSEED will still usually succeed in under
25 * 150 attempts. The maximum ever seen was 230 attempts until success. When
26 * idle, RDSEED usually succeeds in 1 or 2 attempts.
27 *
28 * We set an upper bound of 1024 attempts, because it is possible that due
29 * to firmware issue RDSEED is simply broken and never succeeds. We do not
30 * want to loop forever in that case. If we exceed that limit, then we assume
31 * the hardware is actually just broken, and stop the poll.
32 */
33 const size_t RDSEED_RETRIES = 1024;
34
35 for(size_t i = 0; i != RDSEED_RETRIES; ++i) {
36 uint32_t r = 0;
37 int cf = 0;
38
39#if defined(BOTAN_USE_GCC_INLINE_ASM)
40 asm("rdseed %0; adcl $0,%1" : "=r"(r), "=r"(cf) : "0"(r), "1"(cf) : "cc");
41#else
42 cf = _rdseed32_step(&r);
43#endif
44
45 if(1 == cf) {
46 seed.push_back(r);
47 return true;
48 }
49
50 // Intel suggests pausing if RDSEED fails.
51 _mm_pause();
52 }
53
54 return false; // failed to produce an output after many attempts
55}
56
57} // namespace
58
60 const size_t RDSEED_BYTES = 1024;
61 static_assert(RDSEED_BYTES % 4 == 0, "Bad RDSEED configuration");
62
63 if(CPUID::has_rdseed()) {
65 seed.reserve(RDSEED_BYTES / 4);
66
67 for(size_t p = 0; p != RDSEED_BYTES / 4; ++p) {
68 /*
69 If at any point we exceed our retry count, we stop the entire seed
70 gathering process. This situation will only occur in situations of
71 extremely high RDSEED utilization. If RDSEED is currently so highly
72 contended, then the rest of the poll is likely to also face contention and
73 it is better to quit now rather than (presumably) face very high retry
74 times for the rest of the poll.
75 */
76 if(!read_rdseed(seed)) {
77 break;
78 }
79 }
80
81 if(!seed.empty()) {
82 rng.add_entropy(reinterpret_cast<const uint8_t*>(seed.data()), seed.size() * sizeof(uint32_t));
83 }
84 }
85
86 // RDSEED is used but not trusted
87 return 0;
88}
89
90} // namespace Botan
size_t poll(RandomNumberGenerator &rng) override
Definition rdseed.cpp:59
void add_entropy(std::span< const uint8_t > input)
Definition rng.h:76
#define BOTAN_FUNC_ISA(isa)
Definition compiler.h:42
std::vector< T, secure_allocator< T > > secure_vector
Definition secmem.h:61