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

randombit / botan / 5079590438

25 May 2023 12:28PM UTC coverage: 92.228% (+0.5%) from 91.723%
5079590438

Pull #3502

github

Pull Request #3502: Apply clang-format to the codebase

75589 of 81959 relevant lines covered (92.23%)

12139530.51 hits per line

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

87.25
/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/tls_handshake_hash.h>
17
#include <botan/internal/tls_handshake_io.h>
18
#include <botan/internal/tls_handshake_state.h>
19
#include <botan/internal/tls_reader.h>
20

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

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

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

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

48
      append_tls_length_value(m_key_material, psk_identity, 2);
43✔
49

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

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

54
      append_tls_length_value(m_pre_master, zeros, 2);
43✔
55
      append_tls_length_value(m_pre_master, psk.bits_of(), 2);
129✔
56
   } else if(state.server_kex()) {
795✔
57
      TLS_Data_Reader reader("ClientKeyExchange", state.server_kex()->params());
656✔
58

59
      SymmetricKey psk;
656✔
60

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

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

66
         append_tls_length_value(m_key_material, psk_identity, 2);
24✔
67

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

71
      if(kex_algo == Kex_Algo::DH) {
656✔
72
         const auto modulus = BigInt::decode(reader.get_range<uint8_t>(2, 1, 65535));
13✔
73
         const auto generator = BigInt::decode(reader.get_range<uint8_t>(2, 1, 65535));
10✔
74
         const std::vector<uint8_t> peer_public_value = reader.get_range<uint8_t>(2, 1, 65535);
5✔
75

76
         if(reader.remaining_bytes())
5✔
77
            throw Decoding_Error("Bad params size for DH key exchange");
×
78

79
         DL_Group group(modulus, generator);
5✔
80

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

85
         const auto private_key = state.callbacks().tls_generate_ephemeral_key(group, rng);
5✔
86
         auto shared_secret = CT::strip_leading_zeros(
5✔
87
            state.callbacks().tls_ephemeral_key_agreement(group, *private_key, peer_public_value, rng, policy));
15✔
88

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

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

102
         const Group_Params curve_id = static_cast<Group_Params>(reader.get_uint16_t());
651✔
103
         const std::vector<uint8_t> peer_public_value = reader.get_range<uint8_t>(1, 1, 255);
651✔
104

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

109
         const auto private_key = state.callbacks().tls_generate_ephemeral_key(curve_id, rng);
652✔
110
         auto shared_secret =
649✔
111
            state.callbacks().tls_ephemeral_key_agreement(curve_id, *private_key, peer_public_value, rng, policy);
650✔
112

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

121
         if(kex_algo == Kex_Algo::ECDH) {
648✔
122
            m_pre_master = std::move(shared_secret);
624✔
123
         } else {
124
            append_tls_length_value(m_pre_master, shared_secret, 2);
24✔
125
            append_tls_length_value(m_pre_master, psk.bits_of(), 2);
72✔
126
         }
127

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

145
      reader.assert_done();
653✔
146
   } else {
656✔
147
      // No server key exchange msg better mean RSA kex + RSA key in cert
148

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

152
      if(!server_public_key)
53✔
153
         throw Internal_Error("No server public key for RSA exchange");
×
154

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

158
         rng.random_vec(m_pre_master, 48);
53✔
159
         m_pre_master[0] = offered_version.major_version();
53✔
160
         m_pre_master[1] = offered_version.minor_version();
53✔
161

162
         PK_Encryptor_EME encryptor(*rsa_pub, rng, "PKCS1v15");
53✔
163

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

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

172
   state.hash().update(io.send(*this));
1,498✔
173
}
752✔
174

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

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

190
      if(!server_rsa_kex_key)
57✔
191
         throw Internal_Error("Expected RSA kex but no server kex key set");
×
192

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

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

200
      PK_Decryptor_EME decryptor(*server_rsa_kex_key, rng, "PKCS1v15");
57✔
201

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

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

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

226
      SymmetricKey psk;
587✔
227

228
      if(key_exchange_is_psk(kex_algo)) {
587✔
229
         const std::string psk_identity = reader.get_string(2, 0, 65535);
45✔
230

231
         psk = creds.psk("tls-server", state.client_hello()->sni_hostname(), psk_identity);
90✔
232

233
         if(psk.length() == 0) {
45✔
234
            if(policy.hide_unknown_users())
×
235
               psk = SymmetricKey(rng, 16);
×
236
            else
237
               throw TLS_Exception(Alert::UnknownPSKIdentity, "No PSK for identifier " + psk_identity);
×
238
         }
239
      }
45✔
240

241
      if(kex_algo == Kex_Algo::PSK) {
587✔
242
         std::vector<uint8_t> zeros(psk.length());
34✔
243
         append_tls_length_value(m_pre_master, zeros, 2);
34✔
244
         append_tls_length_value(m_pre_master, psk.bits_of(), 2);
102✔
245
      } else if(kex_algo == Kex_Algo::DH || kex_algo == Kex_Algo::ECDH || kex_algo == Kex_Algo::ECDHE_PSK) {
587✔
246
         const PK_Key_Agreement_Key& ka_key = state.server_kex()->server_kex_key();
553✔
247

248
         const std::vector<uint8_t> client_pubkey = (ka_key.algo_name() == "DH")
556✔
249
                                                       ? reader.get_range<uint8_t>(2, 0, 65535)
250
                                                       : reader.get_range<uint8_t>(1, 1, 255);
553✔
251

252
         const auto shared_group = state.server_kex()->shared_group();
553✔
253
         BOTAN_STATE_CHECK(shared_group && shared_group.value() != Group_Params::NONE);
553✔
254

255
         try {
553✔
256
            auto shared_secret =
553✔
257
               state.callbacks().tls_ephemeral_key_agreement(shared_group.value(), ka_key, client_pubkey, rng, policy);
553✔
258

259
            if(ka_key.algo_name() == "DH")
552✔
260
               shared_secret = CT::strip_leading_zeros(shared_secret);
5✔
261

262
            if(kex_algo == Kex_Algo::ECDH || kex_algo == Kex_Algo::ECDHE_PSK) {
552✔
263
               // RFC 8422 - 5.11.
264
               //   With X25519 and X448, a receiving party MUST check whether the
265
               //   computed premaster secret is the all-zero value and abort the
266
               //   handshake if so, as described in Section 6 of [RFC7748].
267
               BOTAN_ASSERT_NOMSG(state.server_kex()->params().size() >= 3);
547✔
268
               Group_Params group = static_cast<Group_Params>(state.server_kex()->params().at(2));
547✔
269
               if(group == Group_Params::X25519 && CT::all_zeros(shared_secret.data(), shared_secret.size()).is_set()) {
1,016✔
270
                  throw TLS_Exception(Alert::DecryptError, "Bad X25519 key exchange");
×
271
               }
272
            }
273

274
            if(kex_algo == Kex_Algo::ECDHE_PSK) {
552✔
275
               append_tls_length_value(m_pre_master, shared_secret, 2);
11✔
276
               append_tls_length_value(m_pre_master, psk.bits_of(), 2);
33✔
277
            } else
278
               m_pre_master = shared_secret;
541✔
279
         } catch(Invalid_Argument& e) {
553✔
280
            throw TLS_Exception(Alert::IllegalParameter, e.what());
1✔
281
         } catch(TLS_Exception& e) { throw e; } catch(std::exception&) {
1✔
282
            /*
283
            * Something failed in the DH/ECDH computation. To avoid possible
284
            * attacks which are based on triggering and detecting some edge
285
            * failure condition, randomize the pre-master output and carry on,
286
            * allowing the protocol to fail later in the finished checks.
287
            */
288
            rng.random_vec(m_pre_master, ka_key.public_value().size());
×
289
         }
×
290

291
         reader.assert_done();
552✔
292
      } else
553✔
293
         throw Internal_Error("Client_Key_Exchange: Unknown key exchange negotiated");
×
294
   }
587✔
295
}
646✔
296

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