Botan 3.14.1
Crypto and TLS for C&
msg_client_kex.cpp
Go to the documentation of this file.
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_messages_internal.h>
25#include <botan/internal/tls_reader.h>
26
27namespace Botan::TLS {
28
29namespace {
30
31/*
32* RFC 5246 Section 8.1.2: "Leading bytes of Z that contain all zero bits are
33* stripped before it is used as the pre_master_secret."
34*
35* This reveals the length of Z. The Raccoon attack exploits that, but requires
36* the DH key to be reused across handshakes, whereas a new ephemeral key is
37* generated for each one.
38*/
39void strip_leading_zeros(secure_vector<uint8_t>& z) {
40 const size_t leading_zeros = CT::count_leading_zero_bytes(z);
41 z.erase(z.begin(), z.begin() + leading_zeros);
42}
43
44/*
45* If the (p, g) pair the server sent corresponds to a known group
46* (RFC 7919 or RFC 3526), return that group.
47*/
48std::optional<DL_Group> match_well_known_dh_group(const BigInt& p, const BigInt& g) {
49 const size_t p_bits = p.bits();
50
51 if(p_bits != 2048 && p_bits != 3072 && p_bits != 4096 && p_bits != 6144 && p_bits != 8192) {
52 return {};
53 }
54
55 for(const char* prefix : {"ffdhe/ietf", "modp/ietf"}) {
56 const std::string name = fmt("{}/{}", prefix, p_bits);
57 auto candidate = DL_Group::from_name(name);
58 if(candidate.get_p() == p && candidate.get_g() == g) {
59 return candidate;
60 }
61 }
62
63 return std::nullopt;
64}
65
66} // namespace
67
68/*
69* Create a new Client Key Exchange message
70*/
72 Handshake_State& state,
73 const Policy& policy,
75 const Public_Key* server_public_key,
76 std::string_view hostname,
78 const Kex_Algo kex_algo = state.ciphersuite().kex_method();
79
80 if(kex_algo == Kex_Algo::PSK) {
81 std::string identity_hint;
82
83 if(state.has_server_kex()) {
84 TLS_Data_Reader reader("ClientKeyExchange", state.server_kex().params());
85 identity_hint = reader.get_string(2, 0, 65535);
86 }
87
88 m_psk_identity = creds.psk_identity("tls-client", std::string(hostname), identity_hint);
89
90 append_tls_length_value(m_key_material, as_span_of_bytes(m_psk_identity.value()), 2);
91
92 const SymmetricKey psk = creds.psk("tls-client", std::string(hostname), m_psk_identity.value());
93
94 if(psk.empty()) {
95 throw TLS_Exception(Alert::InternalError, "Application did not provide a PSK for the negotiated identity");
96 }
97
98 const std::vector<uint8_t> zeros(psk.length());
99
100 append_tls_length_value(m_pre_master, zeros, 2);
101 append_tls_length_value(m_pre_master, psk.bits_of(), 2);
102 } else if(state.has_server_kex()) {
103 TLS_Data_Reader reader("ClientKeyExchange", state.server_kex().params());
104
105 SymmetricKey psk;
106
107 if(kex_algo == Kex_Algo::ECDHE_PSK) {
108 const std::string identity_hint = reader.get_string(2, 0, 65535);
109
110 m_psk_identity = creds.psk_identity("tls-client", std::string(hostname), identity_hint);
111
112 append_tls_length_value(m_key_material, as_span_of_bytes(m_psk_identity.value()), 2);
113
114 psk = creds.psk("tls-client", std::string(hostname), m_psk_identity.value());
115
116 if(psk.empty()) {
117 throw TLS_Exception(Alert::InternalError, "Application did not provide a PSK for the negotiated identity");
118 }
119 }
120
121 if(kex_algo == Kex_Algo::DH) {
122 const auto modulus = BigInt::from_bytes(reader.get_range<uint8_t>(2, 1, 65535));
123 const auto generator = BigInt::from_bytes(reader.get_range<uint8_t>(2, 1, 65535));
124 const std::vector<uint8_t> peer_public_value = reader.get_range<uint8_t>(2, 1, 65535);
125
126 if(reader.remaining_bytes() > 0) {
127 throw Decoding_Error("Bad params size for DH key exchange");
128 }
129
130 if(modulus.bits() < policy.minimum_dh_group_size()) {
131 throw TLS_Exception(Alert::InsufficientSecurity, "DH prime too small for policy");
132 }
133 if(modulus.bits() > policy.maximum_dh_group_size()) {
134 throw TLS_Exception(Alert::IllegalParameter, "DH prime too large for policy");
135 }
136
137 const auto group = [&] {
138 if(auto matched = match_well_known_dh_group(modulus, generator)) {
139 return std::move(*matched);
140 } else {
141 /*
142 * Even if we sent ffdhe groups in the supported_groups extension
143 * a server may have replied with some other group.
144 */
145 DL_Group ad_hoc(modulus, generator);
146 if(!ad_hoc.verify_group(rng, false)) {
147 throw TLS_Exception(Alert::InsufficientSecurity, "DH group validation failed");
148 }
149 return ad_hoc;
150 }
151 }();
152
153 const auto private_key = state.callbacks().tls_generate_ephemeral_key(group, rng);
154 m_pre_master =
155 state.callbacks().tls_ephemeral_key_agreement(group, *private_key, peer_public_value, rng, policy);
156 strip_leading_zeros(m_pre_master);
157 append_tls_length_value(m_key_material, private_key->public_value(), 2);
158 } else if(kex_algo == Kex_Algo::ECDH || kex_algo == Kex_Algo::ECDHE_PSK) {
159 const uint8_t curve_type = reader.get_byte();
160 if(curve_type != 3) {
161 throw Decoding_Error("Server sent non-named ECC curve");
162 }
163
164 const Group_Params curve_id = static_cast<Group_Params>(reader.get_uint16_t());
165 const std::vector<uint8_t> peer_public_value = reader.get_range<uint8_t>(1, 1, 255);
166
167 if(!group_may_be_ecc(curve_id) || !group_usable_in_version(curve_id, Protocol_Version::TLS_V12)) {
168 throw TLS_Exception(Alert::IllegalParameter,
169 "Server selected a group that is not compatible with the negotiated ciphersuite");
170 }
171
172 // RFC 8422 5.1: the server MUST select a curve from the
173 // supported_groups list the client offered. Check against the actual
174 // offered list (which may be a strict subset of the policy's
175 // key_exchange_groups() if the application narrowed it via
176 // tls_modify_extensions) rather than just the policy.
177 if(!value_exists(state.client_hello().supported_ecc_curves(), curve_id)) {
178 throw TLS_Exception(Alert::IllegalParameter, "Server selected a curve we did not offer");
179 }
180
181 if(policy.choose_key_exchange_group({curve_id}, {}) != curve_id) {
182 throw TLS_Exception(Alert::HandshakeFailure, "Server sent ECC curve prohibited by policy");
183 }
184
185 const auto private_key = [&] {
186 if(curve_id.is_ecdh_named_curve()) {
187 const auto pubkey_point_format = state.server_hello().prefers_compressed_ec_points()
190 return state.callbacks().tls12_generate_ephemeral_ecdh_key(curve_id, rng, pubkey_point_format);
191 } else {
192 return state.callbacks().tls_generate_ephemeral_key(curve_id, rng);
193 }
194 }();
195
196 if(!private_key) {
197 throw TLS_Exception(Alert::InternalError, "Application did not provide an EC key");
198 }
199
200 auto shared_secret =
201 state.callbacks().tls_ephemeral_key_agreement(curve_id, *private_key, peer_public_value, rng, policy);
202
203 if(kex_algo == Kex_Algo::ECDH) {
204 m_pre_master = std::move(shared_secret);
205 } else {
206 append_tls_length_value(m_pre_master, shared_secret, 2);
207 append_tls_length_value(m_pre_master, psk.bits_of(), 2);
208 }
209
210 // Note: In contrast to public_value(), raw_public_key_bits() takes the
211 // point format (compressed vs. uncompressed) into account that was set
212 // in its construction within tls_generate_ephemeral_key().
213 append_tls_length_value(m_key_material, private_key->raw_public_key_bits(), 1);
214 } else {
215 throw Internal_Error("Client_Key_Exchange: Unknown key exchange method was negotiated");
216 }
217
218 reader.assert_done();
219 } else {
220 // No server key exchange msg better mean RSA kex + RSA key in cert
221
222 if(kex_algo != Kex_Algo::STATIC_RSA) {
223 throw Unexpected_Message("No server kex message, but negotiated a key exchange that required it");
224 }
225
226 if(server_public_key == nullptr) {
227 throw Internal_Error("No server public key for RSA exchange");
228 }
229
230 if(const auto* rsa_pub = dynamic_cast<const RSA_PublicKey*>(server_public_key)) {
231 const Protocol_Version offered_version = state.client_hello().legacy_version();
232
233 rng.random_vec(m_pre_master, 48);
234 m_pre_master[0] = offered_version.major_version();
235 m_pre_master[1] = offered_version.minor_version();
236
237 const PK_Encryptor_EME encryptor(*rsa_pub, rng, "PKCS1v15");
238
239 const std::vector<uint8_t> encrypted_key = encryptor.encrypt(m_pre_master, rng);
240
241 append_tls_length_value(m_key_material, encrypted_key, 2);
242 } else {
243 throw TLS_Exception(Alert::HandshakeFailure,
244 "Expected a RSA key in server cert but got " + server_public_key->algo_name());
245 }
246 }
247
248 state.hash().update(io.send(*this));
249}
250
251/*
252* Read a Client Key Exchange message
253*/
254Client_Key_Exchange::Client_Key_Exchange(std::span<const uint8_t> contents,
255 const Handshake_State& state,
256 const Private_Key* server_rsa_kex_key,
257 Credentials_Manager& creds,
258 const Policy& policy,
260 const Kex_Algo kex_algo = state.ciphersuite().kex_method();
261
262 if(kex_algo == Kex_Algo::STATIC_RSA) {
263 BOTAN_ASSERT(!state.server_certs().cert_chain().empty(),
264 "RSA key exchange negotiated so server sent a certificate");
265
266 if(server_rsa_kex_key == nullptr) {
267 throw Internal_Error("Expected RSA kex but no server kex key set");
268 }
269
270 if(server_rsa_kex_key->algo_name() != "RSA") {
271 throw Internal_Error("Expected RSA key but got " + server_rsa_kex_key->algo_name());
272 }
273
274 TLS_Data_Reader reader("ClientKeyExchange", contents);
275 // RFC 5246 7.4.7.1: encrypted_pre_master_secret<1..2^16-1>.
276 const std::vector<uint8_t> encrypted_pre_master = reader.get_range<uint8_t>(2, 1, 65535);
277 reader.assert_done();
278
279 const PK_Decryptor_EME decryptor(*server_rsa_kex_key, rng, "PKCS1v15");
280
281 const uint8_t client_major = state.client_hello().legacy_version().major_version();
282 const uint8_t client_minor = state.client_hello().legacy_version().minor_version();
283
284 /*
285 * PK_Decryptor::decrypt_or_random will return a random value if
286 * either the length does not match the expected value or if the
287 * version number embedded in the PMS does not match the one sent
288 * in the client hello.
289 */
290 const size_t expected_plaintext_size = 48;
291 const size_t expected_content_size = 2;
292 const uint8_t expected_content_bytes[expected_content_size] = {client_major, client_minor};
293 const uint8_t expected_content_pos[expected_content_size] = {0, 1};
294
295 // RFC 5246 7.4.7.1
296 // In any case, a TLS server MUST NOT generate an alert if processing an
297 // RSA-encrypted premaster secret message fails, or the version number
298 // is not as expected. Instead, it MUST continue the handshake with a
299 // randomly generated premaster secret.
300 //
301 // decrypt_or_random throws if the ciphertext is invalid based on public
302 // information alone (such as its length), so this reveals nothing.
303 try {
304 m_pre_master = decryptor.decrypt_or_random(encrypted_pre_master.data(),
305 encrypted_pre_master.size(),
306 expected_plaintext_size,
307 rng,
308 expected_content_bytes,
309 expected_content_pos,
310 expected_content_size);
311 } catch(Decoding_Error&) {
312 m_pre_master = rng.random_vec(expected_plaintext_size);
313 }
314 } else {
315 TLS_Data_Reader reader("ClientKeyExchange", contents);
316
317 SymmetricKey psk;
318
319 if(key_exchange_is_psk(kex_algo)) {
320 m_psk_identity = reader.get_string(2, 0, 65535);
321
322 try {
323 psk = creds.psk("tls-server", state.client_hello().sni_hostname(), m_psk_identity.value());
324 } catch(...) {
325 // Treat any lookup failure for the identity sent by the client as
326 // "no PSK for this identity" and let the logic below handle it
327 }
328
329 if(psk.empty()) {
330 if(policy.hide_unknown_users()) {
331 psk = SymmetricKey(rng, 16);
332 } else {
333 throw TLS_Exception(Alert::UnknownPSKIdentity, "No PSK for identifier " + m_psk_identity.value());
334 }
335 }
336 }
337
338 if(kex_algo == Kex_Algo::PSK) {
339 reader.assert_done();
340 const std::vector<uint8_t> zeros(psk.length());
341 append_tls_length_value(m_pre_master, zeros, 2);
342 append_tls_length_value(m_pre_master, psk.bits_of(), 2);
343 } else if(kex_algo == Kex_Algo::DH || kex_algo == Kex_Algo::ECDH || kex_algo == Kex_Algo::ECDHE_PSK) {
344 const PK_Key_Agreement_Key& ka_key = state.server_kex().server_kex_key();
345
346 const std::vector<uint8_t> client_pubkey = (ka_key.algo_name() == "DH")
347 ? reader.get_range<uint8_t>(2, 1, 65535)
348 : reader.get_range<uint8_t>(1, 1, 255);
349
350 const auto shared_group = state.server_kex().shared_group();
351 BOTAN_STATE_CHECK(shared_group && shared_group.value() != Group_Params::NONE);
352
353 try {
354 auto shared_secret =
355 state.callbacks().tls_ephemeral_key_agreement(shared_group.value(), ka_key, client_pubkey, rng, policy);
356
357 if(ka_key.algo_name() == "DH") {
358 strip_leading_zeros(shared_secret);
359 }
360
361 if(kex_algo == Kex_Algo::ECDHE_PSK) {
362 append_tls_length_value(m_pre_master, shared_secret, 2);
363 append_tls_length_value(m_pre_master, psk.bits_of(), 2);
364 } else {
365 m_pre_master = shared_secret;
366 }
367 } catch(Invalid_Argument& e) {
368 throw TLS_Exception(Alert::IllegalParameter, e.what());
369 } catch(TLS_Exception&) {
370 throw; // rethrow
371 } catch(std::exception&) {
372 /*
373 * Something failed in the DH/ECDH computation. To avoid possible
374 * attacks which are based on triggering and detecting some edge
375 * failure condition, randomize the pre-master output and carry on,
376 * allowing the protocol to fail later in the finished checks.
377 */
378 rng.random_vec(m_pre_master, ka_key.public_value().size());
379 }
380
381 reader.assert_done();
382 } else {
383 throw Internal_Error("Client_Key_Exchange: Unknown key exchange negotiated");
384 }
385 }
386}
387
388} // namespace Botan::TLS
#define BOTAN_STATE_CHECK(expr)
Definition assert.h:49
#define BOTAN_ASSERT(expr, assertion_made)
Definition assert.h:69
virtual std::string algo_name() const =0
static BigInt from_bytes(std::span< const uint8_t > bytes)
Definition bigint.cpp:84
virtual std::string psk_identity(const std::string &type, const std::string &context, const std::string &identity_hint)
virtual SymmetricKey psk(const std::string &type, const std::string &context, const std::string &identity)
static DL_Group from_name(std::string_view name)
Definition dl_group.cpp:266
bool verify_group(RandomNumberGenerator &rng, bool strong=true) const
Definition dl_group.cpp:470
const char * what() const noexcept override
Definition exceptn.h:94
secure_vector< uint8_t > bits_of() const
Definition symkey.h:46
size_t length() const
Definition symkey.h:28
bool empty() const
Definition symkey.h:40
secure_vector< uint8_t > decrypt_or_random(const uint8_t in[], size_t length, size_t expected_pt_len, RandomNumberGenerator &rng) const
Definition pubkey.cpp:98
std::vector< uint8_t > encrypt(const uint8_t in[], size_t length, RandomNumberGenerator &rng) const
Definition pubkey.h:37
virtual std::vector< uint8_t > public_value() const =0
void random_vec(std::span< uint8_t > v)
Definition rng.h:254
virtual std::unique_ptr< PK_Key_Agreement_Key > tls12_generate_ephemeral_ecdh_key(TLS::Group_Params group, RandomNumberGenerator &rng, EC_Point_Format tls12_ecc_pubkey_encoding_format)
virtual secure_vector< uint8_t > tls_ephemeral_key_agreement(const std::variant< TLS::Group_Params, DL_Group > &group, const PK_Key_Agreement_Key &private_key, const std::vector< uint8_t > &public_value, RandomNumberGenerator &rng, const Policy &policy)
virtual std::unique_ptr< PK_Key_Agreement_Key > tls_generate_ephemeral_key(const std::variant< TLS::Group_Params, DL_Group > &group, RandomNumberGenerator &rng)
Kex_Algo kex_method() const
Client_Key_Exchange(Handshake_IO &io, Handshake_State &state, const Policy &policy, Credentials_Manager &creds, const Public_Key *server_public_key, std::string_view hostname, RandomNumberGenerator &rng)
constexpr bool is_ecdh_named_curve() const
Definition tls_algos.h:177
void update(const uint8_t in[], size_t length)
virtual std::vector< uint8_t > send(const Handshake_Message &msg)=0
void client_hello(std::unique_ptr< Client_Hello_12 > client_hello)
void server_hello(std::unique_ptr< Server_Hello_12 > server_hello)
const Ciphersuite & ciphersuite() const
void server_kex(std::unique_ptr< Server_Key_Exchange > server_kex)
void server_certs(std::unique_ptr< Certificate_12 > server_certs)
virtual size_t maximum_dh_group_size() const
virtual bool hide_unknown_users() const
virtual size_t minimum_dh_group_size() const
virtual Group_Params choose_key_exchange_group(const std::vector< Group_Params > &supported_by_peer, const std::vector< Group_Params > &offered_by_peer) const
uint8_t major_version() const
Definition tls_version.h:88
uint8_t minor_version() const
Definition tls_version.h:93
std::string get_string(size_t len_bytes, size_t min_bytes, size_t max_bytes)
Definition tls_reader.h:128
std::vector< T > get_range(size_t len_bytes, size_t min_elems, size_t max_elems)
Definition tls_reader.h:115
size_t remaining_bytes() const
Definition tls_reader.h:37
const char * name
Definition ffi_tls.h:59
size_t count_leading_zero_bytes(std::span< const uint8_t > input)
Definition ct_utils.cpp:81
bool group_usable_in_version(Group_Params group, Protocol_Version version)
void append_tls_length_value(std::vector< uint8_t, Alloc > &buf, const T *vals, size_t vals_size, size_t tag_size)
Definition tls_reader.h:182
bool group_may_be_ecc(Group_Params group)
bool key_exchange_is_psk(Kex_Algo m)
Definition tls_algos.h:284
OctetString SymmetricKey
Definition symkey.h:153
std::span< const uint8_t > as_span_of_bytes(const char *s, size_t len)
Definition mem_utils.h:59
std::string fmt(std::string_view format, const T &... args)
Definition fmt.h:53
bool value_exists(const std::vector< T > &vec, const V &val)
Definition stl_util.h:44
std::vector< T, secure_allocator< T > > secure_vector
Definition secmem.h:128