Botan 3.14.1
Crypto and TLS for C&
msg_certificate_13.cpp
Go to the documentation of this file.
1/*
2* Certificate Message
3* (C) 2022 Jack Lloyd
4* 2022 Hannes Rantzsch, René Meusel - neXenio GmbH
5* 2023 René Meusel, Fabian Albert - Rohde & Schwarz Cybersecurity
6*
7* Botan is released under the Simplified BSD License (see license.txt)
8*/
9
10#include <botan/tls_messages_13.h>
11
12#include <botan/ber_dec.h>
13#include <botan/credentials_manager.h>
14#include <botan/ocsp.h>
15#include <botan/pk_algs.h>
16#include <botan/tls_alert.h>
17#include <botan/tls_callbacks.h>
18#include <botan/tls_exceptn.h>
19#include <botan/tls_extensions.h>
20#include <botan/tls_extensions_13.h>
21#include <botan/tls_policy.h>
22#include <botan/x509_key.h>
23#include <botan/internal/stl_util.h>
24#include <botan/internal/tls_reader.h>
25#include <algorithm>
26#include <iterator>
27#include <memory>
28
29namespace Botan::TLS {
30
31namespace {
32
33// RFC 8446 4.4.2.2
34// The certificate MUST allow the key to be used for signing (i.e.,
35// the digitalSignature bit MUST be set if the Key Usage extension is
36// present) [...]
37bool certificate_allows_signing(const X509_Certificate& cert) {
38 const auto constraints = cert.constraints();
39 if(constraints.empty()) {
40 return true;
41 }
42
43 return constraints.includes(Key_Constraints::DigitalSignature);
44}
45
46// RFC 7250 3.
47// The SubjectPublicKeyInfo value in the Certificate payload MUST
48// contain the DER encoding [X.690] of the SubjectPublicKeyInfo.
49std::unique_ptr<Public_Key> decode_raw_public_key(std::span<const uint8_t> spki) {
50 AlgorithmIdentifier alg_id;
51 std::vector<uint8_t> key_bits;
52
53 BER_Decoder(spki, BER_Decoder::Limits::DER())
54 .start_sequence()
55 .decode(alg_id)
56 .decode_octet_aligned_bitstring(key_bits)
57 .end_cons()
58 .verify_end();
59
60 if(key_bits.empty()) {
61 throw Decoding_Error("Empty raw public key");
62 }
63
64 return load_public_key(alg_id, key_bits);
65}
66
67} // namespace
68
70 return !empty() && m_entries.front().has_certificate();
71}
72
74 return !empty() && !has_certificate_chain();
75}
76
77std::vector<X509_Certificate> Certificate_13::cert_chain() const {
79 std::vector<X509_Certificate> result;
80 std::transform(m_entries.cbegin(), m_entries.cend(), std::back_inserter(result), [](const auto& cert_entry) {
81 return cert_entry.certificate();
82 });
83 return result;
84}
85
86void Certificate_13::validate_extensions(const std::set<Extension_Code>& requested_extensions, Callbacks& cb) const {
87 // RFC 8446 4.4.2
88 // Extensions in the Certificate message from the server MUST
89 // correspond to ones from the ClientHello message. Extensions in
90 // the Certificate message from the client MUST correspond to
91 // extensions in the CertificateRequest message from the server.
92 for(const auto& entry : m_entries) {
93 if(entry.extensions().contains_other_than(requested_extensions)) {
94 throw TLS_Exception(Alert::IllegalParameter, "Certificate Entry contained an extension that was not offered");
95 }
96
97 cb.tls_examine_extensions(entry.extensions(), m_side, type());
98 }
99}
100
101std::shared_ptr<const Public_Key> Certificate_13::public_key() const {
103 return m_entries.front().public_key();
104}
105
108 return m_entries.front().certificate();
109}
110
112 const Policy& policy,
113 Credentials_Manager& creds,
114 std::string_view hostname,
115 bool use_ocsp) const {
117
118 // Without a certificate type extension the peer sends an X.509 chain,
119 // which the policy may not accept
121 const auto accepted_types = (m_side == Connection_Side::Client) ? policy.accepted_client_certificate_types()
123 if(!value_exists(accepted_types, cert_type)) {
124 throw TLS_Exception(Alert::UnsupportedCertificate,
125 "Peer sent a certificate of a type that is not accepted by the policy");
126 }
127
128 if(is_raw_public_key()) {
129 callbacks.tls_verify_raw_public_key(*public_key(), usage, hostname, policy);
130 } else {
131 verify_certificate_chain(callbacks, policy, creds, hostname, use_ocsp, usage);
132 }
133}
134
135void Certificate_13::verify_certificate_chain(Callbacks& callbacks,
136 const Policy& policy,
137 Credentials_Manager& creds,
138 std::string_view hostname,
139 bool use_ocsp,
140 Usage_Type usage_type) const {
141 std::vector<X509_Certificate> certs;
142 std::vector<std::optional<OCSP::Response>> ocsp_responses;
143 for(const auto& entry : m_entries) {
144 certs.push_back(entry.certificate());
145 if(use_ocsp) {
146 if(entry.extensions().has<Certificate_Status_Request>()) {
147 ocsp_responses.push_back(callbacks.tls_parse_ocsp_response(
148 entry.extensions().get<Certificate_Status_Request>()->get_ocsp_response()));
149 } else {
150 ocsp_responses.emplace_back();
151 }
152 }
153 }
154
155 const auto& server_cert = m_entries.front().certificate();
156 if(!certificate_allows_signing(server_cert)) {
157 throw TLS_Exception(Alert::BadCertificate, "Certificate usage constraints do not allow signing");
158 }
159
160 // Note that m_side represents the sender, so the usages here are swapped
161 const auto trusted_CAs = creds.trusted_certificate_authorities(
162 m_side == Connection_Side::Client ? "tls-server" : "tls-client", std::string(hostname));
163
164 callbacks.tls_verify_cert_chain(certs, ocsp_responses, trusted_CAs, usage_type, hostname, policy);
165}
166
167void Certificate_13::setup_entries(std::vector<X509_Certificate> cert_chain,
169 Callbacks& callbacks) {
170 // RFC 8446 4.4.2.1
171 // A server MAY request that a client present an OCSP response with its
172 // certificate by sending an empty "status_request" extension in its
173 // CertificateRequest message.
174 const auto ocsp_responses = (csr != nullptr) ? callbacks.tls_provide_cert_chain_status(cert_chain, *csr)
175 : std::vector<std::vector<uint8_t>>(cert_chain.size());
176
177 if(ocsp_responses.size() != cert_chain.size()) {
178 throw TLS_Exception(Alert::InternalError, "Application didn't provide the correct number of OCSP responses");
179 }
180
181 for(size_t i = 0; i < cert_chain.size(); ++i) {
182 auto& entry = m_entries.emplace_back(cert_chain[i]);
183 if(!ocsp_responses[i].empty()) {
184 entry.extensions().add(new Certificate_Status_Request(ocsp_responses[i])); // NOLINT(*-owning-memory)
185 }
186
187 // This will call the modification callback multiple times. Once for
188 // each certificate in the `cert_chain`. Users that want to add an
189 // extension to a specific Certificate Entry might have a hard time
190 // to distinguish them.
191 //
192 // TODO: Callbacks::tls_modify_extensions() might need even more
193 // context depending on the message whose extensions should be
194 // manipulatable.
195 callbacks.tls_modify_extensions(entry.extensions(), m_side, type());
196 }
197}
198
199void Certificate_13::setup_entry(std::shared_ptr<Public_Key> raw_public_key, Callbacks& callbacks) {
200 BOTAN_ASSERT_NONNULL(raw_public_key);
201 auto& entry = m_entries.emplace_back(std::move(raw_public_key));
202 callbacks.tls_modify_extensions(entry.extensions(), m_side, type());
203}
204
205/**
206 * Create a Client Certificate message
207 */
209 std::string_view hostname,
210 Credentials_Manager& credentials_manager,
211 Callbacks& callbacks,
212 Certificate_Type cert_type) :
213 m_request_context(cert_request.context()), m_side(Connection_Side::Client) {
214 // RFC 8446 4.4.2
215 // If the server requests client authentication but no suitable
216 // certificate is available, the client MUST send a Certificate message
217 // containing no certificates [...].
218 const auto key_types = filter_signature_schemes(cert_request.signature_schemes(), Protocol_Version::TLS_V13);
219 if(key_types.empty()) {
220 return;
221 }
222 const std::string op_type = "tls-client";
223
224 if(cert_type == Certificate_Type::X509) {
225 setup_entries(
226 credentials_manager.find_cert_chain(key_types,
228 cert_request.acceptable_CAs(),
229 op_type,
230 std::string(hostname)),
231 cert_request.extensions().get<Certificate_Status_Request>(),
232 callbacks);
233 } else if(cert_type == Certificate_Type::RawPublicKey) {
234 auto raw_public_key = credentials_manager.find_raw_public_key(key_types, op_type, std::string(hostname));
235
236 // RFC 8446 4.4.2
237 // If the RawPublicKey certificate type was negotiated, then the
238 // certificate_list MUST contain no more than one CertificateEntry
239 // [...].
240 // A client will send an empty certificate_list if it does not have
241 // an appropriate certificate to send in response to the server's
242 // authentication request.
243 if(raw_public_key) {
244 setup_entry(std::move(raw_public_key), callbacks);
245 }
246 }
247}
248
249/**
250 * Create a Server Certificate message
251 */
253 Credentials_Manager& credentials_manager,
254 Callbacks& callbacks,
255 Certificate_Type cert_type) :
256 // RFC 8446 4.4.2:
257 // [In the case of server authentication], the request context
258 // SHALL be zero length
259 m_request_context(/* NOLINT(*-redundant-member-init) */), m_side(Connection_Side::Server) {
260 /*
261 RFC 8446 4.2.3:
262 Clients which desire the server to authenticate itself via a
263 certificate MUST send the "signature_algorithms" extension. If a
264 server is authenticating via a certificate and the client has not sent
265 a "signature_algorithms" extension, then the server MUST abort the
266 handshake with a "missing_extension" alert.
267 */
268 if(!client_hello.extensions().has<Signature_Algorithms>()) {
269 throw TLS_Exception(Alert::MissingExtension, "Client Hello is missing required signature_algorithms extension");
270 }
271
272 const auto key_types = filter_signature_schemes(client_hello.signature_schemes(), Protocol_Version::TLS_V13);
273 if(key_types.empty()) {
274 throw TLS_Exception(Alert::HandshakeFailure, "Failed to agree on any signature algorithm");
275 }
276 const std::string op_type = "tls-server";
277 const std::string context = client_hello.sni_hostname();
278
279 if(cert_type == Certificate_Type::X509) {
280 // RFC 8446 4.2.4
281 // The "certificate_authorities" extension is used to indicate the
282 // certificate authorities (CAs) which an endpoint supports and which
283 // SHOULD be used by the receiving endpoint to guide certificate
284 // selection.
285 std::vector<X509_DN> acceptable_CAs;
286 if(const auto* cas = client_hello.extensions().get<Certificate_Authorities>()) {
287 acceptable_CAs = cas->distinguished_names();
288 }
289
290 auto cert_chain =
291 credentials_manager.find_cert_chain(key_types,
293 acceptable_CAs,
294 op_type,
295 context);
296
297 // RFC 8446 4.4.2
298 // The server's certificate_list MUST always be non-empty.
299 if(cert_chain.empty()) {
300 throw TLS_Exception(Alert::HandshakeFailure, "No sufficient server certificate available");
301 }
302
303 setup_entries(std::move(cert_chain), client_hello.extensions().get<Certificate_Status_Request>(), callbacks);
304 } else if(cert_type == Certificate_Type::RawPublicKey) {
305 auto raw_public_key = credentials_manager.find_raw_public_key(key_types, op_type, context);
306
307 // RFC 8446 4.4.2
308 // If the RawPublicKey certificate type was negotiated, then the
309 // certificate_list MUST contain no more than one CertificateEntry
310 // [...].
311 // The server's certificate_list MUST always be non-empty
312 if(!raw_public_key) {
313 throw TLS_Exception(Alert::HandshakeFailure, "No sufficient server raw public key available");
314 }
315
316 setup_entry(std::move(raw_public_key), callbacks);
317 }
318}
319
321 Connection_Side side,
322 Certificate_Type cert_type,
323 bool is_leaf) {
324 if(cert_type == Certificate_Type::X509) {
325 // RFC 8446 4.2.2
326 // [...] each CertificateEntry contains a DER-encoded X.509
327 // certificate.
328 const auto cert_bytes = reader.get_tls_length_value(3);
329 try {
330 m_certificate = std::make_unique<X509_Certificate>(cert_bytes);
331
332 // We only need the public key for the leaf
333 if(is_leaf) {
334 m_raw_public_key = m_certificate->subject_public_key();
335 }
336 } catch(Exception& e) {
337 // bad_certificate would make more sense but BoGo expects decoding_error
338 throw TLS_Exception(Alert::DecodeError, e.what());
339 }
340 } else if(cert_type == Certificate_Type::RawPublicKey) {
341 // RFC 7250 3.
342 // This specification uses raw public keys whereby the already
343 // available encoding used in a PKIX certificate in the form of a
344 // SubjectPublicKeyInfo structure is reused.
345 try {
346 m_raw_public_key = decode_raw_public_key(reader.get_tls_length_value(3));
347 } catch(Exception& e) {
348 throw TLS_Exception(Alert::DecodeError, e.what());
349 }
350 } else {
351 throw TLS_Exception(Alert::InternalError, "Unknown certificate type");
352 }
353
354 // Extensions are simply tacked at the end of the certificate entry. This
355 // is a departure from the typical "tag-length-value" in a sense that the
356 // Extensions deserializer needs the length value of the extensions.
357 const size_t extensions_length = reader.peek_uint16_t();
358 const auto exts_buf = reader.get_fixed<uint8_t>(extensions_length + 2);
359 TLS_Data_Reader exts_reader("extensions reader", exts_buf);
360 m_extensions.deserialize(exts_reader, side, Handshake_Type::Certificate);
361
362 if(cert_type == Certificate_Type::X509) {
363 // RFC 8446 4.4.2
364 // Valid extensions for server certificates at present include the
365 // OCSP Status extension [RFC6066] and the SignedCertificateTimestamp
366 // extension [RFC6962]; future extensions may be defined for this
367 // message as well.
368 //
369 // RFC 8446 4.4.2.1
370 // A server MAY request that a client present an OCSP response with its
371 // certificate by sending an empty "status_request" extension in its
372 // CertificateRequest message.
373 if(m_extensions.contains_implemented_extensions_other_than({
374 Extension_Code::CertificateStatusRequest,
375 // Extension_Code::SignedCertificateTimestamp
376 })) {
377 throw TLS_Exception(Alert::IllegalParameter, "Certificate Entry contained an extension that is not allowed");
378 }
379 } else if(m_extensions.contains_implemented_extensions_other_than({})) {
380 throw TLS_Exception(
381 Alert::IllegalParameter,
382 "Certificate Entry holding something else than a certificate contained unexpected extensions");
383 }
384}
385
387
390 Certificate_13::Certificate_Entry&& other) noexcept = default;
391
393 m_certificate(std::make_unique<X509_Certificate>(cert)), m_raw_public_key(m_certificate->subject_public_key()) {}
394
395Certificate_13::Certificate_Entry::Certificate_Entry(std::shared_ptr<Public_Key> raw_public_key) :
396 m_raw_public_key(std::move(raw_public_key)) {
397 BOTAN_ASSERT_NONNULL(m_raw_public_key);
398}
399
404
405std::shared_ptr<const Public_Key> Certificate_13::Certificate_Entry::public_key() const {
406 BOTAN_ASSERT_NONNULL(m_raw_public_key);
407 return m_raw_public_key;
408}
409
411 return (has_certificate()) ? m_certificate->BER_encode() : X509::BER_encode(*m_raw_public_key);
412}
413
414/**
415* Deserialize a Certificate message
416*/
417Certificate_13::Certificate_13(std::span<const uint8_t> buf,
418 const Policy& policy,
419 Connection_Side side,
420 Certificate_Type cert_type) :
421 m_side(side) {
422 TLS_Data_Reader reader("cert message reader", buf);
423
424 m_request_context = reader.get_range<uint8_t>(1, 0, 255);
425
426 // RFC 8446 4.4.2
427 // [...] in the case of server authentication, this field SHALL be zero length.
428 if(m_side == Connection_Side::Server && !m_request_context.empty()) {
429 throw TLS_Exception(Alert::IllegalParameter, "Server Certificate message must not contain a request context");
430 }
431
432 const auto cert_entries_len = reader.get_uint24_t();
433
434 if(reader.remaining_bytes() != cert_entries_len) {
435 throw TLS_Exception(Alert::DecodeError, "Certificate: Message malformed");
436 }
437
438 const size_t max_size = policy.maximum_certificate_chain_size();
439 if(max_size > 0 && cert_entries_len > max_size) {
440 throw Decoding_Error("Certificate chain exceeds policy specified maximum size");
441 }
442
443 while(reader.has_remaining()) {
444 const bool is_leaf = m_entries.empty();
445
446 // RFC 8446 4.4.2
447 // If the RawPublicKey certificate type was negotiated, then the
448 // certificate_list MUST contain no more than one CertificateEntry.
449 if(cert_type == Certificate_Type::RawPublicKey && !is_leaf) {
450 throw TLS_Exception(Alert::IllegalParameter, "Certificate message contained more than one RawPublicKey");
451 }
452
453 m_entries.emplace_back(reader, side, cert_type, is_leaf);
454 }
455
456 // RFC 8446 4.4.2
457 // The server's certificate_list MUST always be non-empty. A client
458 // will send an empty certificate_list if it does not have an
459 // appropriate certificate to send in response to the server's
460 // authentication request.
461 if(m_entries.empty()) {
462 // RFC 8446 4.4.2.4
463 // If the server supplies an empty Certificate message, the client MUST
464 // abort the handshake with a "decode_error" alert.
465 if(m_side == Connection_Side::Server) {
466 throw TLS_Exception(Alert::DecodeError, "No certificates sent by server");
467 }
468
469 return;
470 }
471
472 BOTAN_ASSERT_NOMSG(!m_entries.empty());
473
474 // RFC 8446 4.4.2.2
475 // The certificate type MUST be X.509v3 [RFC5280], unless explicitly
476 // negotiated otherwise (e.g., [RFC7250]).
477 //
478 // TLS 1.0 through 1.3 all seem to require that the certificate be
479 // precisely a v3 certificate. In fact the strict wording would seem
480 // to require that every certificate in the chain be v3. But often
481 // the intermediates are outside of the control of the server.
482 // But, require that the leaf certificate be v3.
483 if(cert_type == Certificate_Type::X509 && m_entries.front().certificate().x509_version() != 3) {
484 throw TLS_Exception(Alert::BadCertificate, "The leaf certificate must be v3");
485 }
486
487 // Validate the provided (certificate) public key against our policy
488 const auto pubkey = public_key();
489 policy.check_peer_key_acceptable(*pubkey);
490
491 if(!policy.allowed_signature_method(pubkey->algo_name())) {
492 throw TLS_Exception(Alert::HandshakeFailure, "Rejecting " + pubkey->algo_name() + " signature");
493 }
494}
495
496/**
497* Serialize a Certificate message
498*/
499std::vector<uint8_t> Certificate_13::serialize() const {
500 std::vector<uint8_t> buf;
501
502 append_tls_length_value(buf, m_request_context, 1);
503
504 std::vector<uint8_t> entries;
505 for(const auto& entry : m_entries) {
506 append_tls_length_value(entries, entry.serialize(), 3);
507
508 // Extensions are tacked at the end of certificate entries. Note that
509 // Extensions::serialize() usually emits the required length field,
510 // except when no extensions are added at all, then it returns an
511 // empty buffer.
512 //
513 // TODO: look into this issue more generally when overhauling the
514 // message marshalling.
515 const auto extensions = entry.extensions().serialize(m_side);
516 entries += (!extensions.empty()) ? extensions : std::vector<uint8_t>{0, 0};
517 }
518
519 append_tls_length_value(buf, entries, 3);
520
521 return buf;
522}
523
524} // namespace Botan::TLS
#define BOTAN_ASSERT_NOMSG(expr)
Definition assert.h:82
#define BOTAN_STATE_CHECK(expr)
Definition assert.h:49
#define BOTAN_ASSERT_NONNULL(ptr)
Definition assert.h:121
static Limits DER()
Definition ber_dec.h:44
virtual std::vector< Certificate_Store * > trusted_certificate_authorities(const std::string &type, const std::string &context)
virtual std::vector< X509_Certificate > find_cert_chain(const std::vector< std::string > &cert_key_types, const std::vector< AlgorithmIdentifier > &cert_signature_schemes, const std::vector< X509_DN > &acceptable_CAs, const std::string &type, const std::string &context)
virtual std::shared_ptr< Public_Key > find_raw_public_key(const std::vector< std::string > &key_types, const std::string &type, const std::string &context)
const char * what() const noexcept override
Definition exceptn.h:94
virtual std::optional< OCSP::Response > tls_parse_ocsp_response(const std::vector< uint8_t > &raw_response)
virtual void tls_examine_extensions(const Extensions &extn, Connection_Side which_side, Handshake_Type which_message)
virtual void tls_verify_raw_public_key(const Public_Key &raw_public_key, Usage_Type usage, std::string_view hostname, const TLS::Policy &policy)
virtual void tls_verify_cert_chain(const std::vector< X509_Certificate > &cert_chain, const std::vector< std::optional< OCSP::Response > > &ocsp_responses, const std::vector< Certificate_Store * > &trusted_roots, Usage_Type usage, std::string_view hostname, const TLS::Policy &policy)
Certificate_Entry & operator=(const Certificate_Entry &other)=delete
const X509_Certificate & certificate() const
std::shared_ptr< const Public_Key > public_key() const
~Certificate_Entry()
bool has_certificate() const
std::vector< uint8_t > serialize() const
Certificate_Entry(TLS_Data_Reader &reader, Connection_Side side, Certificate_Type cert_type, bool is_leaf)
const X509_Certificate & leaf() const
void validate_extensions(const std::set< Extension_Code > &requested_extensions, Callbacks &cb) const
std::shared_ptr< const Public_Key > public_key() const
Handshake_Type type() const override
void verify(Callbacks &callbacks, const Policy &policy, Credentials_Manager &creds, std::string_view hostname, bool use_ocsp) const
std::vector< uint8_t > serialize() const override
std::vector< X509_Certificate > cert_chain() const
Certificate_13(const Certificate_Request_13 &cert_request, std::string_view hostname, Credentials_Manager &credentials_manager, Callbacks &callbacks, Certificate_Type cert_type)
const std::vector< Signature_Scheme > & signature_schemes() const
const Extensions & extensions() const
const std::vector< Signature_Scheme > & certificate_signature_schemes() const
std::vector< X509_DN > acceptable_CAs() const
const std::vector< uint8_t > & get_ocsp_response() const
std::string sni_hostname() const
std::vector< Signature_Scheme > signature_schemes() const
const Extensions & extensions() const
std::vector< Signature_Scheme > certificate_signature_schemes() const
virtual void check_peer_key_acceptable(const Public_Key &public_key) const
virtual std::vector< Certificate_Type > accepted_server_certificate_types() const
virtual std::vector< Certificate_Type > accepted_client_certificate_types() const
bool allowed_signature_method(std::string_view sig_method) const
virtual size_t maximum_certificate_chain_size() const
std::vector< T > get_range(size_t len_bytes, size_t min_elems, size_t max_elems)
Definition tls_reader.h:115
size_t remaining_bytes() const
Definition tls_reader.h:37
std::vector< uint8_t > get_tls_length_value(size_t len_bytes)
Definition tls_reader.h:110
std::vector< T > get_fixed(size_t size)
Definition tls_reader.h:134
uint16_t peek_uint16_t() const
Definition tls_reader.h:78
std::vector< AlgorithmIdentifier > to_algorithm_identifiers(const std::vector< Signature_Scheme > &schemes)
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
std::vector< std::string > filter_signature_schemes(const std::vector< Signature_Scheme > &schemes, const Protocol_Version &version)
std::vector< uint8_t > BER_encode(const Public_Key &key)
Definition x509_key.h:24
bool value_exists(const std::vector< T > &vec, const V &val)
Definition stl_util.h:44
std::unique_ptr< Public_Key > load_public_key(const AlgorithmIdentifier &alg_id, std::span< const uint8_t > key_bits)
Definition pk_algs.cpp:130