Botan 3.9.0
Crypto and TLS for C&
tls_extensions_key_share.cpp
Go to the documentation of this file.
1/*
2* TLS Extension Key Share
3* (C) 2011,2012,2015,2016 Jack Lloyd
4* 2016 Juraj Somorovsky
5* 2021 Elektrobit Automotive GmbH
6* 2022 Hannes Rantzsch, René Meusel, neXenio GmbH
7*
8* Botan is released under the Simplified BSD License (see license.txt)
9*/
10
11#include <botan/tls_extensions.h>
12
13#include <botan/ecdh.h>
14#include <botan/tls_callbacks.h>
15#include <botan/tls_exceptn.h>
16#include <botan/tls_policy.h>
17#include <botan/internal/stl_util.h>
18#include <botan/internal/tls_reader.h>
19#include <algorithm>
20#include <utility>
21
22namespace Botan::TLS {
23
24namespace {
25
26class Key_Share_Entry {
27 public:
28 explicit Key_Share_Entry(TLS_Data_Reader& reader) {
29 // TODO check that the group actually exists before casting...
30 m_group = static_cast<Named_Group>(reader.get_uint16_t());
31 m_key_exchange = reader.get_tls_length_value(2);
32 }
33
34 // Create an empty Key_Share_Entry with the selected group
35 // but don't pre-generate a keypair, yet.
36 explicit Key_Share_Entry(const TLS::Group_Params group) : m_group(group) {}
37
38 Key_Share_Entry(const TLS::Group_Params group, Callbacks& cb, RandomNumberGenerator& rng) :
39 m_group(group), m_private_key(cb.tls_kem_generate_key(group, rng)) {
40 if(!m_private_key) {
41 throw TLS_Exception(Alert::InternalError, "Application did not provide a suitable ephemeral key pair");
42 }
43
44 if(group.is_kem()) {
45 m_key_exchange = m_private_key->public_key_bits();
46 } else if(group.is_ecdh_named_curve()) {
47 auto* pkey = dynamic_cast<ECDH_PublicKey*>(m_private_key.get());
48 if(pkey == nullptr) {
49 throw TLS_Exception(Alert::InternalError, "Application did not provide a ECDH_PublicKey");
50 }
51
52 // RFC 8446 Ch. 4.2.8.2
53 //
54 // Note: Versions of TLS prior to 1.3 permitted point format
55 // negotiation; TLS 1.3 removes this feature in favor of a single point
56 // format for each curve.
57 //
58 // Hence, we neither need to take Policy::use_ecc_point_compression() nor
59 // ClientHello::prefers_compressed_ec_points() into account here.
60 m_key_exchange = pkey->public_value(EC_Point_Format::Uncompressed);
61 } else {
62 auto* pkey = dynamic_cast<PK_Key_Agreement_Key*>(m_private_key.get());
63 if(pkey == nullptr) {
64 throw TLS_Exception(Alert::InternalError, "Application did not provide a key-agreement key");
65 }
66
67 m_key_exchange = pkey->public_value();
68 }
69 }
70
71 bool empty() const { return (m_group == Group_Params::NONE) && m_key_exchange.empty(); }
72
73 std::vector<uint8_t> serialize() const {
74 std::vector<uint8_t> result;
75 result.reserve(m_key_exchange.size() + 4);
76
77 const uint16_t named_curve_id = m_group.wire_code();
78 result.push_back(get_byte<0>(named_curve_id));
79 result.push_back(get_byte<1>(named_curve_id));
80 append_tls_length_value(result, m_key_exchange, 2);
81
82 return result;
83 }
84
85 Named_Group group() const { return m_group; }
86
87 secure_vector<uint8_t> encapsulate(const Key_Share_Entry& client_share,
88 const Policy& policy,
89 Callbacks& cb,
90 RandomNumberGenerator& rng) {
91 auto [encapsulated_shared_key, shared_key] =
92 KEM_Encapsulation::destructure(cb.tls_kem_encapsulate(m_group, client_share.m_key_exchange, rng, policy));
93 m_key_exchange = std::move(encapsulated_shared_key);
94 return std::move(shared_key);
95 }
96
97 /**
98 * Perform KEM decapsulation with another Key_Share_Entry's public key
99 *
100 * The caller must ensure that both this and `received` have the same group.
101 * This method must not be called on Key_Share_Entries without a private key.
102 */
103 secure_vector<uint8_t> decapsulate(const Key_Share_Entry& received,
104 const Policy& policy,
105 Callbacks& cb,
106 RandomNumberGenerator& rng) {
107 auto scope = scoped_cleanup([&] { m_private_key.reset(); });
108 BOTAN_ASSERT_NOMSG(m_group == received.m_group);
109 BOTAN_STATE_CHECK(m_private_key != nullptr);
110 return cb.tls_kem_decapsulate(m_group, *m_private_key, received.m_key_exchange, rng, policy);
111 }
112
113 private:
114 Named_Group m_group;
115 std::vector<uint8_t> m_key_exchange;
116 std::unique_ptr<Private_Key> m_private_key;
117};
118
119class Key_Share_ClientHello;
120
121class Key_Share_ServerHello {
122 public:
123 Key_Share_ServerHello(TLS_Data_Reader& reader, uint16_t) : m_server_share(reader) {}
124
125 Key_Share_ServerHello(Named_Group group,
126 const Key_Share_ClientHello& client_keyshare,
127 const Policy& policy,
128 Callbacks& cb,
129 RandomNumberGenerator& rng);
130
131 ~Key_Share_ServerHello() = default;
132
133 Key_Share_ServerHello(const Key_Share_ServerHello&) = delete;
134 Key_Share_ServerHello& operator=(const Key_Share_ServerHello&) = delete;
135
136 Key_Share_ServerHello(Key_Share_ServerHello&&) = default;
137 Key_Share_ServerHello& operator=(Key_Share_ServerHello&&) = default;
138
139 std::vector<uint8_t> serialize() const { return m_server_share.serialize(); }
140
141 bool empty() const { return m_server_share.empty(); }
142
143 Key_Share_Entry& get_singleton_entry() { return m_server_share; }
144
145 const Key_Share_Entry& get_singleton_entry() const { return m_server_share; }
146
147 std::vector<Named_Group> offered_groups() const { return {selected_group()}; }
148
149 Named_Group selected_group() const { return m_server_share.group(); }
150
151 secure_vector<uint8_t> take_shared_secret() {
152 BOTAN_STATE_CHECK(!m_shared_secret.empty());
153 return std::exchange(m_shared_secret, {});
154 }
155
156 private:
157 Key_Share_Entry m_server_share;
158 secure_vector<uint8_t> m_shared_secret;
159};
160
161class Key_Share_ClientHello {
162 public:
163 Key_Share_ClientHello(TLS_Data_Reader& reader, uint16_t /* extension_size */) {
164 // This construction is a crutch to make working with the incoming
165 // TLS_Data_Reader bearable. Currently, this reader spans the entire
166 // Client_Hello message. Hence, if offset or length fields are skewed
167 // or maliciously fabricated, it is possible to read further than the
168 // bounds of the current extension.
169 // Note that this aplies to many locations in the code base.
170 //
171 // TODO: Overhaul the TLS_Data_Reader to allow for cheap "sub-readers"
172 // that enforce read bounds of sub-structures while parsing.
173 const auto client_key_share_length = reader.get_uint16_t();
174 const auto read_bytes_so_far_begin = reader.read_so_far();
175 auto remaining = [&] {
176 const auto read_so_far = reader.read_so_far() - read_bytes_so_far_begin;
177 BOTAN_STATE_CHECK(read_so_far <= client_key_share_length);
178 return client_key_share_length - read_so_far;
179 };
180
181 while(reader.has_remaining() && remaining() > 0) {
182 if(remaining() < 4) {
183 throw TLS_Exception(Alert::DecodeError, "Not enough data to read another KeyShareEntry");
184 }
185
186 Key_Share_Entry new_entry(reader);
187
188 // RFC 8446 4.2.8
189 // Clients MUST NOT offer multiple KeyShareEntry values for the same
190 // group. [...]
191 // Servers MAY check for violations of these rules and abort the
192 // handshake with an "illegal_parameter" alert if one is violated.
193 if(std::find_if(m_client_shares.begin(), m_client_shares.end(), [&](const auto& entry) {
194 return entry.group() == new_entry.group();
195 }) != m_client_shares.end()) {
196 throw TLS_Exception(Alert::IllegalParameter, "Received multiple key share entries for the same group");
197 }
198
199 m_client_shares.emplace_back(std::move(new_entry));
200 }
201
202 if((reader.read_so_far() - read_bytes_so_far_begin) != client_key_share_length) {
203 throw Decoding_Error("Read bytes are not equal client KeyShare length");
204 }
205 }
206
207 Key_Share_ClientHello(const Policy& policy, Callbacks& cb, RandomNumberGenerator& rng) {
208 const auto supported = policy.key_exchange_groups();
209 const auto offers = policy.key_exchange_groups_to_offer();
210
211 // RFC 8446 P. 48
212 //
213 // This vector MAY be empty if the client is requesting a
214 // HelloRetryRequest. Each KeyShareEntry value MUST correspond to a
215 // group offered in the "supported_groups" extension and MUST appear in
216 // the same order. However, the values MAY be a non-contiguous subset
217 // of the "supported_groups" extension and MAY omit the most preferred
218 // groups.
219 //
220 // ... hence, we're going through the supported groups and find those that
221 // should be used to offer a key exchange. This will satisfy above spec.
222 for(const auto group : supported) {
223 if(std::find(offers.begin(), offers.end(), group) == offers.end()) {
224 continue;
225 }
226 m_client_shares.emplace_back(group, cb, rng);
227 }
228 }
229
230 ~Key_Share_ClientHello() = default;
231
232 Key_Share_ClientHello(const Key_Share_ClientHello&) = delete;
233 Key_Share_ClientHello& operator=(const Key_Share_ClientHello&) = delete;
234
235 Key_Share_ClientHello(Key_Share_ClientHello&&) = default;
236 Key_Share_ClientHello& operator=(Key_Share_ClientHello&&) = default;
237
238 void retry_offer(const TLS::Group_Params to_offer, Callbacks& cb, RandomNumberGenerator& rng) {
239 // RFC 8446 4.2.8
240 // The selected_group field [MUST] not correspond to a group which was provided
241 // in the "key_share" extension in the original ClientHello.
242 if(std::find_if(m_client_shares.cbegin(), m_client_shares.cend(), [&](const auto& kse) {
243 return kse.group() == to_offer;
244 }) != m_client_shares.cend()) {
245 throw TLS_Exception(Alert::IllegalParameter, "group was already offered");
246 }
247
248 m_client_shares.clear();
249 m_client_shares.emplace_back(to_offer, cb, rng);
250 }
251
252 std::vector<Named_Group> offered_groups() const {
253 std::vector<Named_Group> offered_groups;
254 offered_groups.reserve(m_client_shares.size());
255 for(const auto& share : m_client_shares) {
256 offered_groups.push_back(share.group());
257 }
258 return offered_groups;
259 }
260
261 Named_Group selected_group() const { throw Invalid_Argument("Client Hello Key Share does not select a group"); }
262
263 std::vector<uint8_t> serialize() const {
264 std::vector<uint8_t> shares;
265 for(const auto& share : m_client_shares) {
266 const auto serialized_share = share.serialize();
267 shares.insert(shares.end(), serialized_share.cbegin(), serialized_share.cend());
268 }
269
270 std::vector<uint8_t> result;
271 append_tls_length_value(result, shares, 2);
272 return result;
273 }
274
275 bool empty() const {
276 // RFC 8446 4.2.8
277 // Clients MAY send an empty client_shares vector in order to request
278 // group selection from the server, at the cost of an additional round
279 // trip [...].
280 return false;
281 }
282
283 secure_vector<uint8_t> encapsulate(Key_Share_ServerHello& server_share,
284 const Policy& policy,
285 Callbacks& cb,
286 RandomNumberGenerator& rng) const {
287 auto& server_selected = server_share.get_singleton_entry();
288
289 // find the client offer that matches the server offer
290 auto match = std::find_if(m_client_shares.begin(), m_client_shares.end(), [&](const auto& offered) {
291 return offered.group() == server_selected.group();
292 });
293
294 // We validated that the selected group was indeed offered by the
295 // client before even constructing the Server Hello that contains the
296 // Key_Share_ServerHello extension.
297 BOTAN_STATE_CHECK(match != m_client_shares.end());
298
299 return server_selected.encapsulate(*match, policy, cb, rng);
300 }
301
302 secure_vector<uint8_t> decapsulate(const Key_Share_ServerHello& server_share,
303 const Policy& policy,
304 Callbacks& cb,
305 RandomNumberGenerator& rng) {
306 const auto& server_selected = server_share.get_singleton_entry();
307
308 // find the client offer that matches the server offer
309 auto match = std::find_if(m_client_shares.begin(), m_client_shares.end(), [&](const auto& offered) {
310 return offered.group() == server_selected.group();
311 });
312
313 // RFC 8446 4.2.8:
314 // [The KeyShareEntry in the ServerHello] MUST be in the same group
315 // as the KeyShareEntry value offered by the client that the server
316 // has selected for the negotiated key exchange.
317 if(match == m_client_shares.end()) {
318 throw TLS_Exception(Alert::IllegalParameter, "Server selected a key exchange group we didn't offer.");
319 }
320
321 return match->decapsulate(server_selected, policy, cb, rng);
322 }
323
324 private:
325 std::vector<Key_Share_Entry> m_client_shares;
326};
327
328Key_Share_ServerHello::Key_Share_ServerHello(Named_Group group,
329 const Key_Share_ClientHello& client_keyshare,
330 const Policy& policy,
331 Callbacks& cb,
332 RandomNumberGenerator& rng) :
333 m_server_share(group) {
334 m_shared_secret = client_keyshare.encapsulate(*this, policy, cb, rng);
335}
336
337class Key_Share_HelloRetryRequest {
338 public:
339 Key_Share_HelloRetryRequest(TLS_Data_Reader& reader, uint16_t extension_size) {
340 constexpr auto sizeof_uint16_t = sizeof(uint16_t);
341
342 if(extension_size != sizeof_uint16_t) {
343 throw Decoding_Error("Size of KeyShare extension in HelloRetryRequest must be " +
344 std::to_string(sizeof_uint16_t) + " bytes");
345 }
346
347 m_selected_group = static_cast<Named_Group>(reader.get_uint16_t());
348 }
349
350 explicit Key_Share_HelloRetryRequest(Named_Group selected_group) : m_selected_group(selected_group) {}
351
352 ~Key_Share_HelloRetryRequest() = default;
353
354 Key_Share_HelloRetryRequest(const Key_Share_HelloRetryRequest&) = delete;
355 Key_Share_HelloRetryRequest& operator=(const Key_Share_HelloRetryRequest&) = delete;
356
357 Key_Share_HelloRetryRequest(Key_Share_HelloRetryRequest&&) = default;
358 Key_Share_HelloRetryRequest& operator=(Key_Share_HelloRetryRequest&&) = default;
359
360 std::vector<uint8_t> serialize() const {
361 auto code = m_selected_group.wire_code();
362 return {get_byte<0>(code), get_byte<1>(code)};
363 }
364
365 Named_Group selected_group() const { return m_selected_group; }
366
367 std::vector<Named_Group> offered_groups() const {
368 throw Invalid_Argument("Hello Retry Request never offers any key exchange groups");
369 }
370
371 bool empty() const { return m_selected_group == Group_Params::NONE; }
372
373 private:
374 Named_Group m_selected_group;
375};
376
377} // namespace
378
379class Key_Share::Key_Share_Impl {
380 public:
381 using Key_Share_Type = std::variant<Key_Share_ClientHello, Key_Share_ServerHello, Key_Share_HelloRetryRequest>;
382
383 explicit Key_Share_Impl(Key_Share_Type ks) : key_share(std::move(ks)) {}
384
385 Key_Share_Type key_share; // NOLINT(*-non-private-member-variable*)
386};
387
388Key_Share::Key_Share(TLS_Data_Reader& reader, uint16_t extension_size, Handshake_Type message_type) {
389 if(message_type == Handshake_Type::ClientHello) {
390 m_impl = std::make_unique<Key_Share_Impl>(Key_Share_ClientHello(reader, extension_size));
391 } else if(message_type == Handshake_Type::HelloRetryRequest) {
392 // Connection_Side::Server
393 m_impl = std::make_unique<Key_Share_Impl>(Key_Share_HelloRetryRequest(reader, extension_size));
394 } else if(message_type == Handshake_Type::ServerHello) {
395 // Connection_Side::Server
396 m_impl = std::make_unique<Key_Share_Impl>(Key_Share_ServerHello(reader, extension_size));
397 } else {
398 throw Invalid_Argument(std::string("cannot create a Key_Share extension for message of type: ") +
399 handshake_type_to_string(message_type));
400 }
401}
402
403// ClientHello
405 m_impl(std::make_unique<Key_Share_Impl>(Key_Share_ClientHello(policy, cb, rng))) {}
406
407// HelloRetryRequest
409 m_impl(std::make_unique<Key_Share_Impl>(Key_Share_HelloRetryRequest(selected_group))) {}
410
411// ServerHello
413 const Key_Share& client_keyshare,
414 const Policy& policy,
415 Callbacks& cb,
417 m_impl(std::make_unique<Key_Share_Impl>(Key_Share_ServerHello(
418 selected_group, std::get<Key_Share_ClientHello>(client_keyshare.m_impl->key_share), policy, cb, rng))) {}
419
420Key_Share::~Key_Share() = default;
421
422std::vector<uint8_t> Key_Share::serialize(Connection_Side /*whoami*/) const {
423 return std::visit([](const auto& key_share) { return key_share.serialize(); }, m_impl->key_share);
424}
425
426bool Key_Share::empty() const {
427 return std::visit([](const auto& key_share) { return key_share.empty(); }, m_impl->key_share);
428}
429
431 const Key_Share& client_keyshare,
432 const Policy& policy,
433 Callbacks& cb,
435 return std::unique_ptr<Key_Share>(new Key_Share(selected_group, client_keyshare, policy, cb, rng));
436}
437
439 const Policy& policy,
440 Callbacks& cb,
442 return std::visit(overloaded{[&](Key_Share_ClientHello& ch, const Key_Share_ServerHello& sh) {
443 return ch.decapsulate(sh, policy, cb, rng);
444 },
445 [](const auto&, const auto&) -> secure_vector<uint8_t> {
446 throw Invalid_Argument(
447 "can only decapsulate in ClientHello Key_Share with a ServerHello Key_Share");
448 }},
449 m_impl->key_share,
450 server_keyshare.m_impl->key_share);
451}
452
453std::vector<Named_Group> Key_Share::offered_groups() const {
454 return std::visit([](const auto& keyshare) { return keyshare.offered_groups(); }, m_impl->key_share);
455}
456
458 return std::visit([](const auto& keyshare) { return keyshare.selected_group(); }, m_impl->key_share);
459}
460
462 return std::visit(
463 overloaded{[](Key_Share_ServerHello& server_keyshare) { return server_keyshare.take_shared_secret(); },
464 [](auto&) -> secure_vector<uint8_t> {
465 throw Invalid_Argument("Only the key share in Server Hello contains a shared secret");
466 }},
467 m_impl->key_share);
468}
469
470void Key_Share::retry_offer(const Key_Share& retry_request_keyshare,
471 const std::vector<Named_Group>& supported_groups,
472 Callbacks& cb,
474 std::visit(overloaded{[&](Key_Share_ClientHello& ch, const Key_Share_HelloRetryRequest& hrr) {
475 auto selected = hrr.selected_group();
476 // RFC 8446 4.2.8
477 // [T]he selected_group field [MUST correspond] to a group which was provided in
478 // the "supported_groups" extension in the original ClientHello
479 if(!value_exists(supported_groups, selected)) {
480 throw TLS_Exception(Alert::IllegalParameter, "group was not advertised as supported");
481 }
482
483 return ch.retry_offer(selected, cb, rng);
484 },
485 [](const auto&, const auto&) {
486 throw Invalid_Argument("can only retry with HelloRetryRequest on a ClientHello Key_Share");
487 }},
488 m_impl->key_share,
489 retry_request_keyshare.m_impl->key_share);
490}
491
492} // namespace Botan::TLS
#define BOTAN_ASSERT_NOMSG(expr)
Definition assert.h:75
#define BOTAN_STATE_CHECK(expr)
Definition assert.h:49
static std::pair< std::vector< uint8_t >, secure_vector< uint8_t > > destructure(KEM_Encapsulation &&kem)
Definition pubkey.h:579
std::vector< Named_Group > offered_groups() const
Key_Share(TLS_Data_Reader &reader, uint16_t extension_size, Handshake_Type message_type)
secure_vector< uint8_t > decapsulate(const Key_Share &server_keyshare, const Policy &policy, Callbacks &cb, RandomNumberGenerator &rng)
void retry_offer(const Key_Share &retry_request_keyshare, const std::vector< Named_Group > &supported_groups, Callbacks &cb, RandomNumberGenerator &rng)
static std::unique_ptr< Key_Share > create_as_encapsulation(Group_Params selected_group, const Key_Share &client_keyshare, const Policy &policy, Callbacks &cb, RandomNumberGenerator &rng)
std::vector< uint8_t > serialize(Connection_Side whoami) const override
secure_vector< uint8_t > take_shared_secret()
const char * handshake_type_to_string(Handshake_Type type)
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:184
Group_Params Named_Group
constexpr uint8_t get_byte(T input)
Definition loadstor.h:79
bool value_exists(const std::vector< T > &vec, const OT &val)
Definition stl_util.h:52
std::vector< T, secure_allocator< T > > secure_vector
Definition secmem.h:69