• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

randombit / botan / 16077392360

04 Jul 2025 03:06PM UTC coverage: 90.57% (-0.001%) from 90.571%
16077392360

push

github

web-flow
Merge pull request #4957 from randombit/jack/fix-clang-tidy-hicpp-explicit-conversions

Enable and fix clang-tidy hicpp-explicit-conversions warning

99059 of 109373 relevant lines covered (90.57%)

12389204.35 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

95.23
/src/tests/test_tpm2.cpp
1
/*
2
* (C) 2024 Jack Lloyd
3
* (C) 2024 René Meusel, Amos Treiber Rohde & Schwarz Cybersecurity
4
*
5
* Botan is released under the Simplified BSD License (see license.txt)
6
*/
7

8
#include "tests.h"
9

10
#include <botan/internal/fmt.h>
11
#include <botan/internal/loadstor.h>
12
#include <botan/internal/stl_util.h>
13

14
#if defined(BOTAN_HAS_TPM2)
15
   #include <botan/internal/tpm2_hash.h>
16

17
   #include <botan/pubkey.h>
18
   #include <botan/tpm2_key.h>
19
   #include <botan/tpm2_rng.h>
20
   #include <botan/tpm2_session.h>
21

22
   #if defined(BOTAN_HAS_TPM2_RSA_ADAPTER)
23
      #include <botan/tpm2_rsa.h>
24
   #endif
25

26
   #if defined(BOTAN_HAS_TPM2_ECC_ADAPTER)
27
      #include <botan/ecdsa.h>
28
      #include <botan/tpm2_ecc.h>
29
   #endif
30

31
   #if defined(BOTAN_HAS_TPM2_CRYPTO_BACKEND)
32
      #include <botan/tpm2_crypto_backend.h>
33
   #endif
34

35
   // for testing externally-provided ESYS context
36
   #include <tss2/tss2_esys.h>
37
   #include <tss2/tss2_tctildr.h>
38
#endif
39

40
namespace Botan_Tests {
41

42
#if defined(BOTAN_HAS_TPM2)
43
namespace {
44

45
   #if defined(BOTAN_HAS_TPM2_CRYPTO_BACKEND) && defined(BOTAN_TSS2_SUPPORTS_CRYPTO_CALLBACKS)
46
constexpr bool crypto_backend_should_be_available = true;
47
   #else
48
constexpr bool crypto_backend_should_be_available = false;
49
   #endif
50

51
bool validate_context_environment(const std::shared_ptr<Botan::TPM2::Context>& ctx) {
10✔
52
   return (ctx->vendor() == "SW   TPM" && ctx->manufacturer() == "IBM");
10✔
53
}
54

55
std::shared_ptr<Botan::TPM2::Context> get_tpm2_context(std::string_view rng_tag) {
7✔
56
   const auto tcti_name = Test::options().tpm2_tcti_name();
7✔
57
   if(tcti_name.value() == "disabled") {
7✔
58
      // skip the test if the special 'disabled' TCTI is configured
59
      return {};
×
60
   }
61

62
   auto ctx = Botan::TPM2::Context::create(tcti_name, Test::options().tpm2_tcti_conf());
14✔
63
   if(!validate_context_environment(ctx)) {
7✔
64
      return {};
×
65
   }
66

67
   if(ctx->supports_botan_crypto_backend()) {
7✔
68
      ctx->use_botan_crypto_backend(Test::new_rng(rng_tag));
21✔
69
   }
70

71
   return ctx;
7✔
72
}
14✔
73

74
/// RAII helper to manage raw transient resources (ESYS_TR) handles
75
class TR {
76
   private:
77
      ESYS_CONTEXT* m_esys_ctx;
78
      ESYS_TR m_handle;
79

80
   public:
81
      TR(ESYS_CONTEXT* esys_ctx, ESYS_TR handle) : m_esys_ctx(esys_ctx), m_handle(handle) {}
4✔
82

83
      TR(TR&& other) noexcept { *this = std::move(other); }
4✔
84

85
      TR& operator=(TR&& other) noexcept {
4✔
86
         if(this != &other) {
4✔
87
            m_esys_ctx = other.m_esys_ctx;
4✔
88
            m_handle = std::exchange(other.m_handle, ESYS_TR_NONE);
4✔
89
         }
90
         return *this;
4✔
91
      }
92

93
      TR(const TR&) = delete;
94
      TR& operator=(const TR&) = delete;
95

96
      ~TR() {
8✔
97
         if(m_esys_ctx && m_handle != ESYS_TR_NONE) {
4✔
98
            Esys_FlushContext(m_esys_ctx, m_handle);
4✔
99
         }
100
      }
101

102
      // NOLINTNEXTLINE(*-explicit-conversions) FIXME
103
      constexpr operator ESYS_TR() const { return m_handle; }
3✔
104
};
105

106
struct esys_context_liberator {
107
      void operator()(ESYS_CONTEXT* esys_ctx) {
3✔
108
         TSS2_TCTI_CONTEXT* tcti_ctx = nullptr;
3✔
109
         Esys_GetTcti(esys_ctx, &tcti_ctx);  // ignore error in destructor
3✔
110
         if(tcti_ctx != nullptr) {
3✔
111
            Tss2_TctiLdr_Finalize(&tcti_ctx);
3✔
112
         }
113
         Esys_Finalize(&esys_ctx);
3✔
114
      }
3✔
115
};
116

117
auto get_external_tpm2_context() -> std::unique_ptr<ESYS_CONTEXT, esys_context_liberator> {
3✔
118
   const auto tcti_name = Test::options().tpm2_tcti_name();
3✔
119
   const auto tcti_conf = Test::options().tpm2_tcti_conf();
3✔
120
   if(tcti_name.value() == "disabled") {
3✔
121
      // skip the test if the special 'disabled' TCTI is configured
122
      return nullptr;
×
123
   }
124

125
   TSS2_RC rc;
3✔
126
   TSS2_TCTI_CONTEXT* tcti_ctx;
3✔
127
   std::unique_ptr<ESYS_CONTEXT, esys_context_liberator> esys_ctx;
3✔
128

129
   rc = Tss2_TctiLdr_Initialize_Ex(tcti_name->c_str(), tcti_conf->c_str(), &tcti_ctx);
3✔
130
   if(rc != TSS2_RC_SUCCESS) {
3✔
131
      throw Test_Error("failed to initialize external TCTI");
×
132
   }
133

134
   rc = Esys_Initialize(Botan::out_ptr(esys_ctx), tcti_ctx, nullptr /* ABI version */);
3✔
135
   if(rc != TSS2_RC_SUCCESS) {
3✔
136
      throw Test_Error("failed to initialize external ESYS");
×
137
   }
138

139
   // This TPM2::Context is created for environment validation only.
140
   // It is transient, but the 'externally provided' ESYS_CONTEXT will live on!
141
   auto ctx = Botan::TPM2::Context::create(esys_ctx.get());
3✔
142
   if(!validate_context_environment(ctx)) {
3✔
143
      return nullptr;
×
144
   }
145

146
   return esys_ctx;
3✔
147
}
9✔
148

149
void bail_out(Test::Result& result, std::optional<std::string> reason = {}) {
×
150
   if(reason.has_value()) {
×
151
      result.test_note(reason.value());
×
152
   } else if(Test::options().tpm2_tcti_name() == "disabled") {
×
153
      result.test_note("TPM2 tests are disabled.");
×
154
   } else {
155
      result.test_failure("Not sure we're on a simulated TPM2, cautiously refusing any action.");
×
156
   }
157
}
×
158

159
Test::Result bail_out() {
×
160
   Test::Result result("TPM2 test bail out");
×
161
   bail_out(result);
×
162
   return result;
×
163
}
×
164

165
bool not_zero_64(std::span<const uint8_t> in) {
6✔
166
   Botan::BufferSlicer bs(in);
6✔
167

168
   while(bs.remaining() > 8) {
78✔
169
      if(Botan::load_be(bs.take<8>()) == 0) {
144✔
170
         return false;
171
      }
172
   }
173
   // Ignore remaining bytes
174

175
   return true;
176
}
177

178
std::vector<Test::Result> test_tpm2_properties() {
1✔
179
   auto ctx = get_tpm2_context(__func__);
1✔
180
   if(!ctx) {
1✔
181
      return {bail_out()};
×
182
   }
183

184
   return {
1✔
185
      CHECK("Vendor and Manufacturer",
186
            [&](Test::Result& result) {
1✔
187
               result.test_eq("Vendor", ctx->vendor(), "SW   TPM");
2✔
188
               result.test_eq("Manufacturer", ctx->manufacturer(), "IBM");
2✔
189
            }),
1✔
190

191
      CHECK("Max random bytes per request",
192
            [&](Test::Result& result) {
1✔
193
               const auto prop = ctx->max_random_bytes_per_request();
1✔
194
               result.test_gte("at least as long as SHA-256", prop, 32);
1✔
195
               result.test_lte("at most as long as SHA-512", prop, 64);
1✔
196
            }),
1✔
197

198
      CHECK("Supports basic algorithms",
199
            [&](Test::Result& result) {
1✔
200
               result.confirm("RSA is supported", ctx->supports_algorithm("RSA"));
2✔
201
               result.confirm("AES-128 is supported", ctx->supports_algorithm("AES-128"));
2✔
202
               result.confirm("AES-256 is supported", ctx->supports_algorithm("AES-256"));
2✔
203
               result.confirm("SHA-1 is supported", ctx->supports_algorithm("SHA-1"));
2✔
204
               result.confirm("SHA-256 is supported", ctx->supports_algorithm("SHA-256"));
2✔
205
               result.confirm("OFB(AES-128) is supported", ctx->supports_algorithm("OFB(AES-128)"));
2✔
206
               result.confirm("OFB is supported", ctx->supports_algorithm("OFB"));
2✔
207
            }),
1✔
208

209
      CHECK("Unsupported algorithms aren't supported",
210
            [&](Test::Result& result) {
1✔
211
               result.confirm("Enigma is not supported", !ctx->supports_algorithm("Enigma"));
2✔
212
               result.confirm("MD5 is not supported", !ctx->supports_algorithm("MD5"));
2✔
213
               result.confirm("DES is not supported", !ctx->supports_algorithm("DES"));
2✔
214
               result.confirm("OAEP(Keccak) is not supported", !ctx->supports_algorithm("OAEP(Keccak)"));
2✔
215
            }),
1✔
216
   };
5✔
217
}
2✔
218

219
std::vector<Test::Result> test_tpm2_context() {
1✔
220
   auto ctx = get_tpm2_context(__func__);
1✔
221
   if(!ctx) {
1✔
222
      return {bail_out()};
×
223
   }
224

225
   const auto persistent_key_id = Test::options().tpm2_persistent_rsa_handle();
1✔
226

227
   return {
1✔
228
      CHECK("Persistent handles",
229
            [&](Test::Result& result) {
1✔
230
               const auto handles = ctx->persistent_handles();
1✔
231
               result.confirm("At least one persistent handle", !handles.empty());
2✔
232
               result.confirm("SRK is in the list", Botan::value_exists(handles, 0x81000001));
3✔
233
               result.confirm("Test private key is in the list", Botan::value_exists(handles, persistent_key_id));
3✔
234
               result.confirm("Test persistence location is not in the list",
1✔
235
                              !Botan::value_exists(handles, persistent_key_id + 1));
3✔
236
            }),
1✔
237

238
         CHECK("Crypto backend",
239
               [&](Test::Result& result) {
1✔
240
                  const bool backend_supported = ctx->supports_botan_crypto_backend();
1✔
241
                  const bool backend_used = ctx->uses_botan_crypto_backend();
1✔
242
                  result.require("Crypto backend availability",
1✔
243
                                 backend_supported == crypto_backend_should_be_available);
244
                  result.require("Crypto backend is used in the tests, if it is available",
1✔
245
                                 backend_used == backend_supported);
246

247
                  if(backend_used) {
1✔
248
                     result.test_throws<Botan::Invalid_State>(
3✔
249
                        "If the backend is already in use, we cannot enable it once more",
250
                        [&] { ctx->use_botan_crypto_backend(Test::new_rng(__func__)); });
4✔
251
                  }
252

253
                  if(!backend_supported) {
1✔
254
                     result.test_throws<Botan::Not_Implemented>(
×
255
                        "If the backend is not supported, we cannot enable it",
256
                        [&] { ctx->use_botan_crypto_backend(Test::new_rng(__func__)); });
×
257
                  }
258
               }),
1✔
259

260
   #if defined(BOTAN_HAS_TPM2_RSA_ADAPTER)
261
         // TODO: Since SRK is always RSA in start_tpm2_simulator.sh, the test always requires the RSA adapter?
262
         CHECK("Fetch Storage Root Key RSA", [&](Test::Result& result) {
1✔
263
            auto srk = ctx->storage_root_key({}, {});
2✔
264
            result.require("SRK is not null", srk != nullptr);
1✔
265
            result.test_eq("Algo", srk->algo_name(), "RSA");
2✔
266
            result.test_eq("Key size", srk->key_length(), 2048);
1✔
267
            result.confirm("Has persistent handle", srk->handles().has_persistent_handle());
2✔
268
         }),
1✔
269
   #endif
270
   };
4✔
271
}
2✔
272

273
std::vector<Test::Result> test_external_tpm2_context() {
1✔
274
   auto raw_start_session = [](ESYS_CONTEXT* esys_ctx) -> std::pair<TR, TSS2_RC> {
5✔
275
      const TPMT_SYM_DEF sym_spec{
4✔
276
         .algorithm = TPM2_ALG_AES,
277
         .keyBits = {.sym = 256},
278
         .mode = {.sym = TPM2_ALG_CFB},
279
      };
280
      ESYS_TR session;
4✔
281

282
      auto rc = Esys_StartAuthSession(esys_ctx,
4✔
283
                                      ESYS_TR_NONE,
284
                                      ESYS_TR_NONE,
285
                                      ESYS_TR_NONE,
286
                                      ESYS_TR_NONE,
287
                                      ESYS_TR_NONE,
288
                                      nullptr,
289
                                      TPM2_SE_HMAC,
290
                                      &sym_spec,
291
                                      TPM2_ALG_SHA256,
292
                                      &session);
4✔
293

294
      if(rc == TSS2_RC_SUCCESS) {
4✔
295
         const auto session_attributes = TPMA_SESSION_CONTINUESESSION | TPMA_SESSION_DECRYPT | TPMA_SESSION_ENCRYPT;
3✔
296
         rc = Esys_TRSess_SetAttributes(esys_ctx, session, session_attributes, 0xFF);
3✔
297
      }
298

299
      return {TR{esys_ctx, session}, rc};
4✔
300
   };
301

302
   auto raw_get_random_bytes = [](ESYS_CONTEXT* esys_ctx, uint16_t bytes, ESYS_TR session = ESYS_TR_NONE) {
4✔
303
      Botan::TPM2::unique_esys_ptr<TPM2B_DIGEST> random_bytes;
3✔
304
      const auto rc =
3✔
305
         Esys_GetRandom(esys_ctx, session, ESYS_TR_NONE, ESYS_TR_NONE, bytes, Botan::out_ptr(random_bytes));
3✔
306
      return std::make_pair(std::move(random_bytes), rc);
3✔
307
   };
3✔
308

309
   return {
1✔
310
      CHECK("ESYS context is still functional after TPM2::Context destruction",
311
            [&](Test::Result& result) {
1✔
312
               auto esys_ctx = get_external_tpm2_context();
1✔
313
               if(!esys_ctx) {
1✔
314
                  bail_out(result);
×
315
                  return;
×
316
               }
317

318
               {
1✔
319
                  // Do some TPM2-stuff via the Botan wrappers
320

321
                  auto ctx = Botan::TPM2::Context::create(esys_ctx.get());
1✔
322
                  auto session = Botan::TPM2::Session::unauthenticated_session(ctx);
1✔
323
                  auto rng = Botan::TPM2::RandomNumberGenerator(ctx, session);
3✔
324

325
                  auto bytes = rng.random_vec(16);
1✔
326
                  result.test_eq("some random bytes generated", bytes.size(), 16);
2✔
327

328
                  // All Botan-wrapped things go out of scope...
329
               }
2✔
330

331
               auto [raw_session, rc_session] = raw_start_session(esys_ctx.get());
1✔
332
               Botan::TPM2::check_rc("session creation successful", rc_session);
1✔
333

334
               auto [bytes, rc_random] = raw_get_random_bytes(esys_ctx.get(), 16, raw_session);
1✔
335
               Botan::TPM2::check_rc("random byte generation successful", rc_random);
1✔
336
               result.test_eq_sz("some raw random bytes generated", bytes->size, 16);
2✔
337
            }),
2✔
338

339
         CHECK("TPM2::Context-managed crypto backend fails gracefully after TPM2::Context destruction",
340
               [&](Test::Result& result) {
1✔
341
                  auto esys_ctx = get_external_tpm2_context();
1✔
342
                  if(!esys_ctx) {
1✔
343
                     bail_out(result);
×
344
                     return;
×
345
                  }
346

347
                  {
1✔
348
                     auto ctx = Botan::TPM2::Context::create(esys_ctx.get());
1✔
349
                     if(!ctx->supports_botan_crypto_backend()) {
1✔
350
                        bail_out(result, "skipping, because botan-based crypto backend is not supported");
×
351
                        return;
×
352
                     }
353

354
                     ctx->use_botan_crypto_backend(Test::new_rng(__func__));
3✔
355
                  }
×
356

357
                  auto [session, session_rc1] = raw_start_session(esys_ctx.get());
1✔
358

359
                  // After the destruction of the TPM2::Context in the anonymous
360
                  // scope above the botan-based TSS crypto callbacks aren't able
361
                  // to access the state that was managed by the TPM2::Context.
362
                  result.require("expected error", session_rc1 == TSS2_ESYS_RC_BAD_REFERENCE);
1✔
363

364
   #if defined(BOTAN_TSS2_SUPPORTS_CRYPTO_CALLBACKS)
365
                  // Manually resetting the crypto callbacks (in retrospect) fixes this
366
                  const auto callbacks_rc = Esys_SetCryptoCallbacks(esys_ctx.get(), nullptr);
1✔
367
                  Botan::TPM2::check_rc("resetting crypto callbacks", callbacks_rc);
1✔
368

369
                  auto [raw_session, session_rc2] = raw_start_session(esys_ctx.get());
1✔
370
                  Botan::TPM2::check_rc("session creation successful", session_rc2);
1✔
371

372
                  auto [bytes, rc_random] = raw_get_random_bytes(esys_ctx.get(), 16, raw_session);
1✔
373
                  Botan::TPM2::check_rc("random byte generation successful", rc_random);
1✔
374
                  result.test_eq_sz("some raw random bytes generated", bytes->size, 16);
2✔
375
   #endif
376
               }),
3✔
377

378
   #if defined(BOTAN_HAS_TPM2_CRYPTO_BACKEND)
379
         CHECK("free-standing crypto backend", [&](Test::Result& result) {
1✔
380
            if(!Botan::TPM2::supports_botan_crypto_backend()) {
1✔
381
               bail_out(result, "botan crypto backend is not supported");
×
382
               return;
×
383
            }
384

385
            auto esys_ctx = get_external_tpm2_context();
1✔
386
            if(!esys_ctx) {
1✔
387
               bail_out(result);
×
388
               return;
×
389
            }
390

391
            auto cb_state = Botan::TPM2::use_botan_crypto_backend(esys_ctx.get(), Test::new_rng(__func__));
3✔
392

393
            auto [raw_session, session_rc2] = raw_start_session(esys_ctx.get());
1✔
394
            Botan::TPM2::check_rc("session creation successful", session_rc2);
1✔
395

396
            auto [bytes, rc_random] = raw_get_random_bytes(esys_ctx.get(), 16, raw_session);
1✔
397
            Botan::TPM2::check_rc("random byte generation successful", rc_random);
1✔
398
            result.test_eq_sz("some raw random bytes generated", bytes->size, 16);
2✔
399
         }),
3✔
400
   #endif
401
   };
4✔
402
}
1✔
403

404
std::vector<Test::Result> test_tpm2_sessions() {
1✔
405
   auto ctx = get_tpm2_context(__func__);
1✔
406
   if(!ctx) {
1✔
407
      return {bail_out()};
×
408
   }
409

410
   auto ok = [](Test::Result& result, std::string_view name, const std::shared_ptr<Botan::TPM2::Session>& session) {
13✔
411
      result.require(Botan::fmt("Session '{}' is non-null", name), session != nullptr);
12✔
412
      result.confirm(Botan::fmt("Session '{}' has a valid handle", name), session->handle() != ESYS_TR_NONE);
24✔
413
      result.confirm(Botan::fmt("Session '{}' has a non-empty nonce", name), !session->tpm_nonce().empty());
24✔
414
   };
12✔
415

416
   return {
1✔
417
      CHECK("Unauthenticated sessions",
418
            [&](Test::Result& result) {
1✔
419
               using Session = Botan::TPM2::Session;
1✔
420

421
               ok(result, "default", Session::unauthenticated_session(ctx));
1✔
422
               ok(result, "CFB(AES-128)", Session::unauthenticated_session(ctx, "CFB(AES-128)"));
1✔
423
               ok(result, "CFB(AES-128),SHA-384", Session::unauthenticated_session(ctx, "CFB(AES-128)", "SHA-384"));
1✔
424
               ok(result, "CFB(AES-128),SHA-1", Session::unauthenticated_session(ctx, "CFB(AES-128)", "SHA-1"));
1✔
425
            }),
1✔
426

427
   #if defined(BOTAN_HAS_TPM2_RSA_ADAPTER)
428
         CHECK(
429
            "Authenticated sessions SRK",
430
            [&](Test::Result& result) {
1✔
431
               using Session = Botan::TPM2::Session;
1✔
432

433
               auto srk = ctx->storage_root_key({}, {});
2✔
434
               ok(result, "default", Session::authenticated_session(ctx, *srk));
1✔
435
               ok(result, "CFB(AES-128)", Session::authenticated_session(ctx, *srk, "CFB(AES-128)"));
1✔
436
               ok(result, "CFB(AES-128),SHA-384", Session::authenticated_session(ctx, *srk, "CFB(AES-128)", "SHA-384"));
1✔
437
               ok(result, "CFB(AES-128),SHA-1", Session::authenticated_session(ctx, *srk, "CFB(AES-128)", "SHA-1"));
2✔
438
            }),
1✔
439
   #endif
440

441
   #if defined(BOTAN_HAS_TPM2_ECC_ADAPTER)
442
         CHECK("Authenticated sessions ECC", [&](Test::Result& result) {
1✔
443
            using Session = Botan::TPM2::Session;
1✔
444
            const auto persistent_key_id = Test::options().tpm2_persistent_ecc_handle();
1✔
445

446
            auto ecc_key = Botan::TPM2::EC_PrivateKey::load_persistent(ctx, persistent_key_id, {}, {});
2✔
447
            result.require("EK is not null", ecc_key != nullptr);
1✔
448
            result.test_eq("Algo", ecc_key->algo_name(), "ECDSA");
2✔
449
            result.confirm("Has persistent handle", ecc_key->handles().has_persistent_handle());
2✔
450

451
            ok(result, "default", Session::authenticated_session(ctx, *ecc_key));
1✔
452
            ok(result, "CFB(AES-128)", Session::authenticated_session(ctx, *ecc_key, "CFB(AES-128)"));
1✔
453
            ok(result,
1✔
454
               "CFB(AES-128),SHA-384",
455
               Session::authenticated_session(ctx, *ecc_key, "CFB(AES-128)", "SHA-384"));
1✔
456
            ok(result, "CFB(AES-128),SHA-1", Session::authenticated_session(ctx, *ecc_key, "CFB(AES-128)", "SHA-1"));
2✔
457
         }),
1✔
458
   #endif
459
   };
4✔
460
}
2✔
461

462
std::vector<Test::Result> test_tpm2_rng() {
1✔
463
   auto ctx = get_tpm2_context(__func__);
1✔
464
   if(!ctx) {
1✔
465
      return {bail_out()};
×
466
   }
467

468
   auto rng = Botan::TPM2::RandomNumberGenerator(ctx, Botan::TPM2::Session::unauthenticated_session(ctx));
3✔
469

470
   return {
1✔
471
      CHECK("Basic functionalities",
472
            [&](Test::Result& result) {
1✔
473
               result.confirm("Accepts input", rng.accepts_input());
2✔
474
               result.confirm("Is seeded", rng.is_seeded());
2✔
475
               result.test_eq("Right name", rng.name(), "TPM2_RNG");
2✔
476

477
               result.test_no_throw("Clear", [&] { rng.clear(); });
2✔
478
            }),
1✔
479

480
      CHECK("Random number generation",
481
            [&](Test::Result& result) {
1✔
482
               std::array<uint8_t, 8> buf1 = {};
1✔
483
               rng.randomize(buf1);
1✔
484
               result.confirm("Is at least not 0 (8)", not_zero_64(buf1));
2✔
485

486
               std::array<uint8_t, 15> buf2 = {};
1✔
487
               rng.randomize(buf2);
1✔
488
               result.confirm("Is at least not 0 (15)", not_zero_64(buf2));
2✔
489

490
               std::array<uint8_t, 256> buf3 = {};
1✔
491
               rng.randomize(buf3);
1✔
492
               result.confirm("Is at least not 0 (256)", not_zero_64(buf3));
2✔
493
            }),
1✔
494

495
      CHECK("Randomize with inputs",
496
            [&](Test::Result& result) {
1✔
497
               std::array<uint8_t, 9> buf1 = {};
1✔
498
               rng.randomize_with_input(buf1, std::array<uint8_t, 30>{});
1✔
499
               result.confirm("Randomized with inputs is at least not 0 (9)", not_zero_64(buf1));
2✔
500

501
               std::array<uint8_t, 66> buf2 = {};
1✔
502
               rng.randomize_with_input(buf2, std::array<uint8_t, 64>{});
1✔
503
               result.confirm("Randomized with inputs is at least not 0 (66)", not_zero_64(buf2));
2✔
504

505
               std::array<uint8_t, 256> buf3 = {};
1✔
506
               rng.randomize_with_input(buf3, std::array<uint8_t, 196>{});
1✔
507
               result.confirm("Randomized with inputs is at least not 0 (256)", not_zero_64(buf3));
2✔
508
            }),
1✔
509
   };
4✔
510
}
3✔
511

512
   #if defined(BOTAN_HAS_TPM2_RSA_ADAPTER)
513

514
template <typename KeyT>
515
auto load_persistent(Test::Result& result,
32✔
516
                     const std::shared_ptr<Botan::TPM2::Context>& ctx,
517
                     uint32_t persistent_key_id,
518
                     std::span<const uint8_t> auth_value,
519
                     const std::shared_ptr<Botan::TPM2::Session>& session) {
520
   const auto persistent_handles = ctx->persistent_handles();
32✔
521
   result.confirm(
64✔
522
      "Persistent key available",
523
      std::find(persistent_handles.begin(), persistent_handles.end(), persistent_key_id) != persistent_handles.end());
32✔
524

525
   auto key = [&] {
64✔
526
      if constexpr(std::same_as<Botan::TPM2::RSA_PublicKey, KeyT>) {
527
         return KeyT::load_persistent(ctx, persistent_key_id, session);
10✔
528
      } else {
529
         return KeyT::load_persistent(ctx, persistent_key_id, auth_value, session);
54✔
530
      }
531
   }();
532

533
   result.test_eq("Algo", key->algo_name(), "RSA" /* TODO ECC support*/);
64✔
534
   result.test_is_eq("Handle", key->handles().persistent_handle(), persistent_key_id);
64✔
535
   return key;
32✔
536
}
32✔
537

538
std::vector<Test::Result> test_tpm2_rsa() {
1✔
539
   auto ctx = get_tpm2_context(__func__);
1✔
540
   if(!ctx) {
1✔
541
      return {bail_out()};
×
542
   }
543

544
   auto session = Botan::TPM2::Session::unauthenticated_session(ctx);
1✔
545

546
   const auto persistent_key_id = Test::options().tpm2_persistent_rsa_handle();
1✔
547
   const auto password = Test::options().tpm2_persistent_auth_value();
1✔
548

549
   return {
1✔
550
      CHECK("RSA and its helpers are supported",
551
            [&](Test::Result& result) {
1✔
552
               result.confirm("RSA is supported", ctx->supports_algorithm("RSA"));
2✔
553
               result.confirm("PKCS1 is supported", ctx->supports_algorithm("PKCS1v15"));
2✔
554
               result.confirm("PKCS1 with hash is supported", ctx->supports_algorithm("PKCS1v15(SHA-1)"));
2✔
555
               result.confirm("OAEP is supported", ctx->supports_algorithm("OAEP"));
2✔
556
               result.confirm("OAEP with hash is supported", ctx->supports_algorithm("OAEP(SHA-256)"));
2✔
557
               result.confirm("PSS is supported", ctx->supports_algorithm("PSS"));
2✔
558
               result.confirm("PSS with hash is supported", ctx->supports_algorithm("PSS(SHA-256)"));
2✔
559
            }),
1✔
560

561
      CHECK("Load the private key multiple times",
562
            [&](Test::Result& result) {
1✔
563
               for(size_t i = 0; i < 20; ++i) {
21✔
564
                  auto key =
20✔
565
                     load_persistent<Botan::TPM2::RSA_PrivateKey>(result, ctx, persistent_key_id, password, session);
20✔
566
                  result.test_eq(Botan::fmt("Key loaded successfully ({})", i), key->algo_name(), "RSA");
40✔
567
               }
20✔
568
            }),
1✔
569

570
      CHECK("Sign a message",
571
            [&](Test::Result& result) {
1✔
572
               auto key =
1✔
573
                  load_persistent<Botan::TPM2::RSA_PrivateKey>(result, ctx, persistent_key_id, password, session);
1✔
574

575
               Botan::Null_RNG null_rng;
1✔
576
               Botan::PK_Signer signer(*key, null_rng /* TPM takes care of this */, "PSS(SHA-256)");
1✔
577

578
               // create a message that is larger than the TPM2 max buffer size
579
               const auto message = [] {
3✔
580
                  std::vector<uint8_t> msg(TPM2_MAX_DIGEST_BUFFER + 5);
1✔
581
                  for(size_t i = 0; i < msg.size(); ++i) {
1,030✔
582
                     msg[i] = static_cast<uint8_t>(i);
1,029✔
583
                  }
584
                  return msg;
1✔
585
               }();
1✔
586
               const auto signature = signer.sign_message(message, null_rng);
1✔
587
               result.require("signature is not empty", !signature.empty());
1✔
588

589
               auto public_key = key->public_key();
1✔
590
               Botan::PK_Verifier verifier(*public_key, "PSS(SHA-256)");
1✔
591
               result.confirm("Signature is valid", verifier.verify_message(message, signature));
2✔
592
            }),
5✔
593

594
      CHECK("verify signature",
595
            [&](Test::Result& result) {
1✔
596
               auto sign = [&](std::span<const uint8_t> message) {
2✔
597
                  auto key =
1✔
598
                     load_persistent<Botan::TPM2::RSA_PrivateKey>(result, ctx, persistent_key_id, password, session);
1✔
599
                  Botan::Null_RNG null_rng;
1✔
600
                  Botan::PK_Signer signer(*key, null_rng /* TPM takes care of this */, "PSS(SHA-256)");
1✔
601
                  return signer.sign_message(message, null_rng);
1✔
602
               };
2✔
603

604
               auto verify = [&](std::span<const uint8_t> msg, std::span<const uint8_t> sig) {
4✔
605
                  auto key =
3✔
606
                     load_persistent<Botan::TPM2::RSA_PublicKey>(result, ctx, persistent_key_id, password, session);
3✔
607
                  Botan::PK_Verifier verifier(*key, "PSS(SHA-256)");
3✔
608
                  return verifier.verify_message(msg, sig);
3✔
609
               };
6✔
610

611
               const auto message = Botan::hex_decode("baadcafe");
1✔
612
               const auto signature = sign(message);
1✔
613

614
               result.confirm("verification successful", verify(message, signature));
2✔
615

616
               // change the message
617
               auto rng = Test::new_rng(__func__);
1✔
618
               auto mutated_message = Test::mutate_vec(message, *rng);
1✔
619
               result.confirm("verification failed", !verify(mutated_message, signature));
2✔
620

621
               // ESAPI manipulates the session attributes internally and does
622
               // not reset them when an error occurs. A failure to validate a
623
               // signature is an error, and hence behaves surprisingly by
624
               // leaving the session attributes in an unexpected state.
625
               // The Botan wrapper has a workaround for this...
626
               const auto attrs = session->attributes();
1✔
627
               result.confirm("encrypt flag was not cleared by ESAPI", attrs.encrypt);
2✔
628

629
               // orignal message again
630
               result.confirm("verification still successful", verify(message, signature));
2✔
631
            }),
4✔
632

633
      CHECK("sign and verify multiple messages with the same Signer/Verifier objects",
634
            [&](Test::Result& result) {
1✔
635
               const std::vector<std::vector<uint8_t>> messages = {
1✔
636
                  Botan::hex_decode("BAADF00D"),
637
                  Botan::hex_decode("DEADBEEF"),
638
                  Botan::hex_decode("CAFEBABE"),
639
               };
4✔
640

641
               // Generate a few signatures, then deallocate the private key.
642
               auto signatures = [&] {
3✔
643
                  auto sk =
1✔
644
                     load_persistent<Botan::TPM2::RSA_PrivateKey>(result, ctx, persistent_key_id, password, session);
1✔
645
                  Botan::Null_RNG null_rng;
1✔
646
                  Botan::PK_Signer signer(*sk, null_rng /* TPM takes care of this */, "PSS(SHA-256)");
1✔
647
                  std::vector<std::vector<uint8_t>> sigs;
1✔
648
                  sigs.reserve(messages.size());
1✔
649
                  for(const auto& message : messages) {
4✔
650
                     sigs.emplace_back(signer.sign_message(message, null_rng));
9✔
651
                  }
652
                  return sigs;
2✔
653
               }();
2✔
654

655
               // verify via TPM 2.0
656
               auto pk = load_persistent<Botan::TPM2::RSA_PublicKey>(result, ctx, persistent_key_id, password, session);
1✔
657
               Botan::PK_Verifier verifier(*pk, "PSS(SHA-256)");
1✔
658
               for(size_t i = 0; i < messages.size(); ++i) {
4✔
659
                  result.confirm(Botan::fmt("verification successful ({})", i),
3✔
660
                                 verifier.verify_message(messages[i], signatures[i]));
3✔
661
               }
662

663
               // verify via software
664
               auto soft_pk = Botan::RSA_PublicKey(pk->algorithm_identifier(), pk->public_key_bits());
1✔
665
               Botan::PK_Verifier soft_verifier(soft_pk, "PSS(SHA-256)");
1✔
666
               for(size_t i = 0; i < messages.size(); ++i) {
4✔
667
                  result.confirm(Botan::fmt("software verification successful ({})", i),
3✔
668
                                 soft_verifier.verify_message(messages[i], signatures[i]));
3✔
669
               }
670
            }),
4✔
671

672
      CHECK("Wrong password is not accepted during signing",
673
            [&](Test::Result& result) {
1✔
674
               auto key = load_persistent<Botan::TPM2::RSA_PrivateKey>(
1✔
675
                  result, ctx, persistent_key_id, Botan::hex_decode("deadbeef"), session);
1✔
676

677
               Botan::Null_RNG null_rng;
1✔
678
               Botan::PK_Signer signer(*key, null_rng /* TPM takes care of this */, "PSS(SHA-256)");
1✔
679

680
               const auto message = Botan::hex_decode("baadcafe");
1✔
681
               result.test_throws<Botan::TPM2::Error>("Fail with wrong password",
2✔
682
                                                      [&] { signer.sign_message(message, null_rng); });
3✔
683
            }),
2✔
684

685
      CHECK("Encrypt a message",
686
            [&](Test::Result& result) {
1✔
687
               auto pk = load_persistent<Botan::TPM2::RSA_PublicKey>(result, ctx, persistent_key_id, password, session);
1✔
688
               auto sk =
1✔
689
                  load_persistent<Botan::TPM2::RSA_PrivateKey>(result, ctx, persistent_key_id, password, session);
1✔
690

691
               const auto plaintext = Botan::hex_decode("feedc0debaadcafe");
1✔
692

693
               // encrypt a message using the TPM's public key
694
               Botan::Null_RNG null_rng;
1✔
695
               Botan::PK_Encryptor_EME enc(*pk, null_rng, "OAEP(SHA-256)");
1✔
696
               const auto ciphertext = enc.encrypt(plaintext, null_rng);
1✔
697

698
               // decrypt the message using the TPM's private RSA key
699
               Botan::PK_Decryptor_EME dec(*sk, null_rng, "OAEP(SHA-256)");
1✔
700
               const auto decrypted = dec.decrypt(ciphertext);
1✔
701
               result.test_eq("decrypted message", decrypted, plaintext);
2✔
702
            }),
5✔
703

704
      CHECK("Decrypt a message",
705
            [&](Test::Result& result) {
1✔
706
               auto key =
1✔
707
                  load_persistent<Botan::TPM2::RSA_PrivateKey>(result, ctx, persistent_key_id, password, session);
1✔
708

709
               const auto plaintext = Botan::hex_decode("feedface");
1✔
710

711
               // encrypt a message using a software RSA key for the TPM's private key
712
               auto pk = key->public_key();
1✔
713
               auto rng = Test::new_rng("tpm2 rsa decrypt");
1✔
714
               Botan::PK_Encryptor_EME enc(*pk, *rng, "OAEP(SHA-256)");
1✔
715
               const auto ciphertext = enc.encrypt(plaintext, *rng);
1✔
716

717
               // decrypt the message using the TPM's private key
718
               Botan::Null_RNG null_rng;
1✔
719
               Botan::PK_Decryptor_EME dec(*key, null_rng /* TPM takes care of this */, "OAEP(SHA-256)");
1✔
720
               const auto decrypted = dec.decrypt(ciphertext);
1✔
721
               result.test_eq("decrypted message", decrypted, plaintext);
2✔
722

723
               // corrupt the ciphertext and try to decrypt it
724
               auto mutated_ciphertext = Test::mutate_vec(ciphertext, *rng);
1✔
725
               result.test_throws<Botan::Decoding_Error>("Fail with wrong ciphertext",
3✔
726
                                                         [&] { dec.decrypt(mutated_ciphertext); });
2✔
727
            }),
7✔
728

729
      CHECK("Create a transient key and encrypt/decrypt a message",
730
            [&](Test::Result& result) {
1✔
731
               auto srk = ctx->storage_root_key({}, {});
2✔
732
               auto authed_session = Botan::TPM2::Session::authenticated_session(ctx, *srk);
1✔
733

734
               const std::array<uint8_t, 6> secret = {'s', 'e', 'c', 'r', 'e', 't'};
1✔
735
               auto sk =
1✔
736
                  Botan::TPM2::RSA_PrivateKey::create_unrestricted_transient(ctx, authed_session, secret, *srk, 2048);
2✔
737
               auto pk = sk->public_key();
1✔
738

739
               const auto plaintext = Botan::hex_decode("feedc0debaadcafe");
1✔
740

741
               // encrypt a message using the TPM's public key
742
               auto rng = Test::new_rng(__func__);
1✔
743
               Botan::PK_Encryptor_EME enc(*pk, *rng, "OAEP(SHA-256)");
1✔
744
               const auto ciphertext = enc.encrypt(plaintext, *rng);
1✔
745

746
               // decrypt the message using the TPM's private RSA key
747
               Botan::Null_RNG null_rng;
1✔
748
               Botan::PK_Decryptor_EME dec(*sk, null_rng, "OAEP(SHA-256)");
1✔
749
               const auto decrypted = dec.decrypt(ciphertext);
1✔
750
               result.test_eq("decrypted message", decrypted, plaintext);
2✔
751

752
               // encrypt a message using the TPM's public key (using PKCS#1)
753
               Botan::PK_Encryptor_EME enc_pkcs(*pk, *rng, "PKCS1v15");
1✔
754
               const auto ciphertext_pkcs = enc_pkcs.encrypt(plaintext, *rng);
1✔
755

756
               // decrypt the message using the TPM's private RSA key (using PKCS#1)
757
               Botan::PK_Decryptor_EME dec_pkcs(*sk, null_rng, "PKCS1v15");
1✔
758
               const auto decrypted_pkcs = dec_pkcs.decrypt(ciphertext_pkcs);
1✔
759
               result.test_eq("decrypted message", decrypted_pkcs, plaintext);
2✔
760
            }),
10✔
761

762
      CHECK("Cannot export private key blob from persistent key",
763
            [&](Test::Result& result) {
1✔
764
               auto key =
1✔
765
                  load_persistent<Botan::TPM2::RSA_PrivateKey>(result, ctx, persistent_key_id, password, session);
1✔
766
               result.test_throws<Botan::Not_Implemented>("Export private key blob not implemented",
2✔
767
                                                          [&] { key->private_key_bits(); });
2✔
768
               result.test_throws<Botan::Invalid_State>("Export raw private key blob not implemented",
3✔
769
                                                        [&] { key->raw_private_key_bits(); });
2✔
770
            }),
1✔
771

772
      CHECK("Create a new transient key",
773
            [&](Test::Result& result) {
1✔
774
               auto srk = ctx->storage_root_key({}, {});
2✔
775

776
               auto authed_session = Botan::TPM2::Session::authenticated_session(ctx, *srk);
1✔
777

778
               const std::array<uint8_t, 6> secret = {'s', 'e', 'c', 'r', 'e', 't'};
1✔
779

780
               auto sk =
1✔
781
                  Botan::TPM2::RSA_PrivateKey::create_unrestricted_transient(ctx, authed_session, secret, *srk, 2048);
2✔
782

783
               result.require("key was created", sk != nullptr);
1✔
784
               result.confirm("is transient", sk->handles().has_transient_handle());
2✔
785
               result.confirm("is not persistent", !sk->handles().has_persistent_handle());
2✔
786

787
               const auto sk_blob = sk->raw_private_key_bits();
1✔
788
               const auto pk_blob = sk->raw_public_key_bits();
1✔
789
               const auto pk = sk->public_key();
1✔
790

791
               result.confirm("secret blob is not empty", !sk_blob.empty());
2✔
792
               result.confirm("public blob is not empty", !pk_blob.empty());
2✔
793

794
               // Perform a round-trip sign/verify test with the new key pair
795
               std::vector<uint8_t> message = {'h', 'e', 'l', 'l', 'o'};
1✔
796
               Botan::Null_RNG null_rng;
1✔
797
               Botan::PK_Signer signer(*sk, null_rng /* TPM takes care of this */, "PSS(SHA-256)");
1✔
798
               const auto signature = signer.sign_message(message, null_rng);
1✔
799
               result.require("signature is not empty", !signature.empty());
1✔
800

801
               Botan::PK_Verifier verifier(*pk, "PSS(SHA-256)");
1✔
802
               result.confirm("Signature is valid", verifier.verify_message(message, signature));
2✔
803

804
               // Destruct the key and load it again from the encrypted blob
805
               sk.reset();
1✔
806
               auto sk_loaded =
1✔
807
                  Botan::TPM2::PrivateKey::load_transient(ctx, secret, *srk, pk_blob, sk_blob, authed_session);
2✔
808
               result.require("key was loaded", sk_loaded != nullptr);
1✔
809
               result.test_eq("loaded key is RSA", sk_loaded->algo_name(), "RSA");
2✔
810

811
               const auto sk_blob_loaded = sk_loaded->raw_private_key_bits();
1✔
812
               const auto pk_blob_loaded = sk_loaded->raw_public_key_bits();
1✔
813

814
               result.test_is_eq("secret blob did not change", sk_blob, sk_blob_loaded);
1✔
815
               result.test_is_eq("public blob did not change", pk_blob, pk_blob_loaded);
1✔
816

817
               // Perform a round-trip sign/verify test with the new key pair
818
               std::vector<uint8_t> message_loaded = {'g', 'u', 't', 'e', 'n', ' ', 't', 'a', 'g'};
1✔
819
               Botan::PK_Signer signer_loaded(*sk_loaded, null_rng /* TPM takes care of this */, "PSS(SHA-256)");
1✔
820
               const auto signature_loaded = signer_loaded.sign_message(message_loaded, null_rng);
1✔
821
               result.require("Next signature is not empty", !signature_loaded.empty());
1✔
822
               result.confirm("Existing verifier can validate signature",
2✔
823
                              verifier.verify_message(message_loaded, signature_loaded));
1✔
824

825
               // Load the public portion of the key
826
               auto pk_loaded = Botan::TPM2::PublicKey::load_transient(ctx, pk_blob, {});
2✔
827
               result.require("public key was loaded", pk_loaded != nullptr);
1✔
828

829
               Botan::PK_Verifier verifier_loaded(*pk_loaded, "PSS(SHA-256)");
1✔
830
               result.confirm("TPM-verified signature is valid",
2✔
831
                              verifier_loaded.verify_message(message_loaded, signature_loaded));
1✔
832

833
               // Perform a round-trip sign/verify test with the new key pair (PKCS#1)
834
               std::vector<uint8_t> message_pkcs = {'b', 'o', 'n', 'j', 'o', 'u', 'r'};
1✔
835
               Botan::PK_Signer signer_pkcs(*sk_loaded, null_rng /* TPM takes care of this */, "PKCS1v15(SHA-256)");
1✔
836
               const auto signature_pkcs = signer_pkcs.sign_message(message_pkcs, null_rng);
1✔
837
               result.require("Next signature is not empty", !signature_pkcs.empty());
1✔
838
               result.confirm("Existing verifier cannot validate signature",
2✔
839
                              !verifier.verify_message(message_pkcs, signature_pkcs));
1✔
840

841
               // Create a verifier for PKCS#1
842
               Botan::PK_Verifier verifier_pkcs(*pk_loaded, "PKCS1v15(SHA-256)");
1✔
843
               result.confirm("TPM-verified signature is valid",
2✔
844
                              verifier_pkcs.verify_message(message_pkcs, signature_pkcs));
1✔
845
            }),
16✔
846

847
      CHECK("Make a transient key persistent then remove it again",
848
            [&](Test::Result& result) {
1✔
849
               auto srk = ctx->storage_root_key({}, {});
2✔
850

851
               auto sign_verify_roundtrip = [&](const Botan::TPM2::PrivateKey& key) {
3✔
852
                  std::vector<uint8_t> message = {'h', 'e', 'l', 'l', 'o'};
2✔
853
                  Botan::Null_RNG null_rng;
2✔
854
                  Botan::PK_Signer signer(key, null_rng /* TPM takes care of this */, "PSS(SHA-256)");
2✔
855
                  const auto signature = signer.sign_message(message, null_rng);
2✔
856
                  result.require("signature is not empty", !signature.empty());
2✔
857

858
                  auto pk = key.public_key();
2✔
859
                  Botan::PK_Verifier verifier(*pk, "PSS(SHA-256)");
2✔
860
                  result.confirm("Signature is valid", verifier.verify_message(message, signature));
4✔
861
               };
8✔
862

863
               // Create Key
864
               auto authed_session = Botan::TPM2::Session::authenticated_session(ctx, *srk);
1✔
865

866
               const std::array<uint8_t, 6> secret = {'s', 'e', 'c', 'r', 'e', 't'};
1✔
867
               auto sk =
1✔
868
                  Botan::TPM2::RSA_PrivateKey::create_unrestricted_transient(ctx, authed_session, secret, *srk, 2048);
2✔
869
               result.require("key was created", sk != nullptr);
1✔
870
               result.confirm("is transient", sk->handles().has_transient_handle());
2✔
871
               result.confirm("is not persistent", !sk->handles().has_persistent_handle());
2✔
872
               result.test_no_throw("use key after creation", [&] { sign_verify_roundtrip(*sk); });
3✔
873

874
               // Make it persistent
875
               const auto handles = ctx->persistent_handles().size();
1✔
876
               const auto new_location = ctx->persist(*sk, authed_session, secret);
2✔
877
               result.test_eq("One more handle", ctx->persistent_handles().size(), handles + 1);
2✔
878
               result.confirm("New location occupied", Botan::value_exists(ctx->persistent_handles(), new_location));
3✔
879
               result.confirm("is persistent", sk->handles().has_persistent_handle());
2✔
880
               result.test_is_eq(
1✔
881
                  "Persistent handle is the new handle", sk->handles().persistent_handle(), new_location);
1✔
882
               result.test_throws<Botan::Invalid_Argument>(
2✔
883
                  "Cannot persist to the same location", [&] { ctx->persist(*sk, authed_session, {}, new_location); });
2✔
884
               result.test_throws<Botan::Invalid_Argument>("Cannot persist and already persistent key",
2✔
885
                                                           [&] { ctx->persist(*sk, authed_session); });
2✔
886
               result.test_no_throw("use key after persisting", [&] { sign_verify_roundtrip(*sk); });
3✔
887

888
               // Evict it
889
               ctx->evict(std::move(sk), authed_session);
3✔
890
               result.test_eq("One less handle", ctx->persistent_handles().size(), handles);
2✔
891
               result.confirm("New location no longer occupied",
1✔
892
                              !Botan::value_exists(ctx->persistent_handles(), new_location));
3✔
893
            }),
3✔
894
   };
13✔
895
}
4✔
896

897
   #endif
898

899
   #if defined(BOTAN_HAS_TPM2_ECC_ADAPTER)
900
template <typename KeyT>
901
auto load_persistent_ecc(Test::Result& result,
31✔
902
                         const std::shared_ptr<Botan::TPM2::Context>& ctx,
903
                         uint32_t persistent_key_id,
904
                         std::span<const uint8_t> auth_value,
905
                         const std::shared_ptr<Botan::TPM2::Session>& session) {
906
   // TODO: Merge with RSA
907
   const auto persistent_handles = ctx->persistent_handles();
31✔
908
   result.confirm(
62✔
909
      "Persistent key available",
910
      std::find(persistent_handles.begin(), persistent_handles.end(), persistent_key_id) != persistent_handles.end());
31✔
911

912
   auto key = [&] {
62✔
913
      if constexpr(std::same_as<Botan::TPM2::EC_PublicKey, KeyT>) {
914
         return KeyT::load_persistent(ctx, persistent_key_id, session);
10✔
915
      } else {
916
         return KeyT::load_persistent(ctx, persistent_key_id, auth_value, session);
52✔
917
      }
918
   }();
919

920
   result.test_eq("Algo", key->algo_name(), "ECDSA");
62✔
921
   result.test_is_eq("Handle", key->handles().persistent_handle(), persistent_key_id);
62✔
922
   return key;
31✔
923
}
31✔
924

925
std::vector<Test::Result> test_tpm2_ecc() {
1✔
926
   //TODO: Merge with RSA?
927
   auto ctx = get_tpm2_context(__func__);
1✔
928
   if(!ctx) {
1✔
929
      return {bail_out()};
×
930
   }
931

932
   auto session = Botan::TPM2::Session::unauthenticated_session(ctx);
1✔
933

934
   const auto persistent_key_id = Test::options().tpm2_persistent_ecc_handle();
1✔
935
   const auto password = Test::options().tpm2_persistent_auth_value();
1✔
936

937
   return {
1✔
938
      CHECK("ECC and its helpers are supported",
939
            [&](Test::Result& result) {
1✔
940
               result.confirm("ECC is supported", ctx->supports_algorithm("ECC"));
2✔
941
               result.confirm("ECDSA is supported", ctx->supports_algorithm("ECDSA"));
2✔
942
            }),
1✔
943
         CHECK("Load the private key multiple times",
944
               [&](Test::Result& result) {
1✔
945
                  for(size_t i = 0; i < 20; ++i) {
21✔
946
                     auto key = load_persistent_ecc<Botan::TPM2::EC_PrivateKey>(
20✔
947
                        result, ctx, persistent_key_id, password, session);
20✔
948
                     result.test_eq(Botan::fmt("Key loaded successfully ({})", i), key->algo_name(), "ECDSA");
40✔
949
                  }
20✔
950
               }),
1✔
951
         CHECK("Sign a message ECDSA",
952
               [&](Test::Result& result) {
1✔
953
                  auto key =
1✔
954
                     load_persistent_ecc<Botan::TPM2::EC_PrivateKey>(result, ctx, persistent_key_id, password, session);
1✔
955

956
                  Botan::Null_RNG null_rng;
1✔
957
                  Botan::PK_Signer signer(*key, null_rng /* TPM takes care of this */, "SHA-256");
1✔
958

959
                  // create a message that is larger than the TPM2 max buffer size
960
                  const auto message = [] {
3✔
961
                     std::vector<uint8_t> msg(TPM2_MAX_DIGEST_BUFFER + 5);
1✔
962
                     for(size_t i = 0; i < msg.size(); ++i) {
1,030✔
963
                        msg[i] = static_cast<uint8_t>(i);
1,029✔
964
                     }
965
                     return msg;
1✔
966
                  }();
1✔
967
                  const auto signature = signer.sign_message(message, null_rng);
1✔
968
                  result.require("signature is not empty", !signature.empty());
1✔
969

970
                  auto public_key = key->public_key();
1✔
971
                  Botan::PK_Verifier verifier(*public_key, "SHA-256");
1✔
972
                  result.confirm("Signature is valid", verifier.verify_message(message, signature));
2✔
973
               }),
5✔
974
         CHECK("verify signature ECDSA",
975
               [&](Test::Result& result) {
1✔
976
                  auto sign = [&](std::span<const uint8_t> message) {
2✔
977
                     auto key = load_persistent_ecc<Botan::TPM2::EC_PrivateKey>(
1✔
978
                        result, ctx, persistent_key_id, password, session);
1✔
979
                     Botan::Null_RNG null_rng;
1✔
980
                     Botan::PK_Signer signer(*key, null_rng /* TPM takes care of this */, "SHA-256");
1✔
981
                     return signer.sign_message(message, null_rng);
1✔
982
                  };
2✔
983

984
                  auto verify = [&](std::span<const uint8_t> msg, std::span<const uint8_t> sig) {
4✔
985
                     auto key = load_persistent_ecc<Botan::TPM2::EC_PublicKey>(
3✔
986
                        result, ctx, persistent_key_id, password, session);
3✔
987
                     Botan::PK_Verifier verifier(*key, "SHA-256");
3✔
988
                     return verifier.verify_message(msg, sig);
3✔
989
                  };
6✔
990

991
                  const auto message = Botan::hex_decode("baadcafe");
1✔
992
                  const auto signature = sign(message);
1✔
993

994
                  result.confirm("verification successful", verify(message, signature));
2✔
995

996
                  // change the message
997
                  auto rng = Test::new_rng(__func__);
1✔
998
                  auto mutated_message = Test::mutate_vec(message, *rng);
1✔
999
                  result.confirm("verification failed", !verify(mutated_message, signature));
2✔
1000

1001
                  // ESAPI manipulates the session attributes internally and does
1002
                  // not reset them when an error occurs. A failure to validate a
1003
                  // signature is an error, and hence behaves surprisingly by
1004
                  // leaving the session attributes in an unexpected state.
1005
                  // The Botan wrapper has a workaround for this...
1006
                  const auto attrs = session->attributes();
1✔
1007
                  result.confirm("encrypt flag was not cleared by ESAPI", attrs.encrypt);
2✔
1008

1009
                  // orignal message again
1010
                  result.confirm("verification still successful", verify(message, signature));
2✔
1011
               }),
4✔
1012

1013
         CHECK("sign and verify multiple messages with the same Signer/Verifier objects",
1014
               [&](Test::Result& result) {
1✔
1015
                  const std::vector<std::vector<uint8_t>> messages = {
1✔
1016
                     Botan::hex_decode("BAADF00D"),
1017
                     Botan::hex_decode("DEADBEEF"),
1018
                     Botan::hex_decode("CAFEBABE"),
1019
                  };
4✔
1020

1021
                  // Generate a few signatures, then deallocate the private key.
1022
                  auto signatures = [&] {
3✔
1023
                     auto sk = load_persistent_ecc<Botan::TPM2::EC_PrivateKey>(
1✔
1024
                        result, ctx, persistent_key_id, password, session);
1✔
1025
                     Botan::Null_RNG null_rng;
1✔
1026
                     Botan::PK_Signer signer(*sk, null_rng /* TPM takes care of this */, "SHA-256");
1✔
1027
                     std::vector<std::vector<uint8_t>> sigs;
1✔
1028
                     sigs.reserve(messages.size());
1✔
1029
                     for(const auto& message : messages) {
4✔
1030
                        sigs.emplace_back(signer.sign_message(message, null_rng));
9✔
1031
                     }
1032
                     return sigs;
2✔
1033
                  }();
2✔
1034

1035
                  // verify via TPM 2.0
1036
                  auto pk =
1✔
1037
                     load_persistent_ecc<Botan::TPM2::EC_PublicKey>(result, ctx, persistent_key_id, password, session);
1✔
1038
                  Botan::PK_Verifier verifier(*pk, "SHA-256");
1✔
1039
                  for(size_t i = 0; i < messages.size(); ++i) {
4✔
1040
                     result.confirm(Botan::fmt("verification successful ({})", i),
3✔
1041
                                    verifier.verify_message(messages[i], signatures[i]));
3✔
1042
                  }
1043

1044
                  // verify via software
1045
                  auto soft_pk =
1✔
1046
                     load_persistent_ecc<Botan::TPM2::EC_PrivateKey>(result, ctx, persistent_key_id, password, session)
1✔
1047
                        ->public_key();
1✔
1048
                  Botan::PK_Verifier soft_verifier(*soft_pk, "SHA-256");
1✔
1049
                  for(size_t i = 0; i < messages.size(); ++i) {
4✔
1050
                     result.confirm(Botan::fmt("software verification successful ({})", i),
3✔
1051
                                    soft_verifier.verify_message(messages[i], signatures[i]));
3✔
1052
                  }
1053
               }),
5✔
1054

1055
         CHECK("Wrong password is not accepted during ECDSA signing",
1056
               [&](Test::Result& result) {
1✔
1057
                  auto key = load_persistent_ecc<Botan::TPM2::EC_PrivateKey>(
1✔
1058
                     result, ctx, persistent_key_id, Botan::hex_decode("deadbeef"), session);
1✔
1059

1060
                  Botan::Null_RNG null_rng;
1✔
1061
                  Botan::PK_Signer signer(*key, null_rng /* TPM takes care of this */, "SHA-256");
1✔
1062

1063
                  const auto message = Botan::hex_decode("baadcafe");
1✔
1064
                  result.test_throws<Botan::TPM2::Error>("Fail with wrong password",
2✔
1065
                                                         [&] { signer.sign_message(message, null_rng); });
3✔
1066
               }),
2✔
1067

1068
      // SRK is an RSA key, so we can only test with the RSA adapter
1069
      #if defined(BOTAN_HAS_TPM2_RSA_ADAPTER)
1070
         CHECK("Create a transient ECDSA key and sign/verify a message",
1071
               [&](Test::Result& result) {
1✔
1072
                  auto srk = ctx->storage_root_key({}, {});
2✔
1073
                  auto ecc_session_key =
1✔
1074
                     Botan::TPM2::EC_PrivateKey::load_persistent(ctx, persistent_key_id, password, {});
2✔
1075
                  auto authed_session = Botan::TPM2::Session::authenticated_session(ctx, *ecc_session_key);
1✔
1076

1077
                  const std::array<uint8_t, 6> secret = {'s', 'e', 'c', 'r', 'e', 't'};
1✔
1078
                  auto sk = Botan::TPM2::EC_PrivateKey::create_unrestricted_transient(
1✔
1079
                     ctx, authed_session, secret, *srk, Botan::EC_Group::from_name("secp521r1"));
2✔
1080
                  auto pk = sk->public_key();
1✔
1081

1082
                  const auto plaintext = Botan::hex_decode("feedc0debaadcafe");
1✔
1083

1084
                  Botan::Null_RNG null_rng;
1✔
1085
                  Botan::PK_Signer signer(*sk, null_rng /* TPM takes care of this */, "SHA-256");
1✔
1086

1087
                  // create a message that is larger than the TPM2 max buffer size
1088
                  const auto message = [] {
3✔
1089
                     std::vector<uint8_t> msg(TPM2_MAX_DIGEST_BUFFER + 5);
1✔
1090
                     for(size_t i = 0; i < msg.size(); ++i) {
1,030✔
1091
                        msg[i] = static_cast<uint8_t>(i);
1,029✔
1092
                     }
1093
                     return msg;
1✔
1094
                  }();
1✔
1095
                  const auto signature = signer.sign_message(message, null_rng);
1✔
1096
                  result.require("signature is not empty", !signature.empty());
1✔
1097

1098
                  auto public_key = sk->public_key();
1✔
1099
                  Botan::PK_Verifier verifier(*public_key, "SHA-256");
1✔
1100
                  result.confirm("Signature is valid", verifier.verify_message(message, signature));
2✔
1101
               }),
10✔
1102

1103
         CHECK("Create a new transient ECDSA key",
1104
               [&](Test::Result& result) {
1✔
1105
                  auto srk = ctx->storage_root_key({}, {});
2✔
1106
                  auto ecc_session_key =
1✔
1107
                     Botan::TPM2::EC_PrivateKey::load_persistent(ctx, persistent_key_id, password, {});
2✔
1108

1109
                  auto authed_session = Botan::TPM2::Session::authenticated_session(ctx, *ecc_session_key);
1✔
1110

1111
                  const std::array<uint8_t, 6> secret = {'s', 'e', 'c', 'r', 'e', 't'};
1✔
1112

1113
                  auto sk = Botan::TPM2::EC_PrivateKey::create_unrestricted_transient(
1✔
1114
                     ctx, authed_session, secret, *srk, Botan::EC_Group::from_name("secp384r1"));
2✔
1115

1116
                  result.require("key was created", sk != nullptr);
1✔
1117
                  result.confirm("is transient", sk->handles().has_transient_handle());
2✔
1118
                  result.confirm("is not persistent", !sk->handles().has_persistent_handle());
2✔
1119

1120
                  const auto sk_blob = sk->raw_private_key_bits();
1✔
1121
                  const auto pk_blob = sk->raw_public_key_bits();
1✔
1122
                  const auto pk = sk->public_key();
1✔
1123

1124
                  result.confirm("secret blob is not empty", !sk_blob.empty());
2✔
1125
                  result.confirm("public blob is not empty", !pk_blob.empty());
2✔
1126

1127
                  // Perform a round-trip sign/verify test with the new key pair
1128
                  std::vector<uint8_t> message = {'h', 'e', 'l', 'l', 'o'};
1✔
1129
                  Botan::Null_RNG null_rng;
1✔
1130
                  Botan::PK_Signer signer(*sk, null_rng /* TPM takes care of this */, "SHA-256");
1✔
1131
                  const auto signature = signer.sign_message(message, null_rng);
1✔
1132
                  result.require("signature is not empty", !signature.empty());
1✔
1133

1134
                  Botan::PK_Verifier verifier(*pk, "SHA-256");
1✔
1135
                  result.confirm("Signature is valid", verifier.verify_message(message, signature));
2✔
1136

1137
                  // Destruct the key and load it again from the encrypted blob
1138
                  sk.reset();
1✔
1139
                  auto sk_loaded =
1✔
1140
                     Botan::TPM2::PrivateKey::load_transient(ctx, secret, *srk, pk_blob, sk_blob, authed_session);
2✔
1141
                  result.require("key was loaded", sk_loaded != nullptr);
1✔
1142
                  result.test_eq("loaded key is ECDSA", sk_loaded->algo_name(), "ECDSA");
2✔
1143

1144
                  const auto sk_blob_loaded = sk_loaded->raw_private_key_bits();
1✔
1145
                  const auto pk_blob_loaded = sk_loaded->raw_public_key_bits();
1✔
1146

1147
                  result.test_is_eq("secret blob did not change", sk_blob, sk_blob_loaded);
1✔
1148
                  result.test_is_eq("public blob did not change", pk_blob, pk_blob_loaded);
1✔
1149

1150
                  // Perform a round-trip sign/verify test with the new key pair
1151
                  std::vector<uint8_t> message_loaded = {'g', 'u', 't', 'e', 'n', ' ', 't', 'a', 'g'};
1✔
1152
                  Botan::PK_Signer signer_loaded(*sk_loaded, null_rng /* TPM takes care of this */, "SHA-256");
1✔
1153
                  const auto signature_loaded = signer_loaded.sign_message(message_loaded, null_rng);
1✔
1154
                  result.require("Next signature is not empty", !signature_loaded.empty());
1✔
1155
                  result.confirm("Existing verifier can validate signature",
2✔
1156
                                 verifier.verify_message(message_loaded, signature_loaded));
1✔
1157

1158
                  // Load the public portion of the key
1159
                  auto pk_loaded = Botan::TPM2::PublicKey::load_transient(ctx, pk_blob, {});
2✔
1160
                  result.require("public key was loaded", pk_loaded != nullptr);
1✔
1161

1162
                  Botan::PK_Verifier verifier_loaded(*pk_loaded, "SHA-256");
1✔
1163
                  result.confirm("TPM-verified signature is valid",
2✔
1164
                                 verifier_loaded.verify_message(message_loaded, signature_loaded));
1✔
1165
               }),
15✔
1166

1167
         CHECK(
1168
            "Make a transient ECDSA key persistent then remove it again",
1169
            [&](Test::Result& result) {
1✔
1170
               auto srk = ctx->storage_root_key({}, {});
2✔
1171
               auto ecc_session_key = Botan::TPM2::EC_PrivateKey::load_persistent(ctx, persistent_key_id, password, {});
2✔
1172

1173
               auto sign_verify_roundtrip = [&](const Botan::TPM2::PrivateKey& key) {
3✔
1174
                  std::vector<uint8_t> message = {'h', 'e', 'l', 'l', 'o'};
2✔
1175
                  Botan::Null_RNG null_rng;
2✔
1176
                  Botan::PK_Signer signer(key, null_rng /* TPM takes care of this */, "SHA-256");
2✔
1177
                  const auto signature = signer.sign_message(message, null_rng);
2✔
1178
                  result.require("signature is not empty", !signature.empty());
2✔
1179

1180
                  auto pk = key.public_key();
2✔
1181
                  Botan::PK_Verifier verifier(*pk, "SHA-256");
2✔
1182
                  result.confirm("Signature is valid", verifier.verify_message(message, signature));
4✔
1183
               };
8✔
1184

1185
               // Create Key
1186
               auto authed_session = Botan::TPM2::Session::authenticated_session(ctx, *ecc_session_key);
1✔
1187

1188
               const std::array<uint8_t, 6> secret = {'s', 'e', 'c', 'r', 'e', 't'};
1✔
1189
               auto sk = Botan::TPM2::EC_PrivateKey::create_unrestricted_transient(
1✔
1190
                  ctx, authed_session, secret, *srk, Botan::EC_Group::from_name("secp192r1"));
2✔
1191
               result.require("key was created", sk != nullptr);
1✔
1192
               result.confirm("is transient", sk->handles().has_transient_handle());
2✔
1193
               result.confirm("is not persistent", !sk->handles().has_persistent_handle());
2✔
1194
               result.test_no_throw("use key after creation", [&] { sign_verify_roundtrip(*sk); });
3✔
1195

1196
               // Make it persistent
1197
               const auto handles = ctx->persistent_handles().size();
1✔
1198
               const auto new_location = ctx->persist(*sk, authed_session, secret);
2✔
1199
               result.test_eq("One more handle", ctx->persistent_handles().size(), handles + 1);
2✔
1200
               result.confirm("New location occupied", Botan::value_exists(ctx->persistent_handles(), new_location));
3✔
1201
               result.confirm("is persistent", sk->handles().has_persistent_handle());
2✔
1202
               result.test_is_eq(
1✔
1203
                  "Persistent handle is the new handle", sk->handles().persistent_handle(), new_location);
1✔
1204
               result.test_throws<Botan::Invalid_Argument>(
2✔
1205
                  "Cannot persist to the same location", [&] { ctx->persist(*sk, authed_session, {}, new_location); });
2✔
1206
               result.test_throws<Botan::Invalid_Argument>("Cannot persist and already persistent key",
2✔
1207
                                                           [&] { ctx->persist(*sk, authed_session); });
2✔
1208
               result.test_no_throw("use key after persisting", [&] { sign_verify_roundtrip(*sk); });
3✔
1209

1210
               // Evict it
1211
               ctx->evict(std::move(sk), authed_session);
3✔
1212
               result.test_eq("One less handle", ctx->persistent_handles().size(), handles);
2✔
1213
               result.confirm("New location no longer occupied",
1✔
1214
                              !Botan::value_exists(ctx->persistent_handles(), new_location));
3✔
1215
            }),
4✔
1216
      #endif
1217

1218
         CHECK("Read a software public key from a TPM serialization", [&](Test::Result& result) {
1✔
1219
            auto pk = load_persistent_ecc<Botan::TPM2::EC_PublicKey>(result, ctx, persistent_key_id, password, session);
1✔
1220
            result.test_no_throw("Botan can read serialized ECC public key", [&] {
2✔
1221
               std::ignore = Botan::ECDSA_PublicKey(pk->algorithm_identifier(), pk->public_key_bits());
1✔
1222
            });
1✔
1223

1224
            auto sk =
1✔
1225
               load_persistent_ecc<Botan::TPM2::EC_PrivateKey>(result, ctx, persistent_key_id, password, session);
1✔
1226
            result.test_no_throw("Botan can read serialized public key from ECC private key", [&] {
3✔
1227
               std::ignore = Botan::ECDSA_PublicKey(sk->algorithm_identifier(), sk->public_key_bits());
1✔
1228
            });
1✔
1229
         }),
2✔
1230
   };
11✔
1231
}
4✔
1232
   #endif
1233

1234
std::vector<Test::Result> test_tpm2_hash() {
1✔
1235
   auto ctx = get_tpm2_context(__func__);
1✔
1236
   if(!ctx) {
1✔
1237
      return {bail_out()};
×
1238
   }
1239

1240
   auto test = [&](Test::Result& result, std::string_view algo) {
8✔
1241
      auto tpm_hash = [&]() -> std::unique_ptr<Botan::TPM2::HashFunction> {
21✔
1242
         try {
7✔
1243
            return std::make_unique<Botan::TPM2::HashFunction>(
7✔
1244
               ctx, algo, ESYS_TR_RH_NULL, Botan::TPM2::Session::unauthenticated_session(ctx));
7✔
1245
         } catch(const Botan::Lookup_Error&) {
3✔
1246
            return {};
3✔
1247
         }
3✔
1248
      }();
7✔
1249
      auto soft_hash = Botan::HashFunction::create(algo);
7✔
1250

1251
      if(!tpm_hash) {
7✔
1252
         result.test_note(Botan::fmt("Skipping {}, TPM 2.0 does not support it", algo));
3✔
1253
         return;
3✔
1254
      }
1255

1256
      if(!soft_hash) {
4✔
1257
         result.test_note(Botan::fmt("Skipping {}, no software equivalent available", algo));
×
1258
         return;
×
1259
      }
1260

1261
      result.test_eq("Name", tpm_hash->name(), soft_hash->name());
8✔
1262
      result.test_eq("Output length", tpm_hash->output_length(), soft_hash->output_length());
4✔
1263

1264
      // multiple update calls
1265
      tpm_hash->update("Hello, ");
4✔
1266
      tpm_hash->update("world!");
4✔
1267
      result.test_eq("digest (multi-update)", tpm_hash->final(), soft_hash->process("Hello, world!"));
16✔
1268

1269
      // single process call
1270
      result.test_eq("digest (single-process)", tpm_hash->process("Hallo, Welt."), soft_hash->process("Hallo, Welt."));
20✔
1271

1272
      // create a message that is larger than the TPM2 max buffer size
1273
      const auto long_message = [] {
×
1274
         std::vector<uint8_t> msg(TPM2_MAX_DIGEST_BUFFER + 5);
4✔
1275
         for(size_t i = 0; i < msg.size(); ++i) {
4,120✔
1276
            msg[i] = static_cast<uint8_t>(i);
4,116✔
1277
         }
1278
         return msg;
4✔
1279
      }();
4✔
1280

1281
      tpm_hash->update(long_message);
4✔
1282
      result.test_eq("digest (long msg via update)", tpm_hash->final(), soft_hash->process(long_message));
12✔
1283
      result.test_eq(
8✔
1284
         "digest (long msg via process)", tpm_hash->process(long_message), soft_hash->process(long_message));
8✔
1285

1286
      // test clear
1287
      tpm_hash->update("Hello");
4✔
1288
      tpm_hash->clear();
4✔
1289
      tpm_hash->update("Bonjour");
4✔
1290
      result.test_eq("digest (clear)", tpm_hash->final(), soft_hash->process("Bonjour"));
16✔
1291

1292
      // new_object
1293
      auto new_tpm_hash = tpm_hash->new_object();
4✔
1294
      result.test_eq("Name (new_object)", new_tpm_hash->name(), tpm_hash->name());
8✔
1295
      result.test_eq("Output length (new_object)", new_tpm_hash->output_length(), tpm_hash->output_length());
4✔
1296
      result.test_eq("digest (new object)",
16✔
1297
                     new_tpm_hash->process("Salut tout le monde!"),
12✔
1298
                     soft_hash->process("Salut tout le monde!"));
12✔
1299
   };
15✔
1300

1301
   return {
1✔
1302
      CHECK("Hashes are supported",
1303
            [&](Test::Result& result) {
1✔
1304
               result.confirm("SHA-1 is supported", ctx->supports_algorithm("SHA-1"));
2✔
1305
               result.confirm("SHA-256 is supported", ctx->supports_algorithm("SHA-256"));
2✔
1306
               result.confirm("SHA-384 is supported", ctx->supports_algorithm("SHA-384"));
2✔
1307
               result.confirm("SHA-512 is supported", ctx->supports_algorithm("SHA-512"));
2✔
1308
            }),
1✔
1309

1310
      CHECK("SHA-1", [&](Test::Result& result) { test(result, "SHA-1"); }),
1✔
1311
      CHECK("SHA-256", [&](Test::Result& result) { test(result, "SHA-256"); }),
1✔
1312
      CHECK("SHA-384", [&](Test::Result& result) { test(result, "SHA-384"); }),
1✔
1313
      CHECK("SHA-512", [&](Test::Result& result) { test(result, "SHA-512"); }),
1✔
1314
      CHECK("SHA-3(256)", [&](Test::Result& result) { test(result, "SHA-3(256)"); }),
1✔
1315
      CHECK("SHA-3(384)", [&](Test::Result& result) { test(result, "SHA-3(384)"); }),
1✔
1316
      CHECK("SHA-3(512)", [&](Test::Result& result) { test(result, "SHA-3(512)"); }),
1✔
1317

1318
      CHECK("lookup error",
1319
            [&](Test::Result& result) {
1✔
1320
               result.test_throws<Botan::Lookup_Error>(
2✔
1321
                  "Lookup error", [&] { [[maybe_unused]] auto _ = Botan::TPM2::HashFunction(ctx, "MD-5"); });
7✔
1322
            }),
1✔
1323

1324
      CHECK("copy_state is not implemented",
1325
            [&](Test::Result& result) {
1✔
1326
               auto tpm_hash = Botan::TPM2::HashFunction(ctx, "SHA-256");
3✔
1327
               result.test_throws<Botan::Not_Implemented>("TPM2 hash does not support copy_state",
2✔
1328
                                                          [&] { [[maybe_unused]] auto _ = tpm_hash.copy_state(); });
2✔
1329
            }),
1✔
1330

1331
      CHECK("validation ticket",
1332
            [&](Test::Result& result) {
1✔
1333
               // using the NULL hierarchy essentially disables the validation ticket
1334
               auto tpm_hash_null = Botan::TPM2::HashFunction(
1✔
1335
                  ctx, "SHA-256", ESYS_TR_RH_NULL, Botan::TPM2::Session::unauthenticated_session(ctx));
3✔
1336
               tpm_hash_null.update("Hola mundo!");
1✔
1337
               const auto [digest_null, ticket_null] = tpm_hash_null.final_with_ticket();
1✔
1338
               result.require("digest is set", digest_null != nullptr);
1✔
1339
               result.require("ticket is set", ticket_null != nullptr);
1✔
1340
               result.confirm("ticket is empty", ticket_null->digest.size == 0);
2✔
1341

1342
               // using the OWNER hierarchy (for instance) enables the validation ticket
1343
               auto tpm_hash_owner = Botan::TPM2::HashFunction(
1✔
1344
                  ctx, "SHA-256", ESYS_TR_RH_OWNER, Botan::TPM2::Session::unauthenticated_session(ctx));
3✔
1345
               tpm_hash_owner.update("Hola mundo!");
1✔
1346
               const auto [digest_owner, ticket_owner] = tpm_hash_owner.final_with_ticket();
1✔
1347
               result.require("digest is set", digest_owner != nullptr);
1✔
1348
               result.require("ticket is set", ticket_owner != nullptr);
1✔
1349
               result.confirm("ticket is not empty", ticket_owner->digest.size > 0);
2✔
1350

1351
               const auto digest_vec = Botan::TPM2::copy_into<Botan::secure_vector<uint8_t>>(*digest_owner);
1✔
1352
               result.test_eq("digest",
2✔
1353
                              digest_vec,
1354
                              Botan::hex_decode("1e479f4d871e59e9054aad62105a259726801d5f494acbfcd40591c82f9b3136"));
1✔
1355

1356
               result.test_eq("digests are the same, regardless of ticket",
2✔
1357
                              Botan::TPM2::copy_into<std::vector<uint8_t>>(*digest_null),
2✔
1358
                              digest_vec);
1359
            }),
1✔
1360
   };
12✔
1361
}
2✔
1362

1363
}  // namespace
1364

1365
BOTAN_REGISTER_TEST_FN("tpm2", "tpm2_props", test_tpm2_properties);
1366
BOTAN_REGISTER_TEST_FN("tpm2", "tpm2_ctx", test_tpm2_context);
1367
BOTAN_REGISTER_TEST_FN("tpm2", "tpm2_external_ctx", test_external_tpm2_context);
1368
BOTAN_REGISTER_TEST_FN("tpm2", "tpm2_sessions", test_tpm2_sessions);
1369
BOTAN_REGISTER_TEST_FN("tpm2", "tpm2_rng", test_tpm2_rng);
1370
   #if defined(BOTAN_HAS_TPM2_RSA_ADAPTER)
1371
BOTAN_REGISTER_TEST_FN("tpm2", "tpm2_rsa", test_tpm2_rsa);
1372
   #endif
1373
   #if defined(BOTAN_HAS_TPM2_ECC_ADAPTER)
1374
BOTAN_REGISTER_TEST_FN("tpm2", "tpm2_ecc", test_tpm2_ecc);
1375
   #endif
1376
BOTAN_REGISTER_TEST_FN("tpm2", "tpm2_hash", test_tpm2_hash);
1377

1378
#endif
1379

1380
}  // namespace Botan_Tests
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc