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