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

randombit / botan / 21768358452

06 Feb 2026 10:35PM UTC coverage: 90.064% (-0.003%) from 90.067%
21768358452

Pull #5289

github

web-flow
Merge f589db195 into 8ea0ca252
Pull Request #5289: Further misc header reductions, forward declarations, etc

102238 of 113517 relevant lines covered (90.06%)

11357432.36 hits per line

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

87.84
/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/tls_handshake_hash.h>
20
#include <botan/internal/tls_handshake_io.h>
21
#include <botan/internal/tls_handshake_state.h>
22
#include <botan/internal/tls_reader.h>
23

24
namespace Botan::TLS {
25

26
/*
27
* Create a new Client Key Exchange message
28
*/
29
Client_Key_Exchange::Client_Key_Exchange(Handshake_IO& io,
829✔
30
                                         Handshake_State& state,
31
                                         const Policy& policy,
32
                                         Credentials_Manager& creds,
33
                                         const Public_Key* server_public_key,
34
                                         std::string_view hostname,
35
                                         RandomNumberGenerator& rng) {
829✔
36
   const Kex_Algo kex_algo = state.ciphersuite().kex_method();
829✔
37

38
   if(kex_algo == Kex_Algo::PSK) {
829✔
39
      std::string identity_hint;
48✔
40

41
      if(state.server_kex() != nullptr) {
48✔
42
         TLS_Data_Reader reader("ClientKeyExchange", state.server_kex()->params());
31✔
43
         identity_hint = reader.get_string(2, 0, 65535);
31✔
44
      }
45

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

48
      append_tls_length_value(m_key_material, as_span_of_bytes(m_psk_identity.value()), 2);
48✔
49

50
      const SymmetricKey psk = creds.psk("tls-client", std::string(hostname), m_psk_identity.value());
144✔
51

52
      const std::vector<uint8_t> zeros(psk.length());
48✔
53

54
      append_tls_length_value(m_pre_master, zeros, 2);
48✔
55
      append_tls_length_value(m_pre_master, psk.bits_of(), 2);
144✔
56
   } else if(state.server_kex() != nullptr) {
877✔
57
      TLS_Data_Reader reader("ClientKeyExchange", state.server_kex()->params());
701✔
58

59
      SymmetricKey psk;
701✔
60

61
      if(kex_algo == Kex_Algo::ECDHE_PSK) {
701✔
62
         const std::string identity_hint = reader.get_string(2, 0, 65535);
24✔
63

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

66
         append_tls_length_value(m_key_material, as_span_of_bytes(m_psk_identity.value()), 2);
24✔
67

68
         psk = creds.psk("tls-client", std::string(hostname), m_psk_identity.value());
72✔
69
      }
24✔
70

71
      if(kex_algo == Kex_Algo::DH) {
701✔
72
         const auto modulus = BigInt::from_bytes(reader.get_range<uint8_t>(2, 1, 65535));
20✔
73
         const auto generator = BigInt::from_bytes(reader.get_range<uint8_t>(2, 1, 65535));
4✔
74
         const std::vector<uint8_t> peer_public_value = reader.get_range<uint8_t>(2, 1, 65535);
4✔
75

76
         if(reader.remaining_bytes() > 0) {
4✔
77
            throw Decoding_Error("Bad params size for DH key exchange");
×
78
         }
79

80
         DL_Group group(modulus, generator);
4✔
81

82
         if(!group.verify_group(rng, false)) {
4✔
83
            throw TLS_Exception(Alert::InsufficientSecurity, "DH group validation failed");
×
84
         }
85

86
         const auto private_key = state.callbacks().tls_generate_ephemeral_key(group, rng);
4✔
87
         m_pre_master = CT::strip_leading_zeros(
12✔
88
            state.callbacks().tls_ephemeral_key_agreement(group, *private_key, peer_public_value, rng, policy));
12✔
89
         append_tls_length_value(m_key_material, private_key->public_value(), 2);
12✔
90
      } else if(kex_algo == Kex_Algo::ECDH || kex_algo == Kex_Algo::ECDHE_PSK) {
709✔
91
         const uint8_t curve_type = reader.get_byte();
697✔
92
         if(curve_type != 3) {
697✔
93
            throw Decoding_Error("Server sent non-named ECC curve");
×
94
         }
95

96
         const Group_Params curve_id = static_cast<Group_Params>(reader.get_uint16_t());
697✔
97
         const std::vector<uint8_t> peer_public_value = reader.get_range<uint8_t>(1, 1, 255);
697✔
98

99
         if(!curve_id.is_ecdh_named_curve() && !curve_id.is_x25519() && !curve_id.is_x448()) {
697✔
100
            throw TLS_Exception(Alert::IllegalParameter,
3✔
101
                                "Server selected a group that is not compatible with the negotiated ciphersuite");
3✔
102
         }
103

104
         if(policy.choose_key_exchange_group({curve_id}, {}) != curve_id) {
1,388✔
105
            throw TLS_Exception(Alert::HandshakeFailure, "Server sent ECC curve prohibited by policy");
1✔
106
         }
107

108
         const auto private_key = [&] {
16✔
109
            if(curve_id.is_ecdh_named_curve()) {
693✔
110
               const auto pubkey_point_format = state.server_hello()->prefers_compressed_ec_points()
25✔
111
                                                   ? EC_Point_Format::Compressed
25✔
112
                                                   : EC_Point_Format::Uncompressed;
25✔
113
               return state.callbacks().tls12_generate_ephemeral_ecdh_key(curve_id, rng, pubkey_point_format);
25✔
114
            } else {
115
               return state.callbacks().tls_generate_ephemeral_key(curve_id, rng);
1,336✔
116
            }
117
         }();
693✔
118

119
         if(!private_key) {
693✔
120
            throw TLS_Exception(Alert::InternalError, "Application did not provide an EC key");
×
121
         }
122

123
         auto shared_secret =
693✔
124
            state.callbacks().tls_ephemeral_key_agreement(curve_id, *private_key, peer_public_value, rng, policy);
705✔
125

126
         if(kex_algo == Kex_Algo::ECDH) {
681✔
127
            m_pre_master = std::move(shared_secret);
657✔
128
         } else {
129
            append_tls_length_value(m_pre_master, shared_secret, 2);
24✔
130
            append_tls_length_value(m_pre_master, psk.bits_of(), 2);
72✔
131
         }
132

133
         // Note: In contrast to public_value(), raw_public_key_bits() takes the
134
         // point format (compressed vs. uncompressed) into account that was set
135
         // in its construction within tls_generate_ephemeral_key().
136
         append_tls_length_value(m_key_material, private_key->raw_public_key_bits(), 1);
2,043✔
137
      } else {
2,071✔
138
         throw Internal_Error("Client_Key_Exchange: Unknown key exchange method was negotiated");
×
139
      }
140

141
      reader.assert_done();
685✔
142
   } else {
701✔
143
      // No server key exchange msg better mean RSA kex + RSA key in cert
144

145
      if(kex_algo != Kex_Algo::STATIC_RSA) {
80✔
146
         throw Unexpected_Message("No server kex message, but negotiated a key exchange that required it");
×
147
      }
148

149
      if(server_public_key == nullptr) {
80✔
150
         throw Internal_Error("No server public key for RSA exchange");
×
151
      }
152

153
      if(const auto* rsa_pub = dynamic_cast<const RSA_PublicKey*>(server_public_key)) {
80✔
154
         const Protocol_Version offered_version = state.client_hello()->legacy_version();
80✔
155

156
         rng.random_vec(m_pre_master, 48);
80✔
157
         m_pre_master[0] = offered_version.major_version();
80✔
158
         m_pre_master[1] = offered_version.minor_version();
80✔
159

160
         const PK_Encryptor_EME encryptor(*rsa_pub, rng, "PKCS1v15");
80✔
161

162
         const std::vector<uint8_t> encrypted_key = encryptor.encrypt(m_pre_master, rng);
80✔
163

164
         append_tls_length_value(m_key_material, encrypted_key, 2);
160✔
165
      } else {
80✔
166
         throw TLS_Exception(Alert::HandshakeFailure,
×
167
                             "Expected a RSA key in server cert but got " + server_public_key->algo_name());
×
168
      }
169
   }
170

171
   state.hash().update(io.send(*this));
1,626✔
172
}
829✔
173

174
/*
175
* Read a Client Key Exchange message
176
*/
177
Client_Key_Exchange::Client_Key_Exchange(const std::vector<uint8_t>& contents,
698✔
178
                                         const Handshake_State& state,
179
                                         const Private_Key* server_rsa_kex_key,
180
                                         Credentials_Manager& creds,
181
                                         const Policy& policy,
182
                                         RandomNumberGenerator& rng) {
698✔
183
   const Kex_Algo kex_algo = state.ciphersuite().kex_method();
698✔
184

185
   if(kex_algo == Kex_Algo::STATIC_RSA) {
698✔
186
      BOTAN_ASSERT(state.server_certs() && !state.server_certs()->cert_chain().empty(),
58✔
187
                   "RSA key exchange negotiated so server sent a certificate");
188

189
      if(server_rsa_kex_key == nullptr) {
58✔
190
         throw Internal_Error("Expected RSA kex but no server kex key set");
×
191
      }
192

193
      if(server_rsa_kex_key->algo_name() != "RSA") {
58✔
194
         throw Internal_Error("Expected RSA key but got " + server_rsa_kex_key->algo_name());
×
195
      }
196

197
      TLS_Data_Reader reader("ClientKeyExchange", contents);
58✔
198
      const std::vector<uint8_t> encrypted_pre_master = reader.get_range<uint8_t>(2, 0, 65535);
58✔
199
      reader.assert_done();
58✔
200

201
      const PK_Decryptor_EME decryptor(*server_rsa_kex_key, rng, "PKCS1v15");
58✔
202

203
      const uint8_t client_major = state.client_hello()->legacy_version().major_version();
58✔
204
      const uint8_t client_minor = state.client_hello()->legacy_version().minor_version();
58✔
205

206
      /*
207
      * PK_Decryptor::decrypt_or_random will return a random value if
208
      * either the length does not match the expected value or if the
209
      * version number embedded in the PMS does not match the one sent
210
      * in the client hello.
211
      */
212
      const size_t expected_plaintext_size = 48;
58✔
213
      const size_t expected_content_size = 2;
58✔
214
      const uint8_t expected_content_bytes[expected_content_size] = {client_major, client_minor};
58✔
215
      const uint8_t expected_content_pos[expected_content_size] = {0, 1};
58✔
216

217
      m_pre_master = decryptor.decrypt_or_random(encrypted_pre_master.data(),
58✔
218
                                                 encrypted_pre_master.size(),
219
                                                 expected_plaintext_size,
220
                                                 rng,
221
                                                 expected_content_bytes,
222
                                                 expected_content_pos,
223
                                                 expected_content_size);
58✔
224
   } else {
116✔
225
      TLS_Data_Reader reader("ClientKeyExchange", contents);
640✔
226

227
      SymmetricKey psk;
640✔
228

229
      if(key_exchange_is_psk(kex_algo)) {
640✔
230
         m_psk_identity = reader.get_string(2, 0, 65535);
50✔
231

232
         psk = creds.psk("tls-server", state.client_hello()->sni_hostname(), m_psk_identity.value());
100✔
233

234
         if(psk.empty()) {
50✔
235
            if(policy.hide_unknown_users()) {
×
236
               psk = SymmetricKey(rng, 16);
×
237
            } else {
238
               throw TLS_Exception(Alert::UnknownPSKIdentity, "No PSK for identifier " + m_psk_identity.value());
×
239
            }
240
         }
241
      }
242

243
      if(kex_algo == Kex_Algo::PSK) {
50✔
244
         const std::vector<uint8_t> zeros(psk.length());
38✔
245
         append_tls_length_value(m_pre_master, zeros, 2);
38✔
246
         append_tls_length_value(m_pre_master, psk.bits_of(), 2);
114✔
247
      } else if(kex_algo == Kex_Algo::DH || kex_algo == Kex_Algo::ECDH || kex_algo == Kex_Algo::ECDHE_PSK) {
640✔
248
         const PK_Key_Agreement_Key& ka_key = state.server_kex()->server_kex_key();
602✔
249

250
         const std::vector<uint8_t> client_pubkey = (ka_key.algo_name() == "DH")
616✔
251
                                                       ? reader.get_range<uint8_t>(2, 0, 65535)
602✔
252
                                                       : reader.get_range<uint8_t>(1, 1, 255);
602✔
253

254
         const auto shared_group = state.server_kex()->shared_group();
602✔
255
         BOTAN_STATE_CHECK(shared_group && shared_group.value() != Group_Params::NONE);
602✔
256

257
         try {
602✔
258
            auto shared_secret =
602✔
259
               state.callbacks().tls_ephemeral_key_agreement(shared_group.value(), ka_key, client_pubkey, rng, policy);
614✔
260

261
            if(ka_key.algo_name() == "DH") {
590✔
262
               shared_secret = CT::strip_leading_zeros(shared_secret);
8✔
263
            }
264

265
            if(kex_algo == Kex_Algo::ECDHE_PSK) {
590✔
266
               append_tls_length_value(m_pre_master, shared_secret, 2);
12✔
267
               append_tls_length_value(m_pre_master, psk.bits_of(), 2);
36✔
268
            } else {
269
               m_pre_master = shared_secret;
578✔
270
            }
271
         } catch(Invalid_Argument& e) {
602✔
272
            throw TLS_Exception(Alert::IllegalParameter, e.what());
×
273
         } catch(TLS_Exception& e) {
12✔
274
            // NOLINTNEXTLINE(cert-err60-cpp)
275
            throw e;
12✔
276
         } catch(std::exception&) {
12✔
277
            /*
278
            * Something failed in the DH/ECDH computation. To avoid possible
279
            * attacks which are based on triggering and detecting some edge
280
            * failure condition, randomize the pre-master output and carry on,
281
            * allowing the protocol to fail later in the finished checks.
282
            */
283
            rng.random_vec(m_pre_master, ka_key.public_value().size());
×
284
         }
×
285

286
         reader.assert_done();
590✔
287
      } else {
602✔
288
         throw Internal_Error("Client_Key_Exchange: Unknown key exchange negotiated");
×
289
      }
290
   }
640✔
291
}
700✔
292

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