Botan 3.14.1
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_13.h>
12
13#include <botan/tls_callbacks.h>
14#include <botan/tls_exceptn.h>
15#include <botan/tls_policy.h>
16#include <botan/internal/scoped_cleanup.h>
17#include <botan/internal/stl_util.h>
18#include <botan/internal/tls_messages_internal.h>
19#include <botan/internal/tls_reader.h>
20#include <algorithm>
21#include <unordered_set>
22#include <utility>
23
24namespace Botan::TLS {
25
26namespace {
27
28// RFC 8446 4.2.8.2: TLS 1.3 removes ec_point_formats negotiation and
29// requires that ECDH key shares are uncompressed.
30//
31// This logic happens to also work for the existing PQ shares since they
32// place the ECDH part of the key share first
33void check_ecdh_uncompressed_format(Group_Params group, std::span<const uint8_t> bytes) {
34 const auto hybrid_ecc = group.pqc_hybrid_ecc();
35 const bool has_ecdh =
36 group.is_ecdh_named_curve() || (hybrid_ecc.has_value() && Group_Params(hybrid_ecc.value()).is_ecdh_named_curve());
37 if(!has_ecdh) {
38 return;
39 }
40 if(bytes.empty() || bytes[0] != 0x04) {
41 throw TLS_Exception(Alert::IllegalParameter, "TLS 1.3 ECDH key share must use uncompressed point format");
42 }
43}
44
45// RFC 8446 4.2.8.1
46// The opaque value contains the Diffie-Hellman public value (Y = g^X mod p)
47// for the specified group (see [RFC7919] for group definitions) encoded as a
48// big-endian integer and padded to the left with zeros to the size of p in bytes.
49void check_ffdhe_padding(Group_Params group, std::span<const uint8_t> bytes) {
50 const size_t p_bytes = [&]() -> size_t {
51 switch(group.code()) {
53 return 2048 / 8;
55 return 3072 / 8;
57 return 4096 / 8;
59 return 6144 / 8;
61 return 8192 / 8;
62 default:
63 return 0;
64 }
65 }();
66
67 if(p_bytes > 0 && bytes.size() != p_bytes) {
68 throw TLS_Exception(Alert::IllegalParameter, "TLS 1.3 FFDHE key share must be padded to the size of p");
69 }
70}
71
72class Key_Share_Entry {
73 public:
74 explicit Key_Share_Entry(TLS_Data_Reader& reader) {
75 // TODO check that the group actually exists before casting...
76 m_group = static_cast<Named_Group>(reader.get_uint16_t());
77 // RFC 8446 4.2.8: opaque key_exchange<1..2^16-1>
78 m_key_exchange = reader.get_range<uint8_t>(2, 1, 65535);
79 }
80
81 // Create an empty Key_Share_Entry with the selected group
82 // but don't pre-generate a keypair, yet.
83 explicit Key_Share_Entry(const TLS::Group_Params group) : m_group(group) {}
84
85 Key_Share_Entry(const TLS::Group_Params group, Callbacks& cb, RandomNumberGenerator& rng) :
86 m_group(group), m_private_key(cb.tls_kem_generate_key(group, rng)) {
87 if(!m_private_key) {
88 throw TLS_Exception(Alert::InternalError, "Application did not provide a suitable ephemeral key pair");
89 }
90
91 m_key_exchange = m_private_key->raw_public_key_bits();
92 }
93
94 bool empty() const { return (m_group == Group_Params::NONE) && m_key_exchange.empty(); }
95
96 std::vector<uint8_t> serialize() const {
97 std::vector<uint8_t> result;
98 result.reserve(m_key_exchange.size() + 4);
99
100 const uint16_t named_curve_id = m_group.wire_code();
101 result.push_back(get_byte<0>(named_curve_id));
102 result.push_back(get_byte<1>(named_curve_id));
103 append_tls_length_value(result, m_key_exchange, 2);
104
105 return result;
106 }
107
108 Named_Group group() const { return m_group; }
109
110 secure_vector<uint8_t> encapsulate(const Key_Share_Entry& client_share,
111 const Policy& policy,
112 Callbacks& cb,
113 RandomNumberGenerator& rng) {
114 check_ecdh_uncompressed_format(m_group, client_share.m_key_exchange);
115 check_ffdhe_padding(m_group, client_share.m_key_exchange);
116 auto [encapsulated_shared_key, shared_key] =
117 KEM_Encapsulation::destructure(cb.tls_kem_encapsulate(m_group, client_share.m_key_exchange, rng, policy));
118 m_key_exchange = std::move(encapsulated_shared_key);
119 return std::move(shared_key);
120 }
121
122 /**
123 * Perform KEM decapsulation with another Key_Share_Entry's public key
124 *
125 * The caller must ensure that both this and `received` have the same group.
126 * This method must not be called on Key_Share_Entries without a private key.
127 */
128 secure_vector<uint8_t> decapsulate(const Key_Share_Entry& received,
129 const Policy& policy,
130 Callbacks& cb,
131 RandomNumberGenerator& rng) {
132 const auto scope = scoped_cleanup([&] { m_private_key.reset(); });
133 BOTAN_ASSERT_NOMSG(m_group == received.m_group);
134 BOTAN_STATE_CHECK(m_private_key != nullptr);
135 check_ecdh_uncompressed_format(m_group, received.m_key_exchange);
136 check_ffdhe_padding(m_group, received.m_key_exchange);
137 return cb.tls_kem_decapsulate(m_group, *m_private_key, received.m_key_exchange, rng, policy);
138 }
139
140 private:
141 Named_Group m_group;
142 std::vector<uint8_t> m_key_exchange;
143 std::unique_ptr<Private_Key> m_private_key;
144};
145
146class Key_Share_ClientHello;
147
148class Key_Share_ServerHello {
149 public:
150 Key_Share_ServerHello(TLS_Data_Reader& reader, uint16_t /*len*/) : m_server_share(reader) {}
151
152 Key_Share_ServerHello(Named_Group group,
153 const Key_Share_ClientHello& client_keyshare,
154 const Policy& policy,
155 Callbacks& cb,
156 RandomNumberGenerator& rng);
157
158 ~Key_Share_ServerHello() = default;
159
160 Key_Share_ServerHello(const Key_Share_ServerHello&) = delete;
161 Key_Share_ServerHello& operator=(const Key_Share_ServerHello&) = delete;
162
163 Key_Share_ServerHello(Key_Share_ServerHello&&) = default;
164 Key_Share_ServerHello& operator=(Key_Share_ServerHello&&) = default;
165
166 std::vector<uint8_t> serialize() const { return m_server_share.serialize(); }
167
168 bool empty() const { return m_server_share.empty(); }
169
170 Key_Share_Entry& get_singleton_entry() { return m_server_share; }
171
172 const Key_Share_Entry& get_singleton_entry() const { return m_server_share; }
173
174 std::vector<Named_Group> offered_groups() const { return {selected_group()}; }
175
176 Named_Group selected_group() const { return m_server_share.group(); }
177
178 secure_vector<uint8_t> take_shared_secret() {
179 BOTAN_STATE_CHECK(!m_shared_secret.empty());
180 return std::exchange(m_shared_secret, {});
181 }
182
183 private:
184 Key_Share_Entry m_server_share;
185 secure_vector<uint8_t> m_shared_secret;
186};
187
188class Key_Share_ClientHello {
189 public:
190 Key_Share_ClientHello(TLS_Data_Reader& reader, uint16_t /* extension_size */) {
191 // The reader is per-extension (Extensions::deserialize binds it to
192 // exactly extension_size bytes). Enforce that the inner
193 // client_shares length matches what the outer extension has left,
194 // then let the entry loop consume everything; extn_reader's
195 // assert_done() at the deserialize call site catches any leftover.
196 const auto client_key_share_length = reader.get_uint16_t();
197 if(reader.remaining_bytes() != client_key_share_length) {
198 throw TLS_Exception(Alert::DecodeError, "Inconsistent length in client KeyShare extension");
199 }
200
201 std::unordered_set<uint16_t> seen_groups;
202 while(reader.has_remaining()) {
203 // Each KeyShareEntry is at least 4 bytes (group + 2-byte length).
204 // Cleaner failure than the reader underflow we'd otherwise hit
205 // when the inner buffer ends mid-entry.
206 if(reader.remaining_bytes() < 4) {
207 throw TLS_Exception(Alert::DecodeError, "Not enough data to read another KeyShareEntry");
208 }
209
210 Key_Share_Entry new_entry(reader);
211
212 // RFC 8446 4.2.8
213 // Clients MUST NOT offer multiple KeyShareEntry values for the same
214 // group. [...]
215 // Servers MAY check for violations of these rules and abort the
216 // handshake with an "illegal_parameter" alert if one is violated.
217 if(!seen_groups.insert(new_entry.group().wire_code()).second) {
218 throw TLS_Exception(Alert::IllegalParameter, "Received multiple key share entries for the same group");
219 }
220
221 m_client_shares.emplace_back(std::move(new_entry));
222 }
223 }
224
225 Key_Share_ClientHello(const Policy& policy, Callbacks& cb, RandomNumberGenerator& rng) {
226 const auto supported = policy.key_exchange_groups();
227 const auto offers = policy.key_exchange_groups_to_offer();
228
229 // RFC 8446 P. 48
230 //
231 // This vector MAY be empty if the client is requesting a
232 // HelloRetryRequest. Each KeyShareEntry value MUST correspond to a
233 // group offered in the "supported_groups" extension and MUST appear in
234 // the same order. However, the values MAY be a non-contiguous subset
235 // of the "supported_groups" extension and MAY omit the most preferred
236 // groups.
237 //
238 // ... hence, we're going through the supported groups and find those that
239 // should be used to offer a key exchange. This will satisfy above spec.
240 for(const auto group : supported) {
241 if(std::find(offers.begin(), offers.end(), group) == offers.end() ||
242 !group_usable_in_version(group, Protocol_Version::TLS_V13)) {
243 continue;
244 }
245 m_client_shares.emplace_back(group, cb, rng);
246 }
247 }
248
249 ~Key_Share_ClientHello() = default;
250
251 Key_Share_ClientHello(const Key_Share_ClientHello&) = delete;
252 Key_Share_ClientHello& operator=(const Key_Share_ClientHello&) = delete;
253
254 Key_Share_ClientHello(Key_Share_ClientHello&&) = default;
255 Key_Share_ClientHello& operator=(Key_Share_ClientHello&&) = default;
256
257 void retry_offer(const TLS::Group_Params to_offer, Callbacks& cb, RandomNumberGenerator& rng) {
258 // RFC 8446 4.2.8
259 // The selected_group field [MUST] not correspond to a group which was provided
260 // in the "key_share" extension in the original ClientHello.
261 if(std::find_if(m_client_shares.cbegin(), m_client_shares.cend(), [&](const auto& kse) {
262 return kse.group() == to_offer;
263 }) != m_client_shares.cend()) {
264 throw TLS_Exception(Alert::IllegalParameter, "group was already offered");
265 }
266
267 m_client_shares.clear();
268 m_client_shares.emplace_back(to_offer, cb, rng);
269 }
270
271 std::vector<Named_Group> offered_groups() const {
272 std::vector<Named_Group> offered_groups;
273 offered_groups.reserve(m_client_shares.size());
274 for(const auto& share : m_client_shares) {
275 offered_groups.push_back(share.group());
276 }
277 return offered_groups;
278 }
279
280 Named_Group selected_group() const { throw Invalid_Argument("Client Hello Key Share does not select a group"); }
281
282 std::vector<uint8_t> serialize() const {
283 std::vector<uint8_t> shares;
284 for(const auto& share : m_client_shares) {
285 const auto serialized_share = share.serialize();
286 shares.insert(shares.end(), serialized_share.cbegin(), serialized_share.cend());
287 }
288
289 std::vector<uint8_t> result;
290 append_tls_length_value(result, shares, 2);
291 return result;
292 }
293
294 bool empty() const {
295 // RFC 8446 4.2.8
296 // Clients MAY send an empty client_shares vector in order to request
297 // group selection from the server, at the cost of an additional round
298 // trip [...].
299 return false;
300 }
301
302 secure_vector<uint8_t> encapsulate(Key_Share_ServerHello& server_share,
303 const Policy& policy,
304 Callbacks& cb,
305 RandomNumberGenerator& rng) const {
306 auto& server_selected = server_share.get_singleton_entry();
307
308 // find the client offer that matches the server offer
309 const 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 // We validated that the selected group was indeed offered by the
314 // client before even constructing the Server Hello that contains the
315 // Key_Share_ServerHello extension.
316 BOTAN_STATE_CHECK(match != m_client_shares.end());
317
318 return server_selected.encapsulate(*match, policy, cb, rng);
319 }
320
321 secure_vector<uint8_t> decapsulate(const Key_Share_ServerHello& server_share,
322 const Policy& policy,
323 Callbacks& cb,
324 RandomNumberGenerator& rng) {
325 const auto& server_selected = server_share.get_singleton_entry();
326
327 // find the client offer that matches the server offer
328 const auto match = std::find_if(m_client_shares.begin(), m_client_shares.end(), [&](const auto& offered) {
329 return offered.group() == server_selected.group();
330 });
331
332 // RFC 8446 4.2.8:
333 // [The KeyShareEntry in the ServerHello] MUST be in the same group
334 // as the KeyShareEntry value offered by the client that the server
335 // has selected for the negotiated key exchange.
336 if(match == m_client_shares.end()) {
337 throw TLS_Exception(Alert::IllegalParameter, "Server selected a key exchange group we didn't offer.");
338 }
339
340 return match->decapsulate(server_selected, policy, cb, rng);
341 }
342
343 private:
344 std::vector<Key_Share_Entry> m_client_shares;
345};
346
347Key_Share_ServerHello::Key_Share_ServerHello(Named_Group group,
348 const Key_Share_ClientHello& client_keyshare,
349 const Policy& policy,
350 Callbacks& cb,
351 RandomNumberGenerator& rng) :
352 m_server_share(group) {
353 m_shared_secret = client_keyshare.encapsulate(*this, policy, cb, rng);
354}
355
356class Key_Share_HelloRetryRequest {
357 public:
358 Key_Share_HelloRetryRequest(TLS_Data_Reader& reader, uint16_t extension_size) {
359 constexpr auto sizeof_uint16_t = sizeof(uint16_t);
360
361 if(extension_size != sizeof_uint16_t) {
362 throw Decoding_Error("Size of KeyShare extension in HelloRetryRequest must be " +
363 std::to_string(sizeof_uint16_t) + " bytes");
364 }
365
366 m_selected_group = static_cast<Named_Group>(reader.get_uint16_t());
367 }
368
369 explicit Key_Share_HelloRetryRequest(Named_Group selected_group) : m_selected_group(selected_group) {}
370
371 ~Key_Share_HelloRetryRequest() = default;
372
373 Key_Share_HelloRetryRequest(const Key_Share_HelloRetryRequest&) = delete;
374 Key_Share_HelloRetryRequest& operator=(const Key_Share_HelloRetryRequest&) = delete;
375
376 Key_Share_HelloRetryRequest(Key_Share_HelloRetryRequest&&) = default;
377 Key_Share_HelloRetryRequest& operator=(Key_Share_HelloRetryRequest&&) = default;
378
379 std::vector<uint8_t> serialize() const {
380 auto code = m_selected_group.wire_code();
381 return {get_byte<0>(code), get_byte<1>(code)};
382 }
383
384 Named_Group selected_group() const { return m_selected_group; }
385
386 std::vector<Named_Group> offered_groups() const {
387 throw Invalid_Argument("Hello Retry Request never offers any key exchange groups");
388 }
389
390 bool empty() const { return m_selected_group == Group_Params::NONE; }
391
392 private:
393 Named_Group m_selected_group;
394};
395
396} // namespace
397
398class Key_Share::Key_Share_Impl {
399 public:
400 using Key_Share_Type = std::variant<Key_Share_ClientHello, Key_Share_ServerHello, Key_Share_HelloRetryRequest>;
401
402 explicit Key_Share_Impl(Key_Share_Type ks) : key_share(std::move(ks)) {}
403
404 Key_Share_Type key_share; // NOLINT(*-non-private-member-variable*)
405};
406
407Key_Share::Key_Share(TLS_Data_Reader& reader, uint16_t extension_size, Handshake_Type message_type) {
408 if(message_type == Handshake_Type::ClientHello) {
409 m_impl = std::make_unique<Key_Share_Impl>(Key_Share_ClientHello(reader, extension_size));
410 } else if(message_type == Handshake_Type::HelloRetryRequest) {
411 // Connection_Side::Server
412 m_impl = std::make_unique<Key_Share_Impl>(Key_Share_HelloRetryRequest(reader, extension_size));
413 } else if(message_type == Handshake_Type::ServerHello) {
414 // Connection_Side::Server
415 m_impl = std::make_unique<Key_Share_Impl>(Key_Share_ServerHello(reader, extension_size));
416 } else {
417 throw Invalid_Argument(std::string("cannot create a Key_Share extension for message of type: ") +
418 handshake_type_to_string(message_type));
419 }
420}
421
422// ClientHello
424 m_impl(std::make_unique<Key_Share_Impl>(Key_Share_ClientHello(policy, cb, rng))) {}
425
426// HelloRetryRequest
428 m_impl(std::make_unique<Key_Share_Impl>(Key_Share_HelloRetryRequest(selected_group))) {}
429
430// ServerHello
432 const Key_Share& client_keyshare,
433 const Policy& policy,
434 Callbacks& cb,
436 m_impl(std::make_unique<Key_Share_Impl>(Key_Share_ServerHello(
437 selected_group, std::get<Key_Share_ClientHello>(client_keyshare.m_impl->key_share), policy, cb, rng))) {}
438
439Key_Share::~Key_Share() = default;
440
441std::vector<uint8_t> Key_Share::serialize(Connection_Side /*whoami*/) const {
442 return std::visit([](const auto& key_share) { return key_share.serialize(); }, m_impl->key_share);
443}
444
445bool Key_Share::empty() const {
446 return std::visit([](const auto& key_share) { return key_share.empty(); }, m_impl->key_share);
447}
448
450 const Key_Share& client_keyshare,
451 const Policy& policy,
452 Callbacks& cb,
454 return std::unique_ptr<Key_Share>(new Key_Share(selected_group, client_keyshare, policy, cb, rng));
455}
456
458 const Policy& policy,
459 Callbacks& cb,
461 return std::visit(overloaded{[&](Key_Share_ClientHello& ch, const Key_Share_ServerHello& sh) {
462 return ch.decapsulate(sh, policy, cb, rng);
463 },
464 [](const auto&, const auto&) -> secure_vector<uint8_t> {
465 throw Invalid_Argument(
466 "can only decapsulate in ClientHello Key_Share with a ServerHello Key_Share");
467 }},
468 m_impl->key_share,
469 server_keyshare.m_impl->key_share);
470}
471
472std::vector<Named_Group> Key_Share::offered_groups() const {
473 return std::visit([](const auto& keyshare) { return keyshare.offered_groups(); }, m_impl->key_share);
474}
475
477 return std::visit([](const auto& keyshare) { return keyshare.selected_group(); }, m_impl->key_share);
478}
479
481 return std::visit(
482 overloaded{[](Key_Share_ServerHello& server_keyshare) { return server_keyshare.take_shared_secret(); },
483 [](auto&) -> secure_vector<uint8_t> {
484 throw Invalid_Argument("Only the key share in Server Hello contains a shared secret");
485 }},
486 m_impl->key_share);
487}
488
489void Key_Share::retry_offer(const Key_Share& retry_request_keyshare,
490 const std::vector<Named_Group>& supported_groups,
491 Callbacks& cb,
493 std::visit(overloaded{[&](Key_Share_ClientHello& ch, const Key_Share_HelloRetryRequest& hrr) {
494 const auto selected = hrr.selected_group();
495 // RFC 8446 4.2.8
496 // [T]he selected_group field [MUST correspond] to a group which was provided in
497 // the "supported_groups" extension in the original ClientHello
498 if(!value_exists(supported_groups, selected) ||
499 !group_usable_in_version(selected, Protocol_Version::TLS_V13)) {
500 throw TLS_Exception(Alert::IllegalParameter, "group was not advertised as supported");
501 }
502
503 return ch.retry_offer(selected, cb, rng);
504 },
505 [](const auto&, const auto&) {
506 throw Invalid_Argument("can only retry with HelloRetryRequest on a ClientHello Key_Share");
507 }},
508 m_impl->key_share,
509 retry_request_keyshare.m_impl->key_share);
510}
511
512} // namespace Botan::TLS
#define BOTAN_ASSERT_NOMSG(expr)
Definition assert.h:82
#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:654
constexpr bool is_ecdh_named_curve() const
Definition tls_algos.h:177
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)
Definition tls_magic.cpp:15
bool group_usable_in_version(Group_Params group, Protocol_Version version)
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:182
Group_Params Named_Group
constexpr uint8_t get_byte(T input)
Definition loadstor.h:79
bool value_exists(const std::vector< T > &vec, const V &val)
Definition stl_util.h:44
std::vector< T, secure_allocator< T > > secure_vector
Definition secmem.h:128