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

randombit / botan / 24648292556

19 Apr 2026 10:53PM UTC coverage: 89.474% (+0.03%) from 89.442%
24648292556

push

github

web-flow
Merge pull request #5536 from randombit/jack/x509-misc

Various PKIX optimizations and bug fixes

106453 of 118977 relevant lines covered (89.47%)

11452293.24 hits per line

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

80.73
/src/lib/tls/tls_callbacks.cpp
1
/*
2
* TLS Callbacks
3
* (C) 2016 Jack Lloyd
4
*     2017 Harry Reimann, Rohde & Schwarz Cybersecurity
5
*     2022 René Meusel, Hannes Rantzsch - neXenio GmbH
6
*     2023 René Meusel - Rohde & Schwarz Cybersecurity
7
*
8
* Botan is released under the Simplified BSD License (see license.txt)
9
*/
10

11
#include <botan/tls_callbacks.h>
12

13
#include <botan/dh.h>
14
#include <botan/dl_group.h>
15
#include <botan/ec_group.h>
16
#include <botan/ecdh.h>
17
#include <botan/ocsp.h>
18
#include <botan/pk_algs.h>
19
#include <botan/tls_algos.h>
20
#include <botan/tls_exceptn.h>
21
#include <botan/tls_policy.h>
22
#include <botan/tls_session.h>
23
#include <botan/x509path.h>
24
#include <botan/internal/fmt.h>
25
#include <botan/internal/stl_util.h>
26

27
#if defined(BOTAN_HAS_X25519)
28
   #include <botan/x25519.h>
29
#endif
30

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

35
#if defined(BOTAN_HAS_ML_KEM)
36
   #include <botan/ml_kem.h>
37
#endif
38

39
#if defined(BOTAN_HAS_FRODOKEM)
40
   #include <botan/frodokem.h>
41
#endif
42

43
#if defined(BOTAN_HAS_TLS_13_PQC)
44
   #include <botan/internal/hybrid_public_key.h>
45
#endif
46

47
namespace Botan {
48

49
void TLS::Callbacks::tls_inspect_handshake_msg(const Handshake_Message& /*unused*/) {
7,028✔
50
   // default is no op
51
}
7,028✔
52

53
std::string TLS::Callbacks::tls_server_choose_app_protocol(const std::vector<std::string>& /*unused*/) {
×
54
   return "";
×
55
}
56

57
std::string TLS::Callbacks::tls_peer_network_identity() {
952✔
58
   return "";
952✔
59
}
60

61
std::chrono::system_clock::time_point TLS::Callbacks::tls_current_timestamp() {
5,412✔
62
   return std::chrono::system_clock::now();
5,412✔
63
}
64

65
void TLS::Callbacks::tls_modify_extensions(Extensions& /*unused*/,
2,184✔
66
                                           Connection_Side /*unused*/,
67
                                           Handshake_Type /*unused*/) {}
2,184✔
68

69
void TLS::Callbacks::tls_examine_extensions(const Extensions& /*unused*/,
6,198✔
70
                                            Connection_Side /*unused*/,
71
                                            Handshake_Type /*unused*/) {}
6,198✔
72

73
bool TLS::Callbacks::tls_should_persist_resumption_information(const Session& session) {
2,853✔
74
   // RFC 5077 3.3
75
   //    The ticket_lifetime_hint field contains a hint from the server about
76
   //    how long the ticket should be stored. A value of zero is reserved to
77
   //    indicate that the lifetime of the ticket is unspecified.
78
   //
79
   // RFC 8446 4.6.1
80
   //    [A ticket_lifetime] of zero indicates that the ticket should be discarded
81
   //    immediately.
82
   //
83
   // By default we opt to keep all sessions, except for TLS 1.3 with a lifetime
84
   // hint of zero.
85
   return session.lifetime_hint().count() > 0 || session.version().is_pre_tls_13();
2,853✔
86
}
87

88
void TLS::Callbacks::tls_verify_cert_chain(const std::vector<X509_Certificate>& cert_chain,
1,498✔
89
                                           const std::vector<std::optional<OCSP::Response>>& ocsp_responses,
90
                                           const std::vector<Certificate_Store*>& trusted_roots,
91
                                           Usage_Type usage,
92
                                           std::string_view hostname,
93
                                           const TLS::Policy& policy) {
94
   if(cert_chain.empty()) {
1,498✔
95
      throw Invalid_Argument("Certificate chain was empty");
×
96
   }
97

98
   const Path_Validation_Restrictions restrictions(policy.require_cert_revocation_info(),
1,498✔
99
                                                   policy.minimum_signature_strength());
4,494✔
100

101
   const Path_Validation_Result result = x509_path_validate(cert_chain,
1,498✔
102
                                                            restrictions,
103
                                                            trusted_roots,
104
                                                            hostname,
105
                                                            usage,
106
                                                            tls_current_timestamp(),
1,498✔
107
                                                            tls_verify_cert_chain_ocsp_timeout(),
1,498✔
108
                                                            ocsp_responses);
1,498✔
109

110
   if(!result.successful_validation()) {
1,498✔
111
      throw TLS_Exception(Alert::BadCertificate, "Certificate validation failure: " + result.result_string());
480✔
112
   }
113
}
1,738✔
114

115
void TLS::Callbacks::tls_verify_raw_public_key(const Public_Key& raw_public_key,
×
116
                                               Usage_Type usage,
117
                                               std::string_view hostname,
118
                                               const TLS::Policy& policy) {
119
   BOTAN_UNUSED(raw_public_key, usage, hostname, policy);
×
120
   // There is no good default implementation for authenticating raw public key.
121
   // Applications that wish to use them for authentication, must override this.
122
   throw TLS_Exception(Alert::CertificateUnknown, "Application did not provide a means to validate the raw public key");
×
123
}
124

125
std::optional<OCSP::Response> TLS::Callbacks::tls_parse_ocsp_response(const std::vector<uint8_t>& raw_response) {
×
126
   try {
×
127
      return OCSP::Response(raw_response);
×
128
   } catch(const Decoding_Error&) {
×
129
      // ignore parsing errors and just ignore the broken OCSP response
130
      return std::nullopt;
×
131
   }
×
132
}
133

134
std::vector<std::vector<uint8_t>> TLS::Callbacks::tls_provide_cert_chain_status(
261✔
135
   const std::vector<X509_Certificate>& chain, const Certificate_Status_Request& csr) {
136
   std::vector<std::vector<uint8_t>> result(chain.size());
261✔
137
   if(!chain.empty()) {
261✔
138
      result[0] = tls_provide_cert_status(chain, csr);
261✔
139
   }
140
   return result;
253✔
141
}
8✔
142

143
std::vector<uint8_t> TLS::Callbacks::tls_sign_message(const Private_Key& key,
1,029✔
144
                                                      RandomNumberGenerator& rng,
145
                                                      std::string_view padding,
146
                                                      Signature_Format format,
147
                                                      const std::vector<uint8_t>& msg) {
148
   PK_Signer signer(key, rng, padding, format);
1,029✔
149

150
   return signer.sign_message(msg, rng);
2,057✔
151
}
1,029✔
152

153
bool TLS::Callbacks::tls_verify_message(const Public_Key& key,
1,428✔
154
                                        std::string_view padding,
155
                                        Signature_Format format,
156
                                        const std::vector<uint8_t>& msg,
157
                                        const std::vector<uint8_t>& sig) {
158
   PK_Verifier verifier(key, padding, format);
1,428✔
159

160
   return verifier.verify_message(msg, sig);
2,856✔
161
}
1,428✔
162

163
namespace {
164

165
bool is_dh_group(const std::variant<TLS::Group_Params, DL_Group>& group) {
5,121✔
166
   return std::holds_alternative<DL_Group>(group) || std::get<TLS::Group_Params>(group).is_dh_named_group();
10,226✔
167
}
168

169
DL_Group get_dl_group(const std::variant<TLS::Group_Params, DL_Group>& group) {
20✔
170
   BOTAN_ASSERT_NOMSG(is_dh_group(group));
20✔
171

172
   // TLS 1.2 allows specifying arbitrary DL_Group parameters in-lieu of
173
   // a standardized DH group identifier. TLS 1.3 just offers pre-defined
174
   // groups.
175
   return std::visit(
20✔
176
      overloaded{[](const DL_Group& dl_group) { return dl_group; },
8✔
177
                 [&](TLS::Group_Params group_param) { return DL_Group::from_name(group_param.to_string().value()); }},
36✔
178
      group);
20✔
179
}
180

181
}  // namespace
182

183
std::unique_ptr<Public_Key> TLS::Callbacks::tls_deserialize_peer_public_key(
2,252✔
184
   const std::variant<TLS::Group_Params, DL_Group>& group, std::span<const uint8_t> key_bits) {
185
   if(is_dh_group(group)) {
2,252✔
186
      // TLS 1.2 allows specifying arbitrary DL_Group parameters in-lieu of
187
      // a standardized DH group identifier.
188
      const auto dl_group = get_dl_group(group);
8✔
189

190
      auto Y = BigInt::from_bytes(key_bits);
8✔
191

192
      /*
193
       * A basic check for key validity. As we do not know q here we
194
       * cannot check that Y is in the right subgroup. However since
195
       * our key is ephemeral there does not seem to be any
196
       * advantage to bogus keys anyway.
197
       */
198
      if(Y <= 1 || Y >= dl_group.get_p() - 1) {
16✔
199
         throw Decoding_Error("Server sent bad DH key for DHE exchange");
×
200
      }
201

202
      return std::make_unique<DH_PublicKey>(dl_group, Y);
16✔
203
   }
16✔
204

205
   // The special case for TLS 1.2 with an explicit DH group definition is
206
   // handled above. All other cases are based on the opaque group definition.
207
   BOTAN_ASSERT_NOMSG(std::holds_alternative<TLS::Group_Params>(group));
2,244✔
208
   const auto group_params = std::get<TLS::Group_Params>(group);
2,244✔
209

210
   if(group_params.is_ecdh_named_curve()) {
2,244✔
211
      const auto ec_group = EC_Group::from_name(group_params.to_string().value());
198✔
212
      return std::make_unique<ECDH_PublicKey>(ec_group, EC_AffinePoint(ec_group, key_bits));
162✔
213
   }
99✔
214

215
#if defined(BOTAN_HAS_X25519)
216
   if(group_params.is_x25519()) {
2,145✔
217
      return std::make_unique<X25519_PublicKey>(key_bits);
4,224✔
218
   }
219
#endif
220

221
#if defined(BOTAN_HAS_X448)
222
   if(group_params.is_x448()) {
29✔
223
      return std::make_unique<X448_PublicKey>(key_bits);
8✔
224
   }
225
#endif
226

227
#if defined(BOTAN_HAS_TLS_13_PQC)
228
   if(group_params.is_pqc_hybrid()) {
25✔
229
      return Hybrid_KEM_PublicKey::load_for_group(group_params, key_bits);
37✔
230
   }
231
#endif
232

233
#if defined(BOTAN_HAS_ML_KEM)
234
   if(group_params.is_pure_ml_kem()) {
5✔
235
      return std::make_unique<ML_KEM_PublicKey>(key_bits, ML_KEM_Mode(group_params.to_string().value()));
17✔
236
   }
237
#endif
238

239
#if defined(BOTAN_HAS_FRODOKEM)
240
   if(group_params.is_pure_frodokem()) {
×
241
      return std::make_unique<FrodoKEM_PublicKey>(key_bits, FrodoKEMMode(group_params.to_string().value()));
×
242
   }
243
#endif
244

245
   throw Decoding_Error("cannot create a key offering without a group definition");
×
246
}
247

248
std::unique_ptr<Private_Key> TLS::Callbacks::tls_kem_generate_key(TLS::Group_Params group, RandomNumberGenerator& rng) {
2,047✔
249
#if defined(BOTAN_HAS_ML_KEM)
250
   if(group.is_pure_ml_kem()) {
2,047✔
251
      return std::make_unique<ML_KEM_PrivateKey>(rng, ML_KEM_Mode(group.to_string().value()));
33✔
252
   }
253
#endif
254

255
#if defined(BOTAN_HAS_FRODOKEM)
256
   if(group.is_pure_frodokem()) {
2,036✔
257
      return std::make_unique<FrodoKEM_PrivateKey>(rng, FrodoKEMMode(group.to_string().value()));
×
258
   }
259
#endif
260

261
#if defined(BOTAN_HAS_TLS_13_PQC)
262
   if(group.is_pqc_hybrid()) {
2,036✔
263
      return Hybrid_KEM_PrivateKey::generate_from_group(group, rng);
1,914✔
264
   }
265
#endif
266

267
   return tls_generate_ephemeral_key(group, rng);
3,237✔
268
}
269

270
KEM_Encapsulation TLS::Callbacks::tls_kem_encapsulate(TLS::Group_Params group,
417✔
271
                                                      const std::vector<uint8_t>& encoded_public_key,
272
                                                      RandomNumberGenerator& rng,
273
                                                      const Policy& policy) {
274
   if(group.is_kem()) {
417✔
275
      auto kem_pub_key = [&] {
69✔
276
         try {
25✔
277
            return tls_deserialize_peer_public_key(group, encoded_public_key);
50✔
278
         } catch(const Decoding_Error& ex) {
6✔
279
            // This exception means that the public key was invalid. However,
280
            // TLS' DecodeError would imply that a protocol message was invalid.
281
            throw TLS_Exception(Alert::IllegalParameter, ex.what());
4✔
282
         } catch(const Invalid_Argument& ex) {
6✔
283
            throw TLS_Exception(Alert::IllegalParameter, ex.what());
2✔
284
         }
2✔
285
      }();
25✔
286

287
      BOTAN_ASSERT_NONNULL(kem_pub_key);
19✔
288
      policy.check_peer_key_acceptable(*kem_pub_key);
19✔
289

290
      try {
19✔
291
         return PK_KEM_Encryptor(*kem_pub_key, "Raw").encrypt(rng);
19✔
292
      } catch(const Invalid_Argument& ex) {
1✔
293
         throw TLS_Exception(Alert::IllegalParameter, ex.what());
1✔
294
      }
1✔
295
   } else {
19✔
296
      // TODO: We could use the KEX_to_KEM_Adapter to remove the case distinction
297
      //       of KEM and KEX. However, the workarounds in this adapter class
298
      //       should first be addressed.
299
      auto ephemeral_keypair = tls_generate_ephemeral_key(group, rng);
392✔
300
      BOTAN_ASSERT_NONNULL(ephemeral_keypair);
392✔
301
      return {ephemeral_keypair->public_value(),
784✔
302
              tls_ephemeral_key_agreement(group, *ephemeral_keypair, encoded_public_key, rng, policy)};
784✔
303
   }
380✔
304
}
305

306
secure_vector<uint8_t> TLS::Callbacks::tls_kem_decapsulate(TLS::Group_Params group,
502✔
307
                                                           const Private_Key& private_key,
308
                                                           const std::vector<uint8_t>& encapsulated_bytes,
309
                                                           RandomNumberGenerator& rng,
310
                                                           const Policy& policy) {
311
   if(group.is_kem()) {
502✔
312
      PK_KEM_Decryptor kemdec(private_key, rng, "Raw");
30✔
313
      if(encapsulated_bytes.size() != kemdec.encapsulated_key_length()) {
30✔
314
         throw TLS_Exception(Alert::IllegalParameter, "Invalid encapsulated key length");
4✔
315
      }
316
      return kemdec.decrypt(encapsulated_bytes, 0, {});
26✔
317
   }
30✔
318

319
   try {
472✔
320
      const auto& key_agreement_key = dynamic_cast<const PK_Key_Agreement_Key&>(private_key);
472✔
321
      return tls_ephemeral_key_agreement(group, key_agreement_key, encapsulated_bytes, rng, policy);
944✔
322
   } catch(const std::bad_cast&) {
12✔
323
      throw Invalid_Argument("provided ephemeral key is not a PK_Key_Agreement_Key");
×
324
   }
×
325
}
326

327
std::unique_ptr<PK_Key_Agreement_Key> TLS::Callbacks::tls_generate_ephemeral_key(
2,849✔
328
   const std::variant<TLS::Group_Params, DL_Group>& group, RandomNumberGenerator& rng) {
329
   if(is_dh_group(group)) {
2,849✔
330
      const DL_Group dl_group = get_dl_group(group);
12✔
331
      return std::make_unique<DH_PrivateKey>(rng, dl_group);
24✔
332
   }
12✔
333

334
   BOTAN_ASSERT_NOMSG(std::holds_alternative<TLS::Group_Params>(group));
2,837✔
335
   const auto group_params = std::get<TLS::Group_Params>(group);
2,837✔
336

337
   if(group_params.is_ecdh_named_curve()) {
2,837✔
338
      const auto ec_group = EC_Group::from_name(group_params.to_string().value());
256✔
339
      return std::make_unique<ECDH_PrivateKey>(rng, ec_group);
256✔
340
   }
128✔
341

342
#if defined(BOTAN_HAS_X25519)
343
   if(group_params.is_x25519()) {
2,709✔
344
      return std::make_unique<X25519_PrivateKey>(rng);
5,410✔
345
   }
346
#endif
347

348
#if defined(BOTAN_HAS_X448)
349
   if(group_params.is_x448()) {
4✔
350
      return std::make_unique<X448_PrivateKey>(rng);
8✔
351
   }
352
#endif
353

354
   if(group_params.is_kem()) {
×
355
      throw TLS_Exception(Alert::IllegalParameter, "cannot generate an ephemeral KEX key for a KEM");
×
356
   }
357

358
   throw TLS_Exception(Alert::DecodeError, "cannot create a key offering without a group definition");
×
359
}
360

361
std::unique_ptr<PK_Key_Agreement_Key> TLS::Callbacks::tls12_generate_ephemeral_ecdh_key(
49✔
362
   TLS::Group_Params group, RandomNumberGenerator& rng, EC_Point_Format tls12_ecc_pubkey_encoding_format) {
363
   // Delegating to the "universal" callback to obtain an ECDH key pair
364
   auto key = tls_generate_ephemeral_key(group, rng);
49✔
365

366
   // For ordinary ECDH key pairs (that are derived from `ECDH_PublicKey`), we
367
   // set the internal point encoding flag for the key before passing it on into
368
   // the TLS 1.2 implementation. For user-defined keypair types (e.g. to
369
   // offload to some crypto hardware) inheriting from Botan's `ECDH_PublicKey`
370
   // might not be feasible. Such users should consider overriding this
371
   // ECDH-specific callback and ensure that their custom class handles the
372
   // public point encoding as requested by `tls12_ecc_pubkey_encoding_format`.
373
   if(auto* ecc_key = dynamic_cast<ECDH_PublicKey*>(key.get())) {
49✔
374
      ecc_key->set_point_encoding(tls12_ecc_pubkey_encoding_format);
49✔
375
   }
376

377
   return key;
49✔
378
}
×
379

380
secure_vector<uint8_t> TLS::Callbacks::tls_ephemeral_key_agreement(
2,227✔
381
   const std::variant<TLS::Group_Params, DL_Group>& group,
382
   const PK_Key_Agreement_Key& private_key,
383
   const std::vector<uint8_t>& public_value,
384
   RandomNumberGenerator& rng,
385
   const Policy& policy) {
386
   const auto kex_pub_key = [&]() {
6,637✔
387
      try {
2,227✔
388
         return tls_deserialize_peer_public_key(group, public_value);
2,227✔
389
      } catch(const Decoding_Error& ex) {
44✔
390
         // This exception means that the public key was invalid. However,
391
         // TLS' DecodeError would imply that a protocol message was invalid.
392
         throw TLS_Exception(Alert::IllegalParameter, ex.what());
44✔
393
      } catch(const Invalid_Argument& ex) {
44✔
394
         throw TLS_Exception(Alert::IllegalParameter, ex.what());
×
395
      }
×
396
   }();
2,227✔
397

398
   BOTAN_ASSERT_NONNULL(kex_pub_key);
2,183✔
399
   policy.check_peer_key_acceptable(*kex_pub_key);
2,183✔
400

401
   // RFC 8422 - 5.11.
402
   //   With X25519 and X448, a receiving party MUST check whether the
403
   //   computed premaster secret is the all-zero value and abort the
404
   //   handshake if so, as described in Section 6 of [RFC7748].
405
   //
406
   // This is done within the key agreement operation and throws
407
   // an Invalid_Argument exception if the shared secret is all-zero.
408
   try {
2,183✔
409
      const PK_Key_Agreement ka(private_key, rng, "Raw");
2,183✔
410
      return ka.derive_key(0, kex_pub_key->raw_public_key_bits()).bits_of();
6,545✔
411
   } catch(const Invalid_Argument& ex) {
2,187✔
412
      throw TLS_Exception(Alert::IllegalParameter, ex.what());
4✔
413
   }
4✔
414
}
2,179✔
415

416
void TLS::Callbacks::tls_session_established(const Session_Summary& session) {
72✔
417
   BOTAN_UNUSED(session);
72✔
418
}
72✔
419

420
std::vector<uint8_t> TLS::Callbacks::tls_provide_cert_status(const std::vector<X509_Certificate>& chain,
140✔
421
                                                             const Certificate_Status_Request& csr) {
422
   BOTAN_UNUSED(chain, csr);
140✔
423
   return std::vector<uint8_t>();
140✔
424
}
425

426
void TLS::Callbacks::tls_log_error(const char* err) {
×
427
   BOTAN_UNUSED(err);
×
428
}
×
429

430
void TLS::Callbacks::tls_log_debug(const char* what) {
×
431
   BOTAN_UNUSED(what);
×
432
}
×
433

434
void TLS::Callbacks::tls_log_debug_bin(const char* descr, const uint8_t val[], size_t val_len) {
×
435
   BOTAN_UNUSED(descr, val, val_len);
×
436
}
×
437

438
void TLS::Callbacks::tls_ssl_key_log_data(std::string_view label,
×
439
                                          std::span<const uint8_t> client_random,
440
                                          std::span<const uint8_t> secret) const {
441
   BOTAN_UNUSED(label, client_random, secret);
×
442
}
×
443

444
std::unique_ptr<KDF> TLS::Callbacks::tls12_protocol_specific_kdf(std::string_view prf_algo) const {
6,337✔
445
   if(prf_algo == "MD5" || prf_algo == "SHA-1") {
7,099✔
446
      return KDF::create_or_throw("TLS-12-PRF(SHA-256)");
762✔
447
   }
448

449
   return KDF::create_or_throw(Botan::fmt("TLS-12-PRF({})", prf_algo));
11,150✔
450
}
451

452
}  // namespace Botan
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