Botan 3.14.1
Crypto and TLS for C&
tpm2_crypto_backend_impl.cpp
Go to the documentation of this file.
1/*
2* TPM 2 TSS crypto callbacks backend
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/internal/tpm2_crypto_backend_impl.h>
10
11#include <botan/cipher_mode.h>
12#include <botan/hash.h>
13#include <botan/mac.h>
14#include <botan/mem_ops.h>
15#include <botan/pubkey.h>
16#include <botan/tpm2_context.h>
17#include <botan/tpm2_crypto_backend.h>
18#include <botan/tpm2_key.h>
19
20#if defined(BOTAN_HAS_RSA)
21 #include <botan/rsa.h>
22#endif
23
24#if defined(BOTAN_HAS_ECDH)
25 #include <botan/ecdh.h>
26#endif
27
28#include <botan/internal/enc_padding.h>
29#include <botan/internal/fmt.h>
30#include <botan/internal/mem_utils.h>
31#include <botan/internal/pk_options_impl.h>
32#include <botan/internal/tpm2_algo_mappings.h>
33#include <botan/internal/tpm2_util.h>
34
35#if defined(BOTAN_HAS_EME_OAEP)
36 #include <botan/internal/oaep.h>
37#endif
38
39#include <tss2/tss2_esys.h>
40#include <tss2/tss2_mu.h>
41
42#include <variant>
43
44#if defined(BOTAN_TSS2_SUPPORTS_CRYPTO_CALLBACKS)
45
46namespace {
47
48/// Holds the hash state between update callback invocations
49using DigestObject =
50 std::variant<std::unique_ptr<Botan::HashFunction>, std::unique_ptr<Botan::MessageAuthenticationCode>>;
51
52} // namespace
53
54extern "C" {
55
56/**
57 * Some ESYS crypto callbacks require to hold state between calls.
58 * This struct is forward-declared in tss2_esys.h and we're implementing it here.
59 */
60typedef struct ESYS_CRYPTO_CONTEXT_BLOB {
61 DigestObject ctx;
62} DigestCallbackState;
63
64} // extern "C"
65
66namespace {
67
68/// Safely converts the @p blob to a Botan crypto object of type @p T.
69template <typename T>
70 requires std::constructible_from<DigestObject, std::unique_ptr<T>>
71[[nodiscard]] std::optional<std::reference_wrapper<T>> get(DigestCallbackState* blob) noexcept {
72 if(!blob) {
73 return std::nullopt;
74 }
75
76 auto* ctx = std::get_if<std::unique_ptr<T>>(&blob->ctx);
77 if(ctx == nullptr) {
78 return std::nullopt;
79 }
80
81 return {std::ref(**ctx)};
82}
83
84template <typename T>
85 requires std::constructible_from<DigestObject, std::unique_ptr<T>>
86[[nodiscard]] std::optional<std::reference_wrapper<T>> get(DigestCallbackState** blob) noexcept {
87 if(!blob) {
88 return std::nullopt;
89 }
90
91 return get<T>(*blob);
92}
93
94/// Safely converts the @p userdata to the Botan crypto context object.
95[[nodiscard]] std::optional<std::reference_wrapper<Botan::TPM2::CryptoCallbackState>> get(void* userdata) noexcept {
96 if(auto* ccs = reinterpret_cast<Botan::TPM2::CryptoCallbackState*>(userdata)) {
97 return *ccs;
98 } else {
99 return std::nullopt;
100 }
101}
102
103/**
104 * Wraps the Botan-specific implementations of the TSS crypto callbacks into a
105 * try-catch block and converts encountered exceptions to TSS2_RC error codes as
106 * needed.
107 */
108template <std::invocable<> F>
109 requires std::same_as<std::invoke_result_t<F>, TSS2_RC>
110[[nodiscard]] TSS2_RC thunk(F f) noexcept {
111 try {
112 return f();
113 } catch(const Botan::Invalid_Argument&) {
114 return TSS2_ESYS_RC_BAD_VALUE;
115 } catch(const Botan::Invalid_State&) {
116 return TSS2_ESYS_RC_BAD_SEQUENCE;
117 } catch(const Botan::Lookup_Error&) {
118 return TSS2_ESYS_RC_NOT_IMPLEMENTED;
119 } catch(const Botan::Invalid_Authentication_Tag&) {
120 return TSS2_ESYS_RC_MALFORMED_RESPONSE;
121 } catch(const Botan::Exception&) {
122 return TSS2_ESYS_RC_GENERAL_FAILURE;
123 } catch(...) {
124 return TSS2_ESYS_RC_GENERAL_FAILURE;
125 }
126}
127
128/**
129 * Encrypts or decrypts @p data using the symmetric cipher specified.
130 * The bytes in @p data are encrypted/decrypted in-place.
131 */
132[[nodiscard]] TSS2_RC symmetric_algo(Botan::Cipher_Dir direction,
133 const uint8_t* key,
134 TPM2_ALG_ID tpm_sym_alg,
135 TPMI_AES_KEY_BITS key_bits,
136 TPM2_ALG_ID tpm_mode,
137 uint8_t* buffer,
138 size_t buffer_size,
139 const uint8_t* iv) noexcept {
140 return thunk([&] {
141 if(key == nullptr) {
142 return (direction == Botan::Cipher_Dir::Encryption) ? TSS2_ESYS_RC_NO_ENCRYPT_PARAM
143 : TSS2_ESYS_RC_NO_DECRYPT_PARAM;
144 }
145
146 // nullptr buffer with size 0 is alright
147 if(buffer == nullptr && buffer_size != 0) {
148 return TSS2_ESYS_RC_BAD_VALUE;
149 }
150
151 const auto cipher_name = Botan::TPM2::cipher_tss2_to_botan({
152 .algorithm = tpm_sym_alg,
153 .keyBits = {.sym = key_bits},
154 .mode = {.sym = tpm_mode},
155 });
156 if(!cipher_name) {
157 return TSS2_ESYS_RC_NOT_SUPPORTED;
158 }
159
160 auto cipher = Botan::Cipher_Mode::create(cipher_name.value(), direction);
161 if(!cipher) {
162 return TSS2_ESYS_RC_NOT_IMPLEMENTED;
163 }
164
165 // AEADs aren't supported by the crypto callback API, as there's
166 // no way to append the authentication tag to the ciphertext.
167 if(cipher->authenticated()) {
168 return TSS2_ESYS_RC_INSUFFICIENT_BUFFER;
169 }
170
171 BOTAN_ASSERT_NOMSG(key_bits % 8 == 0);
172 const size_t keylength = static_cast<size_t>(key_bits) / 8;
173 if(!cipher->valid_keylength(keylength)) {
174 return TSS2_ESYS_RC_BAD_VALUE;
175 }
176
177 const auto s_data = std::span{buffer, buffer_size};
178 const auto s_key = std::span{key, keylength};
179 const auto s_iv = [&]() -> std::span<const uint8_t> {
180 if(iv != nullptr) {
181 return {iv, cipher->default_nonce_length()};
182 } else {
183 return {};
184 }
185 }();
186
187 cipher->set_key(s_key);
188 cipher->start(s_iv);
189 cipher->process(s_data);
190 return TSS2_RC_SUCCESS;
191 });
192}
193
194extern "C" {
195
196/** Provide the context for the computation of a hash digest.
197 *
198 * The context will be created and initialized according to the hash function.
199 * @param[out] context The created context (callee-allocated).
200 * @param[in] hash_alg The hash algorithm for the creation of the context.
201 * @param[in,out] userdata information.
202 * @retval TSS2_RC_SUCCESS on success.
203 * @retval USER_DEFINED user defined errors on failure.
204 */
205TSS2_RC hash_start(ESYS_CRYPTO_CONTEXT_BLOB** context, TPM2_ALG_ID hash_alg, void* userdata) {
206 BOTAN_UNUSED(userdata);
207 return thunk([&] {
208 if(context == nullptr) {
209 return TSS2_ESYS_RC_BAD_REFERENCE;
210 }
211
212 const auto hash_name = Botan::TPM2::hash_algo_tss2_to_botan(hash_alg);
213 if(!hash_name) {
214 return TSS2_ESYS_RC_NOT_SUPPORTED;
215 }
216
217 auto hash = Botan::HashFunction::create(hash_name.value());
218 if(hash == nullptr) {
219 return TSS2_ESYS_RC_NOT_IMPLEMENTED;
220 }
221
222 // Will be deleted in hash_abort() or hash_finish()
223 *context = new DigestCallbackState{std::move(hash)}; // NOLINT(*-owning-memory)
224 return TSS2_RC_SUCCESS;
225 });
226}
227
228/** Update the digest value of a digest object from a byte buffer.
229 *
230 * The context of a digest object will be updated according to the hash
231 * algorithm of the context. <
232 * @param[in,out] context The context of the digest object which will be updated.
233 * @param[in] buffer The data for the update.
234 * @param[in] size The size of the data buffer.
235 * @param[in,out] userdata information.
236 * @retval TSS2_RC_SUCCESS on success.
237 * @retval USER_DEFINED user defined errors on failure.
238 */
239TSS2_RC hash_update(ESYS_CRYPTO_CONTEXT_BLOB* context, const uint8_t* buffer, size_t size, void* userdata) {
240 BOTAN_UNUSED(userdata);
241 return thunk([&] {
242 const auto hash = get<Botan::HashFunction>(context);
243 if(!hash) {
244 return TSS2_ESYS_RC_BAD_REFERENCE;
245 }
246
247 // nullptr buffer with size 0 is alright
248 if(buffer == nullptr && size != 0) {
249 return TSS2_ESYS_RC_BAD_VALUE;
250 }
251
252 hash->get().update(std::span{buffer, size});
253 return TSS2_RC_SUCCESS;
254 });
255}
256
257/** Get the digest value of a digest object and close the context.
258 *
259 * The digest value will written to a passed buffer and the resources of the
260 * digest object are released.
261 * @param[in,out] context The context of the digest object to be released
262 * @param[out] buffer The buffer for the digest value (caller-allocated).
263 * @param[out] size The size of the digest.
264 * @param[in,out] userdata information.
265 * @retval TSS2_RC_SUCCESS on success.
266 * @retval USER_DEFINED user defined errors on failure.
267 */
268TSS2_RC hash_finish(ESYS_CRYPTO_CONTEXT_BLOB** context, uint8_t* buffer, size_t* size, void* userdata) {
269 BOTAN_UNUSED(userdata);
270 if(size != nullptr) {
271 *size = 0;
272 }
273
274 return thunk([&] {
275 auto hash = get<Botan::HashFunction>(context);
276 if(!hash || buffer == nullptr) {
277 return TSS2_ESYS_RC_BAD_REFERENCE;
278 }
279
280 const auto digest_size = hash->get().output_length();
281 hash->get().final(std::span{buffer, digest_size});
282 if(size != nullptr) {
283 *size = digest_size;
284 }
285
286 // allocated in hash_start()
287 delete *context; // NOLINT(*-owning-memory)
288 *context = nullptr;
289 return TSS2_RC_SUCCESS;
290 });
291}
292
293/** Release the resources of a digest object.
294 *
295 * The assigned resources will be released and the context will be set to NULL.
296 * @param[in,out] context The context of the digest object.
297 * @param[in,out] userdata information.
298 */
299void hash_abort(ESYS_CRYPTO_CONTEXT_BLOB** context, void* userdata) {
300 BOTAN_UNUSED(userdata);
301 if(context != nullptr) {
302 // allocated in hash_start()
303 delete *context; // NOLINT(*-owning-memory)
304 *context = nullptr;
305 }
306}
307
308/** Provide the context an HMAC digest object from a byte buffer key.
309 *
310 * The context will be created and initialized according to the hash function
311 * and the used HMAC key.
312 * @param[out] context The created context (callee-allocated).
313 * @param[in] hash_alg The hash algorithm for the HMAC computation.
314 * @param[in] key The byte buffer of the HMAC key.
315 * @param[in] size The size of the HMAC key.
316 * @param[in,out] userdata information.
317 * @retval TSS2_RC_SUCCESS on success.
318 * @retval USER_DEFINED user defined errors on failure.
319 */
320TSS2_RC hmac_start(
321 ESYS_CRYPTO_CONTEXT_BLOB** context, TPM2_ALG_ID hash_alg, const uint8_t* key, size_t size, void* userdata) {
322 BOTAN_UNUSED(userdata);
323 return thunk([&] {
324 if(Botan::any_null_pointers(context, key)) {
325 return TSS2_ESYS_RC_BAD_REFERENCE;
326 }
327
328 const auto hash_name = Botan::TPM2::hash_algo_tss2_to_botan(hash_alg);
329 if(!hash_name) {
330 return TSS2_ESYS_RC_NOT_SUPPORTED;
331 }
332
333 auto hmac = Botan::MessageAuthenticationCode::create(Botan::fmt("HMAC({})", hash_name.value()));
334 if(hmac == nullptr) {
335 return TSS2_ESYS_RC_NOT_IMPLEMENTED;
336 }
337
338 hmac->set_key(std::span{key, size});
339
340 // Will be deleted in hmac_abort() or hmac_finish()
341 *context = new DigestCallbackState{std::move(hmac)}; // NOLINT(*-owning-memory)
342 return TSS2_RC_SUCCESS;
343 });
344}
345
346/** Update and HMAC digest value from a byte buffer.
347 *
348 * The context of a digest object will be updated according to the hash
349 * algorithm and the key of the context.
350 * @param[in,out] context The context of the digest object which will be updated.
351 * @param[in] buffer The data for the update.
352 * @param[in] size The size of the data buffer.
353 * @param[in,out] userdata information.
354 * @retval TSS2_RC_SUCCESS on success.
355 * @retval USER_DEFINED user defined errors on failure.
356 */
357TSS2_RC hmac_update(ESYS_CRYPTO_CONTEXT_BLOB* context, const uint8_t* buffer, size_t size, void* userdata) {
358 BOTAN_UNUSED(userdata);
359 return thunk([&] {
360 auto hmac = get<Botan::MessageAuthenticationCode>(context);
361 if(!hmac) {
362 return TSS2_ESYS_RC_BAD_REFERENCE;
363 }
364
365 // nullptr buffer with size 0 is alright
366 if(buffer == nullptr && size != 0) {
367 return TSS2_ESYS_RC_BAD_VALUE;
368 }
369
370 hmac->get().update(std::span{buffer, size});
371 return TSS2_RC_SUCCESS;
372 });
373}
374
375/** Write the HMAC digest value to a byte buffer and close the context.
376 *
377 * The digest value will written to a passed buffer and the resources of the
378 * HMAC object are released.
379 * @param[in,out] context The context of the HMAC object.
380 * @param[out] buffer The buffer for the digest value (caller-allocated).
381 * @param[out] size The size of the digest.
382 * @param[in,out] userdata information.
383 * @retval TSS2_RC_SUCCESS on success.
384 * @retval USER_DEFINED user defined errors on failure.
385 */
386TSS2_RC hmac_finish(ESYS_CRYPTO_CONTEXT_BLOB** context, uint8_t* buffer, size_t* size, void* userdata) {
387 BOTAN_UNUSED(userdata);
388 if(size != nullptr) {
389 *size = 0;
390 }
391
392 return thunk([&] {
393 auto hmac = get<Botan::MessageAuthenticationCode>(context);
394 if(!hmac || buffer == nullptr) {
395 return TSS2_ESYS_RC_BAD_REFERENCE;
396 }
397
398 const auto digest_size = hmac->get().output_length();
399 hmac->get().final(std::span{buffer, digest_size});
400 if(size != nullptr) {
401 *size = digest_size;
402 }
403
404 // allocated in hmac_start()
405 delete *context; // NOLINT(*-owning-memory)
406 *context = nullptr;
407 return TSS2_RC_SUCCESS;
408 });
409}
410
411/** Release the resources of an HMAC object.
412 *
413 * The assigned resources will be released and the context will be set to NULL.
414 * @param[in,out] context The context of the HMAC object.
415 * @param[in,out] userdata information.
416 */
417void hmac_abort(ESYS_CRYPTO_CONTEXT_BLOB** context, void* userdata) {
418 BOTAN_UNUSED(userdata);
419 if(context != nullptr) {
420 // allocated in hmac_start()
421 delete *context; // NOLINT(*-owning-memory)
422 *context = nullptr;
423 }
424}
425
426/** Compute random TPM2B data.
427 *
428 * The random data will be generated and written to a passed TPM2B structure.
429 * @param[out] nonce The TPM2B structure for the random data (caller-allocated).
430 * @param[in] num_bytes The number of bytes to be generated.
431 * @param[in,out] userdata information.
432 * @retval TSS2_RC_SUCCESS on success.
433 * @retval USER_DEFINED user defined errors on failure.
434 * @note: the TPM should not be used to obtain the random data
435 */
436TSS2_RC get_random2b(TPM2B_NONCE* nonce, size_t num_bytes, void* userdata) {
437 return thunk([&] {
438 auto ccs = get(userdata);
439 if(!ccs || !ccs->get().rng || Botan::any_null_pointers(nonce)) {
440 return TSS2_ESYS_RC_BAD_REFERENCE;
441 }
442
443 ccs->get().rng->randomize(Botan::TPM2::as_span(*nonce, num_bytes));
444 return TSS2_RC_SUCCESS;
445 });
446}
447
448/** Encryption of a buffer using a public (RSA) key.
449 *
450 * Encrypting a buffer using a public key is used for example during
451 * Esys_StartAuthSession in order to encrypt the salt value.
452 * @param[in] pub_tpm_key The key to be used for encryption.
453 * @param[in] in_size The size of the buffer to be encrypted.
454 * @param[in] in_buffer The data buffer to be encrypted.
455 * @param[in] max_out_size The maximum size for the output encrypted buffer.
456 * @param[out] out_buffer The encrypted buffer.
457 * @param[out] out_size The size of the encrypted output.
458 * @param[in] label The label used in the encryption scheme.
459 * @param[in,out] userdata information.
460 * @retval TSS2_RC_SUCCESS on success
461 * @retval USER_DEFINED user defined errors on failure.
462 */
463TSS2_RC rsa_pk_encrypt(TPM2B_PUBLIC* pub_tpm_key,
464 size_t in_size,
465 BYTE* in_buffer,
466 size_t max_out_size,
467 BYTE* out_buffer,
468 size_t* out_size,
469 const char* label,
470 void* userdata) {
471 if(out_size != nullptr) {
472 *out_size = 0;
473 }
474
475 // TODO: This is currently a dumpster fire of code duplication and
476 // YOLO manual padding.
477 //
478 // I'm hoping that a follow-up of Jack's work will help clean
479 // this up. See the extensive discussions in:
480 //
481 // https://github.com/randombit/botan/pull/4318#issuecomment-2297682058
482 #if defined(BOTAN_HAS_RSA)
483 auto create_eme = [&](const TPMT_RSA_SCHEME& scheme,
484 [[maybe_unused]] TPM2_ALG_ID name_algo,
485 [[maybe_unused]] TPMU_ASYM_SCHEME scheme_detail)
486 -> std::optional<std::unique_ptr<Botan::EncryptionPaddingScheme>> {
487 // OAEP is more complex by requiring a hash function and an optional
488 // label. To avoid marshalling this into Botan's algorithm descriptor
489 // we create an OAEP instance manually.
490 const auto create_oaep = [&]() -> std::optional<std::unique_ptr<Botan::EncryptionPaddingScheme>> {
491 #if defined(BOTAN_HAS_EME_OAEP)
492 // TPM Library, Part 1: Architecture, Annex B.4
493 // The RSA key's scheme hash algorithm (or, if it is TPM_ALG_NULL,
494 // the RSA key's Name algorithm) is used to compute H(label).
495 const auto label_hash = Botan::TPM2::hash_algo_tss2_to_botan(
496 (scheme_detail.oaep.hashAlg == TPM2_ALG_NULL || scheme_detail.oaep.hashAlg == TPM2_ALG_ERROR)
497 ? pub_tpm_key->publicArea.nameAlg
498 : scheme_detail.oaep.hashAlg);
499
500 // TPM Library, Part 1: Architecture, Annex B.4
501 // The mask-generation function uses the Name algorithm of the RSA
502 // key as the hash algorithm.
503 const auto mgf1_hash = Botan::TPM2::hash_algo_tss2_to_botan(name_algo);
504 if(!label_hash || !mgf1_hash) {
505 return std::nullopt; // -> not supported
506 }
507
508 auto H_label = Botan::HashFunction::create(label_hash.value());
509 auto H_mgf1 = Botan::HashFunction::create(mgf1_hash.value());
510 if(!H_label || !H_mgf1) {
511 return nullptr; // -> not implemented
512 }
513
514 // TPM Library, Part 1: Architecture, Annex B.4
515 // [...] is used to compute lhash := H(label), and the null
516 // termination octet is included in the digest.
517 const std::string_view label_with_zero_terminator{label, std::strlen(label) + 1};
518 return std::make_unique<Botan::OAEP>(std::move(H_label), std::move(H_mgf1), label_with_zero_terminator);
519 #else
520 BOTAN_UNUSED(label);
521 return nullptr; // -> not implemented
522 #endif
523 };
524
525 try { // EncryptionPaddingScheme::create_or_throw throws if algorithm is not available
526 switch(scheme.scheme) {
527 case TPM2_ALG_OAEP:
528 return create_oaep();
529 case TPM2_ALG_NULL:
532 case TPM2_ALG_RSAES:
535 default:
536 return std::nullopt; // -> not supported
537 }
538 } catch(const Botan::Lookup_Error&) {
539 /* ignore */
540 }
541
542 return nullptr; // -> not implemented (EncryptionPaddingScheme::create_or_throw() threw)
543 };
544
545 return thunk([&] {
546 auto ccs = get(userdata);
547 if(!ccs || !ccs->get().rng || Botan::any_null_pointers(pub_tpm_key, in_buffer, out_buffer)) {
548 return TSS2_ESYS_RC_BAD_REFERENCE;
549 }
550
551 Botan::RandomNumberGenerator& rng = *ccs->get().rng;
552
553 BOTAN_ASSERT_NOMSG(pub_tpm_key->publicArea.type == TPM2_ALG_RSA);
554
555 const auto maybe_eme = create_eme(pub_tpm_key->publicArea.parameters.rsaDetail.scheme,
556 pub_tpm_key->publicArea.nameAlg,
557 pub_tpm_key->publicArea.parameters.rsaDetail.scheme.details);
558 if(!maybe_eme.has_value()) {
559 return TSS2_ESYS_RC_NOT_SUPPORTED;
560 }
561
562 const auto& eme = maybe_eme.value();
563 if(!eme) {
564 return TSS2_ESYS_RC_NOT_IMPLEMENTED;
565 }
566
567 // The code below is duplicated logic with Botan's PK_Encryptor_EME.
568 // Currently, there's no way to instantiate the encryptor without
569 // marshalling the optional `label` into Botan's algorithm name.
570 //
571 // The label contains characters that are not allowed in Botan's string-
572 // based algorithm names, namely the \0 terminator. We currently handle
573 // the padding manually and then encrypt the padded data with raw RSA.
574 //
575 // TODO: Provide a way to instantiate an PK_Encryptor_EME that accepts a
576 // pre-made EME object. See: https://github.com/randombit/botan/pull/4318
577
578 const auto pubkey = Botan::TPM2::rsa_pubkey_from_tss2_public(pub_tpm_key);
579 const auto keybits = pubkey.key_length();
580 const auto output_size = keybits / 8;
581 if(eme->maximum_input_size(keybits) < in_size) {
582 return TSS2_ESYS_RC_BAD_VALUE;
583 }
584
585 if(output_size > max_out_size) {
586 return TSS2_ESYS_RC_INSUFFICIENT_BUFFER;
587 }
588
589 const auto max_raw_bits = keybits - 1;
590 const auto max_raw_bytes = (max_raw_bits + 7) / 8;
591 const auto padded_bytes = eme->pad({out_buffer, max_raw_bytes}, {in_buffer, in_size}, max_raw_bits, rng);
592
593 // PK_Encryptor_EME does not provide a way to pass in an output buffer.
594 // TODO: provide an `.encrypt()` overload that accepts an output buffer.
595 const Botan::PK_Encryptor_EME encryptor(pubkey, rng, "Raw");
596 const auto encrypted = encryptor.encrypt({out_buffer, padded_bytes}, rng);
597 BOTAN_DEBUG_ASSERT(encrypted.size() == output_size);
598
599 // We abused the `out_buffer` to hold the result of the padding. Hence, we
600 // now have to copy the encrypted data over the padded plaintext data.
601 Botan::copy_mem(std::span{out_buffer, encrypted.size()}, encrypted);
602 if(out_size != nullptr) {
603 *out_size = encrypted.size();
604 }
605
606 return TSS2_RC_SUCCESS;
607 });
608 #else
609 BOTAN_UNUSED(pub_tpm_key, in_size, in_buffer, max_out_size, out_buffer, label, userdata);
610 return TSS2_ESYS_RC_NOT_IMPLEMENTED;
611 #endif
612}
613
614/** Computation of an ephemeral ECC key and shared secret Z.
615 *
616 * According to the description in TPM spec part 1 C 6.1 a shared secret
617 * between application and TPM is computed (ECDH). An ephemeral ECC key and a
618 * TPM key are used for the ECDH key exchange.
619 * @param[in] key The key to be used for ECDH key exchange.
620 * @param[in] max_out_size the max size for the output of the public key of the
621 * computed ephemeral key.
622 * @param[out] Z The computed shared secret.
623 * @param[out] Q The public part of the ephemeral key in TPM format.
624 * @param[out] out_buffer The public part of the ephemeral key will be marshaled
625 * to this buffer.
626 * @param[out] out_size The size of the marshaled output.
627 * @param[in,out] userdata information.
628 * @retval TSS2_RC_SUCCESS on success
629 * @retval USER_DEFINED user defined errors on failure.
630 */
631TSS2_RC get_ecdh_point(TPM2B_PUBLIC* key,
632 size_t max_out_size,
633 TPM2B_ECC_PARAMETER* Z,
634 TPMS_ECC_POINT* Q,
635 BYTE* out_buffer,
636 size_t* out_size,
637 void* userdata) {
638 if(out_size != nullptr) {
639 *out_size = 0;
640 }
641
642 #if defined(BOTAN_HAS_ECDH)
643 return thunk([&] {
644 auto ccs = get(userdata);
645 if(!ccs || !ccs->get().rng || Botan::any_null_pointers(key, Z, Q, out_buffer)) {
646 return TSS2_ESYS_RC_BAD_REFERENCE;
647 }
648
649 Botan::RandomNumberGenerator& rng = *ccs->get().rng;
650
651 // 1: Get TPM public key
652 const auto [tpm_ec_group, tpm_ec_point] = Botan::TPM2::ecc_pubkey_from_tss2_public(key);
653 const auto tpm_sw_pubkey = Botan::ECDH_PublicKey(tpm_ec_group, tpm_ec_point);
654
655 const auto curve_order_byte_size = tpm_sw_pubkey.domain().get_p_bytes();
656
657 // 2: Generate ephemeral key
658 const auto eph_key = Botan::ECDH_PrivateKey(rng, tpm_sw_pubkey.domain());
659
660 // Serialize public key coordinates into TPM2B_ECC_PARAMETER with Big Endian encoding.
661 // This ensures bn_{x,y}.bytes() <= curve_order_byte_size.
662 const auto& eph_pub_point = eph_key.public_ec_point();
663 eph_pub_point.serialize_x_to(Botan::TPM2::as_span(Q->x, curve_order_byte_size));
664 eph_pub_point.serialize_y_to(Botan::TPM2::as_span(Q->y, curve_order_byte_size));
665
666 // 3: ECDH Key Agreement
667 const Botan::PK_Key_Agreement ecdh(eph_key, rng, Botan::PK_Key_Agreement_Options().with_raw_shared_key());
668 const auto shared_secret = ecdh.derive_key(0 /*Ignored for raw KDF*/, tpm_sw_pubkey.public_value()).bits_of();
669
670 Botan::TPM2::copy_into(*Z, shared_secret);
671
672 Botan::TPM2::check_rc("Tss2_MU_TPMS_ECC_POINT_Marshal",
673 Tss2_MU_TPMS_ECC_POINT_Marshal(Q, out_buffer, max_out_size, out_size));
674
675 return TSS2_RC_SUCCESS;
676 });
677 #else
678 BOTAN_UNUSED(key, max_out_size, Z, Q, out_buffer, userdata);
679 return TSS2_ESYS_RC_NOT_IMPLEMENTED;
680 #endif
681}
682
683// The signatures of these callbacks are dictated by the TSS2 crypto callback interface
684// NOLINTBEGIN(*-const-correctness)
685
686/** Encrypt data with AES.
687 *
688 * @param[in] key key used for AES.
689 * @param[in] tpm_sym_alg AES type in TSS2 notation (must be TPM2_ALG_AES).
690 * @param[in] key_bits Key size in bits.
691 * @param[in] tpm_mode Block cipher mode of operation in TSS2 notation (CFB).
692 * For parameter encryption only CFB can be used.
693 * @param[in,out] buffer Data to be encrypted. The encrypted date will be stored
694 * in this buffer.
695 * @param[in] buffer_size size of data to be encrypted.
696 * @param[in] iv The initialization vector.
697 * @param[in,out] userdata information.
698 * @retval TSS2_RC_SUCCESS on success
699 * @retval USER_DEFINED user defined errors on failure.
700 */
701TSS2_RC aes_encrypt(uint8_t* key,
702 TPM2_ALG_ID tpm_sym_alg,
703 TPMI_AES_KEY_BITS key_bits,
704 TPM2_ALG_ID tpm_mode,
705 uint8_t* buffer,
706 size_t buffer_size,
707 uint8_t* iv,
708 void* userdata) {
709 BOTAN_UNUSED(userdata);
710 if(tpm_sym_alg != TPM2_ALG_AES) {
711 return TSS2_ESYS_RC_BAD_VALUE;
712 }
713
714 return symmetric_algo(Botan::Cipher_Dir::Encryption, key, tpm_sym_alg, key_bits, tpm_mode, buffer, buffer_size, iv);
715}
716
717/** Decrypt data with AES.
718 *
719 * @param[in] key key used for AES.
720 * @param[in] tpm_sym_alg AES type in TSS2 notation (must be TPM2_ALG_AES).
721 * @param[in] key_bits Key size in bits.
722 * @param[in] tpm_mode Block cipher mode of operation in TSS2 notation (CFB).
723 * For parameter encryption only CFB can be used.
724 * @param[in,out] buffer Data to be decrypted. The decrypted date will be stored
725 * in this buffer.
726 * @param[in] buffer_size size of data to be encrypted.
727 * @param[in] iv The initialization vector.
728 * @param[in,out] userdata information.
729 * @retval TSS2_RC_SUCCESS on success
730 * @retval USER_DEFINED user defined errors on failure.
731 */
732TSS2_RC aes_decrypt(uint8_t* key,
733 TPM2_ALG_ID tpm_sym_alg,
734 TPMI_AES_KEY_BITS key_bits,
735 TPM2_ALG_ID tpm_mode,
736 uint8_t* buffer,
737 size_t buffer_size,
738 uint8_t* iv,
739 void* userdata) {
740 BOTAN_UNUSED(userdata);
741 if(tpm_sym_alg != TPM2_ALG_AES) {
742 return TSS2_ESYS_RC_BAD_VALUE;
743 }
744
745 return symmetric_algo(Botan::Cipher_Dir::Decryption, key, tpm_sym_alg, key_bits, tpm_mode, buffer, buffer_size, iv);
746}
747
748// NOLINTEND(*-const-correctness)
749
750 #if defined(BOTAN_TSS2_SUPPORTS_SM4_IN_CRYPTO_CALLBACKS)
751
752// NOLINTBEGIN(*-const-correctness)
753
754/** Encrypt data with SM4.
755 *
756 * @param[in] key key used for SM4.
757 * @param[in] tpm_sym_alg SM4 type in TSS2 notation (must be TPM2_ALG_SM4).
758 * @param[in] key_bits Key size in bits.
759 * @param[in] tpm_mode Block cipher mode of operation in TSS2 notation (CFB).
760 * For parameter encryption only CFB can be used.
761 * @param[in,out] buffer Data to be encrypted. The encrypted date will be stored
762 * in this buffer.
763 * @param[in] buffer_size size of data to be encrypted.
764 * @param[in] iv The initialization vector.
765 * @param[in,out] userdata information.
766 * @retval TSS2_RC_SUCCESS on success
767 * @retval USER_DEFINED user defined errors on failure.
768 */
769TSS2_RC sm4_encrypt(uint8_t* key,
770 TPM2_ALG_ID tpm_sym_alg,
771 TPMI_SM4_KEY_BITS key_bits,
772 TPM2_ALG_ID tpm_mode,
773 uint8_t* buffer,
774 size_t buffer_size,
775 uint8_t* iv,
776 void* userdata) {
777 BOTAN_UNUSED(userdata);
778 if(tpm_sym_alg != TPM2_ALG_SM4) {
779 return TSS2_ESYS_RC_BAD_VALUE;
780 }
781
782 return symmetric_algo(Botan::Cipher_Dir::Encryption, key, tpm_sym_alg, key_bits, tpm_mode, buffer, buffer_size, iv);
783}
784
785/** Decrypt data with SM4.
786 *
787 * @param[in] key key used for SM4.
788 * @param[in] tpm_sym_alg SM4 type in TSS2 notation (must be TPM2_ALG_SM4).
789 * @param[in] key_bits Key size in bits.
790 * @param[in] tpm_mode Block cipher mode of operation in TSS2 notation (CFB).
791 * For parameter encryption only CFB can be used.
792 * @param[in,out] buffer Data to be decrypted. The decrypted date will be stored
793 * in this buffer.
794 * @param[in] buffer_size size of data to be encrypted.
795 * @param[in] iv The initialization vector.
796 * @param[in,out] userdata information.
797 * @retval TSS2_RC_SUCCESS on success
798 * @retval USER_DEFINED user defined errors on failure.
799 */
800TSS2_RC sm4_decrypt(uint8_t* key,
801 TPM2_ALG_ID tpm_sym_alg,
802 TPMI_SM4_KEY_BITS key_bits,
803 TPM2_ALG_ID tpm_mode,
804 uint8_t* buffer,
805 size_t buffer_size,
806 uint8_t* iv,
807 void* userdata) {
808 BOTAN_UNUSED(userdata);
809 if(tpm_sym_alg != TPM2_ALG_SM4) {
810 return TSS2_ESYS_RC_BAD_VALUE;
811 }
812
813 return symmetric_algo(Botan::Cipher_Dir::Decryption, key, tpm_sym_alg, key_bits, tpm_mode, buffer, buffer_size, iv);
814}
815
816 // NOLINTEND(*-const-correctness)
817
818 #endif /* TPM2_ALG_SM4 */
819
820/** Initialize crypto backend.
821 *
822 * Initialize internal tables of crypto backend.
823 *
824 * @param[in,out] userdata Optional userdata pointer.
825 *
826 * @retval TSS2_RC_SUCCESS ong success.
827 * @retval USER_DEFINED user defined errors on failure.
828 */
829TSS2_RC init(void* userdata) {
830 BOTAN_UNUSED(userdata);
831 return TSS2_RC_SUCCESS;
832}
833
834} // extern "C"
835
836} // namespace
837
838#endif /* BOTAN_TSS2_SUPPORTS_CRYPTO_CALLBACKS */
839
840namespace Botan::TPM2 {
841
842/**
843 * Enable the Botan crypto callbacks for the given ESYS context.
844 *
845 * The callbacks may maintain two types of state:
846 *
847 * * 'userdata' is a pointer to a CryptoCallbackState object that is passed
848 * to all callback functions. This provides access to a random
849 * number generator specified by the user.
850 * The lifetime of this object is bound to the TPM2::Context.
851 *
852 * * 'context' is a pointer to a DigestCallbackState object that contains
853 * either a HashFunction or a MessageAuthenticationCode object.
854 * This holds the hash state between update callback invocations.
855 * The lifetime of this object is bound to the digest callbacks,
856 * hence *_finish() and *_abort() will delete the object.
857 *
858 * The runtime crypto backend is available since TSS2 4.0.0 and later. Explicit
859 * support for SM4 was added in TSS2 4.1.0.
860 *
861 * Note that the callback implementations should be defensive in regard to the
862 * input parameters. All pointers should be checked for nullptr before being
863 * dereferenced. Some output parameters (e.g. out-buffer lengths) may be
864 * regarded as optional, and should be checked for nullptr before being written
865 * to.
866 *
867 * Error code conventions:
868 *
869 * * TSS2_ESYS_RC_BAD_REFERENCE: reference (typically userdata) invalid
870 * * TSS2_ESYS_RC_BAD_VALUE: invalid input (e.g. size != 0 w/ nullptr buffer)
871 * * TSS2_ESYS_RC_NOT_SUPPORTED: algorithm identifier not mapped to Botan
872 * * TSS2_ESYS_RC_NOT_IMPLEMENTED: algorithm not available (e.g. disabled)
873 */
874void set_crypto_callbacks(ESYS_CONTEXT* ctx, void* callback_state) {
875#if defined(BOTAN_TSS2_SUPPORTS_CRYPTO_CALLBACKS)
877
878 // clang-format off
879 ESYS_CRYPTO_CALLBACKS callbacks{
880 .rsa_pk_encrypt = &rsa_pk_encrypt,
881 .hash_start = &hash_start,
882 .hash_update = &hash_update,
883 .hash_finish = &hash_finish,
884 .hash_abort = &hash_abort,
885 .hmac_start = &hmac_start,
886 .hmac_update = &hmac_update,
887 .hmac_finish = &hmac_finish,
888 .hmac_abort = &hmac_abort,
889 .get_random2b = &get_random2b,
890 .get_ecdh_point = &get_ecdh_point,
891 .aes_encrypt = &aes_encrypt,
892 .aes_decrypt = &aes_decrypt,
893#if defined(BOTAN_TSS2_SUPPORTS_SM4_IN_CRYPTO_CALLBACKS)
894 .sm4_encrypt = &sm4_encrypt,
895 .sm4_decrypt = &sm4_decrypt,
896#endif
897 .init = &init,
898 .userdata = callback_state,
899 };
900 // clang-format on
901
902 check_rc("Esys_SetCryptoCallbacks", Esys_SetCryptoCallbacks(ctx, &callbacks));
903#else
904 BOTAN_UNUSED(ctx, callback_state);
905 throw Not_Implemented(
906 "This build of botan was compiled with a TSS2 version lower than 4.0.0, "
907 "which does not support custom runtime crypto backends");
908#endif
909}
910
911} // namespace Botan::TPM2
#define BOTAN_UNUSED
Definition assert.h:151
#define BOTAN_ASSERT_NOMSG(expr)
Definition assert.h:82
#define BOTAN_DEBUG_ASSERT(expr)
Definition assert.h:136
#define BOTAN_ASSERT_NONNULL(ptr)
Definition assert.h:121
static std::unique_ptr< Cipher_Mode > create(std::string_view algo, Cipher_Dir direction, std::string_view provider="")
static std::unique_ptr< EncryptionPaddingScheme > create_or_throw(const PK_Encryption_Options_Reader &options)
static std::unique_ptr< HashFunction > create(std::string_view algo_spec, std::string_view provider="")
Definition hash.cpp:112
static std::unique_ptr< MessageAuthenticationCode > create(std::string_view algo_spec, std::string_view provider="")
Definition mac.cpp:51
static PK_Encryption_Options_Reader read(const PK_Encryption_Options &options)
constexpr void check_rc(std::string_view location, TSS2_RC rc)
Definition tpm2_util.h:53
std::optional< std::string > hash_algo_tss2_to_botan(TPMI_ALG_HASH hash_id)
std::optional< std::string > cipher_tss2_to_botan(TPMT_SYM_DEF cipher_def)
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
void set_crypto_callbacks(ESYS_CONTEXT *ctx, void *callback_state)
std::string fmt(std::string_view format, const T &... args)
Definition fmt.h:53
constexpr void copy_mem(T *out, const T *in, size_t n)
Definition mem_ops.h:144
bool any_null_pointers(Ptrs... ptr)
Definition mem_utils.h:54
uint32_t TSS2_RC
Forward declaration of TSS2 type for convenience.
Definition tpm2_error.h:15