Botan 3.4.0
Crypto and TLS for C&
tls_callbacks.h
Go to the documentation of this file.
1/*
2* TLS Callbacks
3* (C) 2016 Matthias Gierlings
4* 2016 Jack Lloyd
5* 2017 Harry Reimann, Rohde & Schwarz Cybersecurity
6* 2022 René Meusel, Rohde & Schwarz Cybersecurity
7*
8* Botan is released under the Simplified BSD License (see license.txt)
9*/
10
11#ifndef BOTAN_TLS_CALLBACKS_H_
12#define BOTAN_TLS_CALLBACKS_H_
13
14#include <botan/dl_group.h>
15#include <botan/ocsp.h>
16#include <botan/pubkey.h>
17#include <botan/tls_alert.h>
18#include <botan/tls_session.h>
19#include <chrono>
20#include <optional>
21
22namespace Botan {
23
24class Certificate_Store;
25class X509_Certificate;
26
27namespace OCSP {
28
29class Response;
30
31}
32
33namespace TLS {
34
35class Handshake_Message;
36class Policy;
37class Extensions;
38class Certificate_Status_Request;
39
40/**
41* Encapsulates the callbacks that a TLS channel will make which are due to
42* channel specific operations.
43*/
45 public:
46 virtual ~Callbacks() = default;
47
48 /**
49 * Mandatory callback: output function
50 * The channel will call this with data which needs to be sent to the peer
51 * (eg, over a socket or some other form of IPC). The array will be overwritten
52 * when the function returns so a copy must be made if the data cannot be
53 * sent immediately.
54 *
55 * @param data a contiguous data buffer to send
56 */
57 virtual void tls_emit_data(std::span<const uint8_t> data) = 0;
58
59 /**
60 * Mandatory callback: process application data
61 * Called when application data record is received from the peer.
62 * Again the array is overwritten immediately after the function returns.
63 *
64 * @param seq_no the underlying TLS/DTLS record sequence number
65 *
66 * @param data a contiguous data buffer containing the received record
67 */
68 virtual void tls_record_received(uint64_t seq_no, std::span<const uint8_t> data) = 0;
69
70 /**
71 * Mandatory callback: alert received
72 * Called when an alert is received from the peer
73 * If fatal, the connection is closing. If not fatal, the connection may
74 * still be closing (depending on the error and the peer).
75 *
76 * @param alert the source of the alert
77 */
78 virtual void tls_alert(Alert alert) = 0;
79
80 /**
81 * Optional callback: session established
82 * Called when a session is established. Throw an exception to abort
83 * the connection.
84 *
85 * @param session the session descriptor
86 */
87 virtual void tls_session_established(const Session_Summary& session) { BOTAN_UNUSED(session); }
88
89 /**
90 * Optional callback: session activated
91 * Called when a session is active and can be written to
92 */
93 virtual void tls_session_activated() {}
94
95 /**
96 * Optional callback: peer closed connection (sent a "close_notify" alert)
97 *
98 * The peer signaled that it wishes to shut down the connection. The
99 * application should not expect to receive any more data from the peer
100 * and may tear down the underlying transport socket.
101 *
102 * Prior to TLS 1.3 it was required that peers discard pending writes
103 * and immediately respond with their own "close_notify". With TLS 1.3,
104 * applications can continue to send data despite the peer having already
105 * signaled their wish to shut down.
106 *
107 * Returning `true` will cause the TLS 1.3 implementation to write all
108 * pending data and then also signal a connection shut down. Otherwise
109 * the application is responsible to call the `Channel::close()` method.
110 *
111 * For TLS 1.2 the return value has no effect.
112 *
113 * @return true causes the implementation to respond with a "close_notify"
114 */
115 virtual bool tls_peer_closed_connection() { return true; }
116
117 /**
118 * Optional callback: Resumption information was received/established
119 *
120 * TLS 1.3 calls this when we sent or received a TLS 1.3 session ticket at
121 * any point after the initial handshake has finished.
122 *
123 * TLS 1.2 calls this when a session was established successfully and
124 * its resumption information may be stored for later usage.
125 *
126 * Note that for servers this is called as soon as resumption information
127 * is available and _could_ be sent to the client. If this callback
128 * returns 'false', the information will neither be cached nor sent.
129 *
130 * @param session the session descriptor
131 *
132 * @return false to prevent the resumption information from being cached,
133 * and true to cache it in the configured Session_Manager
134 */
135 virtual bool tls_should_persist_resumption_information(const Session& session);
136
137 /**
138 * Optional callback with default impl: verify cert chain
139 *
140 * Default implementation performs a standard PKIX validation
141 * and initiates network OCSP request for end-entity cert.
142 * Override to provide different behavior.
143 *
144 * Check the certificate chain is valid up to a trusted root, and
145 * optionally (if hostname != "") that the hostname given is
146 * consistent with the leaf certificate.
147 *
148 * This function should throw an exception derived from
149 * std::exception with an informative what() result if the
150 * certificate chain cannot be verified.
151 *
152 * @param cert_chain specifies a certificate chain leading to a
153 * trusted root CA certificate.
154 * @param ocsp_responses the server may have provided some
155 * @param trusted_roots the list of trusted certificates
156 * @param usage what this cert chain is being used for
157 * Usage_Type::TLS_SERVER_AUTH for server chains,
158 * Usage_Type::TLS_CLIENT_AUTH for client chains,
159 * Usage_Type::UNSPECIFIED for other uses
160 * @param hostname when authenticating a server, this is the hostname
161 * the client requested (eg via SNI). When authenticating a client,
162 * this is the server name the client is authenticating *to*.
163 * Empty in other cases or if no hostname was used.
164 * @param policy the TLS policy associated with the session being authenticated
165 * using the certificate chain
166 */
167 virtual void tls_verify_cert_chain(const std::vector<X509_Certificate>& cert_chain,
168 const std::vector<std::optional<OCSP::Response>>& ocsp_responses,
169 const std::vector<Certificate_Store*>& trusted_roots,
170 Usage_Type usage,
171 std::string_view hostname,
172 const TLS::Policy& policy);
173
174 /**
175 * Optional callback. Default impl always rejects.
176 *
177 * This allows using raw public keys for authentication of peers as
178 * described in RFC 7250 and RFC 8446 4.2.2. Applications that wish
179 * to use raw public keys MUST override this callback to verify the
180 * authenticity of the received public keys.
181 *
182 * Default implementation always rejects the raw public key.
183 *
184 * This function should throw an exception derived from
185 * std::exception with an informative what() result if the
186 * raw public key cannot be verified.
187 *
188 * @param raw_public_key specifies the raw public key to be used
189 * for peer authentication
190 * @param usage what this cert chain is being used for
191 * Usage_Type::TLS_SERVER_AUTH for server chains,
192 * Usage_Type::TLS_CLIENT_AUTH for client chains,
193 * @param hostname when authenticating a server, this is the hostname
194 * the client requested (eg via SNI). When authenticating a client,
195 * this is the server name the client is authenticating *to*.
196 * Empty in other cases or if no hostname was used.
197 * @param policy the TLS policy associated with the session being authenticated
198 * using the raw public key
199 */
200 virtual void tls_verify_raw_public_key(const Public_Key& raw_public_key,
201 Usage_Type usage,
202 std::string_view hostname,
203 const TLS::Policy& policy);
204
205 /**
206 * Called by default `tls_verify_cert_chain` to get the timeout to use for OCSP
207 * requests. Return 0 to disable online OCSP checks.
208 *
209 * This function should not be "const" since the implementation might need
210 * to perform some side effecting operation to compute the result.
211 */
212 virtual std::chrono::milliseconds tls_verify_cert_chain_ocsp_timeout() const {
213 return std::chrono::milliseconds(0);
214 }
215
216 /**
217 * Called by the TLS server whenever the client included the
218 * status_request extension (see RFC 6066, a.k.a OCSP stapling)
219 * in the ClientHello.
220 *
221 * @return the encoded OCSP response to be sent to the client which
222 * indicates the revocation status of the server certificate. Return an
223 * empty vector to indicate that no response is available, and thus
224 * suppress the Certificate_Status message.
225 */
226 virtual std::vector<uint8_t> tls_provide_cert_status(const std::vector<X509_Certificate>& chain,
227 const Certificate_Status_Request& csr) {
228 BOTAN_UNUSED(chain);
229 BOTAN_UNUSED(csr);
230 return std::vector<uint8_t>();
231 }
232
233 /**
234 * Called by TLS 1.3 client or server whenever the peer indicated that
235 * OCSP stapling is supported. In contrast to `tls_provide_cert_status`,
236 * this allows providing OCSP responses for each certificate in the chain.
237 *
238 * The default implementation invokes `tls_provide_cert_status` assuming
239 * that no OCSP responses for intermediate certificates are available.
240 *
241 * @return a vector of OCSP response buffers. An empty buffer indicates
242 * that no OCSP response should be provided for the respective
243 * certificate (at the same list index). The returned vector
244 * MUST be exactly the same length as the incoming \p chain.
245 */
246 virtual std::vector<std::vector<uint8_t>> tls_provide_cert_chain_status(
247 const std::vector<X509_Certificate>& chain, const Certificate_Status_Request& csr);
248
249 /**
250 * Optional callback with default impl: sign a message
251 *
252 * Default implementation uses PK_Signer::sign_message().
253 * Override to provide a different approach, e.g. using an external device.
254 *
255 * @param key the private key of the signer
256 * @param rng a random number generator
257 * @param padding the encoding method to be applied to the message
258 * @param format the signature format
259 * @param msg the input data for the signature
260 *
261 * @return the signature
262 */
263 virtual std::vector<uint8_t> tls_sign_message(const Private_Key& key,
265 std::string_view padding,
266 Signature_Format format,
267 const std::vector<uint8_t>& msg);
268
269 /**
270 * Optional callback with default impl: verify a message signature
271 *
272 * Default implementation uses PK_Verifier::verify_message().
273 * Override to provide a different approach, e.g. using an external device.
274 *
275 * @param key the public key of the signer
276 * @param padding the encoding method to be applied to the message
277 * @param format the signature format
278 * @param msg the input data for the signature
279 * @param sig the signature to be checked
280 *
281 * @return true if the signature is valid, false otherwise
282 */
283 virtual bool tls_verify_message(const Public_Key& key,
284 std::string_view padding,
285 Signature_Format format,
286 const std::vector<uint8_t>& msg,
287 const std::vector<uint8_t>& sig);
288
289 /**
290 * Generate an ephemeral KEM key for a TLS 1.3 handshake
291 *
292 * Applications may use this to add custom KEM algorithms or entirely
293 * different key exchange schemes to the TLS 1.3 handshake. For instance,
294 * this could provide an entry point to implement a hybrid key exchange
295 * with both a traditional algorithm like ECDH and a quantum-secure KEM.
296 * Typical use cases of the library don't need to do that and serious
297 * security risks are associated with customizing TLS's key encapsulation
298 * mechanism.
299 *
300 * Note that the KEM interface is usable for TLS 1.3 handshakes, only.
301 *
302 * The default implementation simply delegates this to the
303 * tls_generate_ephemeral_key() call when appropriate.
304 *
305 * @param group the group identifier to generate an ephemeral keypair for
306 * @param rng a random number generator
307 *
308 * @returns a keypair whose public key will be provided to the peer and
309 * the private key will be provided to tls_kem_decapsulate later
310 * in the handshake.
311 */
312 virtual std::unique_ptr<Private_Key> tls_kem_generate_key(TLS::Group_Params group, RandomNumberGenerator& rng);
313
314 /**
315 * Performs a key encapsulation operation (used for TLS 1.3 servers)
316 *
317 * Applications may use this to add custom KEM algorithms or entirely
318 * different key exchange schemes to the TLS 1.3 handshake. For instance,
319 * this could provide an entry point to implement a hybrid key exchange
320 * with both a traditional algorithm like ECDH and a quantum-secure KEM.
321 * Typical use cases of the library don't need to do that and serious
322 * security risks are associated with customizing TLS's key encapsulation
323 * mechanism.
324 *
325 * Note that the KEM interface is usable for TLS 1.3 handshakes, only.
326 *
327 * The default implementation implements this key encapsulation as a
328 * combination of tls_generate_ephemeral_key() followed by
329 * tls_ephemeral_key_agreement() with the provided @p encoded_public_key.
330 * The just-generated ephemeral private key is destroyed immediately.
331 *
332 * @param group the group identifier of the KEM/KEX algorithm
333 * @param encoded_public_key the public key used for encapsulation/KEX
334 * @param rng a random number generator
335 * @param policy a TLS policy object
336 *
337 * @returns the shared secret both in plaintext and encapsulated with
338 * @p encoded_public_key.
339 */
340 virtual KEM_Encapsulation tls_kem_encapsulate(TLS::Group_Params group,
341 const std::vector<uint8_t>& encoded_public_key,
343 const Policy& policy);
344
345 /**
346 * Performs a key decapsulation operation (used for TLS 1.3 clients).
347 *
348 * Applications may use this to add custom KEM algorithms or entirely
349 * different key exchange schemes to the TLS 1.3 handshake. For instance,
350 * this could provide an entry point to implement a hybrid key exchange
351 * with both a traditional algorithm like ECDH and a quantum-secure KEM.
352 * Typical use cases of the library don't need to do that and serious
353 * security risks are associated with customizing TLS's key encapsulation
354 * mechanism.
355 *
356 * Note that the KEM interface is usable for TLS 1.3 handshakes, only.
357 *
358 * The default implementation simply delegates this to the
359 * tls_ephemeral_key_agreement() callback to obtain the shared secret.
360 *
361 * @param group the group identifier of the KEM/KEX algorithm
362 * @param private_key the private key used for decapsulation/KEX
363 * @param encapsulated_bytes the content to decapsulate (or the public key share)
364 * @param rng a random number generator
365 * @param policy a TLS policy object
366 *
367 * @returns the plaintext shared secret from @p encapsulated_bytes after
368 * decapsulation with @p private_key.
369 */
370 virtual secure_vector<uint8_t> tls_kem_decapsulate(TLS::Group_Params group,
371 const Private_Key& private_key,
372 const std::vector<uint8_t>& encapsulated_bytes,
374 const Policy& policy);
375
376 /**
377 * Generate an ephemeral key pair for the TLS handshake.
378 *
379 * Applications may use this to add custom groups, curves or entirely
380 * different ephemeral key agreement mechanisms to the TLS handshake.
381 * Note that this callback must be used in conjunction with
382 * Callbacks::tls_ephemeral_key_agreement.
383 *
384 * Typical use cases of the library don't need to do that and serious
385 * security risks are associated with customizing TLS's key exchange
386 * mechanism.
387 *
388 * @throws TLS_Exception(Alert::DecodeError) if the @p group is not known.
389 *
390 * @param group the group identifier to generate an ephemeral keypair for
391 * TLS 1.2 allows for specifying custom discrete logarithm
392 * parameters as part of the protocol. Hence the variant<>.
393 * @param rng a random number generator
394 *
395 * @return a private key of an algorithm usable for key agreement
396 */
397 virtual std::unique_ptr<PK_Key_Agreement_Key> tls_generate_ephemeral_key(
398 const std::variant<TLS::Group_Params, DL_Group>& group, RandomNumberGenerator& rng);
399
400 /**
401 * Agree on a shared secret with the peer's ephemeral public key for
402 * the TLS handshake.
403 *
404 * Applications may use this to add custom groups, curves or entirely
405 * different ephemeral key agreement mechanisms to the TLS handshake.
406 * Note that this callback must be used in conjunction with
407 * Callbacks::tls_generate_ephemeral_key.
408 *
409 * Typical use cases of the library don't need to do that and serious
410 * security risks are associated with customizing TLS's key exchange
411 * mechanism.
412 *
413 * @param group the TLS group identifier to be used
414 * TLS 1.2 allows for specifying custom discrete
415 * logarithm parameters as part of the protocol.
416 * Hence the variant<>.
417 * @param private_key the private key (generated ahead in tls_generate_ephemeral_key)
418 * @param public_value the public key exchange information received by the peer
419 * @param rng a random number generator
420 * @param policy a TLS policy object
421 *
422 * @return the shared secret derived from public_value and private_key
423 */
424 virtual secure_vector<uint8_t> tls_ephemeral_key_agreement(const std::variant<TLS::Group_Params, DL_Group>& group,
425 const PK_Key_Agreement_Key& private_key,
426 const std::vector<uint8_t>& public_value,
428 const Policy& policy);
429
430 /**
431 * Optional callback: inspect handshake message
432 * Throw an exception to abort the handshake.
433 * Default simply ignores the message.
434 *
435 * Note: On connections that negotiated TLS 1.3 this callback is also
436 * invoked for post-handshake messages.
437 *
438 * @param message the handshake message
439 */
440 virtual void tls_inspect_handshake_msg(const Handshake_Message& message);
441
442 /**
443 * Optional callback for server: choose ALPN protocol
444 *
445 * ALPN (RFC 7301) works by the client sending a list of application
446 * protocols it is willing to negotiate. The server then selects which
447 * protocol to use. RFC 7301 requires that if the server does not support
448 * any protocols offered by the client, then it should close the connection
449 * with an alert of no_application_protocol. Within this callback this would
450 * be done by throwing a TLS_Exception(Alert::NoApplicationProtocol)
451 *
452 * @param client_protos the vector of protocols the client is willing to negotiate
453 *
454 * @return the protocol selected by the server; if the empty string is
455 * returned, the server does not reply to the client ALPN extension.
456 *
457 * The default implementation returns the empty string, causing client
458 * ALPN to be ignored.
459 *
460 * It is highly recommended to support ALPN whenever possible to avoid
461 * cross-protocol attacks.
462 */
463 virtual std::string tls_server_choose_app_protocol(const std::vector<std::string>& client_protos);
464
465 /**
466 * Optional callback: examine/modify Extensions before sending.
467 *
468 * Both client and server will call this callback on the Extensions object
469 * before serializing it in the specific handshake message. This allows an
470 * application to modify which extensions are sent during the handshake.
471 *
472 * Default implementation does nothing.
473 *
474 * @param extn the extensions
475 * @param which_side will be Connection_Side::Client or Connection_Side::Server which is the current
476 * applications role in the exchange.
477 * @param which_message will state the handshake message type containing the extensions
478 */
479 virtual void tls_modify_extensions(Extensions& extn, Connection_Side which_side, Handshake_Type which_message);
480
481 /**
482 * Optional callback: examine peer extensions.
483 *
484 * Both client and server will call this callback with the Extensions
485 * object after receiving it from the peer. This allows examining the
486 * Extensions, for example to implement a custom extension. It also allows
487 * an application to require that a particular extension be implemented;
488 * throw an exception from this function to abort the handshake.
489 *
490 * Default implementation does nothing.
491 *
492 * @param extn the extensions
493 * @param which_side will be Connection_Side::Client if these are are the clients extensions (ie we are
494 * the server) or Connection_Side::Server if these are the server extensions (we are the client).
495 * @param which_message will state the handshake message type containing the extensions
496 */
497 virtual void tls_examine_extensions(const Extensions& extn,
498 Connection_Side which_side,
499 Handshake_Type which_message);
500
501 /**
502 * Optional callback: parse a single OCSP Response
503 *
504 * Note: Typically a user of the library would not want to override this
505 * callback. We provide this callback to be able to support OCSP
506 * related tests from BoringSSL's BoGo tests that provide unparsable
507 * responses.
508 *
509 * Default implementation tries to parse the provided raw OCSP response.
510 *
511 * This function should not throw an exception but return a std::nullopt
512 * if the OCSP response cannot be parsed.
513 *
514 * @param raw_response raw OCSP response buffer
515 * @returns the parsed OCSP response or std::nullopt on error
516 */
517 virtual std::optional<OCSP::Response> tls_parse_ocsp_response(const std::vector<uint8_t>& raw_response);
518
519 /**
520 * Optional callback: return peer network identity
521 *
522 * There is no expected or specified format. The only expectation is this
523 * function will return a unique value. For example returning the peer
524 * host IP and port.
525 *
526 * This is used to bind the DTLS cookie to a particular network identity.
527 * It is only called if the dtls-cookie-secret PSK is also defined.
528 */
529 virtual std::string tls_peer_network_identity();
530
531 /**
532 * Optional callback: return a custom time stamp value
533 *
534 * This allows the library user to specify a custom "now" timestamp when
535 * needed. By default it will use the current system clock time.
536 *
537 * Note that typical usages will not need to override this callback but it
538 * is useful for testing purposes to allow for deterministic test outcomes.
539 */
540 virtual std::chrono::system_clock::time_point tls_current_timestamp();
541
542 /**
543 * Optional callback: error logging. (not currently called)
544 * @param err An error message related to this connection.
545 */
546 virtual void tls_log_error(const char* err) { BOTAN_UNUSED(err); }
547
548 /**
549 * Optional callback: debug logging. (not currently called)
550 * @param what Some hopefully informative string
551 */
552 virtual void tls_log_debug(const char* what) { BOTAN_UNUSED(what); }
553
554 /**
555 * Optional callback: debug logging taking a buffer. (not currently called)
556 * @param descr What this buffer is
557 * @param val the bytes
558 * @param val_len length of val
559 */
560 virtual void tls_log_debug_bin(const char* descr, const uint8_t val[], size_t val_len) {
561 BOTAN_UNUSED(descr, val, val_len);
562 }
563};
564
565} // namespace TLS
566
567} // namespace Botan
568
569#endif
#define BOTAN_UNUSED
Definition assert.h:118
virtual std::vector< uint8_t > tls_provide_cert_status(const std::vector< X509_Certificate > &chain, const Certificate_Status_Request &csr)
virtual std::chrono::milliseconds tls_verify_cert_chain_ocsp_timeout() const
virtual void tls_session_established(const Session_Summary &session)
virtual ~Callbacks()=default
virtual void tls_log_debug(const char *what)
virtual void tls_session_activated()
virtual void tls_log_debug_bin(const char *descr, const uint8_t val[], size_t val_len)
virtual void tls_log_error(const char *err)
virtual void tls_record_received(uint64_t seq_no, std::span< const uint8_t > data)=0
virtual void tls_alert(Alert alert)=0
virtual bool tls_peer_closed_connection()
virtual void tls_emit_data(std::span< const uint8_t > data)=0
#define BOTAN_PUBLIC_API(maj, min)
Definition compiler.h:31
Usage_Type
Definition x509cert.h:22
std::vector< T, secure_allocator< T > > secure_vector
Definition secmem.h:61
Signature_Format
Definition pk_keys.h:31