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

randombit / botan / 19012754211

02 Nov 2025 01:10PM UTC coverage: 90.677% (+0.006%) from 90.671%
19012754211

push

github

web-flow
Merge pull request #5137 from randombit/jack/clang-tidy-includes

Remove various unused includes flagged by clang-tidy misc-include-cleaner

100457 of 110786 relevant lines covered (90.68%)

12189873.8 hits per line

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

80.98
/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/ecdh.h>
16
#include <botan/ocsp.h>
17
#include <botan/pk_algs.h>
18
#include <botan/tls_algos.h>
19
#include <botan/tls_exceptn.h>
20
#include <botan/tls_policy.h>
21
#include <botan/x509path.h>
22
#include <botan/internal/stl_util.h>
23

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

28
#if defined(BOTAN_HAS_X448)
29
   #include <botan/x448.h>
30
#endif
31

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

36
#if defined(BOTAN_HAS_FRODOKEM)
37
   #include <botan/frodokem.h>
38
#endif
39

40
#if defined(BOTAN_HAS_TLS_13_PQC)
41
   #include <botan/internal/hybrid_public_key.h>
42
#endif
43

44
namespace Botan {
45

46
void TLS::Callbacks::tls_inspect_handshake_msg(const Handshake_Message& /*unused*/) {
6,498✔
47
   // default is no op
48
}
6,498✔
49

50
std::string TLS::Callbacks::tls_server_choose_app_protocol(const std::vector<std::string>& /*unused*/) {
×
51
   return "";
×
52
}
53

54
std::string TLS::Callbacks::tls_peer_network_identity() {
790✔
55
   return "";
790✔
56
}
57

58
std::chrono::system_clock::time_point TLS::Callbacks::tls_current_timestamp() {
5,421✔
59
   return std::chrono::system_clock::now();
5,421✔
60
}
61

62
void TLS::Callbacks::tls_modify_extensions(Extensions& /*unused*/,
2,184✔
63
                                           Connection_Side /*unused*/,
64
                                           Handshake_Type /*unused*/) {}
2,184✔
65

66
void TLS::Callbacks::tls_examine_extensions(const Extensions& /*unused*/,
5,288✔
67
                                            Connection_Side /*unused*/,
68
                                            Handshake_Type /*unused*/) {}
5,288✔
69

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

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

95
   Path_Validation_Restrictions restrictions(policy.require_cert_revocation_info(),
367✔
96
                                             policy.minimum_signature_strength());
1,101✔
97

98
   Path_Validation_Result result = x509_path_validate(cert_chain,
367✔
99
                                                      restrictions,
100
                                                      trusted_roots,
101
                                                      hostname,
102
                                                      usage,
103
                                                      tls_current_timestamp(),
367✔
104
                                                      tls_verify_cert_chain_ocsp_timeout(),
367✔
105
                                                      ocsp_responses);
367✔
106

107
   if(!result.successful_validation()) {
367✔
108
      throw TLS_Exception(Alert::BadCertificate, "Certificate validation failure: " + result.result_string());
516✔
109
   }
110
}
625✔
111

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

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

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

140
std::vector<uint8_t> TLS::Callbacks::tls_sign_message(const Private_Key& key,
985✔
141
                                                      RandomNumberGenerator& rng,
142
                                                      std::string_view padding,
143
                                                      Signature_Format format,
144
                                                      const std::vector<uint8_t>& msg) {
145
   PK_Signer signer(key, rng, padding, format);
985✔
146

147
   return signer.sign_message(msg, rng);
1,969✔
148
}
985✔
149

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

157
   return verifier.verify_message(msg, sig);
2,706✔
158
}
1,353✔
159

160
namespace {
161

162
bool is_dh_group(const std::variant<TLS::Group_Params, DL_Group>& group) {
4,830✔
163
   return std::holds_alternative<DL_Group>(group) || std::get<TLS::Group_Params>(group).is_dh_named_group();
9,640✔
164
}
165

166
DL_Group get_dl_group(const std::variant<TLS::Group_Params, DL_Group>& group) {
24✔
167
   BOTAN_ASSERT_NOMSG(is_dh_group(group));
24✔
168

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

178
}  // namespace
179

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

187
      auto Y = BigInt::from_bytes(key_bits);
10✔
188

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

199
      return std::make_unique<DH_PublicKey>(dl_group, Y);
20✔
200
   }
20✔
201

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

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

212
#if defined(BOTAN_HAS_X25519)
213
   if(group_params.is_x25519()) {
1,988✔
214
      return std::make_unique<X25519_PublicKey>(key_bits);
3,918✔
215
   }
216
#endif
217

218
#if defined(BOTAN_HAS_X448)
219
   if(group_params.is_x448()) {
25✔
220
      return std::make_unique<X448_PublicKey>(key_bits);
8✔
221
   }
222
#endif
223

224
#if defined(BOTAN_HAS_TLS_13_PQC)
225
   if(group_params.is_pqc_hybrid()) {
21✔
226
      return Hybrid_KEM_PublicKey::load_for_group(group_params, key_bits);
37✔
227
   }
228
#endif
229

230
#if defined(BOTAN_HAS_ML_KEM)
231
   if(group_params.is_pure_ml_kem()) {
1✔
232
      return std::make_unique<ML_KEM_PublicKey>(key_bits, ML_KEM_Mode(group_params.to_string().value()));
4✔
233
   }
234
#endif
235

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

242
   throw Decoding_Error("cannot create a key offering without a group definition");
×
243
}
244

245
std::unique_ptr<Private_Key> TLS::Callbacks::tls_kem_generate_key(TLS::Group_Params group, RandomNumberGenerator& rng) {
1,060✔
246
#if defined(BOTAN_HAS_ML_KEM)
247
   if(group.is_pure_ml_kem()) {
1,060✔
248
      return std::make_unique<ML_KEM_PrivateKey>(rng, ML_KEM_Mode(group.to_string().value()));
3✔
249
   }
250
#endif
251

252
#if defined(BOTAN_HAS_FRODOKEM)
253
   if(group.is_pure_frodokem()) {
1,059✔
254
      return std::make_unique<FrodoKEM_PrivateKey>(rng, FrodoKEMMode(group.to_string().value()));
×
255
   }
256
#endif
257

258
#if defined(BOTAN_HAS_TLS_13_PQC)
259
   if(group.is_pqc_hybrid()) {
1,059✔
260
      return Hybrid_KEM_PrivateKey::generate_from_group(group, rng);
42✔
261
   }
262
#endif
263

264
   return tls_generate_ephemeral_key(group, rng);
3,114✔
265
}
266

267
KEM_Encapsulation TLS::Callbacks::tls_kem_encapsulate(TLS::Group_Params group,
383✔
268
                                                      const std::vector<uint8_t>& encoded_public_key,
269
                                                      RandomNumberGenerator& rng,
270
                                                      const Policy& policy) {
271
   if(group.is_kem()) {
383✔
272
      auto kem_pub_key = [&] {
60✔
273
         try {
21✔
274
            return tls_deserialize_peer_public_key(group, encoded_public_key);
42✔
275
         } catch(const Decoding_Error& ex) {
3✔
276
            // This exception means that the public key was invalid. However,
277
            // TLS' DecodeError would imply that a protocol message was invalid.
278
            throw TLS_Exception(Alert::IllegalParameter, ex.what());
3✔
279
         }
3✔
280
      }();
21✔
281

282
      BOTAN_ASSERT_NONNULL(kem_pub_key);
18✔
283
      policy.check_peer_key_acceptable(*kem_pub_key);
18✔
284

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

301
secure_vector<uint8_t> TLS::Callbacks::tls_kem_decapsulate(TLS::Group_Params group,
442✔
302
                                                           const Private_Key& private_key,
303
                                                           const std::vector<uint8_t>& encapsulated_bytes,
304
                                                           RandomNumberGenerator& rng,
305
                                                           const Policy& policy) {
306
   if(group.is_kem()) {
442✔
307
      PK_KEM_Decryptor kemdec(private_key, rng, "Raw");
22✔
308
      if(encapsulated_bytes.size() != kemdec.encapsulated_key_length()) {
22✔
309
         throw TLS_Exception(Alert::IllegalParameter, "Invalid encapsulated key length");
2✔
310
      }
311
      return kemdec.decrypt(encapsulated_bytes, 0, {});
20✔
312
   }
22✔
313

314
   try {
420✔
315
      const auto& key_agreement_key = dynamic_cast<const PK_Key_Agreement_Key&>(private_key);
420✔
316
      return tls_ephemeral_key_agreement(group, key_agreement_key, encapsulated_bytes, rng, policy);
840✔
317
   } catch(const std::bad_cast&) {
12✔
318
      throw Invalid_Argument("provided ephemeral key is not a PK_Key_Agreement_Key");
×
319
   }
×
320
}
321

322
std::unique_ptr<PK_Key_Agreement_Key> TLS::Callbacks::tls_generate_ephemeral_key(
2,709✔
323
   const std::variant<TLS::Group_Params, DL_Group>& group, RandomNumberGenerator& rng) {
324
   if(is_dh_group(group)) {
2,709✔
325
      const DL_Group dl_group = get_dl_group(group);
14✔
326
      return std::make_unique<DH_PrivateKey>(rng, dl_group);
28✔
327
   }
14✔
328

329
   BOTAN_ASSERT_NOMSG(std::holds_alternative<TLS::Group_Params>(group));
2,695✔
330
   const auto group_params = std::get<TLS::Group_Params>(group);
2,695✔
331

332
   if(group_params.is_ecdh_named_curve()) {
2,695✔
333
      const auto ec_group = EC_Group::from_name(group_params.to_string().value());
296✔
334
      return std::make_unique<ECDH_PrivateKey>(rng, ec_group);
296✔
335
   }
148✔
336

337
#if defined(BOTAN_HAS_X25519)
338
   if(group_params.is_x25519()) {
2,547✔
339
      return std::make_unique<X25519_PrivateKey>(rng);
5,086✔
340
   }
341
#endif
342

343
#if defined(BOTAN_HAS_X448)
344
   if(group_params.is_x448()) {
4✔
345
      return std::make_unique<X448_PrivateKey>(rng);
8✔
346
   }
347
#endif
348

349
   if(group_params.is_kem()) {
×
350
      throw TLS_Exception(Alert::IllegalParameter, "cannot generate an ephemeral KEX key for a KEM");
×
351
   }
352

353
   throw TLS_Exception(Alert::DecodeError, "cannot create a key offering without a group definition");
×
354
}
355

356
std::unique_ptr<PK_Key_Agreement_Key> TLS::Callbacks::tls12_generate_ephemeral_ecdh_key(
50✔
357
   TLS::Group_Params group, RandomNumberGenerator& rng, EC_Point_Format tls12_ecc_pubkey_encoding_format) {
358
   // Delegating to the "universal" callback to obtain an ECDH key pair
359
   auto key = tls_generate_ephemeral_key(group, rng);
50✔
360

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

372
   return key;
50✔
373
}
×
374

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

391
   BOTAN_ASSERT_NONNULL(kex_pub_key);
2,032✔
392
   policy.check_peer_key_acceptable(*kex_pub_key);
2,032✔
393

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

409
void TLS::Callbacks::tls_session_established(const Session_Summary& session) {
72✔
410
   BOTAN_UNUSED(session);
72✔
411
}
72✔
412

413
std::vector<uint8_t> TLS::Callbacks::tls_provide_cert_status(const std::vector<X509_Certificate>& chain,
139✔
414
                                                             const Certificate_Status_Request& csr) {
415
   BOTAN_UNUSED(chain, csr);
139✔
416
   return std::vector<uint8_t>();
139✔
417
}
418

419
void TLS::Callbacks::tls_log_error(const char* err) {
×
420
   BOTAN_UNUSED(err);
×
421
}
×
422

423
void TLS::Callbacks::tls_log_debug(const char* what) {
×
424
   BOTAN_UNUSED(what);
×
425
}
×
426

427
void TLS::Callbacks::tls_log_debug_bin(const char* descr, const uint8_t val[], size_t val_len) {
×
428
   BOTAN_UNUSED(descr, val, val_len);
×
429
}
×
430

431
void TLS::Callbacks::tls_ssl_key_log_data(std::string_view label,
×
432
                                          std::span<const uint8_t> client_random,
433
                                          std::span<const uint8_t> secret) const {
434
   BOTAN_UNUSED(label, client_random, secret);
×
435
}
×
436

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