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

randombit / botan / 5080663405

25 May 2023 02:18PM UTC coverage: 91.675% (-0.01%) from 91.688%
5080663405

Pull #3549

github

Pull Request #3549: SPHINCS+

78519 of 85649 relevant lines covered (91.68%)

12135443.66 hits per line

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

85.23
/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/tls_extensions.h>
12
#include <botan/rng.h>
13

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

21
#include <botan/rsa.h>
22
#include <botan/ecdh.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,
754✔
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)
754✔
36
   {
37
   const Kex_Algo kex_algo = state.ciphersuite().kex_method();
754✔
38

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

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

49
      const std::string psk_identity =
43✔
50
         creds.psk_identity("tls-client", std::string(hostname), identity_hint);
129✔
51

52
      append_tls_length_value(m_key_material, psk_identity, 2);
43✔
53

54
      SymmetricKey psk = creds.psk("tls-client", std::string(hostname), psk_identity);
129✔
55

56
      std::vector<uint8_t> zeros(psk.length());
43✔
57

58
      append_tls_length_value(m_pre_master, zeros, 2);
43✔
59
      append_tls_length_value(m_pre_master, psk.bits_of(), 2);
129✔
60
      }
86✔
61
   else if(state.server_kex())
711✔
62
      {
63
      TLS_Data_Reader reader("ClientKeyExchange", state.server_kex()->params());
658✔
64

65
      SymmetricKey psk;
658✔
66

67
      if(kex_algo == Kex_Algo::ECDHE_PSK)
658✔
68
         {
69
         std::string identity_hint = reader.get_string(2, 0, 65535);
24✔
70

71
         const std::string psk_identity =
24✔
72
            creds.psk_identity("tls-client", std::string(hostname), identity_hint);
72✔
73

74
         append_tls_length_value(m_key_material, psk_identity, 2);
24✔
75

76
         psk = creds.psk("tls-client", std::string(hostname), psk_identity);
76✔
77
         }
24✔
78

79
      if(kex_algo == Kex_Algo::DH)
658✔
80
         {
81
         const auto modulus = BigInt::decode(reader.get_range<uint8_t>(2, 1, 65535));
11✔
82
         const auto generator = BigInt::decode(reader.get_range<uint8_t>(2, 1, 65535));
8✔
83
         const std::vector<uint8_t> peer_public_value = reader.get_range<uint8_t>(2, 1, 65535);
4✔
84

85
         if(reader.remaining_bytes())
4✔
86
            throw Decoding_Error("Bad params size for DH key exchange");
×
87

88
         DL_Group group(modulus, generator);
4✔
89

90
         if(!group.verify_group(rng, false))
4✔
91
            { throw TLS_Exception(Alert::InsufficientSecurity, "DH group validation failed"); }
×
92

93
         const auto private_key = state.callbacks().tls_generate_ephemeral_key(group, rng);
4✔
94
         auto shared_secret =
4✔
95
            CT::strip_leading_zeros(
96
               state.callbacks().tls_ephemeral_key_agreement(group,
8✔
97
                                                             *private_key,
4✔
98
                                                             peer_public_value,
99
                                                             rng,
100
                                                             policy));
4✔
101

102
         if(kex_algo == Kex_Algo::DH)
4✔
103
            m_pre_master = std::move(shared_secret);
4✔
104
         else
105
            {
106
            append_tls_length_value(m_pre_master, shared_secret, 2);
107
            append_tls_length_value(m_pre_master, psk.bits_of(), 2);
108
            }
109

110
         append_tls_length_value(m_key_material, private_key->public_value(), 2);
12✔
111
         }
24✔
112
      else if(kex_algo == Kex_Algo::ECDH ||
654✔
113
              kex_algo == Kex_Algo::ECDHE_PSK)
654✔
114
         {
115
         const uint8_t curve_type = reader.get_byte();
654✔
116
         if(curve_type != 3)
654✔
117
            throw Decoding_Error("Server sent non-named ECC curve");
×
118

119
         const Group_Params curve_id = static_cast<Group_Params>(reader.get_uint16_t());
654✔
120
         const std::vector<uint8_t> peer_public_value = reader.get_range<uint8_t>(1, 1, 255);
654✔
121

122
         if(policy.choose_key_exchange_group({curve_id}, {}) != curve_id)
1,308✔
123
            {
124
            throw TLS_Exception(Alert::HandshakeFailure,
2✔
125
                                "Server sent ECC curve prohibited by policy");
4✔
126
            }
127

128
         const auto private_key = state.callbacks().tls_generate_ephemeral_key(curve_id, rng);
655✔
129
         auto shared_secret =
652✔
130
            state.callbacks().tls_ephemeral_key_agreement(curve_id,
652✔
131
                                                          *private_key,
652✔
132
                                                          peer_public_value,
133
                                                          rng,
134
                                                          policy);
653✔
135

136
         // RFC 8422 - 5.11.
137
         //   With X25519 and X448, a receiving party MUST check whether the
138
         //   computed premaster secret is the all-zero value and abort the
139
         //   handshake if so, as described in Section 6 of [RFC7748].
140
         if(curve_id == Group_Params::X25519 && CT::all_zeros(shared_secret.data(), shared_secret.size()).is_set())
1,286✔
141
            {
142
            throw TLS_Exception(Alert::DecryptError, "Bad X25519 key exchange");
×
143
            }
144

145
         if(kex_algo == Kex_Algo::ECDH)
651✔
146
            {
147
            m_pre_master = std::move(shared_secret);
627✔
148
            }
149
         else
150
            {
151
            append_tls_length_value(m_pre_master, shared_secret, 2);
24✔
152
            append_tls_length_value(m_pre_master, psk.bits_of(), 2);
72✔
153
            }
154

155
         if(is_ecdh(curve_id))
651✔
156
            {
157
            auto ecdh_key = dynamic_cast<ECDH_PublicKey*>(private_key.get());
13✔
158
            if(!ecdh_key)
13✔
159
               {
160
               throw TLS_Exception(Alert::InternalError,
×
161
                                 "Application did not provide a ECDH_PublicKey");
×
162
               }
163
            append_tls_length_value(m_key_material,
13✔
164
                                    ecdh_key->public_value(
39✔
165
                                       state.server_hello()->prefers_compressed_ec_points()
13✔
166
                                          ? EC_Point_Format::Compressed
167
                                          : EC_Point_Format::Uncompressed),
168
                                    1);
169
            }
170
         else
171
            {
172
            append_tls_length_value(m_key_material, private_key->public_value(), 1);
1,914✔
173
            }
174
         }
1,957✔
175
      else
176
         {
177
         throw Internal_Error("Client_Key_Exchange: Unknown key exchange method was negotiated");
×
178
         }
179

180
      reader.assert_done();
655✔
181
      }
658✔
182
   else
183
      {
184
      // No server key exchange msg better mean RSA kex + RSA key in cert
185

186
      if(kex_algo != Kex_Algo::STATIC_RSA)
53✔
187
         throw Unexpected_Message("No server kex message, but negotiated a key exchange that required it");
×
188

189
      if(!server_public_key)
53✔
190
         throw Internal_Error("No server public key for RSA exchange");
×
191

192
      if(auto rsa_pub = dynamic_cast<const RSA_PublicKey*>(server_public_key))
53✔
193
         {
194
         const Protocol_Version offered_version = state.client_hello()->legacy_version();
53✔
195

196
         rng.random_vec(m_pre_master, 48);
53✔
197
         m_pre_master[0] = offered_version.major_version();
53✔
198
         m_pre_master[1] = offered_version.minor_version();
53✔
199

200
         PK_Encryptor_EME encryptor(*rsa_pub, rng, "PKCS1v15");
53✔
201

202
         const std::vector<uint8_t> encrypted_key = encryptor.encrypt(m_pre_master, rng);
53✔
203

204
         append_tls_length_value(m_key_material, encrypted_key, 2);
106✔
205
         }
53✔
206
      else
207
         throw TLS_Exception(Alert::HandshakeFailure,
×
208
                             "Expected a RSA key in server cert but got " +
×
209
                             server_public_key->algo_name());
×
210
      }
211

212
   state.hash().update(io.send(*this));
1,502✔
213
   }
754✔
214

215
/*
216
* Read a Client Key Exchange message
217
*/
218
Client_Key_Exchange::Client_Key_Exchange(const std::vector<uint8_t>& contents,
646✔
219
                                         const Handshake_State& state,
220
                                         const Private_Key* server_rsa_kex_key,
221
                                         Credentials_Manager& creds,
222
                                         const Policy& policy,
223
                                         RandomNumberGenerator& rng)
646✔
224
   {
225
   const Kex_Algo kex_algo = state.ciphersuite().kex_method();
646✔
226

227
   if(kex_algo == Kex_Algo::STATIC_RSA)
646✔
228
      {
229
      BOTAN_ASSERT(state.server_certs() && !state.server_certs()->cert_chain().empty(),
57✔
230
                   "RSA key exchange negotiated so server sent a certificate");
231

232
      if(!server_rsa_kex_key)
57✔
233
         throw Internal_Error("Expected RSA kex but no server kex key set");
×
234

235
      if(server_rsa_kex_key->algo_name() != "RSA")
57✔
236
         throw Internal_Error("Expected RSA key but got " + server_rsa_kex_key->algo_name());
×
237

238
      TLS_Data_Reader reader("ClientKeyExchange", contents);
57✔
239
      const std::vector<uint8_t> encrypted_pre_master = reader.get_range<uint8_t>(2, 0, 65535);
57✔
240
      reader.assert_done();
57✔
241

242
      PK_Decryptor_EME decryptor(*server_rsa_kex_key, rng, "PKCS1v15");
57✔
243

244
      const uint8_t client_major = state.client_hello()->legacy_version().major_version();
57✔
245
      const uint8_t client_minor = state.client_hello()->legacy_version().minor_version();
57✔
246

247
      /*
248
      * PK_Decryptor::decrypt_or_random will return a random value if
249
      * either the length does not match the expected value or if the
250
      * version number embedded in the PMS does not match the one sent
251
      * in the client hello.
252
      */
253
      const size_t expected_plaintext_size = 48;
57✔
254
      const size_t expected_content_size = 2;
57✔
255
      const uint8_t expected_content_bytes[expected_content_size] = { client_major, client_minor };
57✔
256
      const uint8_t expected_content_pos[expected_content_size] = { 0, 1 };
57✔
257

258
      m_pre_master =
57✔
259
         decryptor.decrypt_or_random(encrypted_pre_master.data(),
57✔
260
                                     encrypted_pre_master.size(),
261
                                     expected_plaintext_size,
262
                                     rng,
263
                                     expected_content_bytes,
264
                                     expected_content_pos,
265
                                     expected_content_size);
57✔
266
      }
114✔
267
   else
268
      {
269
      TLS_Data_Reader reader("ClientKeyExchange", contents);
589✔
270

271
      SymmetricKey psk;
589✔
272

273
      if(key_exchange_is_psk(kex_algo))
589✔
274
         {
275
         const std::string psk_identity = reader.get_string(2, 0, 65535);
45✔
276

277
         psk = creds.psk("tls-server",
90✔
278
                         state.client_hello()->sni_hostname(),
45✔
279
                         psk_identity);
45✔
280

281
         if(psk.length() == 0)
45✔
282
            {
283
            if(policy.hide_unknown_users())
×
284
               psk = SymmetricKey(rng, 16);
×
285
            else
286
               throw TLS_Exception(Alert::UnknownPSKIdentity,
×
287
                                   "No PSK for identifier " + psk_identity);
×
288
            }
289
         }
45✔
290

291
      if(kex_algo == Kex_Algo::PSK)
589✔
292
         {
293
         std::vector<uint8_t> zeros(psk.length());
34✔
294
         append_tls_length_value(m_pre_master, zeros, 2);
34✔
295
         append_tls_length_value(m_pre_master, psk.bits_of(), 2);
102✔
296
         }
34✔
297
      else if(kex_algo == Kex_Algo::DH ||
555✔
298
              kex_algo == Kex_Algo::ECDH ||
555✔
299
              kex_algo == Kex_Algo::ECDHE_PSK)
555✔
300
         {
301
         const PK_Key_Agreement_Key& ka_key = state.server_kex()->server_kex_key();
555✔
302

303
         const std::vector<uint8_t> client_pubkey =
555✔
304
            (ka_key.algo_name() == "DH") ? reader.get_range<uint8_t>(2, 0, 65535)
558✔
305
                                         : reader.get_range<uint8_t>(1, 1, 255);
555✔
306

307
         const auto shared_group = state.server_kex()->shared_group();
555✔
308
         BOTAN_STATE_CHECK(shared_group && shared_group.value() != Group_Params::NONE);
555✔
309

310
         try
555✔
311
            {
312
            auto shared_secret =
555✔
313
               state.callbacks().tls_ephemeral_key_agreement(shared_group.value(),
555✔
314
                                                             ka_key,
315
                                                             client_pubkey,
316
                                                             rng,
317
                                                             policy);
555✔
318

319
            if(ka_key.algo_name() == "DH")
554✔
320
               shared_secret = CT::strip_leading_zeros(shared_secret);
4✔
321

322
            if(kex_algo == Kex_Algo::ECDH || kex_algo == Kex_Algo::ECDHE_PSK)
554✔
323
               {
324
                  // RFC 8422 - 5.11.
325
                  //   With X25519 and X448, a receiving party MUST check whether the
326
                  //   computed premaster secret is the all-zero value and abort the
327
                  //   handshake if so, as described in Section 6 of [RFC7748].
328
                  BOTAN_ASSERT_NOMSG(state.server_kex()->params().size() >= 3);
550✔
329
                  Group_Params group = static_cast<Group_Params>(state.server_kex()->params().at(2));
550✔
330
                  if(group == Group_Params::X25519 && CT::all_zeros(shared_secret.data(), shared_secret.size()).is_set())
1,022✔
331
                     {
332
                     throw TLS_Exception(Alert::DecryptError, "Bad X25519 key exchange");
×
333
                     }
334
               }
335

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

363
         reader.assert_done();
554✔
364
         }
555✔
365
      else
366
         throw Internal_Error("Client_Key_Exchange: Unknown key exchange negotiated");
×
367
      }
589✔
368
   }
648✔
369

370
}
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