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