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