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

randombit / botan / 25139258422

29 Apr 2026 08:02PM UTC coverage: 89.37% (-0.02%) from 89.385%
25139258422

push

github

web-flow
Merge pull request #5550 from randombit/jack/tls-misc

TLS conformance, hardening, and performance fixes

107055 of 119789 relevant lines covered (89.37%)

11415549.66 hits per line

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

82.68
/src/lib/tls/tls12/msg_client_kex.cpp
1
/*
2
* Client Key Exchange Message
3
* (C) 2004-2010,2016 Jack Lloyd
4
*     2017 Harry Reimann, Rohde & Schwarz Cybersecurity
5
*
6
* Botan is released under the Simplified BSD License (see license.txt)
7
*/
8

9
#include <botan/tls_messages_12.h>
10

11
#include <botan/credentials_manager.h>
12
#include <botan/dl_group.h>
13
#include <botan/rng.h>
14
#include <botan/rsa.h>
15
#include <botan/tls_callbacks.h>
16
#include <botan/tls_extensions.h>
17
#include <botan/tls_policy.h>
18
#include <botan/internal/ct_utils.h>
19
#include <botan/internal/fmt.h>
20
#include <botan/internal/stl_util.h>
21
#include <botan/internal/tls_handshake_hash.h>
22
#include <botan/internal/tls_handshake_io.h>
23
#include <botan/internal/tls_handshake_state.h>
24
#include <botan/internal/tls_reader.h>
25

26
namespace Botan::TLS {
27

28
namespace {
29

30
/*
31
* If the (p, g) pair the server sent corresponds to a known group
32
* (RFC 7919 or RFC 3526), return that group.
33
*/
34
std::optional<DL_Group> match_well_known_dh_group(const BigInt& p, const BigInt& g) {
7✔
35
   const size_t p_bits = p.bits();
7✔
36

37
   if(p_bits != 2048 && p_bits != 3072 && p_bits != 4096 && p_bits != 6144 && p_bits != 8192) {
7✔
38
      return {};
×
39
   }
40

41
   for(const char* prefix : {"ffdhe/ietf", "modp/ietf"}) {
7✔
42
      const std::string name = fmt("{}/{}", prefix, p_bits);
7✔
43
      auto candidate = DL_Group::from_name(name);
7✔
44
      if(candidate.get_p() == p && candidate.get_g() == g) {
7✔
45
         return candidate;
7✔
46
      }
47
   }
7✔
48

49
   return std::nullopt;
×
50
}
51

52
}  // namespace
53

54
/*
55
* Create a new Client Key Exchange message
56
*/
57
Client_Key_Exchange::Client_Key_Exchange(Handshake_IO& io,
853✔
58
                                         Handshake_State& state,
59
                                         const Policy& policy,
60
                                         Credentials_Manager& creds,
61
                                         const Public_Key* server_public_key,
62
                                         std::string_view hostname,
63
                                         RandomNumberGenerator& rng) {
853✔
64
   const Kex_Algo kex_algo = state.ciphersuite().kex_method();
853✔
65

66
   if(kex_algo == Kex_Algo::PSK) {
853✔
67
      std::string identity_hint;
47✔
68

69
      if(state.server_kex() != nullptr) {
47✔
70
         TLS_Data_Reader reader("ClientKeyExchange", state.server_kex()->params());
30✔
71
         identity_hint = reader.get_string(2, 0, 65535);
30✔
72
      }
73

74
      m_psk_identity = creds.psk_identity("tls-client", std::string(hostname), identity_hint);
94✔
75

76
      append_tls_length_value(m_key_material, as_span_of_bytes(m_psk_identity.value()), 2);
47✔
77

78
      const SymmetricKey psk = creds.psk("tls-client", std::string(hostname), m_psk_identity.value());
141✔
79

80
      if(psk.empty()) {
47✔
81
         throw TLS_Exception(Alert::InternalError, "Application did not provide a PSK for the negotiated identity");
×
82
      }
83

84
      const std::vector<uint8_t> zeros(psk.length());
47✔
85

86
      append_tls_length_value(m_pre_master, zeros, 2);
47✔
87
      append_tls_length_value(m_pre_master, psk.bits_of(), 2);
141✔
88
   } else if(state.server_kex() != nullptr) {
900✔
89
      TLS_Data_Reader reader("ClientKeyExchange", state.server_kex()->params());
734✔
90

91
      SymmetricKey psk;
734✔
92

93
      if(kex_algo == Kex_Algo::ECDHE_PSK) {
734✔
94
         const std::string identity_hint = reader.get_string(2, 0, 65535);
24✔
95

96
         m_psk_identity = creds.psk_identity("tls-client", std::string(hostname), identity_hint);
48✔
97

98
         append_tls_length_value(m_key_material, as_span_of_bytes(m_psk_identity.value()), 2);
24✔
99

100
         psk = creds.psk("tls-client", std::string(hostname), m_psk_identity.value());
72✔
101

102
         if(psk.empty()) {
24✔
103
            throw TLS_Exception(Alert::InternalError, "Application did not provide a PSK for the negotiated identity");
×
104
         }
105
      }
24✔
106

107
      if(kex_algo == Kex_Algo::DH) {
734✔
108
         const auto modulus = BigInt::from_bytes(reader.get_range<uint8_t>(2, 1, 65535));
24✔
109
         const auto generator = BigInt::from_bytes(reader.get_range<uint8_t>(2, 1, 65535));
7✔
110
         const std::vector<uint8_t> peer_public_value = reader.get_range<uint8_t>(2, 1, 65535);
7✔
111

112
         if(reader.remaining_bytes() > 0) {
7✔
113
            throw Decoding_Error("Bad params size for DH key exchange");
×
114
         }
115

116
         if(modulus.bits() < policy.minimum_dh_group_size()) {
7✔
117
            throw TLS_Exception(Alert::InsufficientSecurity, "DH prime too small for policy");
×
118
         }
119
         if(modulus.bits() > policy.maximum_dh_group_size()) {
7✔
120
            throw TLS_Exception(Alert::IllegalParameter, "DH prime too large for policy");
×
121
         }
122

123
         const auto group = [&] {
×
124
            if(auto matched = match_well_known_dh_group(modulus, generator)) {
7✔
125
               return std::move(*matched);
7✔
126
            } else {
127
               /*
128
               * Even if we sent ffdhe groups in the supported_groups extension
129
               * a server may have replied with some other group.
130
               */
131
               DL_Group ad_hoc(modulus, generator);
×
132
               if(!ad_hoc.verify_group(rng, false)) {
×
133
                  throw TLS_Exception(Alert::InsufficientSecurity, "DH group validation failed");
×
134
               }
135
               return ad_hoc;
×
136
            }
7✔
137
         }();
7✔
138

139
         const auto private_key = state.callbacks().tls_generate_ephemeral_key(group, rng);
7✔
140
         m_pre_master = CT::strip_leading_zeros(
21✔
141
            state.callbacks().tls_ephemeral_key_agreement(group, *private_key, peer_public_value, rng, policy));
21✔
142
         append_tls_length_value(m_key_material, private_key->public_value(), 2);
21✔
143
      } else if(kex_algo == Kex_Algo::ECDH || kex_algo == Kex_Algo::ECDHE_PSK) {
748✔
144
         const uint8_t curve_type = reader.get_byte();
727✔
145
         if(curve_type != 3) {
727✔
146
            throw Decoding_Error("Server sent non-named ECC curve");
×
147
         }
148

149
         const Group_Params curve_id = static_cast<Group_Params>(reader.get_uint16_t());
727✔
150
         const std::vector<uint8_t> peer_public_value = reader.get_range<uint8_t>(1, 1, 255);
727✔
151

152
         if(!curve_id.is_ecdh_named_curve() && !curve_id.is_x25519() && !curve_id.is_x448()) {
727✔
153
            throw TLS_Exception(Alert::IllegalParameter,
4✔
154
                                "Server selected a group that is not compatible with the negotiated ciphersuite");
4✔
155
         }
156

157
         // RFC 8422 5.1: the server MUST select a curve from the
158
         // supported_groups list the client offered. Check against the actual
159
         // offered list (which may be a strict subset of the policy's
160
         // key_exchange_groups() if the application narrowed it via
161
         // tls_modify_extensions) rather than just the policy.
162
         if(!value_exists(state.client_hello()->supported_ecc_curves(), curve_id)) {
2,169✔
163
            throw TLS_Exception(Alert::IllegalParameter, "Server selected a curve we did not offer");
1✔
164
         }
165

166
         if(policy.choose_key_exchange_group({curve_id}, {}) != curve_id) {
1,444✔
167
            throw TLS_Exception(Alert::HandshakeFailure, "Server sent ECC curve prohibited by policy");
×
168
         }
169

170
         const auto private_key = [&] {
17✔
171
            if(curve_id.is_ecdh_named_curve()) {
722✔
172
               const auto pubkey_point_format = state.server_hello()->prefers_compressed_ec_points()
25✔
173
                                                   ? EC_Point_Format::Compressed
25✔
174
                                                   : EC_Point_Format::Uncompressed;
25✔
175
               return state.callbacks().tls12_generate_ephemeral_ecdh_key(curve_id, rng, pubkey_point_format);
25✔
176
            } else {
177
               return state.callbacks().tls_generate_ephemeral_key(curve_id, rng);
1,394✔
178
            }
179
         }();
722✔
180

181
         if(!private_key) {
722✔
182
            throw TLS_Exception(Alert::InternalError, "Application did not provide an EC key");
×
183
         }
184

185
         auto shared_secret =
722✔
186
            state.callbacks().tls_ephemeral_key_agreement(curve_id, *private_key, peer_public_value, rng, policy);
734✔
187

188
         if(kex_algo == Kex_Algo::ECDH) {
710✔
189
            m_pre_master = std::move(shared_secret);
686✔
190
         } else {
191
            append_tls_length_value(m_pre_master, shared_secret, 2);
24✔
192
            append_tls_length_value(m_pre_master, psk.bits_of(), 2);
72✔
193
         }
194

195
         // Note: In contrast to public_value(), raw_public_key_bits() takes the
196
         // point format (compressed vs. uncompressed) into account that was set
197
         // in its construction within tls_generate_ephemeral_key().
198
         append_tls_length_value(m_key_material, private_key->raw_public_key_bits(), 1);
2,130✔
199
      } else {
2,159✔
200
         throw Internal_Error("Client_Key_Exchange: Unknown key exchange method was negotiated");
×
201
      }
202

203
      reader.assert_done();
717✔
204
   } else {
734✔
205
      // No server key exchange msg better mean RSA kex + RSA key in cert
206

207
      if(kex_algo != Kex_Algo::STATIC_RSA) {
72✔
208
         throw Unexpected_Message("No server kex message, but negotiated a key exchange that required it");
×
209
      }
210

211
      if(server_public_key == nullptr) {
72✔
212
         throw Internal_Error("No server public key for RSA exchange");
×
213
      }
214

215
      if(const auto* rsa_pub = dynamic_cast<const RSA_PublicKey*>(server_public_key)) {
72✔
216
         const Protocol_Version offered_version = state.client_hello()->legacy_version();
72✔
217

218
         rng.random_vec(m_pre_master, 48);
72✔
219
         m_pre_master[0] = offered_version.major_version();
72✔
220
         m_pre_master[1] = offered_version.minor_version();
72✔
221

222
         const PK_Encryptor_EME encryptor(*rsa_pub, rng, "PKCS1v15");
72✔
223

224
         const std::vector<uint8_t> encrypted_key = encryptor.encrypt(m_pre_master, rng);
72✔
225

226
         append_tls_length_value(m_key_material, encrypted_key, 2);
144✔
227
      } else {
72✔
228
         throw TLS_Exception(Alert::HandshakeFailure,
×
229
                             "Expected a RSA key in server cert but got " + server_public_key->algo_name());
×
230
      }
231
   }
232

233
   state.hash().update(io.send(*this));
1,672✔
234
}
853✔
235

236
/*
237
* Read a Client Key Exchange message
238
*/
239
Client_Key_Exchange::Client_Key_Exchange(const std::vector<uint8_t>& contents,
738✔
240
                                         const Handshake_State& state,
241
                                         const Private_Key* server_rsa_kex_key,
242
                                         Credentials_Manager& creds,
243
                                         const Policy& policy,
244
                                         RandomNumberGenerator& rng) {
738✔
245
   const Kex_Algo kex_algo = state.ciphersuite().kex_method();
738✔
246

247
   if(kex_algo == Kex_Algo::STATIC_RSA) {
738✔
248
      BOTAN_ASSERT(state.server_certs() && !state.server_certs()->cert_chain().empty(),
58✔
249
                   "RSA key exchange negotiated so server sent a certificate");
250

251
      if(server_rsa_kex_key == nullptr) {
58✔
252
         throw Internal_Error("Expected RSA kex but no server kex key set");
×
253
      }
254

255
      if(server_rsa_kex_key->algo_name() != "RSA") {
58✔
256
         throw Internal_Error("Expected RSA key but got " + server_rsa_kex_key->algo_name());
×
257
      }
258

259
      TLS_Data_Reader reader("ClientKeyExchange", contents);
58✔
260
      // RFC 5246 7.4.7.1: encrypted_pre_master_secret<1..2^16-1>.
261
      const std::vector<uint8_t> encrypted_pre_master = reader.get_range<uint8_t>(2, 1, 65535);
58✔
262
      reader.assert_done();
58✔
263

264
      const PK_Decryptor_EME decryptor(*server_rsa_kex_key, rng, "PKCS1v15");
58✔
265

266
      const uint8_t client_major = state.client_hello()->legacy_version().major_version();
58✔
267
      const uint8_t client_minor = state.client_hello()->legacy_version().minor_version();
58✔
268

269
      /*
270
      * PK_Decryptor::decrypt_or_random will return a random value if
271
      * either the length does not match the expected value or if the
272
      * version number embedded in the PMS does not match the one sent
273
      * in the client hello.
274
      */
275
      const size_t expected_plaintext_size = 48;
58✔
276
      const size_t expected_content_size = 2;
58✔
277
      const uint8_t expected_content_bytes[expected_content_size] = {client_major, client_minor};
58✔
278
      const uint8_t expected_content_pos[expected_content_size] = {0, 1};
58✔
279

280
      m_pre_master = decryptor.decrypt_or_random(encrypted_pre_master.data(),
58✔
281
                                                 encrypted_pre_master.size(),
282
                                                 expected_plaintext_size,
283
                                                 rng,
284
                                                 expected_content_bytes,
285
                                                 expected_content_pos,
286
                                                 expected_content_size);
58✔
287
   } else {
116✔
288
      TLS_Data_Reader reader("ClientKeyExchange", contents);
680✔
289

290
      SymmetricKey psk;
680✔
291

292
      if(key_exchange_is_psk(kex_algo)) {
680✔
293
         m_psk_identity = reader.get_string(2, 0, 65535);
49✔
294

295
         try {
49✔
296
            psk = creds.psk("tls-server", state.client_hello()->sni_hostname(), m_psk_identity.value());
98✔
297
         } catch(...) {
×
298
            // Treat any lookup failure for the identity sent by the client as
299
            // "no PSK for this identity" and let the logic below handle it
300
         }
×
301

302
         if(psk.empty()) {
49✔
303
            if(policy.hide_unknown_users()) {
×
304
               psk = SymmetricKey(rng, 16);
×
305
            } else {
306
               throw TLS_Exception(Alert::UnknownPSKIdentity, "No PSK for identifier " + m_psk_identity.value());
×
307
            }
308
         }
309
      }
310

311
      if(kex_algo == Kex_Algo::PSK) {
49✔
312
         reader.assert_done();
37✔
313
         const std::vector<uint8_t> zeros(psk.length());
37✔
314
         append_tls_length_value(m_pre_master, zeros, 2);
37✔
315
         append_tls_length_value(m_pre_master, psk.bits_of(), 2);
111✔
316
      } else if(kex_algo == Kex_Algo::DH || kex_algo == Kex_Algo::ECDH || kex_algo == Kex_Algo::ECDHE_PSK) {
680✔
317
         const PK_Key_Agreement_Key& ka_key = state.server_kex()->server_kex_key();
643✔
318

319
         const std::vector<uint8_t> client_pubkey = (ka_key.algo_name() == "DH")
657✔
320
                                                       ? reader.get_range<uint8_t>(2, 1, 65535)
643✔
321
                                                       : reader.get_range<uint8_t>(1, 1, 255);
643✔
322

323
         const auto shared_group = state.server_kex()->shared_group();
643✔
324
         BOTAN_STATE_CHECK(shared_group && shared_group.value() != Group_Params::NONE);
643✔
325

326
         try {
643✔
327
            auto shared_secret =
643✔
328
               state.callbacks().tls_ephemeral_key_agreement(shared_group.value(), ka_key, client_pubkey, rng, policy);
655✔
329

330
            if(ka_key.algo_name() == "DH") {
631✔
331
               shared_secret = CT::strip_leading_zeros(shared_secret);
14✔
332
            }
333

334
            if(kex_algo == Kex_Algo::ECDHE_PSK) {
631✔
335
               append_tls_length_value(m_pre_master, shared_secret, 2);
12✔
336
               append_tls_length_value(m_pre_master, psk.bits_of(), 2);
36✔
337
            } else {
338
               m_pre_master = shared_secret;
619✔
339
            }
340
         } catch(Invalid_Argument& e) {
643✔
341
            throw TLS_Exception(Alert::IllegalParameter, e.what());
×
342
         } catch(TLS_Exception&) {
12✔
343
            throw;  // rethrow
12✔
344
         } catch(std::exception&) {
12✔
345
            /*
346
            * Something failed in the DH/ECDH computation. To avoid possible
347
            * attacks which are based on triggering and detecting some edge
348
            * failure condition, randomize the pre-master output and carry on,
349
            * allowing the protocol to fail later in the finished checks.
350
            */
351
            rng.random_vec(m_pre_master, ka_key.public_value().size());
×
352
         }
×
353

354
         reader.assert_done();
631✔
355
      } else {
643✔
356
         throw Internal_Error("Client_Key_Exchange: Unknown key exchange negotiated");
×
357
      }
358
   }
680✔
359
}
740✔
360

361
}  // namespace Botan::TLS
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