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

randombit / botan / 16293079084

15 Jul 2025 12:20PM UTC coverage: 90.627% (+0.003%) from 90.624%
16293079084

push

github

web-flow
Merge pull request #4990 from randombit/jack/string-and-span

Improve string<->span conversions

99640 of 109945 relevant lines covered (90.63%)

12253617.72 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/mem_utils.h>
13
#include <botan/internal/stl_util.h>
14

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

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

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

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

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

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

41
namespace Botan_Tests {
42

43
#if defined(BOTAN_HAS_TPM2)
44
namespace {
45

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

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

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

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

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

72
   return ctx;
7✔
73
}
14✔
74

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

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

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

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

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

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

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

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

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

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

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

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

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

147
   return esys_ctx;
3✔
148
}
9✔
149

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

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

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

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

176
   return true;
177
}
178

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

513
   #if defined(BOTAN_HAS_TPM2_RSA_ADAPTER)
514

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

898
   #endif
899

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1364
}  // namespace
1365

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

1379
#endif
1380

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