Botan 3.14.1
Crypto and TLS for C&
tpm2_util.h
Go to the documentation of this file.
1/*
2* TPM 2 internal utilities
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#ifndef BOTAN_TPM2_UTIL_H_
10#define BOTAN_TPM2_UTIL_H_
11
12#include <botan/bigint.h>
13#include <botan/concepts.h>
14#include <botan/mem_ops.h>
15#include <botan/tpm2_context.h>
16#include <botan/tpm2_error.h>
17#include <botan/tpm2_object.h>
18
19#include <bit>
20#include <memory>
21#include <span>
22
23#include <tss2/tss2_esys.h>
24#include <tss2/tss2_rc.h>
25
26// There's no obvious way to get the version of the TSS from its headers,
27// instead the existence of certain return code macro definitions is used
28// as sentinels to pinpoint the TSS' version. Namely:
29//
30// - TSS2_BASE_RC_CALLBACK_NULL -> 4.0.0 or later
31// - TPM2_RC_FW_LIMITED -> 4.1.0 or later
32
33#if defined(TSS2_BASE_RC_CALLBACK_NULL)
34 // The crypto callbacks were added in tpm2-tss 4.0.0.
35 #define BOTAN_TSS2_SUPPORTS_CRYPTO_CALLBACKS
36
37 // Error decoding was added in tpm2-tss 4.0.0
38 #define BOTAN_TSS2_SUPPORTS_ERROR_DECODING
39#endif
40
41#if defined(TPM2_RC_FW_LIMITED)
42 // The crypto callbacks for SM4 were added in tpm2-tss 4.1.0.
43 #define BOTAN_TSS2_SUPPORTS_SM4_IN_CRYPTO_CALLBACKS
44#endif
45
46namespace Botan::TPM2 {
47
48/**
49 * Check the return code and throw an exception if some error occurred.
50 *
51 * @throws TPM2::Error if an error occurred.
52 */
53constexpr void check_rc(std::string_view location, TSS2_RC rc) {
54 if(rc != TSS2_RC_SUCCESS) {
55 throw Error(location, rc);
56 }
57}
58
59/**
60 * Check the return code and throw an exception if an unexpected error occurred.
61 *
62 * Errors that are listed in the `expected_errors` parameter are considered
63 * expected and will not cause an exception to be thrown. Instead the error
64 * code is decoded and returned to the caller for further processing.
65 *
66 * @throws TPM2::Error if an unexpected error occurred.
67 * @returns TSS2_RC_SUCCESS or one of the expected error codes.
68 */
69template <TSS2_RC... expected_errors>
70 requires(sizeof...(expected_errors) > 0)
71[[nodiscard]] constexpr TSS2_RC check_rc_expecting(std::string_view location, TSS2_RC rc) {
72 // If the RC is success, we can return early and avoid the decoding.
73 if(rc == TSS2_RC_SUCCESS) {
74 return rc;
75 }
76
77 // An error occurred, we need to decode it to check if it was expected.
78 const TSS2_RC decoded_rc = get_raw_rc(rc);
79
80 // Check if the error is one of the expected and return those to the caller.
81 const bool is_expected_by_caller = ((decoded_rc == expected_errors) || ...);
82 if(is_expected_by_caller) {
83 return decoded_rc;
84 }
85
86 // The error was not expected, so call the normal error handling which
87 // will throw an exception.
88 check_rc(location, rc);
89
90 // We know, rc is not 'success', so this won't ever be reached.
91 return rc;
92}
93
94template <typename T>
95concept tpm2_buffer = requires(T t) {
96 { t.buffer } -> std::convertible_to<const uint8_t*>;
97 { t.size } -> std::convertible_to<size_t>;
98};
99
100/// Construct a std::span as a view into a TPM2 buffer
101constexpr auto as_span(tpm2_buffer auto& data) {
102 return std::span{data.buffer, data.size};
103}
104
105/// Set the size of @p data to @p length and construct a std::span
106/// as a view into @p data
107constexpr auto as_span(tpm2_buffer auto& data, size_t length) {
108 BOTAN_ASSERT_NOMSG(length <= sizeof(data.buffer));
109 data.size = static_cast<decltype(data.size)>(length);
110 return as_span(data);
111}
112
113/// Copy the @p data into the TPM2 buffer @p dest, assuming that the
114/// provided @p data is not larger than the capacity of the buffer.
115template <tpm2_buffer T>
116constexpr void copy_into(T& dest, std::span<const uint8_t> data) {
117 copy_mem(as_span(dest, data.size()), data);
118}
119
120/// Create a TPM2 buffer from the provided @p data, assuming that the
121/// provided @p data is not larger than the capacity of the buffer type.
122template <tpm2_buffer T>
123constexpr T copy_into(std::span<const uint8_t> data) {
124 T result{};
125 copy_into(result, data);
126 return result;
127}
128
129/// Copy the content of the TPM2 buffer @p data into a new resizable byte buffer
130/// of the user's choosing.
131template <concepts::resizable_byte_buffer OutT>
132constexpr OutT copy_into(const tpm2_buffer auto& data) {
133 OutT result;
134 result.resize(data.size);
135 copy_mem(result, as_span(data));
136 return result;
137}
138
139/// Create a TPM2 buffer of a given type and @p length.
140template <tpm2_buffer T>
141constexpr T init_with_size(size_t length) {
142 T result{};
143 BOTAN_ASSERT_NOMSG(length <= sizeof(result.buffer));
144 result.size = static_cast<decltype(result.size)>(length);
145 clear_bytes(result.buffer, length);
146 return result;
147}
148
149/// Create an empty TPM2 buffer of the given type.
150template <tpm2_buffer T>
151constexpr T init_empty() {
152 return init_with_size<T>(0);
153}
154
156 void operator()(void* handle) { Esys_Free(handle); }
157};
158
159/// A unique pointer type for ESYS handles that automatically frees the handle.
160template <typename T>
161using unique_esys_ptr = std::unique_ptr<T, esys_liberator>;
162
168
170 std::optional<TPM2_HANDLE> persistent = std::nullopt;
171 ESYS_TR transient = ESYS_TR_NONE;
172};
173
174/**
175 * Helper type setting a TPM2_HANDLE or ESYS_TR on a given instance of Object
176 * from a TSS2 library function's out parameter.
177 *
178 * This is not used directly, but through the out_transient_handle() and
179 * out_persistent_handle() respectively.
180 */
182 public:
183 constexpr explicit ObjectSetter(Object& object, bool persistent = false) :
184 m_object(object), m_persistent(persistent), m_handle(persistent ? 0 : ESYS_TR_NONE) {}
185
186 constexpr ~ObjectSetter() noexcept {
187 if(!was_written()) {
188 return;
189 }
190
191 if(m_persistent) {
192 m_object.handles().persistent = m_handle;
193 } else {
194 m_object.handles().transient = m_handle;
195 }
196 }
197
198 ObjectSetter(const ObjectSetter&) = delete;
202
203 // NOLINTNEXTLINE(*-explicit-conversions,*-explicit-constructor) FIXME
204 [[nodiscard]] constexpr operator uint32_t*() && noexcept { return &m_handle; }
205
206 private:
207 constexpr bool was_written() const { return m_handle != (m_persistent ? 0 : ESYS_TR_NONE); }
208
209 private:
210 Object& m_object;
211 bool m_persistent;
212 uint32_t m_handle; /// TPM2_HANDLE or ESYS_TR, both are typedefs to uint32_t
213};
214
215/// Helper to set the transient handle of an object from a TSS2 library
216/// function's out parameter.
217constexpr auto out_transient_handle(Object& object) {
218 return ObjectSetter{object, false};
219}
220
221/// Helper to set the persistent handle of an object from a TSS2 library
222/// function's out parameter.
223constexpr auto out_persistent_handle(Object& object) {
224 return ObjectSetter{object, true};
225}
226
227/// Helper for the AttributeWrapper to define mappings between
228/// boolean members of a struct and the corresponding bit masks
229template <typename FieldPointerT, std::unsigned_integral MaskT>
230 requires std::is_member_object_pointer_v<FieldPointerT>
231struct PropMap {
232 FieldPointerT field;
233 MaskT mask;
234
235 /// Access the boolean member 'field' from the given @p object
236 [[nodiscard]] constexpr bool& operator()(auto& object) const noexcept { return object.*field; }
237
238 /// Read-only access the boolean member 'field' from the given @p object
239 [[nodiscard]] constexpr bool operator()(const auto& object) const noexcept { return object.*field; }
240};
241
242/// Deduction guide to simplify the creation of PropMap instances
243template <typename MaskT, typename FieldPointerT>
244PropMap(MaskT, FieldPointerT) -> PropMap<MaskT, FieldPointerT>;
245
246/**
247 * This is an internal helper structure to wrap TPMA_* attribute bit fields.
248 *
249 * @tparam UnderlyingT the TPMA_* bit field type
250 * @tparam AttributeWrapperT the C++ struct type that wraps the TPMA_* bit field
251 * @tparam props a bunch of std::pair mapping boolean members of
252 * AttributeWrapperT to the bit masks of the TPMA_* type
253 */
254template <std::unsigned_integral UnderlyingT,
255 typename AttributeWrapperT,
258 private:
259 template <std::invocable<const PropMap<bool AttributeWrapperT::*, UnderlyingT>&> FnT>
260 static constexpr void for_all(const FnT& fn) {
261 (fn(props), ...);
262 }
263
264 static consteval bool all_single_bit_bitmasks() {
265 bool result = true;
266 for_all([&](auto&& prop) { result = result && (std::popcount(prop.mask) == 1); });
267 return result;
268 }
269
270 static_assert(all_single_bit_bitmasks(), "props... must contain single-bit flags only");
271
272 public:
273 static constexpr UnderlyingT render(AttributeWrapperT attributes) {
274 UnderlyingT result = 0;
275 for_all([&](auto&& prop) {
276 if(prop(attributes)) {
277 result |= prop.mask;
278 }
279 });
280 return result;
281 }
282
283 static constexpr AttributeWrapperT read(UnderlyingT attributes) {
284 AttributeWrapperT result;
285 for_all([&](auto&& prop) { prop(result) = (attributes & prop.mask) != 0; });
286 return result;
287 }
288};
289
290#if defined(BOTAN_HAS_RSA)
291
292/**
293 * This helper function transforms a @p public_blob in a TPM2B_PUBLIC* format
294 * into the functional components of an RSA public key. Namely, a pair of
295 * modulus and exponent as big integers.
296 *
297 * @param public_blob The public blob to decompose into RSA pubkey components
298 */
299inline std::pair<BigInt, BigInt> rsa_pubkey_components_from_tss2_public(const TPM2B_PUBLIC* public_blob) {
300 BOTAN_ASSERT_NONNULL(public_blob);
301 const auto& pub = public_blob->publicArea;
302 BOTAN_ARG_CHECK(pub.type == TPM2_ALG_RSA, "Public key is not an RSA key");
303
304 // TPM2 may report 0 when the exponent is 'the default' (2^16 + 1)
305 const auto exponent = (pub.parameters.rsaDetail.exponent == 0) ? 65537 : pub.parameters.rsaDetail.exponent;
306
307 return {BigInt(as_span(pub.unique.rsa)), exponent};
308}
309
310#endif
311
312} // namespace Botan::TPM2
313
314#endif
#define BOTAN_ASSERT_NOMSG(expr)
Definition assert.h:82
#define BOTAN_ASSERT_NONNULL(ptr)
Definition assert.h:121
#define BOTAN_ARG_CHECK(expr, msg)
Definition assert.h:33
static constexpr AttributeWrapperT read(UnderlyingT attributes)
Definition tpm2_util.h:283
static constexpr UnderlyingT render(AttributeWrapperT attributes)
Definition tpm2_util.h:273
ObjectSetter(const ObjectSetter &)=delete
constexpr ObjectSetter(Object &object, bool persistent=false)
Definition tpm2_util.h:183
ObjectSetter & operator=(ObjectSetter &&)=delete
ObjectSetter(ObjectSetter &&)=delete
constexpr ~ObjectSetter() noexcept
Definition tpm2_util.h:186
ObjectSetter & operator=(const ObjectSetter &)=delete
PropMap(MaskT, FieldPointerT) -> PropMap< MaskT, FieldPointerT >
Deduction guide to simplify the creation of PropMap instances.
constexpr T init_empty()
Create an empty TPM2 buffer of the given type.
Definition tpm2_util.h:151
constexpr void check_rc(std::string_view location, TSS2_RC rc)
Definition tpm2_util.h:53
constexpr auto out_persistent_handle(Object &object)
Definition tpm2_util.h:223
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:161
TSS2_RC get_raw_rc(TSS2_RC rc)
constexpr T init_with_size(size_t length)
Create a TPM2 buffer of a given type and length.
Definition tpm2_util.h:141
constexpr auto out_transient_handle(Object &object)
Definition tpm2_util.h:217
constexpr void copy_into(T &dest, std::span< const uint8_t > data)
Definition tpm2_util.h:116
constexpr auto as_span(tpm2_buffer auto &data)
Construct a std::span as a view into a TPM2 buffer.
Definition tpm2_util.h:101
constexpr TSS2_RC check_rc_expecting(std::string_view location, TSS2_RC rc)
Definition tpm2_util.h:71
constexpr void copy_mem(T *out, const T *in, size_t n)
Definition mem_ops.h:144
constexpr void clear_bytes(void *ptr, size_t bytes)
Definition mem_ops.h:101
std::optional< TPM2_HANDLE > persistent
Definition tpm2_util.h:170
constexpr bool operator()(const auto &object) const noexcept
Read-only access the boolean member 'field' from the given object.
Definition tpm2_util.h:239
FieldPointerT field
Definition tpm2_util.h:232
constexpr bool & operator()(auto &object) const noexcept
Access the boolean member 'field' from the given object.
Definition tpm2_util.h:236
unique_esys_ptr< TPM2B_PUBLIC > pub
Definition tpm2_util.h:164
unique_esys_ptr< TPM2B_NAME > qualified_name
Definition tpm2_util.h:166
unique_esys_ptr< TPM2B_NAME > name
Definition tpm2_util.h:165
void operator()(void *handle)
Definition tpm2_util.h:156
uint32_t ESYS_TR
Forward declaration of TSS2 type for convenience.
uint32_t TSS2_RC
Forward declaration of TSS2 type for convenience.
Definition tpm2_error.h:15