Botan 3.6.0
Crypto and TLS for C&
tpm2_context.cpp
Go to the documentation of this file.
1/*
2* TPM 2 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_context.h>
10
11#include <botan/tpm2_key.h>
12#include <botan/tpm2_session.h>
13
14#include <botan/internal/fmt.h>
15#include <botan/internal/loadstor.h>
16#include <botan/internal/stl_util.h>
17#include <botan/internal/tpm2_algo_mappings.h>
18#include <botan/internal/tpm2_util.h>
19
20#include <tss2/tss2_esys.h>
21#include <tss2/tss2_tcti.h>
22#include <tss2/tss2_tctildr.h>
23
24#if defined(BOTAN_HAS_TPM2_CRYPTO_BACKEND)
25 #include <botan/internal/tpm2_crypto_backend.h>
26#endif
27
28namespace Botan::TPM2 {
29
30namespace {
31
32constexpr TPM2_HANDLE storage_root_key_handle = TPM2_HR_PERSISTENT + 1;
33
34} // namespace
35
36struct Context::Impl {
37 TSS2_TCTI_CONTEXT* m_tcti_ctx;
38 ESYS_CONTEXT* m_ctx;
39
40#if defined(BOTAN_HAS_TPM2_CRYPTO_BACKEND)
41 std::unique_ptr<CryptoCallbackState> m_crypto_callback_state;
42#endif
43};
44
46#if defined(BOTAN_TSS2_SUPPORTS_CRYPTO_CALLBACKS) and defined(BOTAN_HAS_TPM2_CRYPTO_BACKEND)
47 return true;
48#else
49 return false;
50#endif
51}
52
53std::shared_ptr<Context> Context::create(const std::string& tcti_nameconf) {
54 // We cannot std::make_shared as the constructor is private
55 return std::shared_ptr<Context>(new Context(tcti_nameconf.c_str()));
56}
57
58std::shared_ptr<Context> Context::create(std::optional<std::string> tcti, std::optional<std::string> conf) {
59 const auto tcti_ptr = tcti.has_value() ? tcti->c_str() : nullptr;
60 const auto conf_ptr = conf.has_value() ? conf->c_str() : nullptr;
61
62 // We cannot std::make_shared as the constructor is private
63 return std::shared_ptr<Context>(new Context(tcti_ptr, conf_ptr));
64}
65
66Context::Context(const char* tcti_nameconf) : m_impl(std::make_unique<Impl>()) {
67 check_rc("TCTI Initialization", Tss2_TctiLdr_Initialize(tcti_nameconf, &m_impl->m_tcti_ctx));
68 BOTAN_ASSERT_NONNULL(m_impl->m_tcti_ctx);
69 check_rc("TPM2 Initialization", Esys_Initialize(&m_impl->m_ctx, m_impl->m_tcti_ctx, nullptr /* ABI version */));
70 BOTAN_ASSERT_NONNULL(m_impl->m_ctx);
71}
72
73Context::Context(const char* tcti_name, const char* tcti_conf) : m_impl(std::make_unique<Impl>()) {
74 check_rc("TCTI Initialization", Tss2_TctiLdr_Initialize_Ex(tcti_name, tcti_conf, &m_impl->m_tcti_ctx));
75 BOTAN_ASSERT_NONNULL(m_impl->m_tcti_ctx);
76 check_rc("TPM2 Initialization", Esys_Initialize(&m_impl->m_ctx, m_impl->m_tcti_ctx, nullptr /* ABI version */));
77 BOTAN_ASSERT_NONNULL(m_impl->m_ctx);
78}
79
80void Context::use_botan_crypto_backend(const std::shared_ptr<Botan::RandomNumberGenerator>& rng) {
81#if defined(BOTAN_HAS_TPM2_CRYPTO_BACKEND)
83 m_impl->m_crypto_callback_state = std::make_unique<CryptoCallbackState>(rng);
84 enable_crypto_callbacks(shared_from_this());
85#else
86 BOTAN_UNUSED(rng);
87 throw Not_Implemented("This build of botan does not provide the TPM2 crypto backend");
88#endif
89}
90
92#if defined(BOTAN_HAS_TPM2_CRYPTO_BACKEND)
93 return m_impl->m_crypto_callback_state != nullptr;
94#else
95 return false;
96#endif
97}
98
99#if defined(BOTAN_HAS_TPM2_CRYPTO_BACKEND)
100CryptoCallbackState& Context::crypto_callback_state() {
101 BOTAN_ASSERT_NONNULL(m_impl->m_crypto_callback_state);
102 return *m_impl->m_crypto_callback_state;
103}
104#endif
105
106ESYS_CONTEXT* Context::esys_context() noexcept {
107 return m_impl->m_ctx;
108}
109
110namespace {
111
112uint32_t get_tpm_property(ESYS_CONTEXT* ctx, TPM2_PT property) {
113 // We expect to retrieve a single piece of information, not a list.
114 constexpr uint32_t property_count = 1;
115 constexpr TPM2_CAP capability = TPM2_CAP_TPM_PROPERTIES;
116
118 check_rc("Esys_GetCapability",
119 Esys_GetCapability(ctx,
120 ESYS_TR_NONE,
121 ESYS_TR_NONE,
122 ESYS_TR_NONE,
123 capability,
124 property,
125 property_count,
126 nullptr /* more data? - we don't care here */,
127 out_ptr(capability_data)));
128 BOTAN_ASSERT_NONNULL(capability_data);
129 BOTAN_ASSERT_NOMSG(capability_data->capability == capability);
130 BOTAN_ASSERT_NOMSG(capability_data->data.tpmProperties.count == property_count);
131 BOTAN_ASSERT_NOMSG(capability_data->data.tpmProperties.tpmProperty[0].property == property);
132
133 return capability_data->data.tpmProperties.tpmProperty[0].value;
134}
135
136template <TPM2_CAP capability, typename ReturnT>
137[[nodiscard]] std::vector<ReturnT> get_tpm_property_list(ESYS_CONTEXT* ctx, TPM2_PT property, uint32_t count) {
138 auto extract = [](const TPMU_CAPABILITIES& caps, uint32_t max_count) {
139 std::vector<ReturnT> result;
140 if constexpr(capability == TPM2_CAP_HANDLES) {
141 const auto to_read = std::min(caps.handles.count, max_count);
142 result.reserve(to_read);
143 for(size_t i = 0; i < to_read; ++i) {
144 result.push_back(caps.handles.handle[i]);
145 }
146 } else if constexpr(capability == TPM2_CAP_ALGS) {
147 const auto to_read = std::min(caps.algorithms.count, max_count);
148 result.reserve(to_read);
149 for(size_t i = 0; i < to_read; ++i) {
150 // TODO: This also contains an algProperties.algProperties bitfield
151 // that defines some characteristics of the algorithm.
152 // Currently, we don't need that information and ignore it.
153 result.push_back(caps.algorithms.algProperties[i].alg);
154 }
155 } else {
156 // TODO: support reading other capability types as needed
157 static_assert(capability != TPM2_CAP_HANDLES, "Unsupported capability");
158 }
159 return result;
160 };
161
162 TPMI_YES_NO more_data = TPM2_YES;
163 std::vector<ReturnT> properties;
164 while(more_data == TPM2_YES && count > 0) {
166 check_rc("Esys_GetCapability",
167 Esys_GetCapability(ctx,
168 ESYS_TR_NONE,
169 ESYS_TR_NONE,
170 ESYS_TR_NONE,
171 capability,
172 property,
173 count,
174 &more_data,
175 out_ptr(capability_data)));
176 BOTAN_ASSERT_NONNULL(capability_data);
177 BOTAN_ASSERT_NOMSG(capability_data->capability == capability);
178
179 const auto new_properties = extract(capability_data->data, count);
180 BOTAN_ASSERT_NOMSG(new_properties.size() <= count);
181 properties.insert(properties.end(), new_properties.begin(), new_properties.end());
182 count -= new_properties.size();
183 }
184
185 return properties;
186}
187
188} // namespace
189
190std::string Context::vendor() const {
191 constexpr std::array properties = {
192 TPM2_PT_VENDOR_STRING_1, TPM2_PT_VENDOR_STRING_2, TPM2_PT_VENDOR_STRING_3, TPM2_PT_VENDOR_STRING_4};
193 std::array<uint8_t, properties.size() * 4 + 1 /* ensure zero-termination */> vendor_string{};
194
195 BufferStuffer bs(vendor_string);
196
197 // The vendor name is transported in several uint32_t fields that are
198 // loaded as big-endian bytes and concatenated to form the vendor string.
199 for(auto prop : properties) {
200 bs.append(store_be(get_tpm_property(m_impl->m_ctx, prop)));
201 }
202
203 BOTAN_ASSERT_NOMSG(bs.remaining_capacity() == 1); // the ensured zero-termination
204 return std::string(cast_uint8_ptr_to_char(vendor_string.data()));
205}
206
207std::string Context::manufacturer() const {
208 std::array<uint8_t, 4 + 1 /* ensure zero termination */> manufacturer_data{};
209 store_be(std::span{manufacturer_data}.first<4>(), get_tpm_property(m_impl->m_ctx, TPM2_PT_MANUFACTURER));
210 return std::string(cast_uint8_ptr_to_char(manufacturer_data.data()));
211}
212
213bool Context::supports_algorithm(std::string_view algo_name) const {
214 // Go through all the string mappings we have available and check if we
215 // can find the algorithm name in any of them. If we do, we can check if
216 // the TPM supports the required algorithms.
217 const auto required_alg_ids = [&]() -> std::vector<TPM2_ALG_ID> {
218 std::vector<TPM2_ALG_ID> result;
219 if(auto algo_id = asymmetric_algorithm_botan_to_tss2(algo_name)) {
220 result.push_back(algo_id.value());
221 }
222
223 if(auto hash_id = hash_algo_botan_to_tss2(algo_name)) {
224 result.push_back(hash_id.value());
225 }
226
227 if(auto block_id = block_cipher_botan_to_tss2(algo_name)) {
228 result.push_back(block_id->first);
229 }
230
231 if(auto cipher_mode_id = cipher_mode_botan_to_tss2(algo_name)) {
232 result.push_back(cipher_mode_id.value());
233 }
234
235 if(auto cipher_spec = cipher_botan_to_tss2(algo_name)) {
236 result.push_back(cipher_spec->algorithm);
237 result.push_back(cipher_spec->mode.sym);
238 }
239
240 if(auto sig_padding = rsa_signature_padding_botan_to_tss2(algo_name)) {
241 result.push_back(sig_padding.value());
242 }
243
244 if(auto sig = rsa_signature_scheme_botan_to_tss2(algo_name)) {
245 result.push_back(sig->scheme);
246 result.push_back(sig->details.any.hashAlg);
247 }
248
249 if(auto enc_scheme = rsa_encryption_scheme_botan_to_tss2(algo_name)) {
250 result.push_back(enc_scheme->scheme);
251 if(enc_scheme->scheme == TPM2_ALG_OAEP) {
252 result.push_back(enc_scheme->details.oaep.hashAlg);
253 }
254 }
255
256 if(auto enc_id = rsa_encryption_padding_botan_to_tss2(algo_name)) {
257 result.push_back(enc_id.value());
258 }
259
260 return result;
261 }();
262
263 if(required_alg_ids.empty()) {
264 // The algorithm name is not known to us, so we cannot check for support.
265 return false;
266 }
267
268 const auto algo_caps =
269 get_tpm_property_list<TPM2_CAP_ALGS, TPM2_ALG_ID>(m_impl->m_ctx, TPM2_ALG_FIRST, TPM2_MAX_CAP_ALGS);
270
271 return std::all_of(
272 required_alg_ids.begin(), required_alg_ids.end(), [&](TPM2_ALG_ID id) { return value_exists(algo_caps, id); });
273}
274
276 return get_tpm_property(m_impl->m_ctx, TPM2_PT_MAX_DIGEST);
277}
278
279std::unique_ptr<TPM2::PrivateKey> Context::storage_root_key(std::span<const uint8_t> auth_value,
280 const SessionBundle& sessions) {
281 return TPM2::PrivateKey::load_persistent(shared_from_this(), storage_root_key_handle, auth_value, sessions);
282}
283
284std::vector<ESYS_TR> Context::transient_handles() const {
285 return get_tpm_property_list<TPM2_CAP_HANDLES, ESYS_TR>(m_impl->m_ctx, TPM2_TRANSIENT_FIRST, TPM2_MAX_CAP_HANDLES);
286}
287
288std::optional<TPM2_HANDLE> Context::find_free_persistent_handle() const {
289 const auto occupied_handles = persistent_handles();
290
291 // This is modeled after the implementation in tpm2-tools, which also takes
292 // "platform persistent" handles into account. We don't do that here, but
293 // we might need to in the future.
294 //
295 // See: https://github.com/tpm2-software/tpm2-tools/blob/bd832d3f79/lib/tpm2_capability.c#L143-L196
296
297 // all persistent handles are occupied
298 if(occupied_handles.size() >= TPM2_MAX_CAP_HANDLES) {
299 return std::nullopt;
300 }
301
302 // find the lowest handle that is not occupied
303 for(TPM2_HANDLE i = TPM2_PERSISTENT_FIRST; i < TPM2_PERSISTENT_LAST; ++i) {
304 if(!value_exists(occupied_handles, i)) {
305 return i;
306 }
307 }
308
310}
311
312std::vector<TPM2_HANDLE> Context::persistent_handles() const {
313 return get_tpm_property_list<TPM2_CAP_HANDLES, TPM2_HANDLE>(
314 m_impl->m_ctx, TPM2_PERSISTENT_FIRST, TPM2_MAX_CAP_HANDLES);
315}
316
318 const SessionBundle& sessions,
319 std::span<const uint8_t> auth_value,
320 std::optional<TPM2_HANDLE> persistent_handle) {
321 auto& handles = key.handles();
322
323 BOTAN_ARG_CHECK(!persistent_handle || !value_exists(persistent_handles(), persistent_handle.value()),
324 "Persistent handle already in use");
325 BOTAN_ARG_CHECK(!handles.has_persistent_handle(), "Key already has a persistent handle assigned");
326
327 // 1. Decide on the location to persist the key to.
328 // This uses either the handle provided by the caller or a free handle.
329 const TPMI_DH_PERSISTENT new_persistent_handle = [&] {
330 if(persistent_handle.has_value()) {
331 return persistent_handle.value();
332 } else {
333 const auto free_persistent_handle = find_free_persistent_handle();
334 BOTAN_STATE_CHECK(free_persistent_handle.has_value());
335 return free_persistent_handle.value();
336 }
337 }();
338
339 // 2. Persist the transient key in the TPM's NV storage
340 // This will flush the transient key handle and replace it with a new
341 // transient handle that references the persisted key.
342 check_rc("Esys_EvictControl",
343 Esys_EvictControl(m_impl->m_ctx,
344 ESYS_TR_RH_OWNER /*TODO: hierarchy*/,
345 handles.transient_handle(),
346 sessions[0],
347 sessions[1],
348 sessions[2],
349 new_persistent_handle,
350 out_transient_handle(handles)));
351 BOTAN_ASSERT_NOMSG(handles.has_transient_handle());
352
353 // 3. Reset the auth value of the key object
354 // This is necessary to ensure that the key object remains usable after
355 // the transient handle was recreated inside Esys_EvictControl().
356 if(!auth_value.empty()) {
357 const auto user_auth = copy_into<TPM2B_AUTH>(auth_value);
358 check_rc("Esys_TR_SetAuth", Esys_TR_SetAuth(m_impl->m_ctx, handles.transient_handle(), &user_auth));
359 }
360
361 // 4. Update the key object with the new persistent handle
362 // This double-checks that the key was persisted at the correct location,
363 // but also brings the key object into a consistent state.
364 check_rc("Esys_TR_GetTpmHandle",
365 Esys_TR_GetTpmHandle(m_impl->m_ctx, handles.transient_handle(), out_persistent_handle(handles)));
366
367 BOTAN_ASSERT_NOMSG(handles.has_persistent_handle());
368 BOTAN_ASSERT_EQUAL(new_persistent_handle, handles.persistent_handle(), "key was persisted at the correct location");
369
370 return new_persistent_handle;
371}
372
373void Context::evict(std::unique_ptr<TPM2::PrivateKey> key, const SessionBundle& sessions) {
375
376 auto& handles = key->handles();
377 BOTAN_ARG_CHECK(handles.has_persistent_handle(), "Key does not have a persistent handle assigned");
378
379 // 1. Evict the key from the TPM's NV storage
380 // This will free the persistent handle, but the transient handle will
381 // still be valid.
382 ESYS_TR no_new_handle = ESYS_TR_NONE;
383 check_rc("Esys_EvictControl",
384 Esys_EvictControl(m_impl->m_ctx,
385 ESYS_TR_RH_OWNER /*TODO: hierarchy*/,
386 handles.transient_handle(),
387 sessions[0],
388 sessions[1],
389 sessions[2],
390 0,
391 &no_new_handle));
392 BOTAN_ASSERT(no_new_handle == ESYS_TR_NONE, "When deleting a key, no new handle is returned");
393
394 // 2. The persistent key was deleted and the transient key was flushed by
395 // Esys_EvictControl().
396 handles._disengage();
397}
398
400 if(m_impl) {
401 Esys_Finalize(&m_impl->m_ctx);
402 Tss2_TctiLdr_Finalize(&m_impl->m_tcti_ctx);
403 }
404}
405
406} // namespace Botan::TPM2
#define BOTAN_UNUSED
Definition assert.h:118
#define BOTAN_ASSERT_NOMSG(expr)
Definition assert.h:59
#define BOTAN_STATE_CHECK(expr)
Definition assert.h:41
#define BOTAN_ASSERT_EQUAL(expr1, expr2, assertion_made)
Definition assert.h:68
#define BOTAN_ASSERT_NONNULL(ptr)
Definition assert.h:86
#define BOTAN_ARG_CHECK(expr, msg)
Definition assert.h:29
#define BOTAN_ASSERT(expr, assertion_made)
Definition assert.h:50
#define BOTAN_ASSERT_UNREACHABLE()
Definition assert.h:137
Helper class to ease in-place marshalling of concatenated fixed-length values.
Definition stl_util.h:142
constexpr void append(std::span< const uint8_t > buffer)
Definition stl_util.h:177
constexpr size_t remaining_capacity() const
Definition stl_util.h:189
std::optional< TPM2_HANDLE > find_free_persistent_handle() const
bool supports_algorithm(std::string_view algo_name) const
void use_botan_crypto_backend(const std::shared_ptr< Botan::RandomNumberGenerator > &rng)
static bool supports_botan_crypto_backend() noexcept
std::vector< TPM2_HANDLE > persistent_handles() const
size_t max_random_bytes_per_request() const
std::vector< ESYS_TR > transient_handles() const
TPM2_HANDLE persist(TPM2::PrivateKey &key, const SessionBundle &sessions, std::span< const uint8_t > auth_value={}, std::optional< TPM2_HANDLE > persistent_handle=std::nullopt)
Makes key persistent at location persistent_handle or any free.
Context(const Context &)=delete
static std::shared_ptr< Context > create(const std::string &tcti_nameconf)
std::string manufacturer() const
std::string vendor() const
ESYS_CONTEXT * esys_context() noexcept
std::unique_ptr< TPM2::PrivateKey > storage_root_key(std::span< const uint8_t > auth_value, const SessionBundle &sessions)
void evict(std::unique_ptr< TPM2::PrivateKey > key, const SessionBundle &sessions)
Evicts a persistent key from the TPM. The key cannot be used after.
bool uses_botan_crypto_backend() const noexcept
static std::unique_ptr< PrivateKey > load_persistent(const std::shared_ptr< Context > &ctx, TPM2_HANDLE persistent_object_handle, std::span< const uint8_t > auth_value, const SessionBundle &sessions)
Definition tpm2_key.cpp:180
void enable_crypto_callbacks(const std::shared_ptr< Context > &ctx)
std::optional< TPMT_SIG_SCHEME > rsa_signature_scheme_botan_to_tss2(std::string_view name)
std::optional< TPMI_ALG_SIG_SCHEME > rsa_signature_padding_botan_to_tss2(std::string_view padding_name) noexcept
std::optional< TPMI_ALG_ASYM_SCHEME > rsa_encryption_padding_botan_to_tss2(std::string_view name) noexcept
constexpr void check_rc(std::string_view location, TSS2_RC rc)
Definition tpm2_util.h:54
std::optional< std::pair< TPMI_ALG_SYM, TPM2_KEY_BITS > > block_cipher_botan_to_tss2(std::string_view cipher_name) noexcept
constexpr auto out_persistent_handle(Object &object)
Definition tpm2_util.h:215
std::optional< TPMT_SYM_DEF > cipher_botan_to_tss2(std::string_view algo_name)
std::optional< TPMT_RSA_DECRYPT > rsa_encryption_scheme_botan_to_tss2(std::string_view padding)
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
std::optional< TPMI_ALG_HASH > hash_algo_botan_to_tss2(std::string_view hash_name) noexcept
constexpr auto out_transient_handle(Object &object)
Definition tpm2_util.h:209
std::optional< TPM2_ALG_ID > asymmetric_algorithm_botan_to_tss2(std::string_view algo_name) noexcept
constexpr void copy_into(T &dest, std::span< const uint8_t > data)
Definition tpm2_util.h:117
std::optional< TPMI_ALG_SYM_MODE > cipher_mode_botan_to_tss2(std::string_view mode_name) noexcept
constexpr auto out_ptr(T &outptr) noexcept
Definition stl_util.h:420
const char * cast_uint8_ptr_to_char(const uint8_t *b)
Definition mem_ops.h:277
bool value_exists(const std::vector< T > &vec, const OT &val)
Definition stl_util.h:60
constexpr auto store_be(ParamTs &&... params)
Definition loadstor.h:773
uint32_t ESYS_TR
Forward declaration of TSS2 type for convenience.
uint32_t TPM2_HANDLE
Forward declaration of TSS2 type for convenience.