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

randombit / botan / 21753596263

06 Feb 2026 02:13PM UTC coverage: 90.063% (-0.01%) from 90.073%
21753596263

Pull #5289

github

web-flow
Merge 587099284 into 8ea0ca252
Pull Request #5289: Further misc header reductions, forward declarations, etc

102237 of 113517 relevant lines covered (90.06%)

11402137.11 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
#if defined(BOTAN_HAS_TPM2)
11
   #include <botan/hex.h>
12
   #include <botan/pubkey.h>
13
   #include <botan/tpm2_key.h>
14
   #include <botan/tpm2_rng.h>
15
   #include <botan/tpm2_session.h>
16
   #include <botan/internal/buffer_slicer.h>
17
   #include <botan/internal/fmt.h>
18
   #include <botan/internal/loadstor.h>
19
   #include <botan/internal/mem_utils.h>
20
   #include <botan/internal/stl_util.h>
21
   #include <botan/internal/tpm2_hash.h>
22
   #include <algorithm>
23

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

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

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

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

42
namespace Botan_Tests {
43

44
#if defined(BOTAN_HAS_TPM2)
45
namespace {
46

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

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

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

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

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

73
   return ctx;
7✔
74
}
14✔
75

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

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

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

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

95
      TR(const TR&) = delete;
96
      TR& operator=(const TR&) = delete;
97

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

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

108
struct esys_context_liberator {
109
      void operator()(ESYS_CONTEXT* esys_ctx) {
3✔
110
         TSS2_TCTI_CONTEXT* tcti_ctx = nullptr;  // NOLINT(*-const-correctness) clang-tidy bug
3✔
111
         Esys_GetTcti(esys_ctx, &tcti_ctx);      // ignore error in destructor
3✔
112
         if(tcti_ctx != nullptr) {
3✔
113
            Tss2_TctiLdr_Finalize(&tcti_ctx);
3✔
114
         }
115
         Esys_Finalize(&esys_ctx);
3✔
116
      }
3✔
117
};
118

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

127
   TSS2_RC rc = 0;
3✔
128
   TSS2_TCTI_CONTEXT* tcti_ctx = nullptr;
3✔
129
   std::unique_ptr<ESYS_CONTEXT, esys_context_liberator> esys_ctx;
3✔
130

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

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

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

148
   return esys_ctx;
3✔
149
}
9✔
150

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

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

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

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

177
   return true;
178
}
179

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

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

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

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

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

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

227
   const auto persistent_key_id = Test::options().tpm2_persistent_rsa_handle();
1✔
228

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

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

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

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

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

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

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

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

301
      return {TR{esys_ctx, session}, rc};
4✔
302
   };
303

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

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

320
               {
1✔
321
                  // Do some TPM2-stuff via the Botan wrappers
322

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

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

330
                  // All Botan-wrapped things go out of scope...
331
               }
2✔
332

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

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

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

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

356
                     ctx->use_botan_crypto_backend(Test::new_rng("tpm2_backend_context_test"));
3✔
357
                  }
×
358

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

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

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

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

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

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

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

393
            auto cb_state = Botan::TPM2::use_botan_crypto_backend(esys_ctx.get(), Test::new_rng("tpm2_crypto_backend"));
3✔
394

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

514
   #if defined(BOTAN_HAS_TPM2_RSA_ADAPTER)
515

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

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

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

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

546
   auto session = Botan::TPM2::Session::unauthenticated_session(ctx);
1✔
547

548
   const auto persistent_key_id = Test::options().tpm2_persistent_rsa_handle();
1✔
549
   const auto password = Botan::as_span_of_bytes(Test::options().tpm2_persistent_auth_value());
1✔
550

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

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

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

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

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

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

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

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

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

616
               result.confirm("verification successful", verify(message, signature));
2✔
617

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

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

631
               // original message again
632
               result.confirm("verification still successful", verify(message, signature));
2✔
633
            }),
4✔
634

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

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

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

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

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

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

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

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

693
               const auto plaintext = Botan::hex_decode("feedc0debaadcafe");
1✔
694

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

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

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

711
               const auto plaintext = Botan::hex_decode("feedface");
1✔
712

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

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

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

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

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

741
               const auto plaintext = Botan::hex_decode("feedc0debaadcafe");
1✔
742

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

899
   #endif
900

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

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

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

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

934
   auto session = Botan::TPM2::Session::unauthenticated_session(ctx);
1✔
935

936
   const auto persistent_key_id = Test::options().tpm2_persistent_ecc_handle();
1✔
937
   const auto password = Botan::as_span_of_bytes(Test::options().tpm2_persistent_auth_value());
1✔
938

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

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

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

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

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

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

996
                  result.confirm("verification successful", verify(message, signature));
2✔
997

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

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

1011
                  // original message again
1012
                  result.confirm("verification still successful", verify(message, signature));
2✔
1013
               }),
4✔
1014

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

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

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

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

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

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

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

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

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

1084
                  const auto plaintext = Botan::hex_decode("feedc0debaadcafe");
1✔
1085

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1365
}  // namespace
1366

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

1380
#endif
1381

1382
}  // 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