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

randombit / botan / 5587580523

18 Jul 2023 12:45PM UTC coverage: 91.72% (+0.03%) from 91.691%
5587580523

Pull #3618

github

web-flow
Merge b6d23d19e into 65b754862
Pull Request #3618: [TLS 1.3] PSK Support

78438 of 85519 relevant lines covered (91.72%)

12184016.91 hits per line

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

86.0
/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.h>
10

11
#include <botan/rng.h>
12
#include <botan/tls_extensions.h>
13

14
#include <botan/credentials_manager.h>
15
#include <botan/internal/ct_utils.h>
16
#include <botan/internal/stl_util.h>
17
#include <botan/internal/tls_handshake_hash.h>
18
#include <botan/internal/tls_handshake_io.h>
19
#include <botan/internal/tls_handshake_state.h>
20
#include <botan/internal/tls_reader.h>
21

22
#include <botan/ecdh.h>
23
#include <botan/rsa.h>
24

25
namespace Botan::TLS {
26

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

39
   if(kex_algo == Kex_Algo::PSK) {
757✔
40
      std::string identity_hint;
42✔
41

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

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

49
      append_tls_length_value(m_key_material, to_byte_vector(m_psk_identity.value()), 2);
84✔
50

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

53
      std::vector<uint8_t> zeros(psk.length());
42✔
54

55
      append_tls_length_value(m_pre_master, zeros, 2);
42✔
56
      append_tls_length_value(m_pre_master, psk.bits_of(), 2);
126✔
57
   } else if(state.server_kex()) {
799✔
58
      TLS_Data_Reader reader("ClientKeyExchange", state.server_kex()->params());
661✔
59

60
      SymmetricKey psk;
661✔
61

62
      if(kex_algo == Kex_Algo::ECDHE_PSK) {
661✔
63
         std::string identity_hint = reader.get_string(2, 0, 65535);
22✔
64

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

67
         append_tls_length_value(m_key_material, to_byte_vector(m_psk_identity.value()), 2);
44✔
68

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

72
      if(kex_algo == Kex_Algo::DH) {
661✔
73
         const auto modulus = BigInt::decode(reader.get_range<uint8_t>(2, 1, 65535));
9✔
74
         const auto generator = BigInt::decode(reader.get_range<uint8_t>(2, 1, 65535));
6✔
75
         const std::vector<uint8_t> peer_public_value = reader.get_range<uint8_t>(2, 1, 65535);
3✔
76

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

81
         DL_Group group(modulus, generator);
3✔
82

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

87
         const auto private_key = state.callbacks().tls_generate_ephemeral_key(group, rng);
3✔
88
         auto shared_secret = CT::strip_leading_zeros(
3✔
89
            state.callbacks().tls_ephemeral_key_agreement(group, *private_key, peer_public_value, rng, policy));
9✔
90

91
         if(kex_algo == Kex_Algo::DH) {
3✔
92
            m_pre_master = std::move(shared_secret);
3✔
93
         } else {
94
            append_tls_length_value(m_pre_master, shared_secret, 2);
95
            append_tls_length_value(m_pre_master, psk.bits_of(), 2);
96
         }
97

98
         append_tls_length_value(m_key_material, private_key->public_value(), 2);
9✔
99
      } else if(kex_algo == Kex_Algo::ECDH || kex_algo == Kex_Algo::ECDHE_PSK) {
676✔
100
         const uint8_t curve_type = reader.get_byte();
658✔
101
         if(curve_type != 3) {
658✔
102
            throw Decoding_Error("Server sent non-named ECC curve");
×
103
         }
104

105
         const Group_Params curve_id = static_cast<Group_Params>(reader.get_uint16_t());
658✔
106
         const std::vector<uint8_t> peer_public_value = reader.get_range<uint8_t>(1, 1, 255);
658✔
107

108
         if(policy.choose_key_exchange_group({curve_id}, {}) != curve_id) {
1,316✔
109
            throw TLS_Exception(Alert::HandshakeFailure, "Server sent ECC curve prohibited by policy");
2✔
110
         }
111

112
         const auto private_key = state.callbacks().tls_generate_ephemeral_key(curve_id, rng);
659✔
113
         auto shared_secret =
656✔
114
            state.callbacks().tls_ephemeral_key_agreement(curve_id, *private_key, peer_public_value, rng, policy);
657✔
115

116
         // RFC 8422 - 5.11.
117
         //   With X25519 and X448, a receiving party MUST check whether the
118
         //   computed premaster secret is the all-zero value and abort the
119
         //   handshake if so, as described in Section 6 of [RFC7748].
120
         if(curve_id == Group_Params::X25519 && CT::all_zeros(shared_secret.data(), shared_secret.size()).is_set()) {
1,294✔
121
            throw TLS_Exception(Alert::DecryptError, "Bad X25519 key exchange");
×
122
         }
123

124
         if(kex_algo == Kex_Algo::ECDH) {
655✔
125
            m_pre_master = std::move(shared_secret);
633✔
126
         } else {
127
            append_tls_length_value(m_pre_master, shared_secret, 2);
22✔
128
            append_tls_length_value(m_pre_master, psk.bits_of(), 2);
66✔
129
         }
130

131
         if(is_ecdh(curve_id)) {
655✔
132
            auto ecdh_key = dynamic_cast<ECDH_PublicKey*>(private_key.get());
12✔
133
            if(!ecdh_key) {
12✔
134
               throw TLS_Exception(Alert::InternalError, "Application did not provide a ECDH_PublicKey");
×
135
            }
136
            append_tls_length_value(m_key_material,
12✔
137
                                    ecdh_key->public_value(state.server_hello()->prefers_compressed_ec_points()
36✔
138
                                                              ? EC_Point_Format::Compressed
139
                                                              : EC_Point_Format::Uncompressed),
140
                                    1);
141
         } else {
142
            append_tls_length_value(m_key_material, private_key->public_value(), 1);
1,929✔
143
         }
144
      } else {
1,969✔
145
         throw Internal_Error("Client_Key_Exchange: Unknown key exchange method was negotiated");
×
146
      }
147

148
      reader.assert_done();
658✔
149
   } else {
661✔
150
      // No server key exchange msg better mean RSA kex + RSA key in cert
151

152
      if(kex_algo != Kex_Algo::STATIC_RSA) {
54✔
153
         throw Unexpected_Message("No server kex message, but negotiated a key exchange that required it");
×
154
      }
155

156
      if(!server_public_key) {
54✔
157
         throw Internal_Error("No server public key for RSA exchange");
×
158
      }
159

160
      if(auto rsa_pub = dynamic_cast<const RSA_PublicKey*>(server_public_key)) {
54✔
161
         const Protocol_Version offered_version = state.client_hello()->legacy_version();
54✔
162

163
         rng.random_vec(m_pre_master, 48);
54✔
164
         m_pre_master[0] = offered_version.major_version();
54✔
165
         m_pre_master[1] = offered_version.minor_version();
54✔
166

167
         PK_Encryptor_EME encryptor(*rsa_pub, rng, "PKCS1v15");
54✔
168

169
         const std::vector<uint8_t> encrypted_key = encryptor.encrypt(m_pre_master, rng);
54✔
170

171
         append_tls_length_value(m_key_material, encrypted_key, 2);
108✔
172
      } else {
54✔
173
         throw TLS_Exception(Alert::HandshakeFailure,
×
174
                             "Expected a RSA key in server cert but got " + server_public_key->algo_name());
×
175
      }
176
   }
177

178
   state.hash().update(io.send(*this));
1,508✔
179
}
757✔
180

181
/*
182
* Read a Client Key Exchange message
183
*/
184
Client_Key_Exchange::Client_Key_Exchange(const std::vector<uint8_t>& contents,
645✔
185
                                         const Handshake_State& state,
186
                                         const Private_Key* server_rsa_kex_key,
187
                                         Credentials_Manager& creds,
188
                                         const Policy& policy,
189
                                         RandomNumberGenerator& rng) {
645✔
190
   const Kex_Algo kex_algo = state.ciphersuite().kex_method();
645✔
191

192
   if(kex_algo == Kex_Algo::STATIC_RSA) {
645✔
193
      BOTAN_ASSERT(state.server_certs() && !state.server_certs()->cert_chain().empty(),
58✔
194
                   "RSA key exchange negotiated so server sent a certificate");
195

196
      if(!server_rsa_kex_key) {
58✔
197
         throw Internal_Error("Expected RSA kex but no server kex key set");
×
198
      }
199

200
      if(server_rsa_kex_key->algo_name() != "RSA") {
58✔
201
         throw Internal_Error("Expected RSA key but got " + server_rsa_kex_key->algo_name());
×
202
      }
203

204
      TLS_Data_Reader reader("ClientKeyExchange", contents);
58✔
205
      const std::vector<uint8_t> encrypted_pre_master = reader.get_range<uint8_t>(2, 0, 65535);
58✔
206
      reader.assert_done();
58✔
207

208
      PK_Decryptor_EME decryptor(*server_rsa_kex_key, rng, "PKCS1v15");
58✔
209

210
      const uint8_t client_major = state.client_hello()->legacy_version().major_version();
58✔
211
      const uint8_t client_minor = state.client_hello()->legacy_version().minor_version();
58✔
212

213
      /*
214
      * PK_Decryptor::decrypt_or_random will return a random value if
215
      * either the length does not match the expected value or if the
216
      * version number embedded in the PMS does not match the one sent
217
      * in the client hello.
218
      */
219
      const size_t expected_plaintext_size = 48;
58✔
220
      const size_t expected_content_size = 2;
58✔
221
      const uint8_t expected_content_bytes[expected_content_size] = {client_major, client_minor};
58✔
222
      const uint8_t expected_content_pos[expected_content_size] = {0, 1};
58✔
223

224
      m_pre_master = decryptor.decrypt_or_random(encrypted_pre_master.data(),
58✔
225
                                                 encrypted_pre_master.size(),
226
                                                 expected_plaintext_size,
227
                                                 rng,
228
                                                 expected_content_bytes,
229
                                                 expected_content_pos,
230
                                                 expected_content_size);
58✔
231
   } else {
116✔
232
      TLS_Data_Reader reader("ClientKeyExchange", contents);
587✔
233

234
      SymmetricKey psk;
587✔
235

236
      if(key_exchange_is_psk(kex_algo)) {
587✔
237
         m_psk_identity = reader.get_string(2, 0, 65535);
42✔
238

239
         psk = creds.psk("tls-server", state.client_hello()->sni_hostname(), m_psk_identity.value());
84✔
240

241
         if(psk.length() == 0) {
42✔
242
            if(policy.hide_unknown_users()) {
×
243
               psk = SymmetricKey(rng, 16);
×
244
            } else {
245
               throw TLS_Exception(Alert::UnknownPSKIdentity, "No PSK for identifier " + m_psk_identity.value());
×
246
            }
247
         }
248
      }
249

250
      if(kex_algo == Kex_Algo::PSK) {
587✔
251
         std::vector<uint8_t> zeros(psk.length());
33✔
252
         append_tls_length_value(m_pre_master, zeros, 2);
33✔
253
         append_tls_length_value(m_pre_master, psk.bits_of(), 2);
99✔
254
      } else if(kex_algo == Kex_Algo::DH || kex_algo == Kex_Algo::ECDH || kex_algo == Kex_Algo::ECDHE_PSK) {
587✔
255
         const PK_Key_Agreement_Key& ka_key = state.server_kex()->server_kex_key();
554✔
256

257
         const std::vector<uint8_t> client_pubkey = (ka_key.algo_name() == "DH")
557✔
258
                                                       ? reader.get_range<uint8_t>(2, 0, 65535)
259
                                                       : reader.get_range<uint8_t>(1, 1, 255);
554✔
260

261
         const auto shared_group = state.server_kex()->shared_group();
554✔
262
         BOTAN_STATE_CHECK(shared_group && shared_group.value() != Group_Params::NONE);
554✔
263

264
         try {
554✔
265
            auto shared_secret =
554✔
266
               state.callbacks().tls_ephemeral_key_agreement(shared_group.value(), ka_key, client_pubkey, rng, policy);
554✔
267

268
            if(ka_key.algo_name() == "DH") {
553✔
269
               shared_secret = CT::strip_leading_zeros(shared_secret);
3✔
270
            }
271

272
            if(kex_algo == Kex_Algo::ECDH || kex_algo == Kex_Algo::ECDHE_PSK) {
553✔
273
               // RFC 8422 - 5.11.
274
               //   With X25519 and X448, a receiving party MUST check whether the
275
               //   computed premaster secret is the all-zero value and abort the
276
               //   handshake if so, as described in Section 6 of [RFC7748].
277
               BOTAN_ASSERT_NOMSG(state.server_kex()->params().size() >= 3);
550✔
278
               Group_Params group = static_cast<Group_Params>(state.server_kex()->params().at(2));
550✔
279
               if(group == Group_Params::X25519 && CT::all_zeros(shared_secret.data(), shared_secret.size()).is_set()) {
1,074✔
280
                  throw TLS_Exception(Alert::DecryptError, "Bad X25519 key exchange");
×
281
               }
282
            }
283

284
            if(kex_algo == Kex_Algo::ECDHE_PSK) {
553✔
285
               append_tls_length_value(m_pre_master, shared_secret, 2);
9✔
286
               append_tls_length_value(m_pre_master, psk.bits_of(), 2);
27✔
287
            } else {
288
               m_pre_master = shared_secret;
544✔
289
            }
290
         } catch(Invalid_Argument& e) {
554✔
291
            throw TLS_Exception(Alert::IllegalParameter, e.what());
1✔
292
         } catch(TLS_Exception& e) {
1✔
293
            // NOLINTNEXTLINE(cert-err60-cpp)
294
            throw e;
×
295
         } catch(std::exception&) {
×
296
            /*
297
            * Something failed in the DH/ECDH computation. To avoid possible
298
            * attacks which are based on triggering and detecting some edge
299
            * failure condition, randomize the pre-master output and carry on,
300
            * allowing the protocol to fail later in the finished checks.
301
            */
302
            rng.random_vec(m_pre_master, ka_key.public_value().size());
×
303
         }
×
304

305
         reader.assert_done();
553✔
306
      } else {
554✔
307
         throw Internal_Error("Client_Key_Exchange: Unknown key exchange negotiated");
×
308
      }
309
   }
587✔
310
}
647✔
311

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