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

randombit / botan / 20512202773

25 Dec 2025 11:09PM UTC coverage: 90.326% (-0.002%) from 90.328%
20512202773

push

github

web-flow
Merge pull request #5169 from randombit/jack/clang-tidy-config-updates

Some configuration updates for clang-tidy

101306 of 112156 relevant lines covered (90.33%)

12877185.6 hits per line

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

97.35
/src/tests/test_tls_rfc8448.cpp
1
/*
2
* (C) 2021 Jack Lloyd
3
*     2021, 2022 René Meusel, Hannes Rantzsch - neXenio GmbH
4
*     2022       René Meusel - Rohde & Schwarz Cybersecurity GmbH
5
*
6
* Botan is released under the Simplified BSD License (see license.txt)
7
*/
8

9
#include "tests.h"
10
#include <fstream>
11
#include <memory>
12
#include <utility>
13

14
// Since RFC 8448 uses a specific set of cipher suites we can only run this
15
// test if all of them are enabled.
16
#if defined(BOTAN_HAS_TLS_13) && defined(BOTAN_HAS_AEAD_CHACHA20_POLY1305) && defined(BOTAN_HAS_AEAD_GCM) &&          \
17
   defined(BOTAN_HAS_AES) && defined(BOTAN_HAS_X25519) && defined(BOTAN_HAS_SHA2_32) && defined(BOTAN_HAS_SHA2_64) && \
18
   defined(BOTAN_HAS_ECDSA) && defined(BOTAN_HAS_PSS)
19
   #define BOTAN_CAN_RUN_TEST_TLS_RFC8448
20
#endif
21

22
#if defined(BOTAN_CAN_RUN_TEST_TLS_RFC8448)
23
   #include "test_rng.h"
24

25
   #include <botan/assert.h>
26
   #include <botan/credentials_manager.h>
27
   #include <botan/data_src.h>
28
   #include <botan/dl_group.h>
29
   #include <botan/ec_group.h>
30
   #include <botan/pk_algs.h>
31
   #include <botan/pkcs8.h>
32
   #include <botan/tls_callbacks.h>
33
   #include <botan/tls_client.h>
34
   #include <botan/tls_extensions.h>
35
   #include <botan/tls_messages.h>
36
   #include <botan/tls_server.h>
37
   #include <botan/tls_session_manager.h>
38
   #include <botan/x509_key.h>
39
   #include <botan/internal/fmt.h>
40
   #include <botan/internal/stl_util.h>
41
#endif
42

43
namespace Botan_Tests {
44

45
#if defined(BOTAN_CAN_RUN_TEST_TLS_RFC8448)
46

47
namespace {
48

49
void add_entropy(Fixed_Output_RNG& rng, const std::vector<uint8_t>& bin) {
14✔
50
   rng.add_entropy(bin.data(), bin.size());
28✔
51
}
52

53
Botan::X509_Certificate server_certificate() {
4✔
54
   // self-signed certificate with an RSA1024 public key valid until:
55
   //   Jul 30 01:23:59 2026 GMT
56
   Botan::DataSource_Memory in(Test::read_data_file("tls_13_rfc8448/server_certificate.pem"));
8✔
57
   return Botan::X509_Certificate(in);
4✔
58
}
4✔
59

60
Botan::X509_Certificate alternative_server_certificate() {
1✔
61
   // self-signed certificate with a P-256 public key valid until:
62
   //   Jul 30 01:24:00 2026 GMT
63
   //
64
   // This certificate is presented by the server in the "Client Authentication"
65
   // test case. Why the certificate differs in that case remains unclear.
66
   Botan::DataSource_Memory in(Test::read_data_file("tls_13_rfc8448/server_certificate_client_auth.pem"));
2✔
67
   return Botan::X509_Certificate(in);
1✔
68
}
1✔
69

70
Botan::X509_Certificate client_certificate() {
2✔
71
   // self-signed certificate with an RSA1024 public key valid until:
72
   //   Jul 30 01:23:59 2026 GMT
73
   Botan::DataSource_Memory in(Test::read_data_file("tls_13_rfc8448/client_certificate.pem"));
4✔
74
   return Botan::X509_Certificate(in);
2✔
75
}
2✔
76

77
std::unique_ptr<Botan::Private_Key> client_raw_public_key_pair() {
4✔
78
   // P-256 private key (independently generated)
79
   Botan::DataSource_Memory in(Test::read_data_file("tls_13_rfc8448/client_raw_public_keypair.pem"));
8✔
80
   return Botan::PKCS8::load_key(in);
4✔
81
}
4✔
82

83
std::unique_ptr<Botan::Private_Key> server_raw_public_key_pair() {
4✔
84
   // P-256 private key (independently generated)
85
   Botan::DataSource_Memory in(Test::read_data_file("tls_13_rfc8448/server_raw_public_keypair.pem"));
8✔
86
   return Botan::PKCS8::load_key(in);
4✔
87
}
4✔
88

89
/**
90
* Simple version of the Padding extension (RFC 7685) to reproduce the
91
* 2nd Client_Hello in RFC8448 Section 5 (HelloRetryRequest)
92
*/
93
class Padding final : public Botan::TLS::Extension {
94
   public:
95
      static Botan::TLS::Extension_Code static_type() {
96
         // NOLINTNEXTLINE(clang-analyzer-optin.core.EnumCastOutOfRange)
97
         return Botan::TLS::Extension_Code(21);
98
      }
99

100
      Botan::TLS::Extension_Code type() const override { return static_type(); }
46✔
101

102
      explicit Padding(const size_t padding_bytes) : m_padding_bytes(padding_bytes) {}
2✔
103

104
      std::vector<uint8_t> serialize(Botan::TLS::Connection_Side /*whoami*/) const override {
5✔
105
         return std::vector<uint8_t>(m_padding_bytes, 0x00);
5✔
106
      }
107

108
      bool empty() const override { return m_padding_bytes == 0; }
5✔
109

110
   private:
111
      size_t m_padding_bytes;
112
};
113

114
using namespace Botan;
115
using namespace Botan::TLS;
116

117
std::chrono::system_clock::time_point from_milliseconds_since_epoch(uint64_t msecs) {
14✔
118
   const int64_t secs_since_epoch = msecs / 1000;
14✔
119
   const uint32_t additional_millis = msecs % 1000;
14✔
120

121
   BOTAN_ASSERT_NOMSG(secs_since_epoch <= std::numeric_limits<time_t>::max());
14✔
122
   return std::chrono::system_clock::from_time_t(static_cast<time_t>(secs_since_epoch)) +
14✔
123
          std::chrono::milliseconds(additional_millis);
14✔
124
}
125

126
using Modify_Exts_Fn =
127
   std::function<void(Botan::TLS::Extensions&, Botan::TLS::Connection_Side, Botan::TLS::Handshake_Type)>;
128

129
/**
130
 * We cannot actually reproduce the signatures stated in RFC 8448 as their
131
 * signature scheme is probabilistic and we're lacking the correct RNG
132
 * input. Hence, signatures are know beforehand and just reproduced by the
133
 * TLS callback when requested.
134
 */
135
struct MockSignature {
15✔
136
      std::vector<uint8_t> message_to_sign;
137
      std::vector<uint8_t> signature_to_produce;
138
};
139

140
/**
141
 * Subclass of the Botan::TLS::Callbacks instrumenting all available callbacks.
142
 * The invocation counts can be checked in the integration tests to make sure
143
 * all expected callbacks are hit. Furthermore collects the received application
144
 * data and sent record bytes for further inspection by the test cases.
145
 */
146
class Test_TLS_13_Callbacks : public Botan::TLS::Callbacks {
147
   public:
148
      Test_TLS_13_Callbacks(Modify_Exts_Fn modify_exts_cb,
14✔
149
                            std::vector<MockSignature> mock_signatures,
150
                            uint64_t timestamp) :
14✔
151
            session_activated_called(false),
14✔
152
            m_modify_exts(std::move(modify_exts_cb)),
14✔
153
            m_mock_signatures(std::move(mock_signatures)),
14✔
154
            m_timestamp(from_milliseconds_since_epoch(timestamp)) {}
14✔
155

156
      void tls_emit_data(std::span<const uint8_t> data) override {
47✔
157
         count_callback_invocation("tls_emit_data");
47✔
158
         send_buffer.insert(send_buffer.end(), data.begin(), data.end());
47✔
159
      }
47✔
160

161
      void tls_record_received(uint64_t seq_no, std::span<const uint8_t> data) override {
4✔
162
         count_callback_invocation("tls_record_received");
4✔
163
         received_seq_no = seq_no;
4✔
164
         receive_buffer.insert(receive_buffer.end(), data.begin(), data.end());
4✔
165
      }
4✔
166

167
      void tls_alert(Botan::TLS::Alert alert) override {
12✔
168
         count_callback_invocation("tls_alert");
12✔
169
         BOTAN_UNUSED(alert);
12✔
170
         // handle a tls alert received from the tls server
171
      }
12✔
172

173
      bool tls_peer_closed_connection() override {
12✔
174
         count_callback_invocation("tls_peer_closed_connection");
12✔
175
         // we want to handle the closure ourselves
176
         return false;
12✔
177
      }
178

179
      void tls_session_established(const Botan::TLS::Session_Summary& summary) override {
12✔
180
         if(const auto& psk_id = summary.external_psk_identity()) {
12✔
181
            negotiated_psk_identity = *psk_id;
2✔
182
         }
183
         count_callback_invocation("tls_session_established");
12✔
184
      }
12✔
185

186
      void tls_session_activated() override {
12✔
187
         count_callback_invocation("tls_session_activated");
12✔
188
         session_activated_called = true;
12✔
189
      }
12✔
190

191
      bool tls_should_persist_resumption_information(const Session& /*session*/) override {
2✔
192
         count_callback_invocation("tls_should_persist_resumption_information");
2✔
193
         return true;  // should always store the session
2✔
194
      }
195

196
      void tls_verify_cert_chain(const std::vector<Botan::X509_Certificate>& cert_chain,
5✔
197
                                 const std::vector<std::optional<Botan::OCSP::Response>>& /*ocsp*/,
198
                                 const std::vector<Botan::Certificate_Store*>& /*trusted*/,
199
                                 Botan::Usage_Type /*usage*/,
200
                                 std::string_view /*hostname*/,
201
                                 const Botan::TLS::Policy& /*policy*/) override {
202
         count_callback_invocation("tls_verify_cert_chain");
5✔
203
         certificate_chain = cert_chain;
5✔
204
      }
5✔
205

206
      void tls_verify_raw_public_key(const Public_Key& raw_pk,
2✔
207
                                     Usage_Type /*usage*/,
208
                                     std::string_view /*hostname*/,
209
                                     const TLS::Policy& /*policy*/) override {
210
         count_callback_invocation("tls_verify_raw_public_key");
2✔
211
         // TODO: is there a better way to copy a generic public key?
212
         raw_public_key = Botan::X509::load_key(raw_pk.subject_public_key());
2✔
213
      }
2✔
214

215
      std::chrono::milliseconds tls_verify_cert_chain_ocsp_timeout() const override {
×
216
         count_callback_invocation("tls_verify_cert_chain");
×
217
         return std::chrono::milliseconds(0);
×
218
      }
219

220
      std::vector<uint8_t> tls_provide_cert_status(const std::vector<X509_Certificate>& chain,
×
221
                                                   const Certificate_Status_Request& csr) override {
222
         count_callback_invocation("tls_provide_cert_status");
×
223
         return Callbacks::tls_provide_cert_status(chain, csr);
×
224
      }
225

226
      std::vector<uint8_t> tls_sign_message(const Private_Key& key,
7✔
227
                                            RandomNumberGenerator& rng,
228
                                            std::string_view padding,
229
                                            Signature_Format format,
230
                                            const std::vector<uint8_t>& msg) override {
231
         BOTAN_UNUSED(key, rng);
7✔
232
         count_callback_invocation("tls_sign_message");
7✔
233

234
         if(key.algo_name() == "RSA") {
7✔
235
            if(format != Signature_Format::Standard) {
4✔
236
               throw Test_Error("TLS implementation selected unexpected signature format for RSA");
×
237
            }
238

239
            if(padding != "PSS(SHA-256,MGF1,32)") {
8✔
240
               throw Test_Error("TLS implementation selected unexpected padding for RSA: " + std::string(padding));
×
241
            }
242
         } else if(key.algo_name() == "ECDSA") {
3✔
243
            if(format != Signature_Format::DerSequence) {
3✔
244
               throw Test_Error("TLS implementation selected unexpected signature format for ECDSA");
×
245
            }
246

247
            if(padding != "SHA-256") {
6✔
248
               throw Test_Error("TLS implementation selected unexpected padding for ECDSA: " + std::string(padding));
×
249
            }
250
         } else {
251
            throw Test_Error("TLS implementation trying to sign with unexpected algorithm (" + key.algo_name() + ")");
×
252
         }
253

254
         for(const auto& mock : m_mock_signatures) {
9✔
255
            if(mock.message_to_sign == msg) {
9✔
256
               return mock.signature_to_produce;
7✔
257
            }
258
         }
259

260
         throw Test_Error("TLS implementation produced an unexpected message to be signed: " + Botan::hex_encode(msg));
×
261
      }
262

263
      bool tls_verify_message(const Public_Key& key,
7✔
264
                              std::string_view padding,
265
                              Signature_Format format,
266
                              const std::vector<uint8_t>& msg,
267
                              const std::vector<uint8_t>& sig) override {
268
         count_callback_invocation("tls_verify_message");
7✔
269
         return Callbacks::tls_verify_message(key, padding, format, msg, sig);
7✔
270
      }
271

272
      std::unique_ptr<PK_Key_Agreement_Key> tls_generate_ephemeral_key(
15✔
273
         const std::variant<TLS::Group_Params, DL_Group>& group, RandomNumberGenerator& rng) override {
274
         count_callback_invocation("tls_generate_ephemeral_key");
15✔
275
         return Callbacks::tls_generate_ephemeral_key(group, rng);
15✔
276
      }
277

278
      secure_vector<uint8_t> tls_ephemeral_key_agreement(const std::variant<TLS::Group_Params, DL_Group>& group,
13✔
279
                                                         const PK_Key_Agreement_Key& private_key,
280
                                                         const std::vector<uint8_t>& public_value,
281
                                                         RandomNumberGenerator& rng,
282
                                                         const Policy& policy) override {
283
         count_callback_invocation("tls_ephemeral_key_agreement");
13✔
284
         return Callbacks::tls_ephemeral_key_agreement(group, private_key, public_value, rng, policy);
13✔
285
      }
286

287
      void tls_inspect_handshake_msg(const Handshake_Message& message) override {
102✔
288
         count_callback_invocation("tls_inspect_handshake_msg_" + message.type_string());
306✔
289

290
         try {
102✔
291
            auto serialized_message = message.serialize();
102✔
292

293
            serialized_messages.try_emplace(message.type_string())
204✔
294
               .first->second.emplace_back(std::move(serialized_message));
102✔
295
         } catch(const Not_Implemented&) {
102✔
296
            // TODO: Once the server implementation is finished, this crutch
297
            //       can likely be removed, as all message types will have a
298
            //       serialization method with actual business logic. :o)
299
         }
×
300

301
         return Callbacks::tls_inspect_handshake_msg(message);
102✔
302
      }
303

304
      std::string tls_server_choose_app_protocol(const std::vector<std::string>& client_protos) override {
×
305
         count_callback_invocation("tls_server_choose_app_protocol");
×
306
         return Callbacks::tls_server_choose_app_protocol(client_protos);
×
307
      }
308

309
      void tls_modify_extensions(Botan::TLS::Extensions& exts,
33✔
310
                                 Botan::TLS::Connection_Side side,
311
                                 Botan::TLS::Handshake_Type which_message) override {
312
         count_callback_invocation(std::string("tls_modify_extensions_") + handshake_type_to_string(which_message));
99✔
313
         m_modify_exts(exts, side, which_message);
33✔
314
         Callbacks::tls_modify_extensions(exts, side, which_message);
33✔
315
      }
33✔
316

317
      void tls_examine_extensions(const Botan::TLS::Extensions& extn,
31✔
318
                                  Connection_Side which_side,
319
                                  Botan::TLS::Handshake_Type which_message) override {
320
         count_callback_invocation(std::string("tls_examine_extensions_") + handshake_type_to_string(which_message));
93✔
321
         return Callbacks::tls_examine_extensions(extn, which_side, which_message);
31✔
322
      }
323

324
      std::string tls_peer_network_identity() override {
×
325
         count_callback_invocation("tls_peer_network_identity");
×
326
         return Callbacks::tls_peer_network_identity();
×
327
      }
328

329
      std::chrono::system_clock::time_point tls_current_timestamp() override {
23✔
330
         count_callback_invocation("tls_current_timestamp");
23✔
331
         return m_timestamp;
23✔
332
      }
333

334
      std::vector<uint8_t> pull_send_buffer() { return std::exchange(send_buffer, std::vector<uint8_t>()); }
39✔
335

336
      std::vector<uint8_t> pull_receive_buffer() { return std::exchange(receive_buffer, std::vector<uint8_t>()); }
4✔
337

338
      uint64_t last_received_seq_no() const { return received_seq_no; }
4✔
339

340
      const std::map<std::string, unsigned int>& callback_invocations() const { return m_callback_invocations; }
60✔
341

342
      void reset_callback_invocation_counters() { m_callback_invocations.clear(); }
60✔
343

344
   private:
345
      void count_callback_invocation(const std::string& callback_name) const {
339✔
346
         if(!m_callback_invocations.contains(callback_name)) {
339✔
347
            m_callback_invocations[callback_name] = 0;
320✔
348
         }
349

350
         m_callback_invocations[callback_name]++;
339✔
351
      }
339✔
352

353
   public:
354
      bool session_activated_called;                           // NOLINT(*-non-private-member-variable*)
355
      std::vector<Botan::X509_Certificate> certificate_chain;  // NOLINT(*-non-private-member-variable*)
356
      std::unique_ptr<Botan::Public_Key> raw_public_key;       // NOLINT(*-non-private-member-variable*)
357
      std::string negotiated_psk_identity;                     // NOLINT(*-non-private-member-variable*)
358
      std::map<std::string, std::vector<std::vector<uint8_t>>>
359
         serialized_messages;  // NOLINT(*-non-private-member-variable*)
360

361
   private:
362
      std::vector<uint8_t> send_buffer;
363
      std::vector<uint8_t> receive_buffer;
364
      uint64_t received_seq_no = 0;
365
      Modify_Exts_Fn m_modify_exts;
366
      std::vector<MockSignature> m_mock_signatures;
367
      std::chrono::system_clock::time_point m_timestamp;
368

369
      mutable std::map<std::string, unsigned int> m_callback_invocations;
370
};
371

372
class Test_Credentials : public Botan::Credentials_Manager {
373
   public:
374
      explicit Test_Credentials(bool use_alternative_server_certificate, std::optional<ExternalPSK> external_psk) :
14✔
375
            m_alternative_server_certificate(use_alternative_server_certificate),
14✔
376
            m_external_psk(std::move(external_psk)) {
16✔
377
         Botan::DataSource_Memory in(Test::read_data_file("tls_13_rfc8448/server_key.pem"));
28✔
378
         m_server_private_key.reset(Botan::PKCS8::load_key(in).release());
14✔
379

380
         // RFC 8448 does not actually provide these keys. Hence we generate one on the
381
         // fly as a stand-in. Instead of actually using it, the signatures generated
382
         // by this private key must be hard-coded in `Callbacks::sign_message()`; see
383
         // `MockSignature_Fn` for more details.
384
         auto rng = Test::new_rng(__func__);
14✔
385
         m_bogus_alternative_server_private_key.reset(create_private_key("ECDSA", *rng, "secp256r1").release());
14✔
386

387
         m_client_private_key.reset(create_private_key("RSA", *rng, "1024").release());
28✔
388
      }
28✔
389

390
      std::vector<Botan::X509_Certificate> cert_chain(const std::vector<std::string>& cert_key_types,
5✔
391
                                                      const std::vector<AlgorithmIdentifier>& cert_signature_schemes,
392
                                                      const std::string& type,
393
                                                      const std::string& context) override {
394
         BOTAN_UNUSED(cert_key_types, cert_signature_schemes, context);
5✔
395
         if(type == "tls-client") {
5✔
396
            return {client_certificate()};
2✔
397
         } else if(m_alternative_server_certificate) {
4✔
398
            return {alternative_server_certificate()};
2✔
399
         } else {
400
            return {server_certificate()};
6✔
401
         }
402
      }
5✔
403

404
      std::shared_ptr<Public_Key> find_raw_public_key(const std::vector<std::string>& key_types,
2✔
405
                                                      const std::string& type,
406
                                                      const std::string& context) override {
407
         BOTAN_UNUSED(key_types, type, context);
2✔
408
         return (type == "tls-client") ? client_raw_public_key_pair()->public_key()
4✔
409
                                       : server_raw_public_key_pair()->public_key();
5✔
410
      }
411

412
      std::shared_ptr<Botan::Private_Key> private_key_for(const Botan::X509_Certificate& cert,
5✔
413
                                                          const std::string& type,
414
                                                          const std::string& context) override {
415
         BOTAN_UNUSED(cert, context);
5✔
416

417
         if(type == "tls-client") {
5✔
418
            return m_client_private_key;
1✔
419
         }
420

421
         if(m_alternative_server_certificate) {
4✔
422
            return m_bogus_alternative_server_private_key;
1✔
423
         }
424

425
         return m_server_private_key;
3✔
426
      }
427

428
      std::shared_ptr<Botan::Private_Key> private_key_for(const Public_Key& raw_public_key,
2✔
429
                                                          const std::string& type,
430
                                                          const std::string& context) override {
431
         BOTAN_UNUSED(type, context);
2✔
432
         std::vector<std::unique_ptr<Botan::Private_Key>> keys;
2✔
433
         keys.emplace_back(client_raw_public_key_pair());
2✔
434
         keys.emplace_back(server_raw_public_key_pair());
2✔
435
         for(auto& key : keys) {
3✔
436
            if(key->fingerprint_public() == raw_public_key.fingerprint_public()) {
3✔
437
               return std::move(key);
2✔
438
            }
439
         }
440
         return nullptr;
×
441
      }
2✔
442

443
      std::vector<TLS::ExternalPSK> find_preshared_keys(std::string_view /* host */,
8✔
444
                                                        TLS::Connection_Side /* whoami */,
445
                                                        const std::vector<std::string>& identities,
446
                                                        const std::optional<std::string>& prf) override {
447
         if(!m_external_psk.has_value()) {
8✔
448
            return {};
6✔
449
         }
450

451
         ExternalPSK& epsk = m_external_psk.value();
2✔
452
         const auto found = std::find(identities.begin(), identities.end(), epsk.identity());
2✔
453
         if(!identities.empty() && found == identities.end()) {
2✔
454
            return {};
×
455
         }
456

457
         if(prf && prf != epsk.prf_algo()) {
2✔
458
            return {};
×
459
         }
460

461
         // ExternalPSK has a deleted copy constructor. We need to do some gymnastics
462
         // to copy it and leave the data in m_external_psk intact
463
         const auto secret = epsk.extract_master_secret();
2✔
464
         m_external_psk = ExternalPSK(epsk.identity(), epsk.prf_algo(), secret);
2✔
465
         std::vector<ExternalPSK> psks;
2✔
466
         psks.emplace_back(epsk.identity(), epsk.prf_algo(), secret);
2✔
467
         return psks;
2✔
468
      }
4✔
469

470
   private:
471
      bool m_alternative_server_certificate;
472
      std::optional<ExternalPSK> m_external_psk;
473
      std::shared_ptr<Private_Key> m_client_private_key;
474
      std::shared_ptr<Private_Key> m_bogus_alternative_server_private_key;
475
      std::shared_ptr<Private_Key> m_server_private_key;
476
};
477

478
class RFC8448_Text_Policy : public Botan::TLS::Text_Policy {
14✔
479
   private:
480
      Botan::TLS::Text_Policy read_policy(const std::string& policy_file) {
14✔
481
         const std::string fspath = Test::data_file("tls-policy/" + policy_file + ".txt");
42✔
482

483
         std::ifstream is(fspath.c_str());
14✔
484
         if(!is.good()) {
14✔
485
            throw Test_Error("Missing policy file " + fspath);
×
486
         }
487

488
         return Botan::TLS::Text_Policy(is);
14✔
489
      }
14✔
490

491
   public:
492
      explicit RFC8448_Text_Policy(const std::string& policy_file, bool rfc8448 = true) :
14✔
493
            Botan::TLS::Text_Policy(read_policy(policy_file)), m_rfc8448(rfc8448) {}
14✔
494

495
      std::vector<Botan::TLS::Signature_Scheme> allowed_signature_schemes() const override {
16✔
496
         if(!m_rfc8448) {
16✔
497
            return Botan::TLS::Text_Policy::allowed_signature_schemes();
1✔
498
         }
499

500
         // We extend the allowed signature schemes with algorithms that we don't
501
         // actually support. The nature of the RFC 8448 test forces us to generate
502
         // bit-compatible TLS messages. Unfortunately, the test data offers all
503
         // those algorithms in its Client Hellos.
504
         return {
15✔
505
            Botan::TLS::Signature_Scheme::ECDSA_SHA256,
506
            Botan::TLS::Signature_Scheme::ECDSA_SHA384,
507
            Botan::TLS::Signature_Scheme::ECDSA_SHA512,
508
            Botan::TLS::Signature_Scheme::ECDSA_SHA1,  // not actually supported
509
            Botan::TLS::Signature_Scheme::RSA_PSS_SHA256,
510
            Botan::TLS::Signature_Scheme::RSA_PSS_SHA384,
511
            Botan::TLS::Signature_Scheme::RSA_PSS_SHA512,
512
            Botan::TLS::Signature_Scheme::RSA_PKCS1_SHA256,
513
            Botan::TLS::Signature_Scheme::RSA_PKCS1_SHA384,
514
            Botan::TLS::Signature_Scheme::RSA_PKCS1_SHA512,
515
            Botan::TLS::Signature_Scheme::RSA_PKCS1_SHA1,  // not actually supported
516
            Botan::TLS::Signature_Scheme(0x0402),          // DSA_SHA256, not actually supported
517
            Botan::TLS::Signature_Scheme(0x0502),          // DSA_SHA384, not actually supported
518
            Botan::TLS::Signature_Scheme(0x0602),          // DSA_SHA512, not actually supported
519
            Botan::TLS::Signature_Scheme(0x0202),          // DSA_SHA1, not actually supported
520
         };
15✔
521
      }
522

523
      // Overriding the key exchange group selection to favour the server's key
524
      // exchange group preference. This is required to enforce a Hello Retry Request
525
      // when testing RFC 8448 5. from the server side.
526
      Named_Group choose_key_exchange_group(const std::vector<Group_Params>& supported_by_peer,
8✔
527
                                            const std::vector<Group_Params>& offered_by_peer) const override {
528
         BOTAN_UNUSED(offered_by_peer);
8✔
529

530
         const auto supported_by_us = key_exchange_groups();
8✔
531
         const auto selected_group =
8✔
532
            std::find_if(supported_by_us.begin(), supported_by_us.end(), [&](const auto group) {
8✔
533
               return value_exists(supported_by_peer, group);
16✔
534
            });
535

536
         return selected_group != supported_by_us.end() ? *selected_group : Named_Group::NONE;
8✔
537
      }
8✔
538

539
   private:
540
      bool m_rfc8448;
541
};
542

543
/**
544
 * In-Memory Session Manager that stores sessions verbatim, without encryption.
545
 * Therefor it is not dependent on a random number generator and can easily be
546
 * instrumented for test inspection.
547
 */
548
class RFC8448_Session_Manager : public Botan::TLS::Session_Manager {
549
   private:
550
      decltype(auto) find_by_handle(const Session_Handle& handle) {
3✔
551
         return [=](const Session_with_Handle& session) {
18✔
552
            if(session.handle.id().has_value() && handle.id().has_value() &&
4✔
553
               session.handle.id().value() == handle.id().value()) {
2✔
554
               return true;
555
            }
556
            if(session.handle.ticket().has_value() && handle.ticket().has_value() &&
8✔
557
               session.handle.ticket().value() == handle.ticket().value()) {
10✔
558
               return true;
559
            }
560
            return false;
561
         };
6✔
562
      }
563

564
   public:
565
      RFC8448_Session_Manager() : Session_Manager(std::make_shared<Botan::Null_RNG>()) {}
28✔
566

567
      const std::vector<Session_with_Handle>& all_sessions() const { return m_sessions; }
3✔
568

569
      void store(const Session& session, const Session_Handle& handle) override {
4✔
570
         m_sessions.push_back({session, handle});
4✔
571
      }
12✔
572

573
      std::optional<Session_Handle> establish(const Session& session,
1✔
574
                                              const std::optional<Session_ID>& /*session*/,
575
                                              bool /*no_ticket*/) override {
576
         // we assume that the 'mocked' session is already stored in the manager,
577
         // verify that it is equivalent to the one created by the testee and
578
         // return the associated handle stored with it
579

580
         if(m_sessions.size() != 1) {
1✔
581
            throw Test_Error("No mocked session handle available; Test bug?");
×
582
         }
583

584
         const auto& [mocked_session, handle] = m_sessions.front();
1✔
585
         if(mocked_session.master_secret() != session.master_secret()) {
1✔
586
            throw Test_Error("Generated session object does not match the expected mock");
×
587
         }
588

589
         return handle;
1✔
590
      }
591

592
      std::optional<Session> retrieve_one(const Session_Handle& handle) override {
2✔
593
         auto itr = std::find_if(m_sessions.begin(), m_sessions.end(), find_by_handle(handle));
2✔
594
         if(itr == m_sessions.end()) {
2✔
595
            return std::nullopt;
1✔
596
         } else {
597
            return itr->session;
1✔
598
         }
599
      }
600

601
      std::vector<Session_with_Handle> find_some(const Server_Information& info,
7✔
602
                                                 const size_t /*max_sessions_hint*/) override {
603
         std::vector<Session_with_Handle> found_sessions;
7✔
604
         for(const auto& [session, handle] : m_sessions) {
8✔
605
            if(session.server_info() == info) {
1✔
606
               found_sessions.emplace_back(Session_with_Handle{session, handle});
2✔
607
            }
608
         }
609

610
         return found_sessions;
7✔
611
      }
×
612

613
      size_t remove(const Session_Handle& handle) override { return std::erase_if(m_sessions, find_by_handle(handle)); }
2✔
614

615
      size_t remove_all() override {
×
616
         const auto sessions = m_sessions.size();
×
617
         m_sessions.clear();
×
618
         return sessions;
×
619
      }
620

621
   private:
622
      std::vector<Session_with_Handle> m_sessions;
623
};
624

625
/**
626
 * This steers the TLS client handle and is the central entry point for the
627
 * test cases to interact with the TLS 1.3 implementation.
628
 *
629
 * Note: This class is abstract to be subclassed for both client and server tests.
630
 */
631
class TLS_Context {
632
   protected:
633
      TLS_Context(std::shared_ptr<Botan::RandomNumberGenerator> rng_in,
14✔
634
                  std::shared_ptr<const RFC8448_Text_Policy> policy,
635
                  Modify_Exts_Fn modify_exts_cb,
636
                  std::vector<MockSignature> mock_signatures,
637
                  uint64_t timestamp,
638
                  std::optional<std::pair<Session, Session_Ticket>> session_and_ticket,
639
                  std::optional<ExternalPSK> external_psk,
640
                  bool use_alternative_server_certificate) :
14✔
641
            m_callbacks(std::make_shared<Test_TLS_13_Callbacks>(
14✔
642
               std::move(modify_exts_cb), std::move(mock_signatures), timestamp)),
643
            m_creds(std::make_shared<Test_Credentials>(use_alternative_server_certificate, std::move(external_psk))),
14✔
644
            m_rng(std::move(rng_in)),
14✔
645
            m_session_mgr(std::make_shared<RFC8448_Session_Manager>()),
646
            m_policy(std::move(policy)) {
28✔
647
         if(session_and_ticket.has_value()) {
14✔
648
            m_session_mgr->store(std::get<Session>(session_and_ticket.value()),
6✔
649
                                 Botan::TLS::Session_Handle(std::get<Session_Ticket>(session_and_ticket.value())));
9✔
650
         }
651
      }
14✔
652

653
   public:
654
      virtual ~TLS_Context() = default;
70✔
655

656
      TLS_Context(TLS_Context&) = delete;
657
      TLS_Context& operator=(const TLS_Context&) = delete;
658

659
      TLS_Context(TLS_Context&&) = delete;
660
      TLS_Context& operator=(TLS_Context&&) = delete;
661

662
      std::vector<uint8_t> pull_send_buffer() { return m_callbacks->pull_send_buffer(); }
39✔
663

664
      std::vector<uint8_t> pull_receive_buffer() { return m_callbacks->pull_receive_buffer(); }
4✔
665

666
      uint64_t last_received_seq_no() const { return m_callbacks->last_received_seq_no(); }
4✔
667

668
      /**
669
       * Checks that all of the listed callbacks were called at least once, no other
670
       * callbacks were called in addition to the expected ones. After the checks are
671
       * done, the callback invocation counters are reset.
672
       */
673
      void check_callback_invocations(Test::Result& result,
60✔
674
                                      const std::string& context,
675
                                      const std::vector<std::string>& callback_names) {
676
         const auto& invokes = m_callbacks->callback_invocations();
60✔
677
         for(const auto& cbn : callback_names) {
371✔
678
            result.confirm(Botan::fmt("{} was invoked (Context: {})", cbn, context),
933✔
679
                           invokes.contains(cbn) && invokes.at(cbn) > 0);
311✔
680
         }
681

682
         for(const auto& invoke : invokes) {
371✔
683
            if(invoke.second == 0) {
311✔
684
               continue;
×
685
            }
686
            result.confirm(
622✔
687
               invoke.first + " was expected (Context: " + context + ")",
1,244✔
688
               std::find(callback_names.cbegin(), callback_names.cend(), invoke.first) != callback_names.cend());
622✔
689
         }
690

691
         m_callbacks->reset_callback_invocation_counters();
60✔
692
      }
60✔
693

694
      const std::vector<Session_with_Handle>& stored_sessions() const { return m_session_mgr->all_sessions(); }
3✔
695

696
      const std::vector<Botan::X509_Certificate>& certs_verified() const { return m_callbacks->certificate_chain; }
2✔
697

698
      const std::string& psk_identity_negotiated() const { return m_callbacks->negotiated_psk_identity; }
2✔
699

700
      decltype(auto) observed_handshake_messages() const { return m_callbacks->serialized_messages; }
7✔
701

702
      /**
703
       * Send application data through the secure channel
704
       */
705
      virtual void send(const std::vector<uint8_t>& data) = 0;
706

707
   protected:
708
      std::shared_ptr<Test_TLS_13_Callbacks> m_callbacks;  // NOLINT(*-non-private-member-variable*)
709
      std::shared_ptr<Test_Credentials> m_creds;           // NOLINT(*-non-private-member-variable*)
710

711
      std::shared_ptr<Botan::RandomNumberGenerator> m_rng;     // NOLINT(*-non-private-member-variable*)
712
      std::shared_ptr<RFC8448_Session_Manager> m_session_mgr;  // NOLINT(*-non-private-member-variable*)
713
      std::shared_ptr<const RFC8448_Text_Policy> m_policy;     // NOLINT(*-non-private-member-variable*)
714
};
715

716
class Client_Context : public TLS_Context {
717
   public:
718
      Client_Context(std::shared_ptr<Botan::RandomNumberGenerator> rng_in,
7✔
719
                     std::shared_ptr<const RFC8448_Text_Policy> policy,
720
                     uint64_t timestamp,
721
                     Modify_Exts_Fn modify_exts_cb,
722
                     std::optional<std::pair<Session, Session_Ticket>> session_and_ticket = std::nullopt,
723
                     std::optional<ExternalPSK> external_psk = std::nullopt,
724
                     std::vector<MockSignature> mock_signatures = {}) :
7✔
725
            TLS_Context(std::move(rng_in),
726
                        std::move(policy),
727
                        std::move(modify_exts_cb),
728
                        std::move(mock_signatures),
729
                        timestamp,
730
                        std::move(session_and_ticket),
731
                        std::move(external_psk),
732
                        false),
733
            client(m_callbacks,
35✔
734
                   m_session_mgr,
7✔
735
                   m_creds,
7✔
736
                   m_policy,
7✔
737
                   m_rng,
7✔
738
                   Botan::TLS::Server_Information("server"),
14✔
739
                   Botan::TLS::Protocol_Version::TLS_V13) {}
31✔
740

741
      void send(const std::vector<uint8_t>& data) override { client.send(data.data(), data.size()); }
2✔
742

743
      Botan::TLS::Client client;  // NOLINT(*-non-private-member-variable*)
744
};
745

746
class Server_Context : public TLS_Context {
747
   public:
748
      Server_Context(std::shared_ptr<Botan::RandomNumberGenerator> rng,
7✔
749
                     std::shared_ptr<const RFC8448_Text_Policy> policy,
750
                     uint64_t timestamp,
751
                     Modify_Exts_Fn modify_exts_cb,
752
                     std::vector<MockSignature> mock_signatures,
753
                     bool use_alternative_server_certificate = false,
754
                     std::optional<std::pair<Session, Session_Ticket>> session_and_ticket = std::nullopt,
755
                     std::optional<ExternalPSK> external_psk = std::nullopt) :
7✔
756
            TLS_Context(std::move(rng),
757
                        std::move(policy),
758
                        std::move(modify_exts_cb),
759
                        std::move(mock_signatures),
760
                        timestamp,
761
                        std::move(session_and_ticket),
762
                        std::move(external_psk),
763
                        use_alternative_server_certificate),
764
            server(m_callbacks, m_session_mgr, m_creds, m_policy, m_rng, false /* DTLS NYI */) {}
53✔
765

766
      void send(const std::vector<uint8_t>& data) override { server.send(data.data(), data.size()); }
2✔
767

768
      Botan::TLS::Server server;  // NOLINT(*-non-private-member-variable*)
769
};
770

771
void sort_extensions(Botan::TLS::Extensions& exts, const std::vector<Botan::TLS::Extension_Code>& expected_order) {
30✔
772
   for(const auto ext_type : expected_order) {
283✔
773
      auto ext = exts.take(ext_type);
253✔
774
      if(ext != nullptr) {
253✔
775
         exts.add(std::move(ext));
230✔
776
      }
777
   }
253✔
778
}
30✔
779

780
/**
781
 * Because of the nature of the RFC 8448 test data we need to produce bit-compatible
782
 * TLS messages. Hence we sort the generated TLS extensions exactly as expected.
783
 */
784
void sort_rfc8448_extensions(Botan::TLS::Extensions& exts,
23✔
785
                             Botan::TLS::Connection_Side side,
786
                             Botan::TLS::Handshake_Type /*type*/ = Botan::TLS::Handshake_Type::ClientHello) {
787
   if(side == Botan::TLS::Connection_Side::Client) {
23✔
788
      sort_extensions(exts,
12✔
789
                      {
790
                         Botan::TLS::Extension_Code::ServerNameIndication,
791
                         Botan::TLS::Extension_Code::SafeRenegotiation,
792
                         Botan::TLS::Extension_Code::SupportedGroups,
793
                         Botan::TLS::Extension_Code::SessionTicket,
794
                         Botan::TLS::Extension_Code::KeyShare,
795
                         Botan::TLS::Extension_Code::EarlyData,
796
                         Botan::TLS::Extension_Code::SupportedVersions,
797
                         Botan::TLS::Extension_Code::SignatureAlgorithms,
798
                         Botan::TLS::Extension_Code::Cookie,
799
                         Botan::TLS::Extension_Code::PskKeyExchangeModes,
800
                         Botan::TLS::Extension_Code::RecordSizeLimit,
801
                         Padding::static_type(),
802
                         Botan::TLS::Extension_Code::PresharedKey,
803
                      });
804
   } else {
805
      sort_extensions(exts,
34✔
806
                      {
807
                         Botan::TLS::Extension_Code::SupportedGroups,
808
                         Botan::TLS::Extension_Code::KeyShare,
809
                         Botan::TLS::Extension_Code::Cookie,
810
                         Botan::TLS::Extension_Code::SupportedVersions,
811
                         Botan::TLS::Extension_Code::SignatureAlgorithms,
812
                         Botan::TLS::Extension_Code::RecordSizeLimit,
813
                         Botan::TLS::Extension_Code::ServerNameIndication,
814
                         Botan::TLS::Extension_Code::EarlyData,
815
                      });
816
   }
817
}
23✔
818

819
void add_renegotiation_extension(Botan::TLS::Extensions& exts) {
5✔
820
   // Renegotiation is not possible in TLS 1.3. Nevertheless, RFC 8448 requires
821
   // to add this to the Client Hello for reasons.
822
   exts.add(new Renegotiation_Extension());  // NOLINT(*-owning-memory)
5✔
823
}
5✔
824

825
void add_early_data_indication(Botan::TLS::Extensions& exts) {
1✔
826
   exts.add(new Botan::TLS::EarlyDataIndication());  // NOLINT(*-owning-memory)
1✔
827
}
1✔
828

829
std::vector<uint8_t> strip_message_header(const std::vector<uint8_t>& msg) {
31✔
830
   BOTAN_ASSERT_NOMSG(msg.size() >= 4);
31✔
831
   return {msg.begin() + 4, msg.end()};
31✔
832
}
833

834
std::vector<MockSignature> make_mock_signatures(const VarMap& vars) {
9✔
835
   std::vector<MockSignature> result;
9✔
836

837
   auto mock = [&](const std::string& msg, const std::string& sig) {
27✔
838
      if(vars.has_key(msg) && vars.has_key(sig)) {
36✔
839
         result.push_back({vars.get_opt_bin(msg), vars.get_opt_bin(sig)});
11✔
840
      }
841
   };
29✔
842

843
   mock("Server_MessageToSign", "Server_MessageSignature");
18✔
844
   mock("Client_MessageToSign", "Client_MessageSignature");
18✔
845

846
   return result;
9✔
847
}
×
848

849
}  // namespace
850

851
/**
852
 * Traffic transcripts and supporting data for the TLS RFC 8448 and TLS policy
853
 * configuration is kept in data files (accessible via `Test:::data_file()`).
854
 *
855
 * tls_13_rfc8448/transcripts.vec
856
 *   The record transcripts and RNG outputs as defined/required in RFC 8448 in
857
 *   Botan's Text_Based_Test vector format. Data from each RFC 8448 section is
858
 *   placed in a sub-section of the *.vec file. Each of those sections needs a
859
 *   specific test case implementation that is dispatched in `run_one_test()`.
860
 *
861
 * tls_13_rfc8448/client_certificate.pem
862
 *   The client certificate provided in RFC 8448 used to perform client auth.
863
 *   Note that RFC 8448 _does not_ provide the associated private key but only
864
 *   the resulting signature in the client's CertificateVerify message.
865
 *
866
 * tls_13_rfc8448/server_certificate.pem
867
 * tls_13_rfc8448/server_key.pem
868
 *   The server certificate and its associated private key.
869
 *
870
 * tls_13_rfc8448/server_certificate_client_auth.pem
871
 *   The server certificate used in the Client Authentication test case.
872
 *
873
 * tls_13_rfc8448/client_raw_public_keypair.pem
874
 * tls_13_rfc8448/server_raw_public_keypair.pem
875
 *   The raw public key pairs for client and server authentication in the
876
 *   equally named test cases.
877
 *
878
 * tls-policy/rfc8448_*.txt
879
 *   Each RFC 8448 section test required a slightly adapted Botan TLS policy
880
 *   to enable/disable certain features under test.
881
 *
882
 * While the test cases are split into Client-side and Server-side tests, the
883
 * transcript data is reused. See the concrete implementations of the abstract
884
 * Test_TLS_RFC8448 test class.
885
 */
886
class Test_TLS_RFC8448 : public Text_Based_Test {
887
   protected:
888
      // Those tests are based on the test vectors in RFC8448.
889
      virtual std::vector<Test::Result> simple_1_rtt(const VarMap& vars) = 0;
890
      virtual std::vector<Test::Result> resumed_handshake_with_0_rtt(const VarMap& vars) = 0;
891
      virtual std::vector<Test::Result> hello_retry_request(const VarMap& vars) = 0;
892
      virtual std::vector<Test::Result> client_authentication(const VarMap& vars) = 0;
893
      virtual std::vector<Test::Result> middlebox_compatibility(const VarMap& vars) = 0;
894

895
      // Those tests provide the same information as RFC8448 test vectors but
896
      // were sourced otherwise. Typically by temporarily instrumenting our implementation.
897
      virtual std::vector<Test::Result> externally_provided_psk_with_ephemeral_key(const VarMap& vars) = 0;
898
      virtual std::vector<Test::Result> raw_public_key_with_client_authentication(const VarMap& vars) = 0;
899

900
      virtual std::string side() const = 0;
901

902
   public:
903
      Test_TLS_RFC8448() :
2✔
904
            Text_Based_Test("tls_13_rfc8448/transcripts.vec",
905
                            // mandatory data fields
906
                            "Client_RNG_Pool,"
907
                            "Server_RNG_Pool,"
908
                            "CurrentTimestamp,"
909
                            "Record_ClientHello_1,"
910
                            "Record_ServerHello,"
911
                            "Record_ServerHandshakeMessages,"
912
                            "Record_ClientFinished,"
913
                            "Record_Client_CloseNotify,"
914
                            "Record_Server_CloseNotify",
915
                            // optional data fields
916
                            "Message_ServerHello,"
917
                            "Message_EncryptedExtensions,"
918
                            "Message_CertificateRequest,"
919
                            "Message_Server_Certificate,"
920
                            "Message_Server_CertificateVerify,"
921
                            "Message_Server_Finished,"
922
                            "Record_HelloRetryRequest,"
923
                            "Record_ClientHello_2,"
924
                            "Record_NewSessionTicket,"
925
                            "Client_AppData,"
926
                            "Record_Client_AppData,"
927
                            "Server_AppData,"
928
                            "Record_Server_AppData,"
929
                            "Client_EarlyAppData,"
930
                            "Record_Client_EarlyAppData,"
931
                            "SessionTicket,"
932
                            "Client_SessionData,"
933
                            "Server_MessageToSign,"
934
                            "Server_MessageSignature,"
935
                            "Client_MessageToSign,"
936
                            "Client_MessageSignature,"
937
                            "HelloRetryRequest_Cookie,"
938
                            "PskIdentity,"
939
                            "PskPRF,"
940
                            "PskSecret") {}
4✔
941

942
      Test::Result run_one_test(const std::string& header, const VarMap& vars) override {
14✔
943
         if(header == "Simple_1RTT_Handshake") {
14✔
944
            return Test::Result("Simple 1-RTT (" + side() + " side)", simple_1_rtt(vars));
8✔
945
         } else if(header == "Resumed_0RTT_Handshake") {
12✔
946
            return Test::Result("Resumption with 0-RTT data (" + side() + " side)", resumed_handshake_with_0_rtt(vars));
8✔
947
         } else if(header == "HelloRetryRequest_Handshake") {
10✔
948
            return Test::Result("Handshake involving Hello Retry Request (" + side() + " side)",
6✔
949
                                hello_retry_request(vars));
6✔
950
         } else if(header == "Client_Authentication_Handshake") {
8✔
951
            return Test::Result("Client Authentication (" + side() + " side)", client_authentication(vars));
8✔
952
         } else if(header == "Middlebox_Compatibility_Mode") {
6✔
953
            return Test::Result("Middlebox Compatibility Mode (" + side() + " side)", middlebox_compatibility(vars));
8✔
954
         } else if(header == "Externally_Provided_PSK_with_Ephemeral_Key") {
4✔
955
            return Test::Result("Externally Provided PSK with ephemeral key (" + side() + " side)",
6✔
956
                                externally_provided_psk_with_ephemeral_key(vars));
6✔
957
         } else if(header == "RawPublicKey_With_Client_Authentication") {
2✔
958
            return Test::Result("RawPublicKey with Client Authentication (" + side() + " side)",
6✔
959
                                raw_public_key_with_client_authentication(vars));
6✔
960
         } else {
961
            return Test::Result::Failure("test dispatcher", "unknown sub-test: " + header);
×
962
         }
963
      }
964
};
965

966
class Test_TLS_RFC8448_Client : public Test_TLS_RFC8448 {
1✔
967
   private:
968
      std::string side() const override { return "Client"; }
7✔
969

970
      std::vector<Test::Result> simple_1_rtt(const VarMap& vars) override {
1✔
971
         auto rng = std::make_shared<Fixed_Output_RNG>("");
1✔
972

973
         // 32 - for client hello random
974
         // 32 - for KeyShare (eph. x25519 key pair)
975
         add_entropy(*rng, vars.get_req_bin("Client_RNG_Pool"));
2✔
976

977
         auto add_extensions_and_sort = [](Botan::TLS::Extensions& exts,
2✔
978
                                           Botan::TLS::Connection_Side side,
979
                                           Botan::TLS::Handshake_Type which_message) {
980
            if(which_message == Handshake_Type::ClientHello) {
1✔
981
               // For some reason, presumably checking compatibility, the RFC 8448 Client
982
               // Hello includes a (TLS 1.2) Session_Ticket extension. We don't normally add
983
               // this obsoleted extension in a TLS 1.3 client.
984
               exts.add(new Botan::TLS::Session_Ticket_Extension());  // NOLINT(*-owning-memory)
1✔
985

986
               add_renegotiation_extension(exts);
1✔
987
               sort_rfc8448_extensions(exts, side);
1✔
988
            }
989
         };
1✔
990

991
         std::unique_ptr<Client_Context> ctx;
1✔
992

993
         return {
1✔
994
            CHECK("Client Hello",
995
                  [&](Test::Result& result) {
1✔
996
                     ctx = std::make_unique<Client_Context>(rng,
1✔
997
                                                            std::make_shared<RFC8448_Text_Policy>("rfc8448_1rtt"),
2✔
998
                                                            vars.get_req_u64("CurrentTimestamp"),
1✔
999
                                                            add_extensions_and_sort);
1✔
1000

1001
                     result.confirm("client not closed", !ctx->client.is_closed());
2✔
1002
                     ctx->check_callback_invocations(result,
2✔
1003
                                                     "client hello prepared",
1004
                                                     {
1005
                                                        "tls_emit_data",
1006
                                                        "tls_inspect_handshake_msg_client_hello",
1007
                                                        "tls_modify_extensions_client_hello",
1008
                                                        "tls_generate_ephemeral_key",
1009
                                                        "tls_current_timestamp",
1010
                                                     });
1011

1012
                     result.test_eq(
2✔
1013
                        "TLS client hello", ctx->pull_send_buffer(), vars.get_req_bin("Record_ClientHello_1"));
3✔
1014
                  }),
1✔
1015

1016
            CHECK("Server Hello",
1017
                  [&](Test::Result& result) {
1✔
1018
                     result.require("ctx is available", ctx != nullptr);
1✔
1019
                     const auto server_hello = vars.get_req_bin("Record_ServerHello");
1✔
1020
                     // splitting the input data to test partial reads
1021
                     const std::vector<uint8_t> server_hello_a(server_hello.begin(), server_hello.begin() + 20);
1✔
1022
                     const std::vector<uint8_t> server_hello_b(server_hello.begin() + 20, server_hello.end());
1✔
1023

1024
                     ctx->client.received_data(server_hello_a);
1✔
1025
                     ctx->check_callback_invocations(result, "server hello partially received", {});
2✔
1026

1027
                     ctx->client.received_data(server_hello_b);
1✔
1028
                     ctx->check_callback_invocations(result,
2✔
1029
                                                     "server hello received",
1030
                                                     {"tls_inspect_handshake_msg_server_hello",
1031
                                                      "tls_examine_extensions_server_hello",
1032
                                                      "tls_ephemeral_key_agreement"});
1033

1034
                     result.confirm("client is not yet active", !ctx->client.is_active());
2✔
1035
                     result.confirm("handshake is not yet complete", !ctx->client.is_handshake_complete());
2✔
1036
                  }),
3✔
1037

1038
            CHECK("Server HS messages .. Client Finished",
1039
                  [&](Test::Result& result) {
1✔
1040
                     result.require("ctx is available", ctx != nullptr);
1✔
1041
                     ctx->client.received_data(vars.get_req_bin("Record_ServerHandshakeMessages"));
2✔
1042

1043
                     ctx->check_callback_invocations(result,
2✔
1044
                                                     "encrypted handshake messages received",
1045
                                                     {"tls_inspect_handshake_msg_encrypted_extensions",
1046
                                                      "tls_inspect_handshake_msg_certificate",
1047
                                                      "tls_inspect_handshake_msg_certificate_verify",
1048
                                                      "tls_inspect_handshake_msg_finished",
1049
                                                      "tls_examine_extensions_encrypted_extensions",
1050
                                                      "tls_examine_extensions_certificate",
1051
                                                      "tls_emit_data",
1052
                                                      "tls_current_timestamp",
1053
                                                      "tls_session_established",
1054
                                                      "tls_session_activated",
1055
                                                      "tls_verify_cert_chain",
1056
                                                      "tls_verify_message"});
1057
                     result.require("certificate exists", !ctx->certs_verified().empty());
1✔
1058
                     result.require("correct certificate", ctx->certs_verified().front() == server_certificate());
2✔
1059
                     result.require("client is active", ctx->client.is_active());
1✔
1060
                     result.confirm("handshake is complete", ctx->client.is_handshake_complete());
2✔
1061

1062
                     result.test_eq("correct handshake finished",
2✔
1063
                                    ctx->pull_send_buffer(),
2✔
1064
                                    vars.get_req_bin("Record_ClientFinished"));
2✔
1065
                  }),
1✔
1066

1067
            CHECK("Post-Handshake: NewSessionTicket",
1068
                  [&](Test::Result& result) {
1✔
1069
                     result.require("ctx is available", ctx != nullptr);
1✔
1070
                     result.require("no sessions so far", ctx->stored_sessions().empty());
1✔
1071
                     ctx->client.received_data(vars.get_req_bin("Record_NewSessionTicket"));
2✔
1072

1073
                     ctx->check_callback_invocations(result,
2✔
1074
                                                     "new session ticket received",
1075
                                                     {"tls_examine_extensions_new_session_ticket",
1076
                                                      "tls_should_persist_resumption_information",
1077
                                                      "tls_current_timestamp"});
1078
                     if(result.test_eq("session was stored", ctx->stored_sessions().size(), 1)) {
1✔
1079
                        const auto& [stored_session, stored_handle] = ctx->stored_sessions().front();
1✔
1080
                        result.require("session handle contains a ticket", stored_handle.ticket().has_value());
2✔
1081
                        result.test_is_eq("session was serialized as expected",
2✔
1082
                                          Botan::unlock(stored_session.DER_encode()),
4✔
1083
                                          vars.get_req_bin("Client_SessionData"));
2✔
1084
                     }
1085
                  }),
1✔
1086

1087
            CHECK("Send Application Data",
1088
                  [&](Test::Result& result) {
1✔
1089
                     result.require("ctx is available", ctx != nullptr);
1✔
1090
                     ctx->send(vars.get_req_bin("Client_AppData"));
3✔
1091

1092
                     ctx->check_callback_invocations(result, "application data sent", {"tls_emit_data"});
2✔
1093

1094
                     result.test_eq("correct client application data",
2✔
1095
                                    ctx->pull_send_buffer(),
2✔
1096
                                    vars.get_req_bin("Record_Client_AppData"));
2✔
1097
                  }),
1✔
1098

1099
            CHECK("Receive Application Data",
1100
                  [&](Test::Result& result) {
1✔
1101
                     result.require("ctx is available", ctx != nullptr);
1✔
1102
                     ctx->client.received_data(vars.get_req_bin("Record_Server_AppData"));
2✔
1103

1104
                     ctx->check_callback_invocations(result, "application data sent", {"tls_record_received"});
2✔
1105

1106
                     const auto rcvd = ctx->pull_receive_buffer();
1✔
1107
                     result.test_eq("decrypted application traffic", rcvd, vars.get_req_bin("Server_AppData"));
3✔
1108
                     result.test_is_eq("sequence number", ctx->last_received_seq_no(), uint64_t(1));
2✔
1109
                  }),
1✔
1110

1111
            CHECK("Close Connection",
1112
                  [&](Test::Result& result) {
1✔
1113
                     result.require("ctx is available", ctx != nullptr);
1✔
1114
                     ctx->client.close();
1✔
1115

1116
                     result.test_eq(
2✔
1117
                        "close payload", ctx->pull_send_buffer(), vars.get_req_bin("Record_Client_CloseNotify"));
3✔
1118
                     ctx->check_callback_invocations(result, "CLOSE_NOTIFY sent", {"tls_emit_data"});
2✔
1119

1120
                     ctx->client.received_data(vars.get_req_bin("Record_Server_CloseNotify"));
2✔
1121
                     ctx->check_callback_invocations(
2✔
1122
                        result, "CLOSE_NOTIFY received", {"tls_alert", "tls_peer_closed_connection"});
1123

1124
                     result.confirm("connection is closed", ctx->client.is_closed());
2✔
1125
                  }),
1✔
1126
         };
8✔
1127
      }
3✔
1128

1129
      std::vector<Test::Result> resumed_handshake_with_0_rtt(const VarMap& vars) override {
1✔
1130
         auto rng = std::make_unique<Fixed_Output_RNG>("");
1✔
1131

1132
         // 32 - for client hello random
1133
         // 32 - for KeyShare (eph. x25519 key pair)
1134
         add_entropy(*rng, vars.get_req_bin("Client_RNG_Pool"));
2✔
1135

1136
         auto add_extensions_and_sort = [](Botan::TLS::Extensions& exts,
2✔
1137
                                           Botan::TLS::Connection_Side side,
1138
                                           Botan::TLS::Handshake_Type which_message) {
1139
            if(which_message == Handshake_Type::ClientHello) {
1✔
1140
               exts.add(new Padding(87));  // NOLINT(*-owning-memory)
1✔
1141

1142
               add_renegotiation_extension(exts);
1✔
1143

1144
               // TODO: Implement early data support and remove this 'hack'.
1145
               //
1146
               // Currently, the production implementation will never add this
1147
               // extension even if the resumed session would allow early data.
1148
               add_early_data_indication(exts);
1✔
1149
               sort_rfc8448_extensions(exts, side);
1✔
1150
            }
1151
         };
1✔
1152

1153
         std::unique_ptr<Client_Context> ctx;
1✔
1154

1155
         return {
1✔
1156
            CHECK("Client Hello",
1157
                  [&](Test::Result& result) {
1✔
1158
                     ctx = std::make_unique<Client_Context>(
1✔
1159
                        std::move(rng),
1160
                        std::make_shared<RFC8448_Text_Policy>("rfc8448_1rtt"),
2✔
1161
                        vars.get_req_u64("CurrentTimestamp"),
1✔
1162
                        add_extensions_and_sort,
1163
                        std::pair{Botan::TLS::Session(vars.get_req_bin("Client_SessionData")),
5✔
1164
                                  Botan::TLS::Session_Ticket(vars.get_req_bin("SessionTicket"))});
3✔
1165

1166
                     result.confirm("client not closed", !ctx->client.is_closed());
2✔
1167
                     ctx->check_callback_invocations(result,
2✔
1168
                                                     "client hello prepared",
1169
                                                     {
1170
                                                        "tls_emit_data",
1171
                                                        "tls_inspect_handshake_msg_client_hello",
1172
                                                        "tls_modify_extensions_client_hello",
1173
                                                        "tls_current_timestamp",
1174
                                                        "tls_generate_ephemeral_key",
1175
                                                     });
1176

1177
                     result.test_eq(
2✔
1178
                        "TLS client hello", ctx->pull_send_buffer(), vars.get_req_bin("Record_ClientHello_1"));
3✔
1179
                  })
1✔
1180

1181
            // TODO: The rest of this test vector requires 0-RTT which is not
1182
            //       yet implemented. For now we can only test the client's
1183
            //       ability to offer a session resumption via PSK.
1184
         };
2✔
1185
      }
2✔
1186

1187
      std::vector<Test::Result> hello_retry_request(const VarMap& vars) override {
1✔
1188
         auto add_extensions_and_sort = [flights = 0](Botan::TLS::Extensions& exts,
3✔
1189
                                                      Botan::TLS::Connection_Side side,
1190
                                                      Botan::TLS::Handshake_Type which_message) mutable {
1191
            if(which_message == Handshake_Type::ClientHello) {
2✔
1192
               ++flights;
2✔
1193

1194
               if(flights == 1) {
2✔
1195
                  add_renegotiation_extension(exts);
1✔
1196
               }
1197

1198
               // For some reason RFC8448 decided to require this (fairly obscure) extension
1199
               // in the second flight of the Client_Hello.
1200
               if(flights == 2) {
2✔
1201
                  exts.add(new Padding(175));  // NOLINT(*-owning-memory)
1✔
1202
               }
1203

1204
               sort_rfc8448_extensions(exts, side);
2✔
1205
            }
1206
         };
2✔
1207

1208
         // Fallback RNG is required to for blinding in ECDH with P-256
1209
         auto& fallback_rng = this->rng();
1✔
1210
         auto rng = std::make_unique<Fixed_Output_RNG>(fallback_rng);
1✔
1211

1212
         // 32 - client hello random
1213
         // 32 - eph. x25519 key pair
1214
         // 32 - eph. P-256 key pair
1215
         add_entropy(*rng, vars.get_req_bin("Client_RNG_Pool"));
2✔
1216

1217
         std::unique_ptr<Client_Context> ctx;
1✔
1218

1219
         return {
1✔
1220
            CHECK("Client Hello",
1221
                  [&](Test::Result& result) {
1✔
1222
                     ctx = std::make_unique<Client_Context>(std::move(rng),
1✔
1223
                                                            std::make_shared<RFC8448_Text_Policy>("rfc8448_hrr_client"),
2✔
1224
                                                            vars.get_req_u64("CurrentTimestamp"),
1✔
1225
                                                            add_extensions_and_sort);
1✔
1226
                     result.confirm("client not closed", !ctx->client.is_closed());
2✔
1227

1228
                     ctx->check_callback_invocations(result,
2✔
1229
                                                     "client hello prepared",
1230
                                                     {
1231
                                                        "tls_emit_data",
1232
                                                        "tls_inspect_handshake_msg_client_hello",
1233
                                                        "tls_modify_extensions_client_hello",
1234
                                                        "tls_generate_ephemeral_key",
1235
                                                        "tls_current_timestamp",
1236
                                                     });
1237

1238
                     result.test_eq(
2✔
1239
                        "TLS client hello (1)", ctx->pull_send_buffer(), vars.get_req_bin("Record_ClientHello_1"));
3✔
1240
                  }),
1✔
1241

1242
            CHECK("Hello Retry Request .. second Client Hello",
1243
                  [&](Test::Result& result) {
1✔
1244
                     result.require("ctx is available", ctx != nullptr);
1✔
1245
                     ctx->client.received_data(vars.get_req_bin("Record_HelloRetryRequest"));
2✔
1246

1247
                     ctx->check_callback_invocations(result,
2✔
1248
                                                     "hello retry request received",
1249
                                                     {
1250
                                                        "tls_emit_data",
1251
                                                        "tls_inspect_handshake_msg_hello_retry_request",
1252
                                                        "tls_examine_extensions_hello_retry_request",
1253
                                                        "tls_inspect_handshake_msg_client_hello",
1254
                                                        "tls_modify_extensions_client_hello",
1255
                                                        "tls_generate_ephemeral_key",
1256
                                                     });
1257

1258
                     result.test_eq(
2✔
1259
                        "TLS client hello (2)", ctx->pull_send_buffer(), vars.get_req_bin("Record_ClientHello_2"));
3✔
1260
                  }),
1✔
1261

1262
            CHECK("Server Hello",
1263
                  [&](Test::Result& result) {
1✔
1264
                     result.require("ctx is available", ctx != nullptr);
1✔
1265
                     ctx->client.received_data(vars.get_req_bin("Record_ServerHello"));
2✔
1266

1267
                     ctx->check_callback_invocations(result,
2✔
1268
                                                     "server hello received",
1269
                                                     {
1270
                                                        "tls_inspect_handshake_msg_server_hello",
1271
                                                        "tls_examine_extensions_server_hello",
1272
                                                        "tls_ephemeral_key_agreement",
1273
                                                     });
1274
                  }),
1✔
1275

1276
            CHECK("Server HS Messages .. Client Finished",
1277
                  [&](Test::Result& result) {
1✔
1278
                     result.require("ctx is available", ctx != nullptr);
1✔
1279
                     ctx->client.received_data(vars.get_req_bin("Record_ServerHandshakeMessages"));
2✔
1280

1281
                     ctx->check_callback_invocations(result,
2✔
1282
                                                     "encrypted handshake messages received",
1283
                                                     {"tls_inspect_handshake_msg_encrypted_extensions",
1284
                                                      "tls_inspect_handshake_msg_certificate",
1285
                                                      "tls_inspect_handshake_msg_certificate_verify",
1286
                                                      "tls_inspect_handshake_msg_finished",
1287
                                                      "tls_examine_extensions_encrypted_extensions",
1288
                                                      "tls_examine_extensions_certificate",
1289
                                                      "tls_emit_data",
1290
                                                      "tls_current_timestamp",
1291
                                                      "tls_session_established",
1292
                                                      "tls_session_activated",
1293
                                                      "tls_verify_cert_chain",
1294
                                                      "tls_verify_message"});
1295

1296
                     result.test_eq(
2✔
1297
                        "client finished", ctx->pull_send_buffer(), vars.get_req_bin("Record_ClientFinished"));
3✔
1298
                  }),
1✔
1299

1300
            CHECK("Close Connection",
1301
                  [&](Test::Result& result) {
1✔
1302
                     result.require("ctx is available", ctx != nullptr);
1✔
1303
                     ctx->client.close();
1✔
1304
                     ctx->check_callback_invocations(
2✔
1305
                        result, "encrypted handshake messages received", {"tls_emit_data"});
1306
                     result.test_eq(
2✔
1307
                        "client close notify", ctx->pull_send_buffer(), vars.get_req_bin("Record_Client_CloseNotify"));
3✔
1308

1309
                     ctx->client.received_data(vars.get_req_bin("Record_Server_CloseNotify"));
2✔
1310
                     ctx->check_callback_invocations(
2✔
1311
                        result, "encrypted handshake messages received", {"tls_alert", "tls_peer_closed_connection"});
1312

1313
                     result.confirm("connection is closed", ctx->client.is_closed());
2✔
1314
                  }),
1✔
1315
         };
6✔
1316
      }
2✔
1317

1318
      std::vector<Test::Result> client_authentication(const VarMap& vars) override {
1✔
1319
         auto rng = std::make_unique<Fixed_Output_RNG>("");
1✔
1320

1321
         // 32 - for client hello random
1322
         // 32 - for eph. x25519 key pair
1323
         add_entropy(*rng, vars.get_req_bin("Client_RNG_Pool"));
2✔
1324

1325
         auto add_extensions_and_sort = [&](Botan::TLS::Extensions& exts,
3✔
1326
                                            Botan::TLS::Connection_Side side,
1327
                                            Botan::TLS::Handshake_Type which_message) {
1328
            if(which_message == Handshake_Type::ClientHello) {
2✔
1329
               add_renegotiation_extension(exts);
1✔
1330
               sort_rfc8448_extensions(exts, side);
1✔
1331
            }
1332
         };
1333

1334
         std::unique_ptr<Client_Context> ctx;
1✔
1335

1336
         return {
1✔
1337
            CHECK("Client Hello",
1338
                  [&](Test::Result& result) {
1✔
1339
                     ctx = std::make_unique<Client_Context>(std::move(rng),
1✔
1340
                                                            std::make_shared<RFC8448_Text_Policy>("rfc8448_1rtt"),
2✔
1341
                                                            vars.get_req_u64("CurrentTimestamp"),
1✔
1342
                                                            add_extensions_and_sort,
1343
                                                            std::nullopt,
1344
                                                            std::nullopt,
1345
                                                            make_mock_signatures(vars));
3✔
1346

1347
                     ctx->check_callback_invocations(result,
2✔
1348
                                                     "initial callbacks",
1349
                                                     {
1350
                                                        "tls_emit_data",
1351
                                                        "tls_inspect_handshake_msg_client_hello",
1352
                                                        "tls_modify_extensions_client_hello",
1353
                                                        "tls_generate_ephemeral_key",
1354
                                                        "tls_current_timestamp",
1355
                                                     });
1356

1357
                     result.test_eq("Client Hello", ctx->pull_send_buffer(), vars.get_req_bin("Record_ClientHello_1"));
4✔
1358
                  }),
1✔
1359

1360
            CHECK("Server Hello",
1361
                  [&](auto& result) {
1✔
1362
                     result.require("ctx is available", ctx != nullptr);
1✔
1363
                     ctx->client.received_data(vars.get_req_bin("Record_ServerHello"));
2✔
1364

1365
                     ctx->check_callback_invocations(result,
2✔
1366
                                                     "callbacks after server hello",
1367
                                                     {
1368
                                                        "tls_examine_extensions_server_hello",
1369
                                                        "tls_inspect_handshake_msg_server_hello",
1370
                                                        "tls_ephemeral_key_agreement",
1371
                                                     });
1372
                  }),
1✔
1373

1374
            CHECK("other handshake messages and client auth",
1375
                  [&](Test::Result& result) {
1✔
1376
                     result.require("ctx is available", ctx != nullptr);
1✔
1377
                     ctx->client.received_data(vars.get_req_bin("Record_ServerHandshakeMessages"));
2✔
1378

1379
                     ctx->check_callback_invocations(result,
2✔
1380
                                                     "signing callbacks invoked",
1381
                                                     {
1382
                                                        "tls_sign_message",
1383
                                                        "tls_emit_data",
1384
                                                        "tls_examine_extensions_encrypted_extensions",
1385
                                                        "tls_examine_extensions_certificate",
1386
                                                        "tls_examine_extensions_certificate_request",
1387
                                                        "tls_modify_extensions_certificate",
1388
                                                        "tls_inspect_handshake_msg_certificate",
1389
                                                        "tls_inspect_handshake_msg_certificate_request",
1390
                                                        "tls_inspect_handshake_msg_certificate_verify",
1391
                                                        "tls_inspect_handshake_msg_encrypted_extensions",
1392
                                                        "tls_inspect_handshake_msg_finished",
1393
                                                        "tls_current_timestamp",
1394
                                                        "tls_session_established",
1395
                                                        "tls_session_activated",
1396
                                                        "tls_verify_cert_chain",
1397
                                                        "tls_verify_message",
1398
                                                     });
1399

1400
                     // ClientFinished contains the entire coalesced client authentication flight
1401
                     // Messages: Certificate, CertificateVerify, Finished
1402
                     result.test_eq(
2✔
1403
                        "Client Auth and Finished", ctx->pull_send_buffer(), vars.get_req_bin("Record_ClientFinished"));
3✔
1404
                  }),
1✔
1405

1406
            CHECK("Close Connection",
1407
                  [&](Test::Result& result) {
1✔
1408
                     result.require("ctx is available", ctx != nullptr);
1✔
1409
                     ctx->client.close();
1✔
1410
                     result.test_eq(
2✔
1411
                        "Client close_notify", ctx->pull_send_buffer(), vars.get_req_bin("Record_Client_CloseNotify"));
3✔
1412

1413
                     ctx->check_callback_invocations(result,
2✔
1414
                                                     "after sending close notify",
1415
                                                     {
1416
                                                        "tls_emit_data",
1417
                                                     });
1418

1419
                     ctx->client.received_data(vars.get_req_bin("Record_Server_CloseNotify"));
2✔
1420
                     result.confirm("connection closed", ctx->client.is_closed());
2✔
1421

1422
                     ctx->check_callback_invocations(
2✔
1423
                        result, "after receiving close notify", {"tls_alert", "tls_peer_closed_connection"});
1424
                  }),
1✔
1425
         };
5✔
1426
      }
2✔
1427

1428
      std::vector<Test::Result> middlebox_compatibility(const VarMap& vars) override {
1✔
1429
         auto rng = std::make_unique<Fixed_Output_RNG>("");
1✔
1430

1431
         // 32 - client hello random
1432
         // 32 - legacy session ID
1433
         // 32 - eph. x25519 key pair
1434
         add_entropy(*rng, vars.get_req_bin("Client_RNG_Pool"));
2✔
1435

1436
         auto add_extensions_and_sort = [&](Botan::TLS::Extensions& exts,
2✔
1437
                                            Botan::TLS::Connection_Side side,
1438
                                            Botan::TLS::Handshake_Type which_message) {
1439
            if(which_message == Handshake_Type::ClientHello) {
1✔
1440
               add_renegotiation_extension(exts);
1✔
1441
               sort_rfc8448_extensions(exts, side);
1✔
1442
            }
1443
         };
1444

1445
         std::unique_ptr<Client_Context> ctx;
1✔
1446

1447
         return {
1✔
1448
            CHECK("Client Hello",
1449
                  [&](Test::Result& result) {
1✔
1450
                     ctx =
1✔
1451
                        std::make_unique<Client_Context>(std::move(rng),
1✔
1452
                                                         std::make_shared<RFC8448_Text_Policy>("rfc8448_compat_client"),
2✔
1453
                                                         vars.get_req_u64("CurrentTimestamp"),
1✔
1454
                                                         add_extensions_and_sort);
1✔
1455

1456
                     result.test_eq("Client Hello", ctx->pull_send_buffer(), vars.get_req_bin("Record_ClientHello_1"));
4✔
1457

1458
                     ctx->check_callback_invocations(result,
2✔
1459
                                                     "client hello prepared",
1460
                                                     {
1461
                                                        "tls_emit_data",
1462
                                                        "tls_inspect_handshake_msg_client_hello",
1463
                                                        "tls_modify_extensions_client_hello",
1464
                                                        "tls_generate_ephemeral_key",
1465
                                                        "tls_current_timestamp",
1466
                                                     });
1467
                  }),
1✔
1468

1469
            CHECK("Server Hello + other handshake messages",
1470
                  [&](Test::Result& result) {
1✔
1471
                     result.require("ctx is available", ctx != nullptr);
1✔
1472
                     ctx->client.received_data(
2✔
1473
                        Botan::concat(vars.get_req_bin("Record_ServerHello"),
4✔
1474
                                      // ServerHandshakeMessages contains the expected ChangeCipherSpec record
1475
                                      vars.get_req_bin("Record_ServerHandshakeMessages")));
2✔
1476

1477
                     ctx->check_callback_invocations(result,
2✔
1478
                                                     "callbacks after server's first flight",
1479
                                                     {
1480
                                                        "tls_inspect_handshake_msg_server_hello",
1481
                                                        "tls_inspect_handshake_msg_encrypted_extensions",
1482
                                                        "tls_inspect_handshake_msg_certificate",
1483
                                                        "tls_inspect_handshake_msg_certificate_verify",
1484
                                                        "tls_inspect_handshake_msg_finished",
1485
                                                        "tls_examine_extensions_server_hello",
1486
                                                        "tls_examine_extensions_encrypted_extensions",
1487
                                                        "tls_examine_extensions_certificate",
1488
                                                        "tls_emit_data",
1489
                                                        "tls_current_timestamp",
1490
                                                        "tls_session_established",
1491
                                                        "tls_session_activated",
1492
                                                        "tls_verify_cert_chain",
1493
                                                        "tls_verify_message",
1494
                                                        "tls_ephemeral_key_agreement",
1495
                                                     });
1496

1497
                     result.test_eq("CCS + Client Finished",
2✔
1498
                                    ctx->pull_send_buffer(),
2✔
1499
                                    // ClientFinished contains the expected ChangeCipherSpec record
1500
                                    vars.get_req_bin("Record_ClientFinished"));
2✔
1501

1502
                     result.confirm("client is ready to send application traffic", ctx->client.is_active());
2✔
1503
                     result.confirm("handshake is complete", ctx->client.is_handshake_complete());
2✔
1504
                  }),
1✔
1505

1506
            CHECK("Close connection",
1507
                  [&](Test::Result& result) {
1✔
1508
                     result.require("ctx is available", ctx != nullptr);
1✔
1509
                     ctx->client.close();
1✔
1510

1511
                     result.test_eq(
2✔
1512
                        "Client close_notify", ctx->pull_send_buffer(), vars.get_req_bin("Record_Client_CloseNotify"));
3✔
1513

1514
                     result.require("client cannot send application traffic anymore", !ctx->client.is_active());
1✔
1515
                     result.require("client is not fully closed yet", !ctx->client.is_closed());
1✔
1516
                     result.confirm("handshake stays completed", ctx->client.is_handshake_complete());
2✔
1517

1518
                     ctx->client.received_data(vars.get_req_bin("Record_Server_CloseNotify"));
2✔
1519

1520
                     result.confirm("client connection was terminated", ctx->client.is_closed());
2✔
1521
                  }),
1✔
1522
         };
4✔
1523
      }
2✔
1524

1525
      std::vector<Test::Result> externally_provided_psk_with_ephemeral_key(const VarMap& vars) override {
1✔
1526
         auto rng = std::make_unique<Fixed_Output_RNG>("");
1✔
1527

1528
         // 32 - for client hello random
1529
         // 32 - for KeyShare (eph. x25519 key pair)
1530
         add_entropy(*rng, vars.get_req_bin("Client_RNG_Pool"));
2✔
1531

1532
         auto sort_our_extensions = [](Botan::TLS::Extensions& exts,
2✔
1533
                                       Botan::TLS::Connection_Side /* side */,
1534
                                       Botan::TLS::Handshake_Type /* which_message */) {
1535
            // This is the order of extensions when we first introduced the PSK
1536
            // implementation and generated the transcript. To stay compatible
1537
            // with the now hard-coded transcript, we pin the extension order.
1538
            sort_extensions(exts,
1✔
1539
                            {
1540
                               Botan::TLS::Extension_Code::ServerNameIndication,
1541
                               Botan::TLS::Extension_Code::SupportedGroups,
1542
                               Botan::TLS::Extension_Code::KeyShare,
1543
                               Botan::TLS::Extension_Code::SupportedVersions,
1544
                               Botan::TLS::Extension_Code::SignatureAlgorithms,
1545
                               Botan::TLS::Extension_Code::PskKeyExchangeModes,
1546
                               Botan::TLS::Extension_Code::RecordSizeLimit,
1547
                               Botan::TLS::Extension_Code::PresharedKey,
1548
                            });
1549
         };
1✔
1550

1551
         std::unique_ptr<Client_Context> ctx;
1✔
1552

1553
         return {
1✔
1554
            CHECK("Client Hello",
1555
                  [&](Test::Result& result) {
1✔
1556
                     ctx = std::make_unique<Client_Context>(
1✔
1557
                        std::move(rng),
1558
                        std::make_shared<RFC8448_Text_Policy>("rfc8448_psk_dhe", false /* no rfc8448 */),
2✔
1559
                        vars.get_req_u64("CurrentTimestamp"),
1✔
1560
                        sort_our_extensions,
1561
                        std::nullopt,
1562
                        ExternalPSK(vars.get_req_str("PskIdentity"),
2✔
1563
                                    vars.get_req_str("PskPRF"),
2✔
1564
                                    lock(vars.get_req_bin("PskSecret"))));
5✔
1565

1566
                     result.confirm("client not closed", !ctx->client.is_closed());
2✔
1567
                     ctx->check_callback_invocations(result,
2✔
1568
                                                     "client hello prepared",
1569
                                                     {
1570
                                                        "tls_emit_data",
1571
                                                        "tls_inspect_handshake_msg_client_hello",
1572
                                                        "tls_modify_extensions_client_hello",
1573
                                                        "tls_current_timestamp",
1574
                                                        "tls_generate_ephemeral_key",
1575
                                                     });
1576

1577
                     result.test_eq(
2✔
1578
                        "TLS client hello", ctx->pull_send_buffer(), vars.get_req_bin("Record_ClientHello_1"));
3✔
1579
                  }),
1✔
1580

1581
            CHECK("Server Hello",
1582
                  [&](Test::Result& result) {
1✔
1583
                     result.require("ctx is available", ctx != nullptr);
1✔
1584
                     const auto server_hello = vars.get_req_bin("Record_ServerHello");
1✔
1585
                     ctx->client.received_data(server_hello);
1✔
1586
                     ctx->check_callback_invocations(result,
2✔
1587
                                                     "server hello received",
1588
                                                     {"tls_inspect_handshake_msg_server_hello",
1589
                                                      "tls_examine_extensions_server_hello",
1590
                                                      "tls_ephemeral_key_agreement"});
1591

1592
                     result.confirm("client is not yet active", !ctx->client.is_active());
2✔
1593
                     result.confirm("handshake is not yet complete", !ctx->client.is_handshake_complete());
2✔
1594
                  }),
1✔
1595

1596
            CHECK(
1597
               "Server HS messages .. Client Finished",
1598
               [&](Test::Result& result) {
1✔
1599
                  result.require("ctx is available", ctx != nullptr);
1✔
1600
                  ctx->client.received_data(vars.get_req_bin("Record_ServerHandshakeMessages"));
2✔
1601

1602
                  ctx->check_callback_invocations(result,
2✔
1603
                                                  "encrypted handshake messages received",
1604
                                                  {"tls_inspect_handshake_msg_encrypted_extensions",
1605
                                                   "tls_inspect_handshake_msg_finished",
1606
                                                   "tls_examine_extensions_encrypted_extensions",
1607
                                                   "tls_emit_data",
1608
                                                   "tls_current_timestamp",
1609
                                                   "tls_session_established",
1610
                                                   "tls_session_activated"});
1611
                  result.require("PSK negotiated", ctx->psk_identity_negotiated() == vars.get_req_str("PskIdentity"));
2✔
1612
                  result.require("client is active", ctx->client.is_active());
1✔
1613
                  result.confirm("handshake is complete", ctx->client.is_handshake_complete());
2✔
1614

1615
                  result.test_eq(
2✔
1616
                     "correct handshake finished", ctx->pull_send_buffer(), vars.get_req_bin("Record_ClientFinished"));
3✔
1617
               }),
1✔
1618

1619
            CHECK("Send Application Data",
1620
                  [&](Test::Result& result) {
1✔
1621
                     result.require("ctx is available", ctx != nullptr);
1✔
1622
                     ctx->send(vars.get_req_bin("Client_AppData"));
3✔
1623

1624
                     ctx->check_callback_invocations(result, "application data sent", {"tls_emit_data"});
2✔
1625

1626
                     result.test_eq("correct client application data",
2✔
1627
                                    ctx->pull_send_buffer(),
2✔
1628
                                    vars.get_req_bin("Record_Client_AppData"));
2✔
1629
                  }),
1✔
1630

1631
            CHECK("Receive Application Data",
1632
                  [&](Test::Result& result) {
1✔
1633
                     result.require("ctx is available", ctx != nullptr);
1✔
1634
                     ctx->client.received_data(vars.get_req_bin("Record_Server_AppData"));
2✔
1635

1636
                     ctx->check_callback_invocations(result, "application data sent", {"tls_record_received"});
2✔
1637

1638
                     const auto rcvd = ctx->pull_receive_buffer();
1✔
1639
                     result.test_eq("decrypted application traffic", rcvd, vars.get_req_bin("Server_AppData"));
3✔
1640
                     result.test_is_eq("sequence number", ctx->last_received_seq_no(), uint64_t(0));
2✔
1641
                  }),
1✔
1642

1643
            CHECK("Close Connection",
1644
                  [&](Test::Result& result) {
1✔
1645
                     result.require("ctx is available", ctx != nullptr);
1✔
1646
                     ctx->client.close();
1✔
1647

1648
                     result.test_eq(
2✔
1649
                        "close payload", ctx->pull_send_buffer(), vars.get_req_bin("Record_Client_CloseNotify"));
3✔
1650
                     ctx->check_callback_invocations(result, "CLOSE_NOTIFY sent", {"tls_emit_data"});
2✔
1651

1652
                     ctx->client.received_data(vars.get_req_bin("Record_Server_CloseNotify"));
2✔
1653
                     ctx->check_callback_invocations(
2✔
1654
                        result, "CLOSE_NOTIFY received", {"tls_alert", "tls_peer_closed_connection"});
1655

1656
                     result.confirm("connection is closed", ctx->client.is_closed());
2✔
1657
                  }),
1✔
1658
         };
7✔
1659
      }
2✔
1660

1661
      std::vector<Test::Result> raw_public_key_with_client_authentication(const VarMap& vars) override {
1✔
1662
         auto rng = std::make_unique<Fixed_Output_RNG>("");
1✔
1663

1664
         // 32 - for client hello random
1665
         // 32 - for KeyShare (eph. x25519 key pair)
1666
         add_entropy(*rng, vars.get_req_bin("Client_RNG_Pool"));
2✔
1667

1668
         auto sort_our_extensions = [&](Botan::TLS::Extensions& exts,
3✔
1669
                                        Botan::TLS::Connection_Side /* side */,
1670
                                        Botan::TLS::Handshake_Type /* which_message */) {
1671
            // This is the order of extensions when we first introduced the raw
1672
            // public key authentication implementation and generated the transcript.
1673
            // To stay compatible with the now hard-coded transcript, we pin the
1674
            // extension order.
1675
            sort_extensions(exts,
2✔
1676
                            {
1677
                               Botan::TLS::Extension_Code::ServerNameIndication,
1678
                               Botan::TLS::Extension_Code::SupportedGroups,
1679
                               Botan::TLS::Extension_Code::KeyShare,
1680
                               Botan::TLS::Extension_Code::SupportedVersions,
1681
                               Botan::TLS::Extension_Code::SignatureAlgorithms,
1682
                               Botan::TLS::Extension_Code::PskKeyExchangeModes,
1683
                               Botan::TLS::Extension_Code::RecordSizeLimit,
1684
                               Botan::TLS::Extension_Code::ClientCertificateType,
1685
                               Botan::TLS::Extension_Code::ServerCertificateType,
1686
                            });
1687
         };
2✔
1688

1689
         std::unique_ptr<Client_Context> ctx;
1✔
1690

1691
         return {
1✔
1692
            CHECK("Client Hello",
1693
                  [&](Test::Result& result) {
1✔
1694
                     ctx = std::make_unique<Client_Context>(std::move(rng),
1✔
1695
                                                            std::make_shared<RFC8448_Text_Policy>("rfc8448_rawpubkey"),
2✔
1696
                                                            vars.get_req_u64("CurrentTimestamp"),
1✔
1697
                                                            sort_our_extensions,
1698
                                                            std::nullopt,
1699
                                                            std::nullopt,
1700
                                                            make_mock_signatures(vars));
3✔
1701

1702
                     ctx->check_callback_invocations(result,
2✔
1703
                                                     "initial callbacks",
1704
                                                     {
1705
                                                        "tls_emit_data",
1706
                                                        "tls_inspect_handshake_msg_client_hello",
1707
                                                        "tls_modify_extensions_client_hello",
1708
                                                        "tls_generate_ephemeral_key",
1709
                                                        "tls_current_timestamp",
1710
                                                     });
1711

1712
                     result.test_eq("Client Hello", ctx->pull_send_buffer(), vars.get_req_bin("Record_ClientHello_1"));
4✔
1713
                  }),
1✔
1714

1715
            CHECK("Server Hello",
1716
                  [&](auto& result) {
1✔
1717
                     result.require("ctx is available", ctx != nullptr);
1✔
1718
                     ctx->client.received_data(vars.get_req_bin("Record_ServerHello"));
2✔
1719

1720
                     ctx->check_callback_invocations(result,
2✔
1721
                                                     "callbacks after server hello",
1722
                                                     {
1723
                                                        "tls_examine_extensions_server_hello",
1724
                                                        "tls_inspect_handshake_msg_server_hello",
1725
                                                        "tls_ephemeral_key_agreement",
1726
                                                     });
1727
                  }),
1✔
1728

1729
            CHECK("other handshake messages and client auth",
1730
                  [&](Test::Result& result) {
1✔
1731
                     result.require("ctx is available", ctx != nullptr);
1✔
1732
                     ctx->client.received_data(vars.get_req_bin("Record_ServerHandshakeMessages"));
2✔
1733

1734
                     ctx->check_callback_invocations(result,
2✔
1735
                                                     "signing callbacks invoked",
1736
                                                     {
1737
                                                        "tls_sign_message",
1738
                                                        "tls_emit_data",
1739
                                                        "tls_examine_extensions_encrypted_extensions",
1740
                                                        "tls_examine_extensions_certificate",
1741
                                                        "tls_examine_extensions_certificate_request",
1742
                                                        "tls_modify_extensions_certificate",
1743
                                                        "tls_inspect_handshake_msg_certificate",
1744
                                                        "tls_inspect_handshake_msg_certificate_request",
1745
                                                        "tls_inspect_handshake_msg_certificate_verify",
1746
                                                        "tls_inspect_handshake_msg_encrypted_extensions",
1747
                                                        "tls_inspect_handshake_msg_finished",
1748
                                                        "tls_current_timestamp",
1749
                                                        "tls_session_established",
1750
                                                        "tls_session_activated",
1751
                                                        "tls_verify_raw_public_key",
1752
                                                        "tls_verify_message",
1753
                                                     });
1754

1755
                     const auto raw_pk = ctx->client.peer_raw_public_key();
1✔
1756
                     result.confirm(
2✔
1757
                        "Received server's raw public key",
1758
                        raw_pk && raw_pk->fingerprint_public() == server_raw_public_key_pair()->fingerprint_public());
5✔
1759

1760
                     // ClientFinished contains the entire coalesced client authentication flight
1761
                     // Messages: Certificate, CertificateVerify, Finished
1762
                     result.test_eq(
2✔
1763
                        "Client Auth and Finished", ctx->pull_send_buffer(), vars.get_req_bin("Record_ClientFinished"));
3✔
1764
                  }),
1✔
1765

1766
            CHECK("Close Connection",
1767
                  [&](Test::Result& result) {
1✔
1768
                     result.require("ctx is available", ctx != nullptr);
1✔
1769
                     ctx->client.close();
1✔
1770
                     result.test_eq(
2✔
1771
                        "Client close_notify", ctx->pull_send_buffer(), vars.get_req_bin("Record_Client_CloseNotify"));
3✔
1772

1773
                     ctx->check_callback_invocations(result,
2✔
1774
                                                     "after sending close notify",
1775
                                                     {
1776
                                                        "tls_emit_data",
1777
                                                     });
1778

1779
                     ctx->client.received_data(vars.get_req_bin("Record_Server_CloseNotify"));
2✔
1780
                     result.confirm("connection closed", ctx->client.is_closed());
2✔
1781

1782
                     ctx->check_callback_invocations(
2✔
1783
                        result, "after receiving close notify", {"tls_alert", "tls_peer_closed_connection"});
1784
                  }),
1✔
1785
         };
5✔
1786
      }
2✔
1787
};
1788

1789
class Test_TLS_RFC8448_Server : public Test_TLS_RFC8448 {
1✔
1790
   private:
1791
      std::string side() const override { return "Server"; }
7✔
1792

1793
      std::vector<Test::Result> simple_1_rtt(const VarMap& vars) override {
1✔
1794
         auto rng = std::make_unique<Fixed_Output_RNG>("");
1✔
1795

1796
         // 32 - for server hello random
1797
         // 32 - for KeyShare (eph. x25519 key pair)  --  I guess?
1798
         //  4 - for ticket_age_add (in New Session Ticket)
1799
         add_entropy(*rng, vars.get_req_bin("Server_RNG_Pool"));
2✔
1800

1801
         std::unique_ptr<Server_Context> ctx;
1✔
1802

1803
         return {
1✔
1804
            CHECK("Send Client Hello",
1805
                  [&](Test::Result& result) {
1✔
1806
                     auto add_early_data_and_sort = [&](Botan::TLS::Extensions& exts,
5✔
1807
                                                        Botan::TLS::Connection_Side side,
1808
                                                        Botan::TLS::Handshake_Type type) {
1809
                        if(type == Handshake_Type::NewSessionTicket) {
4✔
1810
                           exts.add(new EarlyDataIndication(1024));  // NOLINT(*-owning-memory)
1✔
1811
                        }
1812
                        sort_rfc8448_extensions(exts, side, type);
4✔
1813
                     };
4✔
1814

1815
                     ctx = std::make_unique<Server_Context>(
1✔
1816
                        std::move(rng),
1817
                        std::make_shared<RFC8448_Text_Policy>("rfc8448_1rtt"),
2✔
1818
                        vars.get_req_u64("CurrentTimestamp"),
1✔
1819
                        add_early_data_and_sort,
1820
                        make_mock_signatures(vars),
1✔
1821
                        false,
2✔
1822
                        std::pair{Botan::TLS::Session(vars.get_req_bin("Client_SessionData")),
5✔
1823
                                  Botan::TLS::Session_Ticket(vars.get_req_bin("SessionTicket"))});
3✔
1824
                     result.confirm("server not closed", !ctx->server.is_closed());
2✔
1825

1826
                     ctx->server.received_data(vars.get_req_bin("Record_ClientHello_1"));
2✔
1827

1828
                     ctx->check_callback_invocations(result,
2✔
1829
                                                     "client hello received",
1830
                                                     {"tls_emit_data",
1831
                                                      "tls_examine_extensions_client_hello",
1832
                                                      "tls_modify_extensions_server_hello",
1833
                                                      "tls_modify_extensions_encrypted_extensions",
1834
                                                      "tls_modify_extensions_certificate",
1835
                                                      "tls_sign_message",
1836
                                                      "tls_generate_ephemeral_key",
1837
                                                      "tls_ephemeral_key_agreement",
1838
                                                      "tls_inspect_handshake_msg_client_hello",
1839
                                                      "tls_inspect_handshake_msg_server_hello",
1840
                                                      "tls_inspect_handshake_msg_encrypted_extensions",
1841
                                                      "tls_inspect_handshake_msg_certificate",
1842
                                                      "tls_inspect_handshake_msg_certificate_verify",
1843
                                                      "tls_inspect_handshake_msg_finished"});
1844
                  }),
1✔
1845

1846
            CHECK("Verify generated messages in server's first flight",
1847
                  [&](Test::Result& result) {
1✔
1848
                     result.require("ctx is available", ctx != nullptr);
1✔
1849
                     const auto& msgs = ctx->observed_handshake_messages();
1✔
1850

1851
                     result.test_eq("Server Hello",
3✔
1852
                                    msgs.at("server_hello")[0],
2✔
1853
                                    strip_message_header(vars.get_opt_bin("Message_ServerHello")));
3✔
1854
                     result.test_eq("Encrypted Extensions",
3✔
1855
                                    msgs.at("encrypted_extensions")[0],
2✔
1856
                                    strip_message_header(vars.get_opt_bin("Message_EncryptedExtensions")));
3✔
1857
                     result.test_eq("Certificate",
3✔
1858
                                    msgs.at("certificate")[0],
2✔
1859
                                    strip_message_header(vars.get_opt_bin("Message_Server_Certificate")));
3✔
1860
                     result.test_eq("CertificateVerify",
3✔
1861
                                    msgs.at("certificate_verify")[0],
2✔
1862
                                    strip_message_header(vars.get_opt_bin("Message_Server_CertificateVerify")));
3✔
1863

1864
                     result.test_eq("Server's entire first flight",
2✔
1865
                                    ctx->pull_send_buffer(),
2✔
1866
                                    concat(vars.get_req_bin("Record_ServerHello"),
4✔
1867
                                           vars.get_req_bin("Record_ServerHandshakeMessages")));
2✔
1868

1869
                     // Note: is_active() defines that we can send application data.
1870
                     //       RFC 8446 Section 4.4.4 explicitly allows that for servers
1871
                     //       that did not receive the client's Finished message, yet.
1872
                     //       However, before receiving and validating this message,
1873
                     //       the handshake is not yet finished.
1874
                     result.confirm("Server can now send application data", ctx->server.is_active());
2✔
1875
                     result.confirm("handshake is not yet complete", !ctx->server.is_handshake_complete());
2✔
1876
                  }),
1✔
1877

1878
            CHECK("Send Client Finished",
1879
                  [&](Test::Result& result) {
1✔
1880
                     result.require("ctx is available", ctx != nullptr);
1✔
1881
                     ctx->server.received_data(vars.get_req_bin("Record_ClientFinished"));
2✔
1882

1883
                     ctx->check_callback_invocations(result,
2✔
1884
                                                     "client finished received",
1885
                                                     {"tls_inspect_handshake_msg_finished",
1886
                                                      "tls_current_timestamp",
1887
                                                      "tls_session_established",
1888
                                                      "tls_session_activated"});
1889
                  }),
1✔
1890

1891
            CHECK("Send Session Ticket",
1892
                  [&](Test::Result& result) {
1✔
1893
                     result.require("ctx is available", ctx != nullptr);
1✔
1894
                     const auto new_tickets = ctx->server.send_new_session_tickets(1);
1✔
1895

1896
                     result.test_eq("session ticket was sent", new_tickets, 1);
1✔
1897

1898
                     ctx->check_callback_invocations(result,
2✔
1899
                                                     "issued new session ticket",
1900
                                                     {"tls_inspect_handshake_msg_new_session_ticket",
1901
                                                      "tls_current_timestamp",
1902
                                                      "tls_emit_data",
1903
                                                      "tls_modify_extensions_new_session_ticket",
1904
                                                      "tls_should_persist_resumption_information"});
1905
                  }),
1✔
1906

1907
            CHECK("Verify generated new session ticket message",
1908
                  [&](Test::Result& result) {
1✔
1909
                     result.require("ctx is available", ctx != nullptr);
1✔
1910
                     result.test_eq(
2✔
1911
                        "New Session Ticket", ctx->pull_send_buffer(), vars.get_req_bin("Record_NewSessionTicket"));
3✔
1912
                  }),
1✔
1913

1914
            CHECK("Receive Application Data",
1915
                  [&](Test::Result& result) {
1✔
1916
                     result.require("ctx is available", ctx != nullptr);
1✔
1917
                     ctx->server.received_data(vars.get_req_bin("Record_Client_AppData"));
2✔
1918
                     ctx->check_callback_invocations(result, "application data received", {"tls_record_received"});
2✔
1919

1920
                     const auto rcvd = ctx->pull_receive_buffer();
1✔
1921
                     result.test_eq("decrypted application traffic", rcvd, vars.get_req_bin("Client_AppData"));
3✔
1922
                     result.test_is_eq("sequence number", ctx->last_received_seq_no(), uint64_t(0));
2✔
1923
                  }),
1✔
1924

1925
            CHECK("Send Application Data",
1926
                  [&](Test::Result& result) {
1✔
1927
                     result.require("ctx is available", ctx != nullptr);
1✔
1928
                     ctx->send(vars.get_req_bin("Server_AppData"));
3✔
1929

1930
                     ctx->check_callback_invocations(result, "application data sent", {"tls_emit_data"});
2✔
1931

1932
                     result.test_eq("correct server application data",
2✔
1933
                                    ctx->pull_send_buffer(),
2✔
1934
                                    vars.get_req_bin("Record_Server_AppData"));
2✔
1935
                  }),
1✔
1936

1937
            CHECK("Receive Client's close_notify",
1938
                  [&](Test::Result& result) {
1✔
1939
                     result.require("ctx is available", ctx != nullptr);
1✔
1940
                     ctx->server.received_data(vars.get_req_bin("Record_Client_CloseNotify"));
2✔
1941

1942
                     ctx->check_callback_invocations(
2✔
1943
                        result, "client finished received", {"tls_alert", "tls_peer_closed_connection"});
1944

1945
                     result.confirm("connection is not yet closed", !ctx->server.is_closed());
2✔
1946
                     result.confirm("connection is still active", ctx->server.is_active());
2✔
1947
                     result.confirm("handshake is still finished", ctx->server.is_handshake_complete());
2✔
1948
                  }),
1✔
1949

1950
            CHECK("Expect Server close_notify",
1951
                  [&](Test::Result& result) {
1✔
1952
                     result.require("ctx is available", ctx != nullptr);
1✔
1953
                     ctx->server.close();
1✔
1954

1955
                     result.confirm("connection is now inactive", !ctx->server.is_active());
2✔
1956
                     result.confirm("connection is now closed", ctx->server.is_closed());
2✔
1957
                     result.confirm("handshake is still finished", ctx->server.is_handshake_complete());
2✔
1958
                     result.test_eq("Server's close notify",
2✔
1959
                                    ctx->pull_send_buffer(),
2✔
1960
                                    vars.get_req_bin("Record_Server_CloseNotify"));
2✔
1961
                  }),
1✔
1962
         };
10✔
1963
      }
2✔
1964

1965
      std::vector<Test::Result> resumed_handshake_with_0_rtt(const VarMap& vars) override {
1✔
1966
         auto rng = std::make_unique<Fixed_Output_RNG>();
1✔
1967

1968
         // 32 - for server hello random
1969
         // 32 - for KeyShare (eph. x25519 key pair)
1970
         add_entropy(*rng, vars.get_req_bin("Server_RNG_Pool"));
2✔
1971

1972
         std::unique_ptr<Server_Context> ctx;
1✔
1973

1974
         return {
1✔
1975
            CHECK("Receive Client Hello",
1976
                  [&](Test::Result& result) {
1✔
1977
                     auto add_cookie_and_sort = [&](Botan::TLS::Extensions& exts,
3✔
1978
                                                    Botan::TLS::Connection_Side side,
1979
                                                    Botan::TLS::Handshake_Type type) {
1980
                        if(type == Handshake_Type::EncryptedExtensions) {
2✔
1981
                           exts.add(new EarlyDataIndication());  // NOLINT(*-owning-memory)
1✔
1982
                        }
1983
                        sort_rfc8448_extensions(exts, side, type);
2✔
1984
                     };
2✔
1985

1986
                     ctx = std::make_unique<Server_Context>(
1✔
1987
                        std::move(rng),
1988
                        std::make_shared<RFC8448_Text_Policy>("rfc8448_1rtt"),
2✔
1989
                        vars.get_req_u64("CurrentTimestamp"),
1✔
1990
                        add_cookie_and_sort,
1991
                        make_mock_signatures(vars),
1✔
1992
                        false,
2✔
1993
                        std::pair{Botan::TLS::Session(vars.get_req_bin("Client_SessionData")),
5✔
1994
                                  Botan::TLS::Session_Ticket(vars.get_req_bin("SessionTicket"))});
3✔
1995
                     result.confirm("server not closed", !ctx->server.is_closed());
2✔
1996

1997
                     ctx->server.received_data(vars.get_req_bin("Record_ClientHello_1"));
2✔
1998

1999
                     ctx->check_callback_invocations(result,
2✔
2000
                                                     "client hello received",
2001
                                                     {
2002
                                                        "tls_emit_data",
2003
                                                        "tls_current_timestamp",
2004
                                                        "tls_generate_ephemeral_key",
2005
                                                        "tls_ephemeral_key_agreement",
2006
                                                        "tls_examine_extensions_client_hello",
2007
                                                        "tls_modify_extensions_server_hello",
2008
                                                        "tls_modify_extensions_encrypted_extensions",
2009
                                                        "tls_inspect_handshake_msg_client_hello",
2010
                                                        "tls_inspect_handshake_msg_server_hello",
2011
                                                        "tls_inspect_handshake_msg_encrypted_extensions",
2012
                                                        "tls_inspect_handshake_msg_finished",
2013
                                                     });
2014
                  }),
1✔
2015

2016
            CHECK("Verify generated messages in server's first flight",
2017
                  [&](Test::Result& result) {
1✔
2018
                     result.require("ctx is available", ctx != nullptr);
1✔
2019
                     const auto& msgs = ctx->observed_handshake_messages();
1✔
2020

2021
                     result.test_eq("Server Hello",
3✔
2022
                                    msgs.at("server_hello")[0],
2✔
2023
                                    strip_message_header(vars.get_opt_bin("Message_ServerHello")));
3✔
2024
                     result.test_eq("Encrypted Extensions",
3✔
2025
                                    msgs.at("encrypted_extensions")[0],
2✔
2026
                                    strip_message_header(vars.get_opt_bin("Message_EncryptedExtensions")));
3✔
2027

2028
                     result.test_eq("Server's entire first flight",
2✔
2029
                                    ctx->pull_send_buffer(),
2✔
2030
                                    concat(vars.get_req_bin("Record_ServerHello"),
4✔
2031
                                           vars.get_req_bin("Record_ServerHandshakeMessages")));
2✔
2032

2033
                     // Note: is_active() defines that we can send application data.
2034
                     //       RFC 8446 Section 4.4.4 explicitly allows that for servers
2035
                     //       that did not receive the client's Finished message, yet.
2036
                     //       However, before receiving and validating this message,
2037
                     //       the handshake is not yet finished.
2038
                     result.confirm("Server can now send application data", ctx->server.is_active());
2✔
2039
                     result.confirm("handshake is not yet complete", !ctx->server.is_handshake_complete());
2✔
2040
                  }),
1✔
2041

2042
            // TODO: The rest of this test vector requires 0-RTT which is not
2043
            //       yet implemented. For now we can only test the server's
2044
            //       ability to acknowledge a session resumption via PSK.
2045
         };
3✔
2046
      }
2✔
2047

2048
      std::vector<Test::Result> hello_retry_request(const VarMap& vars) override {
1✔
2049
         // Fallback RNG is required to for blinding in ECDH with P-256
2050
         auto& fallback_rng = this->rng();
1✔
2051
         auto rng = std::make_unique<Fixed_Output_RNG>(fallback_rng);
1✔
2052

2053
         // 32 - for server hello random
2054
         // 32 - for KeyShare (eph. P-256 key pair)
2055
         add_entropy(*rng, vars.get_req_bin("Server_RNG_Pool"));
2✔
2056

2057
         std::unique_ptr<Server_Context> ctx;
1✔
2058

2059
         return {
1✔
2060
            CHECK("Receive Client Hello",
2061
                  [&](Test::Result& result) {
1✔
2062
                     auto add_cookie_and_sort = [&](Botan::TLS::Extensions& exts,
5✔
2063
                                                    Botan::TLS::Connection_Side side,
2064
                                                    Botan::TLS::Handshake_Type type) {
2065
                        if(type == Handshake_Type::HelloRetryRequest) {
4✔
2066
                           // This cookie needs to be mocked into the HRR since RFC 8448 contains it.
2067
                           exts.add(
1✔
2068
                              new Cookie(vars.get_opt_bin("HelloRetryRequest_Cookie")));  // NOLINT(*-owning-memory)
2✔
2069
                        }
2070
                        sort_rfc8448_extensions(exts, side, type);
4✔
2071
                     };
4✔
2072

2073
                     ctx = std::make_unique<Server_Context>(std::move(rng),
1✔
2074
                                                            std::make_shared<RFC8448_Text_Policy>("rfc8448_hrr_server"),
2✔
2075
                                                            vars.get_req_u64("CurrentTimestamp"),
1✔
2076
                                                            add_cookie_and_sort,
2077
                                                            make_mock_signatures(vars));
3✔
2078
                     result.confirm("server not closed", !ctx->server.is_closed());
2✔
2079

2080
                     ctx->server.received_data(vars.get_req_bin("Record_ClientHello_1"));
2✔
2081

2082
                     ctx->check_callback_invocations(result,
2✔
2083
                                                     "client hello received",
2084
                                                     {"tls_emit_data",
2085
                                                      "tls_examine_extensions_client_hello",
2086
                                                      "tls_modify_extensions_hello_retry_request",
2087
                                                      "tls_inspect_handshake_msg_client_hello",
2088
                                                      "tls_inspect_handshake_msg_hello_retry_request"});
2089
                  }),
1✔
2090

2091
            CHECK("Verify generated Hello Retry Request message",
2092
                  [&](Test::Result& result) {
1✔
2093
                     result.require("ctx is available", ctx != nullptr);
1✔
2094
                     result.test_eq("Server's Hello Retry Request record",
2✔
2095
                                    ctx->pull_send_buffer(),
2✔
2096
                                    vars.get_req_bin("Record_HelloRetryRequest"));
2✔
2097
                     result.confirm("TLS handshake not yet finished", !ctx->server.is_active());
2✔
2098
                     result.confirm("handshake is not yet complete", !ctx->server.is_handshake_complete());
2✔
2099
                  }),
1✔
2100

2101
            CHECK("Receive updated Client Hello message",
2102
                  [&](Test::Result& result) {
1✔
2103
                     result.require("ctx is available", ctx != nullptr);
1✔
2104
                     ctx->server.received_data(vars.get_req_bin("Record_ClientHello_2"));
2✔
2105

2106
                     ctx->check_callback_invocations(result,
2✔
2107
                                                     "updated client hello received",
2108
                                                     {"tls_emit_data",
2109
                                                      "tls_examine_extensions_client_hello",
2110
                                                      "tls_modify_extensions_server_hello",
2111
                                                      "tls_modify_extensions_encrypted_extensions",
2112
                                                      "tls_modify_extensions_certificate",
2113
                                                      "tls_sign_message",
2114
                                                      "tls_generate_ephemeral_key",
2115
                                                      "tls_ephemeral_key_agreement",
2116
                                                      "tls_inspect_handshake_msg_client_hello",
2117
                                                      "tls_inspect_handshake_msg_server_hello",
2118
                                                      "tls_inspect_handshake_msg_encrypted_extensions",
2119
                                                      "tls_inspect_handshake_msg_certificate",
2120
                                                      "tls_inspect_handshake_msg_certificate_verify",
2121
                                                      "tls_inspect_handshake_msg_finished"});
2122
                  }),
1✔
2123

2124
            CHECK("Verify generated messages in server's second flight",
2125
                  [&](Test::Result& result) {
1✔
2126
                     result.require("ctx is available", ctx != nullptr);
1✔
2127
                     const auto& msgs = ctx->observed_handshake_messages();
1✔
2128

2129
                     result.test_eq("Server Hello",
3✔
2130
                                    msgs.at("server_hello")[0],
2✔
2131
                                    strip_message_header(vars.get_opt_bin("Message_ServerHello")));
3✔
2132
                     result.test_eq("Encrypted Extensions",
3✔
2133
                                    msgs.at("encrypted_extensions")[0],
2✔
2134
                                    strip_message_header(vars.get_opt_bin("Message_EncryptedExtensions")));
3✔
2135
                     result.test_eq("Certificate",
3✔
2136
                                    msgs.at("certificate")[0],
2✔
2137
                                    strip_message_header(vars.get_opt_bin("Message_Server_Certificate")));
3✔
2138
                     result.test_eq("CertificateVerify",
3✔
2139
                                    msgs.at("certificate_verify")[0],
2✔
2140
                                    strip_message_header(vars.get_opt_bin("Message_Server_CertificateVerify")));
3✔
2141
                     result.test_eq("Finished",
3✔
2142
                                    msgs.at("finished")[0],
2✔
2143
                                    strip_message_header(vars.get_opt_bin("Message_Server_Finished")));
3✔
2144

2145
                     result.test_eq("Server's entire second flight",
2✔
2146
                                    ctx->pull_send_buffer(),
2✔
2147
                                    concat(vars.get_req_bin("Record_ServerHello"),
4✔
2148
                                           vars.get_req_bin("Record_ServerHandshakeMessages")));
2✔
2149
                     result.confirm("Server could now send application data", ctx->server.is_active());
2✔
2150
                     result.confirm("handshake is not yet complete",
1✔
2151
                                    !ctx->server.is_handshake_complete());  // See RFC 8446 4.4.4
1✔
2152
                  }),
1✔
2153

2154
            CHECK("Receive Client Finished",
2155
                  [&](Test::Result& result) {
1✔
2156
                     result.require("ctx is available", ctx != nullptr);
1✔
2157
                     ctx->server.received_data(vars.get_req_bin("Record_ClientFinished"));
2✔
2158

2159
                     ctx->check_callback_invocations(result,
2✔
2160
                                                     "client finished received",
2161
                                                     {"tls_inspect_handshake_msg_finished",
2162
                                                      "tls_current_timestamp",
2163
                                                      "tls_session_established",
2164
                                                      "tls_session_activated"});
2165

2166
                     result.confirm("TLS handshake finished", ctx->server.is_active());
2✔
2167
                     result.confirm("handshake is complete", ctx->server.is_handshake_complete());
2✔
2168
                  }),
1✔
2169

2170
            CHECK("Receive Client close_notify",
2171
                  [&](Test::Result& result) {
1✔
2172
                     result.require("ctx is available", ctx != nullptr);
1✔
2173
                     ctx->server.received_data(vars.get_req_bin("Record_Client_CloseNotify"));
2✔
2174

2175
                     ctx->check_callback_invocations(
2✔
2176
                        result, "client finished received", {"tls_alert", "tls_peer_closed_connection"});
2177

2178
                     result.confirm("connection is not yet closed", !ctx->server.is_closed());
2✔
2179
                     result.confirm("connection is still active", ctx->server.is_active());
2✔
2180
                     result.confirm("handshake is still complete", ctx->server.is_handshake_complete());
2✔
2181
                  }),
1✔
2182

2183
            CHECK("Expect Server close_notify",
2184
                  [&](Test::Result& result) {
1✔
2185
                     result.require("ctx is available", ctx != nullptr);
1✔
2186
                     ctx->server.close();
1✔
2187

2188
                     result.confirm("connection is now inactive", !ctx->server.is_active());
2✔
2189
                     result.confirm("connection is now closed", ctx->server.is_closed());
2✔
2190
                     result.confirm("handshake is still complete", ctx->server.is_handshake_complete());
2✔
2191
                     result.test_eq("Server's close notify",
2✔
2192
                                    ctx->pull_send_buffer(),
2✔
2193
                                    vars.get_req_bin("Record_Server_CloseNotify"));
2✔
2194
                  }),
1✔
2195

2196
         };
8✔
2197
      }
2✔
2198

2199
      std::vector<Test::Result> client_authentication(const VarMap& vars) override {
1✔
2200
         auto rng = std::make_unique<Fixed_Output_RNG>("");
1✔
2201

2202
         // 32 - for server hello random
2203
         // 32 - for KeyShare (eph. x25519 pair)
2204
         add_entropy(*rng, vars.get_req_bin("Server_RNG_Pool"));
2✔
2205

2206
         std::unique_ptr<Server_Context> ctx;
1✔
2207

2208
         return {
1✔
2209
            CHECK("Receive Client Hello",
2210
                  [&](Test::Result& result) {
1✔
2211
                     ctx = std::make_unique<Server_Context>(
1✔
2212
                        std::move(rng),
2213
                        std::make_shared<RFC8448_Text_Policy>("rfc8448_client_auth_server"),
2✔
2214
                        vars.get_req_u64("CurrentTimestamp"),
1✔
2215
                        sort_rfc8448_extensions,
2216
                        make_mock_signatures(vars),
1✔
2217
                        true /* use alternative certificate */);
2✔
2218
                     result.confirm("server not closed", !ctx->server.is_closed());
2✔
2219

2220
                     ctx->server.received_data(vars.get_req_bin("Record_ClientHello_1"));
2✔
2221

2222
                     ctx->check_callback_invocations(result,
2✔
2223
                                                     "client hello received",
2224
                                                     {"tls_emit_data",
2225
                                                      "tls_examine_extensions_client_hello",
2226
                                                      "tls_modify_extensions_server_hello",
2227
                                                      "tls_modify_extensions_encrypted_extensions",
2228
                                                      "tls_modify_extensions_certificate_request",
2229
                                                      "tls_modify_extensions_certificate",
2230
                                                      "tls_sign_message",
2231
                                                      "tls_generate_ephemeral_key",
2232
                                                      "tls_ephemeral_key_agreement",
2233
                                                      "tls_inspect_handshake_msg_client_hello",
2234
                                                      "tls_inspect_handshake_msg_server_hello",
2235
                                                      "tls_inspect_handshake_msg_encrypted_extensions",
2236
                                                      "tls_inspect_handshake_msg_certificate_request",
2237
                                                      "tls_inspect_handshake_msg_certificate",
2238
                                                      "tls_inspect_handshake_msg_certificate_verify",
2239
                                                      "tls_inspect_handshake_msg_finished"});
2240
                  }),
1✔
2241

2242
            CHECK("Verify server's generated handshake messages",
2243
                  [&](Test::Result& result) {
1✔
2244
                     result.require("ctx is available", ctx != nullptr);
1✔
2245
                     const auto& msgs = ctx->observed_handshake_messages();
1✔
2246

2247
                     result.test_eq("Server Hello",
3✔
2248
                                    msgs.at("server_hello")[0],
2✔
2249
                                    strip_message_header(vars.get_opt_bin("Message_ServerHello")));
3✔
2250
                     result.test_eq("Encrypted Extensions",
3✔
2251
                                    msgs.at("encrypted_extensions")[0],
2✔
2252
                                    strip_message_header(vars.get_opt_bin("Message_EncryptedExtensions")));
3✔
2253
                     result.test_eq("Certificate Request",
3✔
2254
                                    msgs.at("certificate_request")[0],
2✔
2255
                                    strip_message_header(vars.get_opt_bin("Message_CertificateRequest")));
3✔
2256
                     result.test_eq("Certificate",
3✔
2257
                                    msgs.at("certificate")[0],
2✔
2258
                                    strip_message_header(vars.get_opt_bin("Message_Server_Certificate")));
3✔
2259
                     result.test_eq("CertificateVerify",
3✔
2260
                                    msgs.at("certificate_verify")[0],
2✔
2261
                                    strip_message_header(vars.get_opt_bin("Message_Server_CertificateVerify")));
3✔
2262
                     result.test_eq("Finished",
3✔
2263
                                    msgs.at("finished")[0],
2✔
2264
                                    strip_message_header(vars.get_opt_bin("Message_Server_Finished")));
3✔
2265

2266
                     result.test_eq("Server's entire first flight",
2✔
2267
                                    ctx->pull_send_buffer(),
2✔
2268
                                    concat(vars.get_req_bin("Record_ServerHello"),
4✔
2269
                                           vars.get_req_bin("Record_ServerHandshakeMessages")));
2✔
2270

2271
                     result.confirm("Not yet aware of client's cert chain", ctx->server.peer_cert_chain().empty());
2✔
2272
                     result.confirm("Server could now send application data", ctx->server.is_active());
2✔
2273
                     result.confirm("handshake is not yet complete",
1✔
2274
                                    !ctx->server.is_handshake_complete());  // See RFC 8446 4.4.4
1✔
2275
                  }),
1✔
2276

2277
            CHECK("Receive Client's second flight",
2278
                  [&](Test::Result& result) {
1✔
2279
                     result.require("ctx is available", ctx != nullptr);
1✔
2280
                     // This encrypted message contains the following messages:
2281
                     // * client's Certificate message
2282
                     // * client's Certificate_Verify message
2283
                     // * client's Finished message
2284
                     ctx->server.received_data(vars.get_req_bin("Record_ClientFinished"));
2✔
2285

2286
                     ctx->check_callback_invocations(result,
2✔
2287
                                                     "client finished received",
2288
                                                     {"tls_inspect_handshake_msg_certificate",
2289
                                                      "tls_inspect_handshake_msg_certificate_verify",
2290
                                                      "tls_inspect_handshake_msg_finished",
2291
                                                      "tls_examine_extensions_certificate",
2292
                                                      "tls_verify_cert_chain",
2293
                                                      "tls_verify_message",
2294
                                                      "tls_current_timestamp",
2295
                                                      "tls_session_established",
2296
                                                      "tls_session_activated"});
2297

2298
                     const auto cert_chain = ctx->server.peer_cert_chain();
1✔
2299
                     result.confirm("Received client's cert chain",
2✔
2300
                                    !cert_chain.empty() && cert_chain.front() == client_certificate());
2✔
2301

2302
                     result.confirm("TLS handshake finished", ctx->server.is_active());
2✔
2303
                     result.confirm("handshake is complete", ctx->server.is_handshake_complete());
2✔
2304
                  }),
1✔
2305

2306
            CHECK("Receive Client close_notify",
2307
                  [&](Test::Result& result) {
1✔
2308
                     result.require("ctx is available", ctx != nullptr);
1✔
2309
                     ctx->server.received_data(vars.get_req_bin("Record_Client_CloseNotify"));
2✔
2310

2311
                     ctx->check_callback_invocations(
2✔
2312
                        result, "client finished received", {"tls_alert", "tls_peer_closed_connection"});
2313

2314
                     result.confirm("connection is not yet closed", !ctx->server.is_closed());
2✔
2315
                     result.confirm("connection is still active", ctx->server.is_active());
2✔
2316
                     result.confirm("handshake is still complete", ctx->server.is_handshake_complete());
2✔
2317
                  }),
1✔
2318

2319
            CHECK("Expect Server close_notify",
2320
                  [&](Test::Result& result) {
1✔
2321
                     result.require("ctx is available", ctx != nullptr);
1✔
2322
                     ctx->server.close();
1✔
2323

2324
                     result.confirm("connection is now inactive", !ctx->server.is_active());
2✔
2325
                     result.confirm("connection is now closed", ctx->server.is_closed());
2✔
2326
                     result.confirm("handshake is still complete", ctx->server.is_handshake_complete());
2✔
2327
                     result.test_eq("Server's close notify",
2✔
2328
                                    ctx->pull_send_buffer(),
2✔
2329
                                    vars.get_req_bin("Record_Server_CloseNotify"));
2✔
2330
                  }),
1✔
2331

2332
         };
6✔
2333
      }
2✔
2334

2335
      std::vector<Test::Result> middlebox_compatibility(const VarMap& vars) override {
1✔
2336
         auto rng = std::make_unique<Fixed_Output_RNG>("");
1✔
2337

2338
         // 32 - for server hello random
2339
         // 32 - for KeyShare (eph. x25519 pair)
2340
         add_entropy(*rng, vars.get_req_bin("Server_RNG_Pool"));
2✔
2341

2342
         std::unique_ptr<Server_Context> ctx;
1✔
2343

2344
         return {
1✔
2345
            CHECK("Receive Client Hello",
2346
                  [&](Test::Result& result) {
1✔
2347
                     ctx =
1✔
2348
                        std::make_unique<Server_Context>(std::move(rng),
1✔
2349
                                                         std::make_shared<RFC8448_Text_Policy>("rfc8448_compat_server"),
2✔
2350
                                                         vars.get_req_u64("CurrentTimestamp"),
1✔
2351
                                                         sort_rfc8448_extensions,
2352
                                                         make_mock_signatures(vars));
3✔
2353
                     result.confirm("server not closed", !ctx->server.is_closed());
2✔
2354

2355
                     ctx->server.received_data(vars.get_req_bin("Record_ClientHello_1"));
2✔
2356

2357
                     ctx->check_callback_invocations(result,
2✔
2358
                                                     "client hello received",
2359
                                                     {"tls_emit_data",
2360
                                                      "tls_examine_extensions_client_hello",
2361
                                                      "tls_modify_extensions_server_hello",
2362
                                                      "tls_modify_extensions_encrypted_extensions",
2363
                                                      "tls_modify_extensions_certificate",
2364
                                                      "tls_sign_message",
2365
                                                      "tls_generate_ephemeral_key",
2366
                                                      "tls_ephemeral_key_agreement",
2367
                                                      "tls_inspect_handshake_msg_client_hello",
2368
                                                      "tls_inspect_handshake_msg_server_hello",
2369
                                                      "tls_inspect_handshake_msg_encrypted_extensions",
2370
                                                      "tls_inspect_handshake_msg_certificate",
2371
                                                      "tls_inspect_handshake_msg_certificate_verify",
2372
                                                      "tls_inspect_handshake_msg_finished"});
2373
                  }),
1✔
2374

2375
            CHECK("Verify server's generated handshake messages",
2376
                  [&](Test::Result& result) {
1✔
2377
                     result.require("ctx is available", ctx != nullptr);
1✔
2378
                     const auto& msgs = ctx->observed_handshake_messages();
1✔
2379

2380
                     result.test_eq("Server Hello",
3✔
2381
                                    msgs.at("server_hello")[0],
2✔
2382
                                    strip_message_header(vars.get_opt_bin("Message_ServerHello")));
3✔
2383
                     result.test_eq("Encrypted Extensions",
3✔
2384
                                    msgs.at("encrypted_extensions")[0],
2✔
2385
                                    strip_message_header(vars.get_opt_bin("Message_EncryptedExtensions")));
3✔
2386
                     result.test_eq("Certificate",
3✔
2387
                                    msgs.at("certificate")[0],
2✔
2388
                                    strip_message_header(vars.get_opt_bin("Message_Server_Certificate")));
3✔
2389
                     result.test_eq("CertificateVerify",
3✔
2390
                                    msgs.at("certificate_verify")[0],
2✔
2391
                                    strip_message_header(vars.get_opt_bin("Message_Server_CertificateVerify")));
3✔
2392
                     result.test_eq("Finished",
3✔
2393
                                    msgs.at("finished")[0],
2✔
2394
                                    strip_message_header(vars.get_opt_bin("Message_Server_Finished")));
3✔
2395

2396
                     // Those records contain the required Change Cipher Spec message the server must produce for compatibility mode compliance
2397
                     result.test_eq("Server's entire first flight",
2✔
2398
                                    ctx->pull_send_buffer(),
2✔
2399
                                    concat(vars.get_req_bin("Record_ServerHello"),
4✔
2400
                                           vars.get_req_bin("Record_ServerHandshakeMessages")));
2✔
2401

2402
                     result.confirm("Server could now send application data", ctx->server.is_active());
2✔
2403
                     result.confirm("handshake is not yet complete",
1✔
2404
                                    !ctx->server.is_handshake_complete());  // See RFC 8446 4.4.4
1✔
2405
                  }),
1✔
2406

2407
            CHECK("Receive Client Finished",
2408
                  [&](Test::Result& result) {
1✔
2409
                     result.require("ctx is available", ctx != nullptr);
1✔
2410
                     ctx->server.received_data(vars.get_req_bin("Record_ClientFinished"));
2✔
2411

2412
                     ctx->check_callback_invocations(result,
2✔
2413
                                                     "client finished received",
2414
                                                     {"tls_inspect_handshake_msg_finished",
2415
                                                      "tls_current_timestamp",
2416
                                                      "tls_session_established",
2417
                                                      "tls_session_activated"});
2418

2419
                     result.confirm("TLS handshake fully finished", ctx->server.is_active());
2✔
2420
                     result.confirm("handshake is complete", ctx->server.is_handshake_complete());
2✔
2421
                  }),
1✔
2422

2423
            CHECK("Receive Client close_notify",
2424
                  [&](Test::Result& result) {
1✔
2425
                     result.require("ctx is available", ctx != nullptr);
1✔
2426
                     ctx->server.received_data(vars.get_req_bin("Record_Client_CloseNotify"));
2✔
2427

2428
                     ctx->check_callback_invocations(
2✔
2429
                        result, "client finished received", {"tls_alert", "tls_peer_closed_connection"});
2430

2431
                     result.confirm("connection is not yet closed", !ctx->server.is_closed());
2✔
2432
                     result.confirm("connection is still active", ctx->server.is_active());
2✔
2433
                     result.confirm("handshake is still complete", ctx->server.is_handshake_complete());
2✔
2434
                  }),
1✔
2435

2436
            CHECK("Expect Server close_notify",
2437
                  [&](Test::Result& result) {
1✔
2438
                     result.require("ctx is available", ctx != nullptr);
1✔
2439
                     ctx->server.close();
1✔
2440

2441
                     result.confirm("connection is now inactive", !ctx->server.is_active());
2✔
2442
                     result.confirm("connection is now closed", ctx->server.is_closed());
2✔
2443
                     result.confirm("handshake is still complete", ctx->server.is_handshake_complete());
2✔
2444
                     result.test_eq("Server's close notify",
2✔
2445
                                    ctx->pull_send_buffer(),
2✔
2446
                                    vars.get_req_bin("Record_Server_CloseNotify"));
2✔
2447
                  }),
1✔
2448

2449
         };
6✔
2450
      }
2✔
2451

2452
      std::vector<Test::Result> externally_provided_psk_with_ephemeral_key(const VarMap& vars) override {
1✔
2453
         auto rng = std::make_unique<Fixed_Output_RNG>("");
1✔
2454

2455
         // 32 - for server hello random
2456
         // 32 - for KeyShare (eph. x25519 key pair)
2457
         add_entropy(*rng, vars.get_req_bin("Server_RNG_Pool"));
2✔
2458

2459
         std::unique_ptr<Server_Context> ctx;
1✔
2460

2461
         return {
1✔
2462
            CHECK("Send Client Hello",
2463
                  [&](Test::Result& result) {
1✔
2464
                     auto sort_our_extensions = [&](Botan::TLS::Extensions& exts,
3✔
2465
                                                    Botan::TLS::Connection_Side /* side */,
2466
                                                    Botan::TLS::Handshake_Type type) {
2467
                        // This is the order of extensions when we first introduced the PSK
2468
                        // implementation and generated the transcript. To stay compatible
2469
                        // with the now hard-coded transcript, we pin the extension order.
2470
                        if(type == Botan::TLS::Handshake_Type::EncryptedExtensions) {
2✔
2471
                           sort_extensions(exts,
2✔
2472
                                           {
2473
                                              Botan::TLS::Extension_Code::SupportedGroups,
2474
                                              Botan::TLS::Extension_Code::RecordSizeLimit,
2475
                                              Botan::TLS::Extension_Code::ServerNameIndication,
2476
                                           });
2477
                        } else if(type == Botan::TLS::Handshake_Type::ServerHello) {
1✔
2478
                           sort_extensions(exts,
2✔
2479
                                           {
2480
                                              Botan::TLS::Extension_Code::SupportedVersions,
2481
                                              Botan::TLS::Extension_Code::KeyShare,
2482
                                              Botan::TLS::Extension_Code::PresharedKey,
2483
                                           });
2484
                        }
2485
                     };
2✔
2486

2487
                     ctx = std::make_unique<Server_Context>(
1✔
2488
                        std::move(rng),
2489
                        std::make_shared<RFC8448_Text_Policy>("rfc8448_psk_dhe", false /* no rfc8448 */),
2✔
2490
                        vars.get_req_u64("CurrentTimestamp"),
1✔
2491
                        sort_our_extensions,
2492
                        make_mock_signatures(vars),
1✔
2493
                        false,
1✔
2494
                        std::nullopt,
2495
                        ExternalPSK(vars.get_req_str("PskIdentity"),
2✔
2496
                                    vars.get_req_str("PskPRF"),
2✔
2497
                                    lock(vars.get_req_bin("PskSecret"))));
5✔
2498
                     result.confirm("server not closed", !ctx->server.is_closed());
2✔
2499

2500
                     ctx->server.received_data(vars.get_req_bin("Record_ClientHello_1"));
2✔
2501

2502
                     ctx->check_callback_invocations(result,
2✔
2503
                                                     "client hello received",
2504
                                                     {"tls_emit_data",
2505
                                                      "tls_examine_extensions_client_hello",
2506
                                                      "tls_modify_extensions_server_hello",
2507
                                                      "tls_modify_extensions_encrypted_extensions",
2508
                                                      "tls_generate_ephemeral_key",
2509
                                                      "tls_ephemeral_key_agreement",
2510
                                                      "tls_inspect_handshake_msg_client_hello",
2511
                                                      "tls_inspect_handshake_msg_server_hello",
2512
                                                      "tls_inspect_handshake_msg_encrypted_extensions",
2513
                                                      "tls_inspect_handshake_msg_finished"});
2514
                  }),
1✔
2515

2516
            CHECK("Verify generated messages in server's first flight",
2517
                  [&](Test::Result& result) {
1✔
2518
                     result.require("ctx is available", ctx != nullptr);
1✔
2519
                     const auto& msgs = ctx->observed_handshake_messages();
1✔
2520

2521
                     result.test_eq("Server Hello",
3✔
2522
                                    msgs.at("server_hello")[0],
2✔
2523
                                    strip_message_header(vars.get_opt_bin("Message_ServerHello")));
3✔
2524
                     result.test_eq("Encrypted Extensions",
3✔
2525
                                    msgs.at("encrypted_extensions")[0],
2✔
2526
                                    strip_message_header(vars.get_opt_bin("Message_EncryptedExtensions")));
3✔
2527
                     result.test_eq("Server Finished",
3✔
2528
                                    msgs.at("finished")[0],
2✔
2529
                                    strip_message_header(vars.get_opt_bin("Message_Server_Finished")));
3✔
2530

2531
                     result.test_eq("Server's entire first flight",
2✔
2532
                                    ctx->pull_send_buffer(),
2✔
2533
                                    concat(vars.get_req_bin("Record_ServerHello"),
4✔
2534
                                           vars.get_req_bin("Record_ServerHandshakeMessages")));
2✔
2535

2536
                     result.confirm("Server can now send application data", ctx->server.is_active());
2✔
2537
                     result.confirm("handshake is not yet complete",
1✔
2538
                                    !ctx->server.is_handshake_complete());  // See RFC 8446 4.4.4
1✔
2539
                  }),
1✔
2540

2541
            CHECK("Send Client Finished",
2542
                  [&](Test::Result& result) {
1✔
2543
                     result.require("ctx is available", ctx != nullptr);
1✔
2544
                     ctx->server.received_data(vars.get_req_bin("Record_ClientFinished"));
2✔
2545
                     result.require("PSK negotiated",
2✔
2546
                                    ctx->psk_identity_negotiated() == vars.get_req_str("PskIdentity"));
2✔
2547

2548
                     ctx->check_callback_invocations(result,
2✔
2549
                                                     "client finished received",
2550
                                                     {"tls_inspect_handshake_msg_finished",
2551
                                                      "tls_current_timestamp",
2552
                                                      "tls_session_established",
2553
                                                      "tls_session_activated"});
2554
                  }),
1✔
2555

2556
            CHECK("Exchange Application Data",
2557
                  [&](Test::Result& result) {
1✔
2558
                     result.require("ctx is available", ctx != nullptr);
1✔
2559
                     ctx->server.received_data(vars.get_req_bin("Record_Client_AppData"));
2✔
2560
                     ctx->check_callback_invocations(result, "application data received", {"tls_record_received"});
2✔
2561

2562
                     const auto rcvd = ctx->pull_receive_buffer();
1✔
2563
                     result.test_eq("decrypted application traffic", rcvd, vars.get_req_bin("Client_AppData"));
3✔
2564
                     result.test_is_eq("sequence number", ctx->last_received_seq_no(), uint64_t(0));
1✔
2565

2566
                     ctx->send(vars.get_req_bin("Server_AppData"));
3✔
2567
                     ctx->check_callback_invocations(result, "application data sent", {"tls_emit_data"});
2✔
2568
                     result.test_eq("correct server application data",
2✔
2569
                                    ctx->pull_send_buffer(),
2✔
2570
                                    vars.get_req_bin("Record_Server_AppData"));
2✔
2571
                  }),
1✔
2572

2573
            CHECK("Terminate Connection",
2574
                  [&](Test::Result& result) {
1✔
2575
                     result.require("ctx is available", ctx != nullptr);
1✔
2576
                     ctx->server.received_data(vars.get_req_bin("Record_Client_CloseNotify"));
2✔
2577

2578
                     ctx->check_callback_invocations(
2✔
2579
                        result, "client finished received", {"tls_alert", "tls_peer_closed_connection"});
2580

2581
                     result.confirm("connection is not yet closed", !ctx->server.is_closed());
2✔
2582
                     result.confirm("connection is still active", ctx->server.is_active());
2✔
2583
                     result.confirm("handshake is still complete", ctx->server.is_handshake_complete());
2✔
2584

2585
                     ctx->server.close();
1✔
2586

2587
                     result.confirm("connection is now inactive", !ctx->server.is_active());
2✔
2588
                     result.confirm("connection is now closed", ctx->server.is_closed());
2✔
2589
                     result.confirm("handshake is still complete", ctx->server.is_handshake_complete());
2✔
2590
                     result.test_eq("Server's close notify",
2✔
2591
                                    ctx->pull_send_buffer(),
2✔
2592
                                    vars.get_req_bin("Record_Server_CloseNotify"));
2✔
2593
                  }),
1✔
2594
         };
6✔
2595
      }
2✔
2596

2597
      std::vector<Test::Result> raw_public_key_with_client_authentication(const VarMap& vars) override {
1✔
2598
         auto rng = std::make_unique<Fixed_Output_RNG>("");
1✔
2599

2600
         // 32 - for server hello random
2601
         // 32 - for KeyShare (eph. x25519 key pair)
2602
         add_entropy(*rng, vars.get_req_bin("Server_RNG_Pool"));
2✔
2603

2604
         auto sort_our_extensions =
1✔
2605
            [&](Botan::TLS::Extensions& exts, Botan::TLS::Connection_Side /* side */, Botan::TLS::Handshake_Type type) {
4✔
2606
               // This is the order of extensions when we first introduced the raw
2607
               // public key authentication implementation and generated the transcript.
2608
               // To stay compatible with the now hard-coded transcript, we pin the
2609
               // extension order.
2610
               if(type == Botan::TLS::Handshake_Type::EncryptedExtensions) {
4✔
2611
                  sort_extensions(exts,
2✔
2612
                                  {
2613
                                     Botan::TLS::Extension_Code::ClientCertificateType,
2614
                                     Botan::TLS::Extension_Code::ServerCertificateType,
2615
                                     Botan::TLS::Extension_Code::SupportedGroups,
2616
                                     Botan::TLS::Extension_Code::RecordSizeLimit,
2617
                                     Botan::TLS::Extension_Code::ServerNameIndication,
2618
                                  });
2619
               } else if(type == Botan::TLS::Handshake_Type::ServerHello) {
3✔
2620
                  sort_extensions(exts,
2✔
2621
                                  {
2622
                                     Botan::TLS::Extension_Code::KeyShare,
2623
                                     Botan::TLS::Extension_Code::SupportedVersions,
2624
                                  });
2625
               }
2626
            };
4✔
2627

2628
         std::unique_ptr<Server_Context> ctx;
1✔
2629

2630
         return {
1✔
2631
            CHECK("Receive Client Hello",
2632
                  [&](Test::Result& result) {
1✔
2633
                     ctx = std::make_unique<Server_Context>(std::move(rng),
1✔
2634
                                                            std::make_shared<RFC8448_Text_Policy>("rfc8448_rawpubkey"),
2✔
2635
                                                            vars.get_req_u64("CurrentTimestamp"),
1✔
2636
                                                            sort_our_extensions,
2637
                                                            make_mock_signatures(vars));
3✔
2638
                     result.confirm("server not closed", !ctx->server.is_closed());
2✔
2639

2640
                     ctx->server.received_data(vars.get_req_bin("Record_ClientHello_1"));
2✔
2641

2642
                     ctx->check_callback_invocations(result,
2✔
2643
                                                     "client hello received",
2644
                                                     {"tls_emit_data",
2645
                                                      "tls_examine_extensions_client_hello",
2646
                                                      "tls_modify_extensions_server_hello",
2647
                                                      "tls_modify_extensions_encrypted_extensions",
2648
                                                      "tls_modify_extensions_certificate_request",
2649
                                                      "tls_modify_extensions_certificate",
2650
                                                      "tls_sign_message",
2651
                                                      "tls_generate_ephemeral_key",
2652
                                                      "tls_ephemeral_key_agreement",
2653
                                                      "tls_inspect_handshake_msg_client_hello",
2654
                                                      "tls_inspect_handshake_msg_server_hello",
2655
                                                      "tls_inspect_handshake_msg_encrypted_extensions",
2656
                                                      "tls_inspect_handshake_msg_certificate_request",
2657
                                                      "tls_inspect_handshake_msg_certificate",
2658
                                                      "tls_inspect_handshake_msg_certificate_verify",
2659
                                                      "tls_inspect_handshake_msg_finished"});
2660
                  }),
1✔
2661

2662
            CHECK("Verify server's generated handshake messages",
2663
                  [&](Test::Result& result) {
1✔
2664
                     result.require("ctx is available", ctx != nullptr);
1✔
2665
                     const auto& msgs = ctx->observed_handshake_messages();
1✔
2666

2667
                     result.test_eq("Server Hello",
3✔
2668
                                    msgs.at("server_hello")[0],
2✔
2669
                                    strip_message_header(vars.get_opt_bin("Message_ServerHello")));
3✔
2670
                     result.test_eq("Encrypted Extensions",
3✔
2671
                                    msgs.at("encrypted_extensions")[0],
2✔
2672
                                    strip_message_header(vars.get_opt_bin("Message_EncryptedExtensions")));
3✔
2673
                     result.test_eq("Certificate Request",
3✔
2674
                                    msgs.at("certificate_request")[0],
2✔
2675
                                    strip_message_header(vars.get_opt_bin("Message_CertificateRequest")));
3✔
2676
                     result.test_eq("Certificate",
3✔
2677
                                    msgs.at("certificate")[0],
2✔
2678
                                    strip_message_header(vars.get_opt_bin("Message_Server_Certificate")));
3✔
2679
                     result.test_eq("CertificateVerify",
3✔
2680
                                    msgs.at("certificate_verify")[0],
2✔
2681
                                    strip_message_header(vars.get_opt_bin("Message_Server_CertificateVerify")));
3✔
2682
                     result.test_eq("Finished",
3✔
2683
                                    msgs.at("finished")[0],
2✔
2684
                                    strip_message_header(vars.get_opt_bin("Message_Server_Finished")));
3✔
2685

2686
                     result.test_eq("Server's entire first flight",
2✔
2687
                                    ctx->pull_send_buffer(),
2✔
2688
                                    concat(vars.get_req_bin("Record_ServerHello"),
4✔
2689
                                           vars.get_req_bin("Record_ServerHandshakeMessages")));
2✔
2690

2691
                     result.confirm("Not yet aware of client's cert chain", ctx->server.peer_cert_chain().empty());
2✔
2692
                     result.confirm("Server could now send application data", ctx->server.is_active());
2✔
2693
                     result.confirm("handshake is not yet complete",
1✔
2694
                                    !ctx->server.is_handshake_complete());  // See RFC 8446 4.4.4
1✔
2695
                  }),
1✔
2696

2697
            CHECK("Receive Client's second flight",
2698
                  [&](Test::Result& result) {
1✔
2699
                     result.require("ctx is available", ctx != nullptr);
1✔
2700
                     // This encrypted message contains the following messages:
2701
                     // * client's Certificate message
2702
                     // * client's Certificate_Verify message
2703
                     // * client's Finished message
2704
                     ctx->server.received_data(vars.get_req_bin("Record_ClientFinished"));
2✔
2705

2706
                     ctx->check_callback_invocations(result,
2✔
2707
                                                     "client finished received",
2708
                                                     {"tls_inspect_handshake_msg_certificate",
2709
                                                      "tls_inspect_handshake_msg_certificate_verify",
2710
                                                      "tls_inspect_handshake_msg_finished",
2711
                                                      "tls_examine_extensions_certificate",
2712
                                                      "tls_verify_raw_public_key",
2713
                                                      "tls_verify_message",
2714
                                                      "tls_current_timestamp",
2715
                                                      "tls_session_established",
2716
                                                      "tls_session_activated"});
2717

2718
                     const auto raw_pk = ctx->server.peer_raw_public_key();
1✔
2719
                     result.confirm(
2✔
2720
                        "Received client's raw public key",
2721
                        raw_pk && raw_pk->fingerprint_public() == client_raw_public_key_pair()->fingerprint_public());
5✔
2722

2723
                     result.confirm("TLS handshake finished", ctx->server.is_active());
2✔
2724
                     result.confirm("handshake is complete", ctx->server.is_handshake_complete());
2✔
2725
                  }),
1✔
2726

2727
            CHECK("Receive Client close_notify",
2728
                  [&](Test::Result& result) {
1✔
2729
                     result.require("ctx is available", ctx != nullptr);
1✔
2730
                     ctx->server.received_data(vars.get_req_bin("Record_Client_CloseNotify"));
2✔
2731

2732
                     ctx->check_callback_invocations(
2✔
2733
                        result, "client finished received", {"tls_alert", "tls_peer_closed_connection"});
2734

2735
                     result.confirm("connection is not yet closed", !ctx->server.is_closed());
2✔
2736
                     result.confirm("connection is still active", ctx->server.is_active());
2✔
2737
                     result.confirm("handshake is still complete", ctx->server.is_handshake_complete());
2✔
2738
                  }),
1✔
2739

2740
            CHECK("Expect Server close_notify",
2741
                  [&](Test::Result& result) {
1✔
2742
                     result.require("ctx is available", ctx != nullptr);
1✔
2743
                     ctx->server.close();
1✔
2744

2745
                     result.confirm("connection is now inactive", !ctx->server.is_active());
2✔
2746
                     result.confirm("connection is now closed", ctx->server.is_closed());
2✔
2747
                     result.confirm("handshake is still complete", ctx->server.is_handshake_complete());
2✔
2748
                     result.test_eq("Server's close notify",
2✔
2749
                                    ctx->pull_send_buffer(),
2✔
2750
                                    vars.get_req_bin("Record_Server_CloseNotify"));
2✔
2751
                  }),
1✔
2752
         };
6✔
2753
      }
2✔
2754
};
2755

2756
BOTAN_REGISTER_TEST("tls", "tls_rfc8448_client", Test_TLS_RFC8448_Client);
2757
BOTAN_REGISTER_TEST("tls", "tls_rfc8448_server", Test_TLS_RFC8448_Server);
2758

2759
#endif
2760

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