Botan 3.6.0
Crypto and TLS for C&
tpm2_rng.cpp
Go to the documentation of this file.
1/*
2* TPM 2 RNG interface
3* (C) 2024 Jack Lloyd
4* (C) 2024 René Meusel, Amos Treiber - Rohde & Schwarz Cybersecurity GmbH, financed by LANCOM Systems GmbH
5*
6* Botan is released under the Simplified BSD License (see license.txt)
7*/
8
9#include <botan/tpm2_rng.h>
10
11#include <botan/internal/stl_util.h>
12#include <botan/internal/tpm2_util.h>
13
14#include <tss2/tss2_esys.h>
15
16namespace Botan::TPM2 {
17
18RandomNumberGenerator::RandomNumberGenerator(std::shared_ptr<Context> ctx, SessionBundle sessions) :
19 m_ctx(std::move(ctx)), m_sessions(std::move(sessions)) {
21 m_max_tpm2_rng_bytes = m_ctx->max_random_bytes_per_request();
22}
23
24void RandomNumberGenerator::fill_bytes_with_input(std::span<uint8_t> output, std::span<const uint8_t> input) {
25 constexpr size_t MAX_STIR_RANDOM_SIZE = 128; // From specification of tpm2-tool's tpm2_stirrandom
26
27 BufferSlicer in(input);
28 while(!in.empty()) {
29 const size_t chunk = std::min(in.remaining(), MAX_STIR_RANDOM_SIZE);
30 const auto data = copy_into<TPM2B_SENSITIVE_DATA>(in.take(chunk));
31
32 check_rc("Esys_StirRandom", Esys_StirRandom(*m_ctx, m_sessions[0], m_sessions[1], m_sessions[2], &data));
33 }
34 BOTAN_ASSERT_NOMSG(in.empty());
35
36 BufferStuffer out(output);
37 while(!out.full()) {
38 unique_esys_ptr<TPM2B_DIGEST> digest = nullptr;
39 const auto requested_bytes = std::min(out.remaining_capacity(), m_max_tpm2_rng_bytes);
40 check_rc("Esys_GetRandom",
41 Esys_GetRandom(*m_ctx, m_sessions[0], m_sessions[1], m_sessions[2], requested_bytes, out_ptr(digest)));
42
43 BOTAN_ASSERT_NOMSG(digest->size == requested_bytes);
44 out.append(as_span(*digest));
45 }
46 BOTAN_ASSERT_NOMSG(out.full());
47}
48
49} // namespace Botan::TPM2
#define BOTAN_ASSERT_NOMSG(expr)
Definition assert.h:59
#define BOTAN_ASSERT_NONNULL(ptr)
Definition assert.h:86
Helper class to ease in-place marshalling of concatenated fixed-length values.
Definition stl_util.h:142
constexpr void check_rc(std::string_view location, TSS2_RC rc)
Definition tpm2_util.h:54
std::unique_ptr< T, esys_liberator > unique_esys_ptr
A unique pointer type for ESYS handles that automatically frees the handle.
Definition tpm2_util.h:154
constexpr void copy_into(T &dest, std::span< const uint8_t > data)
Definition tpm2_util.h:117
constexpr auto as_span(tpm2_buffer auto &data)
Construct a std::span as a view into a TPM2 buffer.
Definition tpm2_util.h:102
constexpr auto out_ptr(T &outptr) noexcept
Definition stl_util.h:420