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

randombit / botan / 6421338519

05 Oct 2023 03:44PM UTC coverage: 91.703% (-0.08%) from 91.783%
6421338519

push

github

web-flow
Merge pull request #3609 from Rohde-Schwarz/tls13/kem_establishment

[TLS 1.3] Hybrid PQ/T key establishment

79958 of 87192 relevant lines covered (91.7%)

8521367.99 hits per line

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

86.27
/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,
765✔
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) {
765✔
37
   const Kex_Algo kex_algo = state.ciphersuite().kex_method();
765✔
38

39
   if(kex_algo == Kex_Algo::PSK) {
765✔
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()) {
807✔
58
      TLS_Data_Reader reader("ClientKeyExchange", state.server_kex()->params());
669✔
59

60
      SymmetricKey psk;
669✔
61

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

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

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

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

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

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

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

83
         if(!group.verify_group(rng, false)) {
4✔
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);
4✔
88
         auto shared_secret = CT::strip_leading_zeros(
4✔
89
            state.callbacks().tls_ephemeral_key_agreement(group, *private_key, peer_public_value, rng, policy));
12✔
90

91
         if(kex_algo == Kex_Algo::DH) {
4✔
92
            m_pre_master = std::move(shared_secret);
4✔
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);
12✔
99
      } else if(kex_algo == Kex_Algo::ECDH || kex_algo == Kex_Algo::ECDHE_PSK) {
689✔
100
         const uint8_t curve_type = reader.get_byte();
665✔
101
         if(curve_type != 3) {
665✔
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());
665✔
106
         const std::vector<uint8_t> peer_public_value = reader.get_range<uint8_t>(1, 1, 255);
665✔
107

108
         if(!is_ecdh(curve_id) && !is_x25519(curve_id)) {
665✔
109
            throw TLS_Exception(Alert::HandshakeFailure,
6✔
110
                                "Server selected a group that is not compatible with the negotiated ciphersuite");
12✔
111
         }
112

113
         if(policy.choose_key_exchange_group({curve_id}, {}) != curve_id) {
1,318✔
114
            throw TLS_Exception(Alert::HandshakeFailure, "Server sent ECC curve prohibited by policy");
1✔
115
         }
116

117
         const auto private_key = state.callbacks().tls_generate_ephemeral_key(curve_id, rng);
666✔
118
         auto shared_secret =
658✔
119
            state.callbacks().tls_ephemeral_key_agreement(curve_id, *private_key, peer_public_value, rng, policy);
659✔
120

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

129
         if(kex_algo == Kex_Algo::ECDH) {
657✔
130
            m_pre_master = std::move(shared_secret);
633✔
131
         } else {
132
            append_tls_length_value(m_pre_master, shared_secret, 2);
24✔
133
            append_tls_length_value(m_pre_master, psk.bits_of(), 2);
72✔
134
         }
135

136
         if(is_ecdh(curve_id)) {
657✔
137
            auto ecdh_key = dynamic_cast<ECDH_PublicKey*>(private_key.get());
13✔
138
            if(!ecdh_key) {
13✔
139
               throw TLS_Exception(Alert::InternalError, "Application did not provide a ECDH_PublicKey");
×
140
            }
141
            append_tls_length_value(m_key_material,
13✔
142
                                    ecdh_key->public_value(state.server_hello()->prefers_compressed_ec_points()
39✔
143
                                                              ? EC_Point_Format::Compressed
144
                                                              : EC_Point_Format::Uncompressed),
145
                                    1);
146
         } else {
147
            append_tls_length_value(m_key_material, private_key->public_value(), 1);
1,932✔
148
         }
149
      } else {
1,980✔
150
         throw Internal_Error("Client_Key_Exchange: Unknown key exchange method was negotiated");
×
151
      }
152

153
      reader.assert_done();
661✔
154
   } else {
669✔
155
      // No server key exchange msg better mean RSA kex + RSA key in cert
156

157
      if(kex_algo != Kex_Algo::STATIC_RSA) {
54✔
158
         throw Unexpected_Message("No server kex message, but negotiated a key exchange that required it");
×
159
      }
160

161
      if(!server_public_key) {
54✔
162
         throw Internal_Error("No server public key for RSA exchange");
×
163
      }
164

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

168
         rng.random_vec(m_pre_master, 48);
54✔
169
         m_pre_master[0] = offered_version.major_version();
54✔
170
         m_pre_master[1] = offered_version.minor_version();
54✔
171

172
         PK_Encryptor_EME encryptor(*rsa_pub, rng, "PKCS1v15");
54✔
173

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

176
         append_tls_length_value(m_key_material, encrypted_key, 2);
108✔
177
      } else {
54✔
178
         throw TLS_Exception(Alert::HandshakeFailure,
×
179
                             "Expected a RSA key in server cert but got " + server_public_key->algo_name());
×
180
      }
181
   }
182

183
   state.hash().update(io.send(*this));
1,514✔
184
}
765✔
185

186
/*
187
* Read a Client Key Exchange message
188
*/
189
Client_Key_Exchange::Client_Key_Exchange(const std::vector<uint8_t>& contents,
647✔
190
                                         const Handshake_State& state,
191
                                         const Private_Key* server_rsa_kex_key,
192
                                         Credentials_Manager& creds,
193
                                         const Policy& policy,
194
                                         RandomNumberGenerator& rng) {
647✔
195
   const Kex_Algo kex_algo = state.ciphersuite().kex_method();
647✔
196

197
   if(kex_algo == Kex_Algo::STATIC_RSA) {
647✔
198
      BOTAN_ASSERT(state.server_certs() && !state.server_certs()->cert_chain().empty(),
58✔
199
                   "RSA key exchange negotiated so server sent a certificate");
200

201
      if(!server_rsa_kex_key) {
58✔
202
         throw Internal_Error("Expected RSA kex but no server kex key set");
×
203
      }
204

205
      if(server_rsa_kex_key->algo_name() != "RSA") {
58✔
206
         throw Internal_Error("Expected RSA key but got " + server_rsa_kex_key->algo_name());
×
207
      }
208

209
      TLS_Data_Reader reader("ClientKeyExchange", contents);
58✔
210
      const std::vector<uint8_t> encrypted_pre_master = reader.get_range<uint8_t>(2, 0, 65535);
58✔
211
      reader.assert_done();
58✔
212

213
      PK_Decryptor_EME decryptor(*server_rsa_kex_key, rng, "PKCS1v15");
58✔
214

215
      const uint8_t client_major = state.client_hello()->legacy_version().major_version();
58✔
216
      const uint8_t client_minor = state.client_hello()->legacy_version().minor_version();
58✔
217

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

229
      m_pre_master = decryptor.decrypt_or_random(encrypted_pre_master.data(),
58✔
230
                                                 encrypted_pre_master.size(),
231
                                                 expected_plaintext_size,
232
                                                 rng,
233
                                                 expected_content_bytes,
234
                                                 expected_content_pos,
235
                                                 expected_content_size);
58✔
236
   } else {
116✔
237
      TLS_Data_Reader reader("ClientKeyExchange", contents);
589✔
238

239
      SymmetricKey psk;
589✔
240

241
      if(key_exchange_is_psk(kex_algo)) {
589✔
242
         m_psk_identity = reader.get_string(2, 0, 65535);
44✔
243

244
         psk = creds.psk("tls-server", state.client_hello()->sni_hostname(), m_psk_identity.value());
88✔
245

246
         if(psk.length() == 0) {
44✔
247
            if(policy.hide_unknown_users()) {
×
248
               psk = SymmetricKey(rng, 16);
×
249
            } else {
250
               throw TLS_Exception(Alert::UnknownPSKIdentity, "No PSK for identifier " + m_psk_identity.value());
×
251
            }
252
         }
253
      }
254

255
      if(kex_algo == Kex_Algo::PSK) {
589✔
256
         std::vector<uint8_t> zeros(psk.length());
33✔
257
         append_tls_length_value(m_pre_master, zeros, 2);
33✔
258
         append_tls_length_value(m_pre_master, psk.bits_of(), 2);
99✔
259
      } else if(kex_algo == Kex_Algo::DH || kex_algo == Kex_Algo::ECDH || kex_algo == Kex_Algo::ECDHE_PSK) {
589✔
260
         const PK_Key_Agreement_Key& ka_key = state.server_kex()->server_kex_key();
556✔
261

262
         const std::vector<uint8_t> client_pubkey = (ka_key.algo_name() == "DH")
559✔
263
                                                       ? reader.get_range<uint8_t>(2, 0, 65535)
264
                                                       : reader.get_range<uint8_t>(1, 1, 255);
556✔
265

266
         const auto shared_group = state.server_kex()->shared_group();
556✔
267
         BOTAN_STATE_CHECK(shared_group && shared_group.value() != Group_Params::NONE);
556✔
268

269
         try {
556✔
270
            auto shared_secret =
556✔
271
               state.callbacks().tls_ephemeral_key_agreement(shared_group.value(), ka_key, client_pubkey, rng, policy);
556✔
272

273
            if(ka_key.algo_name() == "DH") {
555✔
274
               shared_secret = CT::strip_leading_zeros(shared_secret);
4✔
275
            }
276

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

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

310
         reader.assert_done();
555✔
311
      } else {
556✔
312
         throw Internal_Error("Client_Key_Exchange: Unknown key exchange negotiated");
×
313
      }
314
   }
589✔
315
}
649✔
316

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