Botan 3.11.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/buffer_slicer.h>
12#include <botan/internal/buffer_stuffer.h>
13#include <botan/internal/stl_util.h>
14#include <botan/internal/tpm2_util.h>
15
16#include <tss2/tss2_esys.h>
17
18namespace Botan::TPM2 {
19
20RandomNumberGenerator::RandomNumberGenerator(std::shared_ptr<Context> ctx, SessionBundle sessions) :
21 m_ctx(std::move(ctx)), m_sessions(std::move(sessions)) {
23 m_max_tpm2_rng_bytes = m_ctx->max_random_bytes_per_request();
24}
25
26void RandomNumberGenerator::fill_bytes_with_input(std::span<uint8_t> output, std::span<const uint8_t> input) {
27 constexpr size_t MAX_STIR_RANDOM_SIZE = 128; // From specification of tpm2-tool's tpm2_stirrandom
28
29 BufferSlicer in(input);
30 while(!in.empty()) {
31 const size_t chunk = std::min(in.remaining(), MAX_STIR_RANDOM_SIZE);
32 const auto data = copy_into<TPM2B_SENSITIVE_DATA>(in.take(chunk));
33
34 check_rc("Esys_StirRandom",
35 Esys_StirRandom(m_ctx->esys_context(), m_sessions[0], m_sessions[1], m_sessions[2], &data));
36 }
37 BOTAN_ASSERT_NOMSG(in.empty());
38
39 BufferStuffer out(output);
40 while(!out.full()) {
41 unique_esys_ptr<TPM2B_DIGEST> digest = nullptr;
42 const auto requested_bytes = std::min(out.remaining_capacity(), m_max_tpm2_rng_bytes);
43 check_rc("Esys_GetRandom",
44 Esys_GetRandom(m_ctx->esys_context(),
45 m_sessions[0],
46 m_sessions[1],
47 m_sessions[2],
48 static_cast<uint16_t>(requested_bytes),
49 out_ptr(digest)));
50
51 BOTAN_ASSERT_NOMSG(digest->size == requested_bytes);
52 out.append(as_span(*digest));
53 }
54 BOTAN_ASSERT_NOMSG(out.full());
55}
56
57} // namespace Botan::TPM2
#define BOTAN_ASSERT_NOMSG(expr)
Definition assert.h:75
#define BOTAN_ASSERT_NONNULL(ptr)
Definition assert.h:114
Helper class to ease in-place marshalling of concatenated fixed-length values.
constexpr void check_rc(std::string_view location, TSS2_RC rc)
Definition tpm2_util.h:55
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:163
constexpr void copy_into(T &dest, std::span< const uint8_t > data)
Definition tpm2_util.h:118
constexpr auto as_span(tpm2_buffer auto &data)
Construct a std::span as a view into a TPM2 buffer.
Definition tpm2_util.h:103
constexpr auto out_ptr(T &outptr) noexcept
Definition stl_util.h:127