Botan 3.14.1
Crypto and TLS for C&
esdm_rng.cpp
Go to the documentation of this file.
1/*
2* ESDM RNG
3* (C) 2024, Markus Theil <theil.markus@gmail.com>
4*
5* Botan is released under the Simplified BSD License (see license.txt)
6*/
7
8#include <botan/esdm_rng.h>
9
10#include <botan/exceptn.h>
11#include <esdm/esdm_rpc_client.h>
12#include <mutex>
13
14namespace Botan {
15
16namespace {
17/**
18* This helper makes sure that the ESDM service is initialized and
19* finalized as needed in a threadsafe fashion. Finalization happens
20* as soon as all instances of ESDM_RNG are destructed. This may
21* happen multiple times in the lifetime of the process.
22*/
23class ESDM_Context final {
24 public:
25 [[nodiscard]] static std::shared_ptr<void> instance() {
26 static ESDM_Context g_instance;
27 return g_instance.acquire();
28 }
29
30 private:
31 ESDM_Context() = default;
32
33 [[nodiscard]] std::shared_ptr<void> acquire() {
34 std::scoped_lock lk(m_mutex);
35 if(m_refs == 0) {
36 if(esdm_rpcc_init_unpriv_service(nullptr) != 0) {
37 throw Botan::System_Error("unable to initialize ESDM unprivileged service");
38 }
39 }
40 m_refs++;
41 return std::shared_ptr<void>{nullptr, [this](void*) { this->release(); }};
42 }
43
44 void release() {
45 std::scoped_lock lk(m_mutex);
46 if(m_refs-- == 1) {
47 esdm_rpcc_fini_unpriv_service();
48 }
49 }
50
51 private:
52 std::mutex m_mutex;
53 size_t m_refs = 0;
54};
55} // namespace
56
57ESDM_RNG::ESDM_RNG(bool prediction_resistance) :
58 m_prediction_resistance(prediction_resistance), m_ctx(ESDM_Context::instance()) {}
59
60void ESDM_RNG::fill_bytes_with_input(std::span<uint8_t> out, std::span<const uint8_t> in) {
61 /*
62 * This variable is implicitly set by the "esdm_invoke" macro that comes
63 * with the ESDM library. "esdm_invoke" implements a retry mechanism for
64 * the underlying RPC mechanism of ESDM.
65 */
66 ssize_t ret = 0;
67
68 if(!in.empty()) {
69 ret = 0;
70
71 /*
72 * take additional input, but do not account entropy for it,
73 * as this information is not included in the API
74 */
75 esdm_invoke(esdm_rpcc_write_data(in.data(), in.size()));
76 /*
77 * ret was set by esdm_invoke, as mentioned above
78 */
79 if(ret != 0) {
80 throw Botan::System_Error("Writing additional input to ESDM failed");
81 }
82 }
83
84 if(!out.empty()) {
85 ret = 0;
86
87 if(m_prediction_resistance) {
88 esdm_invoke(esdm_rpcc_get_random_bytes_pr(out.data(), out.size()));
89 } else {
90 esdm_invoke(esdm_rpcc_get_random_bytes_full(out.data(), out.size()));
91 }
92 /*
93 * ret was set by esdm_invoke, as mentioned above
94 */
95 if(ret != static_cast<ssize_t>(out.size())) {
96 throw Botan::System_Error("Fetching random bytes from ESDM failed");
97 }
98 }
99}
100
102 static ESDM_RNG g_esdm_rng;
103 return g_esdm_rng;
104}
105
106} // namespace Botan
void fill_bytes_with_input(std::span< uint8_t > out, std::span< const uint8_t > in) override
Definition esdm_rng.cpp:60
RandomNumberGenerator & esdm_rng()
Definition esdm_rng.cpp:101