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

randombit / botan / 23225340130

18 Mar 2026 01:53AM UTC coverage: 89.677% (-0.001%) from 89.678%
23225340130

push

github

web-flow
Merge pull request #5456 from randombit/jack/clang-tidy-22

Fix various warnings from clang-tidy 22

104438 of 116460 relevant lines covered (89.68%)

11819947.55 hits per line

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

95.12
/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
namespace {
45

46
#if defined(BOTAN_HAS_TPM2)
47

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

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

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

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

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

74
   return ctx;
7✔
75
}
14✔
76

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

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

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

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

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

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

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

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

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

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

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

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

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

149
   return esys_ctx;
3✔
150
}
9✔
151

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

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

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

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

178
   return true;
179
}
180

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

515
   #if defined(BOTAN_HAS_TPM2_RSA_ADAPTER)
516

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

617
               result.test_is_true("verification successful", verify(message, signature));
1✔
618

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

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

632
               // original message again
633
               result.test_is_true("verification still successful", verify(message, signature));
1✔
634
            }),
4✔
635

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

794
               result.test_is_true("secret blob is not empty", !sk_blob.empty());
1✔
795
               result.test_is_true("public blob is not empty", !pk_blob.empty());
1✔
796

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

900
   #endif
901

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

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

923
   result.test_str_eq("Algo", key->algo_name(), "ECDSA");
31✔
924
   result.test_u64_eq("Handle", key->handles().persistent_handle(), persistent_key_id);
31✔
925
   return key;
31✔
926
}
31✔
927

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

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

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

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

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

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

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

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

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

997
                  result.test_is_true("verification successful", verify(message, signature));
1✔
998

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

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

1012
                  // original message again
1013
                  result.test_is_true("verification still successful", verify(message, signature));
1✔
1014
               }),
4✔
1015

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1127
                  result.test_is_true("secret blob is not empty", !sk_blob.empty());
1✔
1128
                  result.test_is_true("public blob is not empty", !pk_blob.empty());
1✔
1129

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1265
      result.test_str_eq("Name", tpm_hash->name(), soft_hash->name());
4✔
1266
      result.test_sz_eq("Output length", tpm_hash->output_length(), soft_hash->output_length());
4✔
1267

1268
      // multiple update calls
1269
      tpm_hash->update("Hello, ");
4✔
1270
      tpm_hash->update("world!");
4✔
1271
      result.test_bin_eq("digest (multi-update)", tpm_hash->final(), soft_hash->process("Hello, world!"));
12✔
1272

1273
      // single process call
1274
      result.test_bin_eq(
12✔
1275
         "digest (single-process)", tpm_hash->process("Hallo, Welt."), soft_hash->process("Hallo, Welt."));
16✔
1276

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

1286
      tpm_hash->update(long_message);
4✔
1287
      result.test_bin_eq("digest (long msg via update)", tpm_hash->final(), soft_hash->process(long_message));
8✔
1288
      result.test_bin_eq(
4✔
1289
         "digest (long msg via process)", tpm_hash->process(long_message), soft_hash->process(long_message));
8✔
1290

1291
      // test clear
1292
      tpm_hash->update("Hello");
4✔
1293
      tpm_hash->clear();
4✔
1294
      tpm_hash->update("Bonjour");
4✔
1295
      result.test_bin_eq("digest (clear)", tpm_hash->final(), soft_hash->process("Bonjour"));
12✔
1296

1297
      // new_object
1298
      auto new_tpm_hash = tpm_hash->new_object();
4✔
1299
      result.test_str_eq("Name (new_object)", new_tpm_hash->name(), tpm_hash->name());
4✔
1300
      result.test_sz_eq("Output length (new_object)", new_tpm_hash->output_length(), tpm_hash->output_length());
4✔
1301
      result.test_bin_eq("digest (new object)",
12✔
1302
                         new_tpm_hash->process("Salut tout le monde!"),
12✔
1303
                         soft_hash->process("Salut tout le monde!"));
12✔
1304
   };
15✔
1305

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

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

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

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

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

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

1356
               const auto digest_vec = Botan::TPM2::copy_into<Botan::secure_vector<uint8_t>>(*digest_owner);
1✔
1357
               result.test_bin_eq(
1✔
1358
                  "digest",
1359
                  digest_vec,
1360
                  Botan::hex_decode("1e479f4d871e59e9054aad62105a259726801d5f494acbfcd40591c82f9b3136"));
1✔
1361

1362
               result.test_bin_eq("digests are the same, regardless of ticket",
1✔
1363
                                  Botan::TPM2::copy_into<std::vector<uint8_t>>(*digest_null),
2✔
1364
                                  digest_vec);
1365
            }),
1✔
1366
   };
12✔
1367
}
2✔
1368

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

1382
#endif
1383

1384
}  // namespace
1385

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