2 * Copyright (c) 2016 Thomas Pornin <pornin@bolet.org>
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
19 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
20 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25 #ifndef BR_BEARSSL_SSL_H__
26 #define BR_BEARSSL_SSL_H__
31 #include "bearssl_block.h"
32 #include "bearssl_hash.h"
33 #include "bearssl_hmac.h"
34 #include "bearssl_prf.h"
35 #include "bearssl_rand.h"
36 #include "bearssl_x509.h"
38 /** \file bearssl_ssl.h
42 * For an overview of the SSL/TLS API, see [the BearSSL Web
43 * site](https://www.bearssl.org/api1.html).
45 * The `BR_TLS_*` constants correspond to the standard cipher suites and
46 * their values in the [IANA
47 * registry](http://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-4).
49 * The `BR_ALERT_*` constants are for standard TLS alert messages. When
50 * a fatal alert message is sent of received, then the SSL engine context
51 * status is set to the sum of that alert value (an integer in the 0..255
52 * range) and a fixed offset (`BR_ERR_SEND_FATAL_ALERT` for a sent alert,
53 * `BR_ERR_RECV_FATAL_ALERT` for a received alert).
56 /** \brief Optimal input buffer size. */
57 #define BR_SSL_BUFSIZE_INPUT (16384 + 325)
59 /** \brief Optimal output buffer size. */
60 #define BR_SSL_BUFSIZE_OUTPUT (16384 + 85)
62 /** \brief Optimal buffer size for monodirectional engine
63 (shared input/output buffer). */
64 #define BR_SSL_BUFSIZE_MONO BR_SSL_BUFSIZE_INPUT
66 /** \brief Optimal buffer size for bidirectional engine
67 (single buffer split into two separate input/output buffers). */
68 #define BR_SSL_BUFSIZE_BIDI (BR_SSL_BUFSIZE_INPUT + BR_SSL_BUFSIZE_OUTPUT)
71 * Constants for known SSL/TLS protocol versions (SSL 3.0, TLS 1.0, TLS 1.1
72 * and TLS 1.2). Note that though there is a constant for SSL 3.0, that
73 * protocol version is not actually supported.
76 /** \brief Protocol version: SSL 3.0 (unsupported). */
77 #define BR_SSL30 0x0300
78 /** \brief Protocol version: TLS 1.0. */
79 #define BR_TLS10 0x0301
80 /** \brief Protocol version: TLS 1.1. */
81 #define BR_TLS11 0x0302
82 /** \brief Protocol version: TLS 1.2. */
83 #define BR_TLS12 0x0303
86 * Error constants. They are used to report the reason why a context has
87 * been marked as failed.
89 * Implementation note: SSL-level error codes should be in the 1..31
90 * range. The 32..63 range is for certificate decoding and validation
91 * errors. Received fatal alerts imply an error code in the 256..511 range.
94 /** \brief SSL status: no error so far (0). */
97 /** \brief SSL status: caller-provided parameter is incorrect. */
98 #define BR_ERR_BAD_PARAM 1
100 /** \brief SSL status: operation requested by the caller cannot be applied
101 with the current context state (e.g. reading data while outgoing data
102 is waiting to be sent). */
103 #define BR_ERR_BAD_STATE 2
105 /** \brief SSL status: incoming protocol or record version is unsupported. */
106 #define BR_ERR_UNSUPPORTED_VERSION 3
108 /** \brief SSL status: incoming record version does not match the expected
110 #define BR_ERR_BAD_VERSION 4
112 /** \brief SSL status: incoming record length is invalid. */
113 #define BR_ERR_BAD_LENGTH 5
115 /** \brief SSL status: incoming record is too large to be processed, or
116 buffer is too small for the handshake message to send. */
117 #define BR_ERR_TOO_LARGE 6
119 /** \brief SSL status: decryption found an invalid padding, or the record
120 MAC is not correct. */
121 #define BR_ERR_BAD_MAC 7
123 /** \brief SSL status: no initial entropy was provided, and none can be
124 obtained from the OS. */
125 #define BR_ERR_NO_RANDOM 8
127 /** \brief SSL status: incoming record type is unknown. */
128 #define BR_ERR_UNKNOWN_TYPE 9
130 /** \brief SSL status: incoming record or message has wrong type with
131 regards to the current engine state. */
132 #define BR_ERR_UNEXPECTED 10
134 /** \brief SSL status: ChangeCipherSpec message from the peer has invalid
136 #define BR_ERR_BAD_CCS 12
138 /** \brief SSL status: alert message from the peer has invalid contents
140 #define BR_ERR_BAD_ALERT 13
142 /** \brief SSL status: incoming handshake message decoding failed. */
143 #define BR_ERR_BAD_HANDSHAKE 14
145 /** \brief SSL status: ServerHello contains a session ID which is larger
147 #define BR_ERR_OVERSIZED_ID 15
149 /** \brief SSL status: server wants to use a cipher suite that we did
150 not claim to support. This is also reported if we tried to advertise
151 a cipher suite that we do not support. */
152 #define BR_ERR_BAD_CIPHER_SUITE 16
154 /** \brief SSL status: server wants to use a compression that we did not
156 #define BR_ERR_BAD_COMPRESSION 17
158 /** \brief SSL status: server's max fragment length does not match
160 #define BR_ERR_BAD_FRAGLEN 18
162 /** \brief SSL status: secure renegotiation failed. */
163 #define BR_ERR_BAD_SECRENEG 19
165 /** \brief SSL status: server sent an extension type that we did not
166 announce, or used the same extension type several times in a single
168 #define BR_ERR_EXTRA_EXTENSION 20
170 /** \brief SSL status: invalid Server Name Indication contents (when
171 used by the server, this extension shall be empty). */
172 #define BR_ERR_BAD_SNI 21
174 /** \brief SSL status: invalid ServerHelloDone from the server (length
176 #define BR_ERR_BAD_HELLO_DONE 22
178 /** \brief SSL status: internal limit exceeded (e.g. server's public key
180 #define BR_ERR_LIMIT_EXCEEDED 23
182 /** \brief SSL status: Finished message from peer does not match the
184 #define BR_ERR_BAD_FINISHED 24
186 /** \brief SSL status: session resumption attempt with distinct version
188 #define BR_ERR_RESUME_MISMATCH 25
190 /** \brief SSL status: unsupported or invalid algorithm (ECDHE curve,
191 signature algorithm, hash function). */
192 #define BR_ERR_INVALID_ALGORITHM 26
194 /** \brief SSL status: invalid signature (on ServerKeyExchange from
195 server, or in CertificateVerify from client). */
196 #define BR_ERR_BAD_SIGNATURE 27
198 /** \brief SSL status: peer's public key does not have the proper type
199 or is not allowed for requested operation. */
200 #define BR_ERR_WRONG_KEY_USAGE 28
202 /** \brief SSL status: client did not send a certificate upon request,
203 or the client certificate could not be validated. */
204 #define BR_ERR_NO_CLIENT_AUTH 29
206 /** \brief SSL status: I/O error or premature close on underlying
207 transport stream. This error code is set only by the simplified
208 I/O API ("br_sslio_*"). */
211 /** \brief SSL status: base value for a received fatal alert.
213 When a fatal alert is received from the peer, the alert value
214 is added to this constant. */
215 #define BR_ERR_RECV_FATAL_ALERT 256
217 /** \brief SSL status: base value for a sent fatal alert.
219 When a fatal alert is sent to the peer, the alert value is added
221 #define BR_ERR_SEND_FATAL_ALERT 512
223 /* ===================================================================== */
226 * \brief Decryption engine for SSL.
228 * When processing incoming records, the SSL engine will use a decryption
229 * engine that uses a specific context structure, and has a set of
230 * methods (a vtable) that follows this template.
232 * The decryption engine is responsible for applying decryption, verifying
233 * MAC, and keeping track of the record sequence number.
235 typedef struct br_sslrec_in_class_ br_sslrec_in_class
;
236 struct br_sslrec_in_class_
{
238 * \brief Context size (in bytes).
243 * \brief Test validity of the incoming record length.
245 * This function returns 1 if the announced length for an
246 * incoming record is valid, 0 otherwise,
248 * \param ctx decryption engine context.
249 * \param record_len incoming record length.
250 * \return 1 of a valid length, 0 otherwise.
252 int (*check_length
)(const br_sslrec_in_class
*const *ctx
,
256 * \brief Decrypt the incoming record.
258 * This function may assume that the record length is valid
259 * (it has been previously tested with `check_length()`).
260 * Decryption is done in place; `*len` is updated with the
261 * cleartext length, and the address of the first plaintext
262 * byte is returned. If the record is correct but empty, then
263 * `*len` is set to 0 and a non-`NULL` pointer is returned.
265 * On decryption/MAC error, `NULL` is returned.
267 * \param ctx decryption engine context.
268 * \param record_type record type (23 for application data, etc).
269 * \param version record version.
270 * \param payload address of encrypted payload.
271 * \param len pointer to payload length (updated).
272 * \return pointer to plaintext, or `NULL` on error.
274 unsigned char *(*decrypt
)(const br_sslrec_in_class
**ctx
,
275 int record_type
, unsigned version
,
276 void *payload
, size_t *len
);
280 * \brief Encryption engine for SSL.
282 * When building outgoing records, the SSL engine will use an encryption
283 * engine that uses a specific context structure, and has a set of
284 * methods (a vtable) that follows this template.
286 * The encryption engine is responsible for applying encryption and MAC,
287 * and keeping track of the record sequence number.
289 typedef struct br_sslrec_out_class_ br_sslrec_out_class
;
290 struct br_sslrec_out_class_
{
292 * \brief Context size (in bytes).
297 * \brief Compute maximum plaintext sizes and offsets.
299 * When this function is called, the `*start` and `*end`
300 * values contain offsets designating the free area in the
301 * outgoing buffer for plaintext data; that free area is
302 * preceded by a 5-byte space which will receive the record
305 * The `max_plaintext()` function is responsible for adjusting
306 * both `*start` and `*end` to make room for any record-specific
307 * header, MAC, padding, and possible split.
309 * \param ctx encryption engine context.
310 * \param start pointer to start of plaintext offset (updated).
311 * \param end pointer to start of plaintext offset (updated).
313 void (*max_plaintext
)(const br_sslrec_out_class
*const *ctx
,
314 size_t *start
, size_t *end
);
317 * \brief Perform record encryption.
319 * This function encrypts the record. The plaintext address and
320 * length are provided. Returned value is the start of the
321 * encrypted record (or sequence of records, if a split was
322 * performed), _including_ the 5-byte header, and `*len` is
323 * adjusted to the total size of the record(s), there again
324 * including the header(s).
326 * \param ctx decryption engine context.
327 * \param record_type record type (23 for application data, etc).
328 * \param version record version.
329 * \param plaintext address of plaintext.
330 * \param len pointer to plaintext length (updated).
331 * \return pointer to start of built record.
333 unsigned char *(*encrypt
)(const br_sslrec_out_class
**ctx
,
334 int record_type
, unsigned version
,
335 void *plaintext
, size_t *len
);
339 * \brief Context for a no-encryption engine.
341 * The no-encryption engine processes outgoing records during the initial
342 * handshake, before encryption is applied.
345 /** \brief No-encryption engine vtable. */
346 const br_sslrec_out_class
*vtable
;
347 } br_sslrec_out_clear_context
;
349 /** \brief Static, constant vtable for the no-encryption engine. */
350 extern const br_sslrec_out_class br_sslrec_out_clear_vtable
;
352 /* ===================================================================== */
355 * \brief Record decryption engine class, for CBC mode.
357 * This class type extends the decryption engine class with an
358 * initialisation method that receives the parameters needed
359 * for CBC processing: block cipher implementation, block cipher key,
360 * HMAC parameters (hash function, key, MAC length), and IV. If the
361 * IV is `NULL`, then a per-record IV will be used (TLS 1.1+).
363 typedef struct br_sslrec_in_cbc_class_ br_sslrec_in_cbc_class
;
364 struct br_sslrec_in_cbc_class_
{
366 * \brief Superclass, as first vtable field.
368 br_sslrec_in_class inner
;
371 * \brief Engine initialisation method.
373 * This method sets the vtable field in the context.
375 * \param ctx context to initialise.
376 * \param bc_impl block cipher implementation (CBC decryption).
377 * \param bc_key block cipher key.
378 * \param bc_key_len block cipher key length (in bytes).
379 * \param dig_impl hash function for HMAC.
380 * \param mac_key HMAC key.
381 * \param mac_key_len HMAC key length (in bytes).
382 * \param mac_out_len HMAC output length (in bytes).
383 * \param iv initial IV (or `NULL`).
385 void (*init
)(const br_sslrec_in_cbc_class
**ctx
,
386 const br_block_cbcdec_class
*bc_impl
,
387 const void *bc_key
, size_t bc_key_len
,
388 const br_hash_class
*dig_impl
,
389 const void *mac_key
, size_t mac_key_len
, size_t mac_out_len
,
394 * \brief Record encryption engine class, for CBC mode.
396 * This class type extends the encryption engine class with an
397 * initialisation method that receives the parameters needed
398 * for CBC processing: block cipher implementation, block cipher key,
399 * HMAC parameters (hash function, key, MAC length), and IV. If the
400 * IV is `NULL`, then a per-record IV will be used (TLS 1.1+).
402 typedef struct br_sslrec_out_cbc_class_ br_sslrec_out_cbc_class
;
403 struct br_sslrec_out_cbc_class_
{
405 * \brief Superclass, as first vtable field.
407 br_sslrec_out_class inner
;
410 * \brief Engine initialisation method.
412 * This method sets the vtable field in the context.
414 * \param ctx context to initialise.
415 * \param bc_impl block cipher implementation (CBC encryption).
416 * \param bc_key block cipher key.
417 * \param bc_key_len block cipher key length (in bytes).
418 * \param dig_impl hash function for HMAC.
419 * \param mac_key HMAC key.
420 * \param mac_key_len HMAC key length (in bytes).
421 * \param mac_out_len HMAC output length (in bytes).
422 * \param iv initial IV (or `NULL`).
424 void (*init
)(const br_sslrec_out_cbc_class
**ctx
,
425 const br_block_cbcenc_class
*bc_impl
,
426 const void *bc_key
, size_t bc_key_len
,
427 const br_hash_class
*dig_impl
,
428 const void *mac_key
, size_t mac_key_len
, size_t mac_out_len
,
433 * \brief Context structure for decrypting incoming records with
436 * The first field points to the vtable. The other fields are opaque
437 * and shall not be accessed directly.
440 /** \brief Pointer to vtable. */
441 const br_sslrec_in_cbc_class
*vtable
;
442 #ifndef BR_DOXYGEN_IGNORE
445 const br_block_cbcdec_class
*vtable
;
446 br_aes_gen_cbcdec_keys aes
;
447 br_des_gen_cbcdec_keys des
;
449 br_hmac_key_context mac
;
451 unsigned char iv
[16];
454 } br_sslrec_in_cbc_context
;
457 * \brief Static, constant vtable for record decryption with CBC.
459 extern const br_sslrec_in_cbc_class br_sslrec_in_cbc_vtable
;
462 * \brief Context structure for encrypting outgoing records with
465 * The first field points to the vtable. The other fields are opaque
466 * and shall not be accessed directly.
469 /** \brief Pointer to vtable. */
470 const br_sslrec_out_cbc_class
*vtable
;
471 #ifndef BR_DOXYGEN_IGNORE
474 const br_block_cbcenc_class
*vtable
;
475 br_aes_gen_cbcenc_keys aes
;
476 br_des_gen_cbcenc_keys des
;
478 br_hmac_key_context mac
;
480 unsigned char iv
[16];
483 } br_sslrec_out_cbc_context
;
486 * \brief Static, constant vtable for record encryption with CBC.
488 extern const br_sslrec_out_cbc_class br_sslrec_out_cbc_vtable
;
490 /* ===================================================================== */
493 * \brief Record decryption engine class, for GCM mode.
495 * This class type extends the decryption engine class with an
496 * initialisation method that receives the parameters needed
497 * for GCM processing: block cipher implementation, block cipher key,
498 * GHASH implementation, and 4-byte IV.
500 typedef struct br_sslrec_in_gcm_class_ br_sslrec_in_gcm_class
;
501 struct br_sslrec_in_gcm_class_
{
503 * \brief Superclass, as first vtable field.
505 br_sslrec_in_class inner
;
508 * \brief Engine initialisation method.
510 * This method sets the vtable field in the context.
512 * \param ctx context to initialise.
513 * \param bc_impl block cipher implementation (CTR).
514 * \param key block cipher key.
515 * \param key_len block cipher key length (in bytes).
516 * \param gh_impl GHASH implementation.
517 * \param iv static IV (4 bytes).
519 void (*init
)(const br_sslrec_in_gcm_class
**ctx
,
520 const br_block_ctr_class
*bc_impl
,
521 const void *key
, size_t key_len
,
527 * \brief Record encryption engine class, for GCM mode.
529 * This class type extends the encryption engine class with an
530 * initialisation method that receives the parameters needed
531 * for GCM processing: block cipher implementation, block cipher key,
532 * GHASH implementation, and 4-byte IV.
534 typedef struct br_sslrec_out_gcm_class_ br_sslrec_out_gcm_class
;
535 struct br_sslrec_out_gcm_class_
{
537 * \brief Superclass, as first vtable field.
539 br_sslrec_out_class inner
;
542 * \brief Engine initialisation method.
544 * This method sets the vtable field in the context.
546 * \param ctx context to initialise.
547 * \param bc_impl block cipher implementation (CTR).
548 * \param key block cipher key.
549 * \param key_len block cipher key length (in bytes).
550 * \param gh_impl GHASH implementation.
551 * \param iv static IV (4 bytes).
553 void (*init
)(const br_sslrec_out_gcm_class
**ctx
,
554 const br_block_ctr_class
*bc_impl
,
555 const void *key
, size_t key_len
,
561 * \brief Context structure for processing records with GCM.
563 * The same context structure is used for encrypting and decrypting.
565 * The first field points to the vtable. The other fields are opaque
566 * and shall not be accessed directly.
569 /** \brief Pointer to vtable. */
572 const br_sslrec_in_gcm_class
*in
;
573 const br_sslrec_out_gcm_class
*out
;
575 #ifndef BR_DOXYGEN_IGNORE
578 const br_block_ctr_class
*vtable
;
579 br_aes_gen_ctr_keys aes
;
585 } br_sslrec_gcm_context
;
588 * \brief Static, constant vtable for record decryption with GCM.
590 extern const br_sslrec_in_gcm_class br_sslrec_in_gcm_vtable
;
593 * \brief Static, constant vtable for record encryption with GCM.
595 extern const br_sslrec_out_gcm_class br_sslrec_out_gcm_vtable
;
597 /* ===================================================================== */
600 * \brief Record decryption engine class, for ChaCha20+Poly1305.
602 * This class type extends the decryption engine class with an
603 * initialisation method that receives the parameters needed
604 * for ChaCha20+Poly1305 processing: ChaCha20 implementation,
605 * Poly1305 implementation, key, and 12-byte IV.
607 typedef struct br_sslrec_in_chapol_class_ br_sslrec_in_chapol_class
;
608 struct br_sslrec_in_chapol_class_
{
610 * \brief Superclass, as first vtable field.
612 br_sslrec_in_class inner
;
615 * \brief Engine initialisation method.
617 * This method sets the vtable field in the context.
619 * \param ctx context to initialise.
620 * \param ichacha ChaCha20 implementation.
621 * \param ipoly Poly1305 implementation.
622 * \param key secret key (32 bytes).
623 * \param iv static IV (12 bytes).
625 void (*init
)(const br_sslrec_in_chapol_class
**ctx
,
626 br_chacha20_run ichacha
,
627 br_poly1305_run ipoly
,
628 const void *key
, const void *iv
);
632 * \brief Record encryption engine class, for ChaCha20+Poly1305.
634 * This class type extends the encryption engine class with an
635 * initialisation method that receives the parameters needed
636 * for ChaCha20+Poly1305 processing: ChaCha20 implementation,
637 * Poly1305 implementation, key, and 12-byte IV.
639 typedef struct br_sslrec_out_chapol_class_ br_sslrec_out_chapol_class
;
640 struct br_sslrec_out_chapol_class_
{
642 * \brief Superclass, as first vtable field.
644 br_sslrec_out_class inner
;
647 * \brief Engine initialisation method.
649 * This method sets the vtable field in the context.
651 * \param ctx context to initialise.
652 * \param ichacha ChaCha20 implementation.
653 * \param ipoly Poly1305 implementation.
654 * \param key secret key (32 bytes).
655 * \param iv static IV (12 bytes).
657 void (*init
)(const br_sslrec_out_chapol_class
**ctx
,
658 br_chacha20_run ichacha
,
659 br_poly1305_run ipoly
,
660 const void *key
, const void *iv
);
664 * \brief Context structure for processing records with ChaCha20+Poly1305.
666 * The same context structure is used for encrypting and decrypting.
668 * The first field points to the vtable. The other fields are opaque
669 * and shall not be accessed directly.
672 /** \brief Pointer to vtable. */
675 const br_sslrec_in_chapol_class
*in
;
676 const br_sslrec_out_chapol_class
*out
;
678 #ifndef BR_DOXYGEN_IGNORE
680 unsigned char key
[32];
681 unsigned char iv
[12];
682 br_chacha20_run ichacha
;
683 br_poly1305_run ipoly
;
685 } br_sslrec_chapol_context
;
688 * \brief Static, constant vtable for record decryption with ChaCha20+Poly1305.
690 extern const br_sslrec_in_chapol_class br_sslrec_in_chapol_vtable
;
693 * \brief Static, constant vtable for record encryption with ChaCha20+Poly1305.
695 extern const br_sslrec_out_chapol_class br_sslrec_out_chapol_vtable
;
697 /* ===================================================================== */
700 * \brief Type for session parameters, to be saved for session resumption.
703 /** \brief Session ID buffer. */
704 unsigned char session_id
[32];
705 /** \brief Session ID length (in bytes, at most 32). */
706 unsigned char session_id_len
;
707 /** \brief Protocol version. */
709 /** \brief Cipher suite. */
710 uint16_t cipher_suite
;
711 /** \brief Master secret. */
712 unsigned char master_secret
[48];
713 } br_ssl_session_parameters
;
715 #ifndef BR_DOXYGEN_IGNORE
717 * Maximum numnber of cipher suites supported by a client or server.
719 #define BR_MAX_CIPHER_SUITES 40
723 * \brief Context structure for SSL engine.
725 * This strucuture is common to the client and server; both the client
726 * context (`br_ssl_client_context`) and the server context
727 * (`br_ssl_server_context`) include a `br_ssl_engine_context` as their
730 * The engine context manages records, including alerts, closures, and
731 * transitions to new encryption/MAC algorithms. Processing of handshake
732 * records is delegated to externally provided code. This structure
733 * should not be used directly.
735 * Structure contents are opaque and shall not be accessed directly.
738 #ifndef BR_DOXYGEN_IGNORE
740 * The error code. When non-zero, then the state is "failed" and
741 * no I/O may occur until reset.
746 * Configured I/O buffers. They are either disjoint, or identical.
748 unsigned char *ibuf
, *obuf
;
749 size_t ibuf_len
, obuf_len
;
752 * Maximum fragment length applies to outgoing records; incoming
753 * records can be processed as long as they fit in the input
754 * buffer. It is guaranteed that incoming records at least as big
755 * as max_frag_len can be processed.
757 uint16_t max_frag_len
;
758 unsigned char log_max_frag_len
;
759 unsigned char peer_log_max_frag_len
;
762 * Buffering management registers.
764 size_t ixa
, ixb
, ixc
;
765 size_t oxa
, oxb
, oxc
;
766 unsigned char iomode
;
767 unsigned char incrypt
;
770 * Shutdown flag: when set to non-zero, incoming record bytes
771 * will not be accepted anymore. This is used after a close_notify
772 * has been received: afterwards, the engine no longer claims that
773 * it could receive bytes from the transport medium.
775 unsigned char shutdown_recv
;
778 * 'record_type_in' is set to the incoming record type when the
779 * record header has been received.
780 * 'record_type_out' is used to make the next outgoing record
781 * header when it is ready to go.
783 unsigned char record_type_in
, record_type_out
;
786 * When a record is received, its version is extracted:
787 * -- if 'version_in' is 0, then it is set to the received version;
788 * -- otherwise, if the received version is not identical to
789 * the 'version_in' contents, then a failure is reported.
791 * This implements the SSL requirement that all records shall
792 * use the negotiated protocol version, once decided (in the
793 * ServerHello). It is up to the handshake handler to adjust this
794 * field when necessary.
799 * 'version_out' is used when the next outgoing record is ready
802 uint16_t version_out
;
805 * Record handler contexts.
808 const br_sslrec_in_class
*vtable
;
809 br_sslrec_in_cbc_context cbc
;
810 br_sslrec_gcm_context gcm
;
811 br_sslrec_chapol_context chapol
;
814 const br_sslrec_out_class
*vtable
;
815 br_sslrec_out_clear_context clear
;
816 br_sslrec_out_cbc_context cbc
;
817 br_sslrec_gcm_context gcm
;
818 br_sslrec_chapol_context chapol
;
822 * The "application data" flag. It is set when application data
823 * can be exchanged, cleared otherwise.
825 unsigned char application_data
;
830 br_hmac_drbg_context rng
;
832 int rng_os_rand_done
;
835 * Supported minimum and maximum versions, and cipher suites.
837 uint16_t version_min
;
838 uint16_t version_max
;
839 uint16_t suites_buf
[BR_MAX_CIPHER_SUITES
];
840 unsigned char suites_num
;
843 * For clients, the server name to send as a SNI extension. For
844 * servers, the name received in the SNI extension (if any).
846 char server_name
[256];
849 * "Security parameters". These are filled by the handshake
850 * handler, and used when switching encryption state.
852 unsigned char client_random
[32];
853 unsigned char server_random
[32];
854 br_ssl_session_parameters session
;
857 * ECDHE elements: curve and point from the peer. The server also
858 * uses that buffer for the point to send to the client.
860 unsigned char ecdhe_curve
;
861 unsigned char ecdhe_point
[133];
862 unsigned char ecdhe_point_len
;
865 * Secure renegotiation (RFC 5746): 'reneg' can be:
866 * 0 first handshake (server support is not known)
867 * 1 server does not support secure renegotiation
868 * 2 server supports secure renegotiation
870 * The saved_finished buffer contains the client and the
871 * server "Finished" values from the last handshake, in
872 * that order (12 bytes each).
875 unsigned char saved_finished
[24];
883 * Context variables for the handshake processor. The 'pad' must
884 * be large enough to accommodate an RSA-encrypted pre-master
885 * secret, or an RSA signature; since we want to support up to
886 * RSA-4096, this means at least 512 bytes. (Other pad usages
887 * require its length to be at least 256.)
892 const unsigned char *ip
;
894 uint32_t dp_stack
[32];
895 uint32_t rp_stack
[32];
896 unsigned char pad
[512];
897 unsigned char *hbuf_in
, *hbuf_out
, *saved_hbuf_out
;
898 size_t hlen_in
, hlen_out
;
899 void (*hsrun
)(void *ctx
);
902 * The 'action' value communicates OOB information between the
903 * engine and the handshake processor.
906 * 0 invocation triggered by I/O
907 * 1 invocation triggered by explicit close
908 * 2 invocation triggered by explicit renegotiation
910 unsigned char action
;
913 * State for alert messages. Value is either 0, or the value of
914 * the alert level byte (level is either 1 for warning, or 2 for
915 * fatal; we convert all other values to 'fatal').
920 * Closure flags. This flag is set when a close_notify has been
921 * received from the peer.
923 unsigned char close_received
;
926 * Multi-hasher for the handshake messages. The handshake handler
927 * is responsible for resetting it when appropriate.
929 br_multihash_context mhash
;
932 * Pointer to the X.509 engine. The engine is supposed to be
933 * already initialized. It is used to validate the peer's
936 const br_x509_class
**x509ctx
;
939 * Certificate chain to send. This is used by both client and
940 * server, when they send their respective Certificate messages.
941 * If chain_len is 0, then chain may be NULL.
943 const br_x509_certificate
*chain
;
945 const unsigned char *cert_cur
;
949 * List of supported protocol names (ALPN extension). If unset,
950 * (number of names is 0), then:
951 * - the client sends no ALPN extension;
952 * - the server ignores any incoming ALPN extension.
955 * - the client sends an ALPN extension with all the names;
956 * - the server selects the first protocol in its list that
957 * the client also supports, or fails (fatal alert 120)
958 * if the client sends an ALPN extension and there is no
961 * The 'selected_protocol' field contains 1+n if the matching
962 * name has index n in the list (the value is 0 if no match was
963 * performed, e.g. the peer did not send an ALPN extension).
965 const char **protocol_names
;
966 uint16_t protocol_names_num
;
967 uint16_t selected_protocol
;
970 * Pointers to implementations; left to NULL for unsupported
971 * functions. For the raw hash functions, implementations are
972 * referenced from the multihasher (mhash field).
974 br_tls_prf_impl prf10
;
975 br_tls_prf_impl prf_sha256
;
976 br_tls_prf_impl prf_sha384
;
977 const br_block_cbcenc_class
*iaes_cbcenc
;
978 const br_block_cbcdec_class
*iaes_cbcdec
;
979 const br_block_ctr_class
*iaes_ctr
;
980 const br_block_cbcenc_class
*ides_cbcenc
;
981 const br_block_cbcdec_class
*ides_cbcdec
;
983 br_chacha20_run ichacha
;
984 br_poly1305_run ipoly
;
985 const br_sslrec_in_cbc_class
*icbc_in
;
986 const br_sslrec_out_cbc_class
*icbc_out
;
987 const br_sslrec_in_gcm_class
*igcm_in
;
988 const br_sslrec_out_gcm_class
*igcm_out
;
989 const br_sslrec_in_chapol_class
*ichapol_in
;
990 const br_sslrec_out_chapol_class
*ichapol_out
;
991 const br_ec_impl
*iec
;
992 br_rsa_pkcs1_vrfy irsavrfy
;
993 br_ecdsa_vrfy iecdsa
;
995 } br_ssl_engine_context
;
998 * \brief Get currently defined engine behavioural flags.
1000 * \param cc SSL engine context.
1001 * \return the flags.
1003 static inline uint32_t
1004 br_ssl_engine_get_flags(br_ssl_engine_context
*cc
)
1010 * \brief Set all engine behavioural flags.
1012 * \param cc SSL engine context.
1013 * \param flags new value for all flags.
1016 br_ssl_engine_set_all_flags(br_ssl_engine_context
*cc
, uint32_t flags
)
1022 * \brief Set some engine behavioural flags.
1024 * The flags set in the `flags` parameter are set in the context; other
1025 * flags are untouched.
1027 * \param cc SSL engine context.
1028 * \param flags additional set flags.
1031 br_ssl_engine_add_flags(br_ssl_engine_context
*cc
, uint32_t flags
)
1037 * \brief Clear some engine behavioural flags.
1039 * The flags set in the `flags` parameter are cleared from the context; other
1040 * flags are untouched.
1042 * \param cc SSL engine context.
1043 * \param flags flags to remove.
1046 br_ssl_engine_remove_flags(br_ssl_engine_context
*cc
, uint32_t flags
)
1048 cc
->flags
&= ~flags
;
1052 * \brief Behavioural flag: enforce server preferences.
1054 * If this flag is set, then the server will enforce its own cipher suite
1055 * preference order; otherwise, it follows the client preferences.
1057 #define BR_OPT_ENFORCE_SERVER_PREFERENCES ((uint32_t)1 << 0)
1060 * \brief Behavioural flag: disable renegotiation.
1062 * If this flag is set, then renegotiations are rejected unconditionally:
1063 * they won't be honoured if asked for programmatically, and requests from
1064 * the peer are rejected.
1066 #define BR_OPT_NO_RENEGOTIATION ((uint32_t)1 << 1)
1069 * \brief Behavioural flag: tolerate lack of client authentication.
1071 * If this flag is set in a server and the server requests a client
1072 * certificate, but the authentication fails (the client does not send
1073 * a certificate, or the client's certificate chain cannot be validated),
1074 * then the connection keeps on. Without this flag, a failed client
1075 * authentication terminates the connection.
1079 * - If the client's certificate can be validated and its public key is
1080 * supported, then a wrong signature value terminates the connection
1081 * regardless of that flag.
1083 * - If using full-static ECDH, then a failure to validate the client's
1084 * certificate prevents the handshake from succeeding.
1086 #define BR_OPT_TOLERATE_NO_CLIENT_AUTH ((uint32_t)1 << 2)
1089 * \brief Behavioural flag: fail on application protocol mismatch.
1091 * The ALPN extension ([RFC 7301](https://tools.ietf.org/html/rfc7301))
1092 * allows the client to send a list of application protocol names, and
1093 * the server to select one. A mismatch is one of the following occurrences:
1095 * - On the client: the client sends a list of names, the server
1096 * responds with a protocol name which is _not_ part of the list of
1097 * names sent by the client.
1099 * - On the server: the client sends a list of names, and the server
1100 * is also configured with a list of names, but there is no common
1101 * protocol name between the two lists.
1103 * Normal behaviour in case of mismatch is to report no matching name
1104 * (`br_ssl_engine_get_selected_protocol()` returns `NULL`) and carry on.
1105 * If the flag is set, then a mismatch implies a protocol failure (if
1106 * the mismatch is detected by the server, it will send a fatal alert).
1108 * Note: even with this flag, `br_ssl_engine_get_selected_protocol()`
1109 * may still return `NULL` if the client or the server does not send an
1110 * ALPN extension at all.
1112 #define BR_OPT_FAIL_ON_ALPN_MISMATCH ((uint32_t)1 << 3)
1115 * \brief Set the minimum and maximum supported protocol versions.
1117 * The two provided versions MUST be supported by the implementation
1118 * (i.e. TLS 1.0, 1.1 and 1.2), and `version_max` MUST NOT be lower
1119 * than `version_min`.
1121 * \param cc SSL engine context.
1122 * \param version_min minimum supported TLS version.
1123 * \param version_max maximum supported TLS version.
1126 br_ssl_engine_set_versions(br_ssl_engine_context
*cc
,
1127 unsigned version_min
, unsigned version_max
)
1129 cc
->version_min
= version_min
;
1130 cc
->version_max
= version_max
;
1134 * \brief Set the list of cipher suites advertised by this context.
1136 * The provided array is copied into the context. It is the caller
1137 * responsibility to ensure that all provided suites will be supported
1138 * by the context. The engine context has enough room to receive _all_
1139 * suites supported by the implementation. The provided array MUST NOT
1140 * contain duplicates.
1142 * If the engine is for a client, the "signaling" pseudo-cipher suite
1143 * `TLS_FALLBACK_SCSV` can be added at the end of the list, if the
1144 * calling application is performing a voluntary downgrade (voluntary
1145 * downgrades are not recommended, but if such a downgrade is done, then
1146 * adding the fallback pseudo-suite is a good idea).
1148 * \param cc SSL engine context.
1149 * \param suites cipher suites.
1150 * \param suites_num number of cipher suites.
1152 void br_ssl_engine_set_suites(br_ssl_engine_context
*cc
,
1153 const uint16_t *suites
, size_t suites_num
);
1156 * \brief Set the X.509 engine.
1158 * The caller shall ensure that the X.509 engine is properly initialised.
1160 * \param cc SSL engine context.
1161 * \param x509ctx X.509 certificate validation context.
1164 br_ssl_engine_set_x509(br_ssl_engine_context
*cc
, const br_x509_class
**x509ctx
)
1166 cc
->x509ctx
= x509ctx
;
1170 * \brief Set the supported protocol names.
1172 * Protocol names are part of the ALPN extension ([RFC
1173 * 7301](https://tools.ietf.org/html/rfc7301)). Each protocol name is a
1174 * character string, containing no more than 255 characters (256 with the
1175 * terminating zero). When names are set, then:
1177 * - The client will send an ALPN extension, containing the names. If
1178 * the server responds with an ALPN extension, the client will verify
1179 * that the response contains one of its name, and report that name
1180 * through `br_ssl_engine_get_selected_protocol()`.
1182 * - The server will parse incoming ALPN extension (from clients), and
1183 * try to find a common protocol; if none is found, the connection
1184 * is aborted with a fatal alert. On match, a response ALPN extension
1185 * is sent, and name is reported through
1186 * `br_ssl_engine_get_selected_protocol()`.
1188 * The provided array is linked in, and must remain valid while the
1189 * connection is live.
1191 * Names MUST NOT be empty. Names MUST NOT be longer than 255 characters
1192 * (excluding the terminating 0).
1194 * \param ctx SSL engine context.
1195 * \param names list of protocol names (zero-terminated).
1196 * \param num number of protocol names (MUST be 1 or more).
1199 br_ssl_engine_set_protocol_names(br_ssl_engine_context
*ctx
,
1200 const char **names
, size_t num
)
1202 ctx
->protocol_names
= names
;
1203 ctx
->protocol_names_num
= num
;
1207 * \brief Get the selected protocol.
1209 * If this context was initialised with a non-empty list of protocol
1210 * names, and both client and server sent ALPN extensions during the
1211 * handshake, and a common name was found, then that name is returned.
1212 * Otherwise, `NULL` is returned.
1214 * The returned pointer is one of the pointers provided to the context
1215 * with `br_ssl_engine_set_protocol_names()`.
1217 * \return the selected protocol, or `NULL`.
1219 static inline const char *
1220 br_ssl_engine_get_selected_protocol(br_ssl_engine_context
*ctx
)
1224 k
= ctx
->selected_protocol
;
1225 return (k
== 0 || k
== 0xFFFF) ? NULL
: ctx
->protocol_names
[k
- 1];
1229 * \brief Set a hash function implementation (by ID).
1231 * Hash functions set with this call will be used for SSL/TLS specific
1232 * usages, not X.509 certificate validation. Only "standard" hash functions
1233 * may be set (MD5, SHA-1, SHA-224, SHA-256, SHA-384, SHA-512). If `impl`
1234 * is `NULL`, then the hash function support is removed, not added.
1236 * \param ctx SSL engine context.
1237 * \param id hash function identifier.
1238 * \param impl hash function implementation (or `NULL`).
1241 br_ssl_engine_set_hash(br_ssl_engine_context
*ctx
,
1242 int id
, const br_hash_class
*impl
)
1244 br_multihash_setimpl(&ctx
->mhash
, id
, impl
);
1248 * \brief Get a hash function implementation (by ID).
1250 * This function retrieves a hash function implementation which was
1251 * set with `br_ssl_engine_set_hash()`.
1253 * \param ctx SSL engine context.
1254 * \param id hash function identifier.
1255 * \return the hash function implementation (or `NULL`).
1257 static inline const br_hash_class
*
1258 br_ssl_engine_get_hash(br_ssl_engine_context
*ctx
, int id
)
1260 return br_multihash_getimpl(&ctx
->mhash
, id
);
1264 * \brief Set the PRF implementation (for TLS 1.0 and 1.1).
1266 * This function sets (or removes, if `impl` is `NULL`) the implemenation
1267 * for the PRF used in TLS 1.0 and 1.1.
1269 * \param cc SSL engine context.
1270 * \param impl PRF implementation (or `NULL`).
1273 br_ssl_engine_set_prf10(br_ssl_engine_context
*cc
, br_tls_prf_impl impl
)
1279 * \brief Set the PRF implementation with SHA-256 (for TLS 1.2).
1281 * This function sets (or removes, if `impl` is `NULL`) the implemenation
1282 * for the SHA-256 variant of the PRF used in TLS 1.2.
1284 * \param cc SSL engine context.
1285 * \param impl PRF implementation (or `NULL`).
1288 br_ssl_engine_set_prf_sha256(br_ssl_engine_context
*cc
, br_tls_prf_impl impl
)
1290 cc
->prf_sha256
= impl
;
1294 * \brief Set the PRF implementation with SHA-384 (for TLS 1.2).
1296 * This function sets (or removes, if `impl` is `NULL`) the implemenation
1297 * for the SHA-384 variant of the PRF used in TLS 1.2.
1299 * \param cc SSL engine context.
1300 * \param impl PRF implementation (or `NULL`).
1303 br_ssl_engine_set_prf_sha384(br_ssl_engine_context
*cc
, br_tls_prf_impl impl
)
1305 cc
->prf_sha384
= impl
;
1309 * \brief Set the AES/CBC implementations.
1311 * \param cc SSL engine context.
1312 * \param impl_enc AES/CBC encryption implementation (or `NULL`).
1313 * \param impl_dec AES/CBC decryption implementation (or `NULL`).
1316 br_ssl_engine_set_aes_cbc(br_ssl_engine_context
*cc
,
1317 const br_block_cbcenc_class
*impl_enc
,
1318 const br_block_cbcdec_class
*impl_dec
)
1320 cc
->iaes_cbcenc
= impl_enc
;
1321 cc
->iaes_cbcdec
= impl_dec
;
1325 * \brief Set the AES/CTR implementation.
1327 * \param cc SSL engine context.
1328 * \param impl AES/CTR encryption/decryption implementation (or `NULL`).
1331 br_ssl_engine_set_aes_ctr(br_ssl_engine_context
*cc
,
1332 const br_block_ctr_class
*impl
)
1334 cc
->iaes_ctr
= impl
;
1338 * \brief Set the DES/CBC implementations.
1340 * \param cc SSL engine context.
1341 * \param impl_enc DES/CBC encryption implementation (or `NULL`).
1342 * \param impl_dec DES/CBC decryption implementation (or `NULL`).
1345 br_ssl_engine_set_des_cbc(br_ssl_engine_context
*cc
,
1346 const br_block_cbcenc_class
*impl_enc
,
1347 const br_block_cbcdec_class
*impl_dec
)
1349 cc
->ides_cbcenc
= impl_enc
;
1350 cc
->ides_cbcdec
= impl_dec
;
1354 * \brief Set the GHASH implementation (used in GCM mode).
1356 * \param cc SSL engine context.
1357 * \param impl GHASH implementation (or `NULL`).
1360 br_ssl_engine_set_ghash(br_ssl_engine_context
*cc
, br_ghash impl
)
1366 * \brief Set the ChaCha20 implementation.
1368 * \param cc SSL engine context.
1369 * \param ichacha ChaCha20 implementation (or `NULL`).
1372 br_ssl_engine_set_chacha20(br_ssl_engine_context
*cc
,
1373 br_chacha20_run ichacha
)
1375 cc
->ichacha
= ichacha
;
1379 * \brief Set the Poly1305 implementation.
1381 * \param cc SSL engine context.
1382 * \param ipoly Poly1305 implementation (or `NULL`).
1385 br_ssl_engine_set_poly1305(br_ssl_engine_context
*cc
,
1386 br_poly1305_run ipoly
)
1392 * \brief Set the record encryption and decryption engines for CBC + HMAC.
1394 * \param cc SSL engine context.
1395 * \param impl_in record CBC decryption implementation (or `NULL`).
1396 * \param impl_out record CBC encryption implementation (or `NULL`).
1399 br_ssl_engine_set_cbc(br_ssl_engine_context
*cc
,
1400 const br_sslrec_in_cbc_class
*impl_in
,
1401 const br_sslrec_out_cbc_class
*impl_out
)
1403 cc
->icbc_in
= impl_in
;
1404 cc
->icbc_out
= impl_out
;
1408 * \brief Set the record encryption and decryption engines for GCM.
1410 * \param cc SSL engine context.
1411 * \param impl_in record GCM decryption implementation (or `NULL`).
1412 * \param impl_out record GCM encryption implementation (or `NULL`).
1415 br_ssl_engine_set_gcm(br_ssl_engine_context
*cc
,
1416 const br_sslrec_in_gcm_class
*impl_in
,
1417 const br_sslrec_out_gcm_class
*impl_out
)
1419 cc
->igcm_in
= impl_in
;
1420 cc
->igcm_out
= impl_out
;
1424 * \brief Set the record encryption and decryption engines for
1425 * ChaCha20+Poly1305.
1427 * \param cc SSL engine context.
1428 * \param impl_in record ChaCha20 decryption implementation (or `NULL`).
1429 * \param impl_out record ChaCha20 encryption implementation (or `NULL`).
1432 br_ssl_engine_set_chapol(br_ssl_engine_context
*cc
,
1433 const br_sslrec_in_chapol_class
*impl_in
,
1434 const br_sslrec_out_chapol_class
*impl_out
)
1436 cc
->ichapol_in
= impl_in
;
1437 cc
->ichapol_out
= impl_out
;
1441 * \brief Set the EC implementation.
1443 * The elliptic curve implementation will be used for ECDH and ECDHE
1444 * cipher suites, and for ECDSA support.
1446 * \param cc SSL engine context.
1447 * \param iec EC implementation (or `NULL`).
1450 br_ssl_engine_set_ec(br_ssl_engine_context
*cc
, const br_ec_impl
*iec
)
1456 * \brief Set the RSA signature verification implementation.
1458 * On the client, this is used to verify the server's signature on its
1459 * ServerKeyExchange message (for ECDHE_RSA cipher suites). On the server,
1460 * this is used to verify the client's CertificateVerify message (if a
1461 * client certificate is requested, and that certificate contains a RSA key).
1463 * \param cc SSL engine context.
1464 * \param irsavrfy RSA signature verification implementation.
1467 br_ssl_engine_set_rsavrfy(br_ssl_engine_context
*cc
, br_rsa_pkcs1_vrfy irsavrfy
)
1469 cc
->irsavrfy
= irsavrfy
;
1473 * \brief Set the ECDSA implementation (signature verification).
1475 * On the client, this is used to verify the server's signature on its
1476 * ServerKeyExchange message (for ECDHE_ECDSA cipher suites). On the server,
1477 * this is used to verify the client's CertificateVerify message (if a
1478 * client certificate is requested, that certificate contains an EC key,
1479 * and full-static ECDH is not used).
1481 * The ECDSA implementation will use the EC core implementation configured
1482 * in the engine context.
1484 * \param cc client context.
1485 * \param iecdsa ECDSA verification implementation.
1488 br_ssl_engine_set_ecdsa(br_ssl_engine_context
*cc
, br_ecdsa_vrfy iecdsa
)
1490 cc
->iecdsa
= iecdsa
;
1494 * \brief Set the I/O buffer for the SSL engine.
1496 * Once this call has been made, `br_ssl_client_reset()` or
1497 * `br_ssl_server_reset()` MUST be called before using the context.
1499 * The provided buffer will be used as long as the engine context is
1500 * used. The caller is responsible for keeping it available.
1502 * If `bidi` is 0, then the engine will operate in half-duplex mode
1503 * (it won't be able to send data while there is unprocessed incoming
1504 * data in the buffer, and it won't be able to receive data while there
1505 * is unsent data in the buffer). The optimal buffer size in half-duplex
1506 * mode is `BR_SSL_BUFSIZE_MONO`; if the buffer is larger, then extra
1507 * bytes are ignored. If the buffer is smaller, then this limits the
1508 * capacity of the engine to support all allowed record sizes.
1510 * If `bidi` is 1, then the engine will split the buffer into two
1511 * parts, for separate handling of outgoing and incoming data. This
1512 * enables full-duplex processing, but requires more RAM. The optimal
1513 * buffer size in full-duplex mode is `BR_SSL_BUFSIZE_BIDI`; if the
1514 * buffer is larger, then extra bytes are ignored. If the buffer is
1515 * smaller, then the split will favour the incoming part, so that
1516 * interoperability is maximised.
1518 * \param cc SSL engine context
1519 * \param iobuf I/O buffer.
1520 * \param iobuf_len I/O buffer length (in bytes).
1521 * \param bidi non-zero for full-duplex mode.
1523 void br_ssl_engine_set_buffer(br_ssl_engine_context
*cc
,
1524 void *iobuf
, size_t iobuf_len
, int bidi
);
1527 * \brief Set the I/O buffers for the SSL engine.
1529 * Once this call has been made, `br_ssl_client_reset()` or
1530 * `br_ssl_server_reset()` MUST be called before using the context.
1532 * This function is similar to `br_ssl_engine_set_buffer()`, except
1533 * that it enforces full-duplex mode, and the two I/O buffers are
1534 * provided as separate chunks.
1536 * The macros `BR_SSL_BUFSIZE_INPUT` and `BR_SSL_BUFSIZE_OUTPUT`
1537 * evaluate to the optimal (maximum) sizes for the input and output
1538 * buffer, respectively.
1540 * \param cc SSL engine context
1541 * \param ibuf input buffer.
1542 * \param ibuf_len input buffer length (in bytes).
1543 * \param obuf output buffer.
1544 * \param obuf_len output buffer length (in bytes).
1546 void br_ssl_engine_set_buffers_bidi(br_ssl_engine_context
*cc
,
1547 void *ibuf
, size_t ibuf_len
, void *obuf
, size_t obuf_len
);
1550 * \brief Inject some "initial entropy" in the context.
1552 * This entropy will be added to what can be obtained from the
1553 * underlying operating system, if that OS is supported.
1555 * This function may be called several times; all injected entropy chunks
1556 * are cumulatively mixed.
1558 * If entropy gathering from the OS is supported and compiled in, then this
1559 * step is optional. Otherwise, it is mandatory to inject randomness, and
1560 * the caller MUST take care to push (as one or several successive calls)
1561 * enough entropy to achieve cryptographic resistance (at least 80 bits,
1562 * preferably 128 or more). The engine will report an error if no entropy
1563 * was provided and none can be obtained from the OS.
1565 * Take care that this function cannot assess the cryptographic quality of
1566 * the provided bytes.
1568 * In all generality, "entropy" must here be considered to mean "that
1569 * which the attacker cannot predict". If your OS/architecture does not
1570 * have a suitable source of randomness, then you can make do with the
1571 * combination of a large enough secret value (possibly a copy of an
1572 * asymmetric private key that you also store on the system) AND a
1573 * non-repeating value (e.g. current time, provided that the local clock
1574 * cannot be reset or altered by the attacker).
1576 * \param cc SSL engine context.
1577 * \param data extra entropy to inject.
1578 * \param len length of the extra data (in bytes).
1580 void br_ssl_engine_inject_entropy(br_ssl_engine_context
*cc
,
1581 const void *data
, size_t len
);
1584 * \brief Get the "server name" in this engine.
1586 * For clients, this is the name provided with `br_ssl_client_reset()`;
1587 * for servers, this is the name received from the client as part of the
1588 * ClientHello message. If there is no such name (e.g. the client did
1589 * not send an SNI extension) then the returned string is empty
1590 * (returned pointer points to a byte of value 0).
1592 * The returned pointer refers to a buffer inside the context, which may
1593 * be overwritten as part of normal SSL activity (even within the same
1594 * connection, if a renegotiation occurs).
1596 * \param cc SSL engine context.
1597 * \return the server name (possibly empty).
1599 static inline const char *
1600 br_ssl_engine_get_server_name(const br_ssl_engine_context
*cc
)
1602 return cc
->server_name
;
1606 * \brief Get the protocol version.
1608 * This function returns the protocol version that is used by the
1609 * engine. That value is set after sending (for a server) or receiving
1610 * (for a client) the ServerHello message.
1612 * \param cc SSL engine context.
1613 * \return the protocol version.
1615 static inline unsigned
1616 br_ssl_engine_get_version(const br_ssl_engine_context
*cc
)
1618 return cc
->session
.version
;
1622 * \brief Get a copy of the session parameters.
1624 * The session parameters are filled during the handshake, so this
1625 * function shall not be called before completion of the handshake.
1626 * The initial handshake is completed when the context first allows
1627 * application data to be injected.
1629 * This function copies the current session parameters into the provided
1630 * structure. Beware that the session parameters include the master
1631 * secret, which is sensitive data, to handle with great care.
1633 * \param cc SSL engine context.
1634 * \param pp destination structure for the session parameters.
1637 br_ssl_engine_get_session_parameters(const br_ssl_engine_context
*cc
,
1638 br_ssl_session_parameters
*pp
)
1640 memcpy(pp
, &cc
->session
, sizeof *pp
);
1644 * \brief Set the session parameters to the provided values.
1646 * This function is meant to be used in the client, before doing a new
1647 * handshake; a session resumption will be attempted with these
1648 * parameters. In the server, this function has no effect.
1650 * \param cc SSL engine context.
1651 * \param pp source structure for the session parameters.
1654 br_ssl_engine_set_session_parameters(br_ssl_engine_context
*cc
,
1655 const br_ssl_session_parameters
*pp
)
1657 memcpy(&cc
->session
, pp
, sizeof *pp
);
1661 * \brief Get identifier for the curve used for key exchange.
1663 * If the cipher suite uses ECDHE, then this function returns the
1664 * identifier for the curve used for transient parameters. This is
1665 * defined during the course of the handshake, when the ServerKeyExchange
1666 * is sent (on the server) or received (on the client). If the
1667 * cipher suite does not use ECDHE (e.g. static ECDH, or RSA key
1668 * exchange), then this value is indeterminate.
1670 * @param cc SSL engine context.
1671 * @return the ECDHE curve identifier.
1674 br_ssl_engine_get_ecdhe_curve(br_ssl_engine_context
*cc
)
1676 return cc
->ecdhe_curve
;
1680 * \brief Get the current engine state.
1682 * An SSL engine (client or server) has, at any time, a state which is
1683 * the combination of zero, one or more of these flags:
1687 * Engine is finished, no more I/O (until next reset).
1689 * - `BR_SSL_SENDREC`
1691 * Engine has some bytes to send to the peer.
1693 * - `BR_SSL_RECVREC`
1695 * Engine expects some bytes from the peer.
1697 * - `BR_SSL_SENDAPP`
1699 * Engine may receive application data to send (or flush).
1701 * - `BR_SSL_RECVAPP`
1703 * Engine has obtained some application data from the peer,
1704 * that should be read by the caller.
1706 * If no flag at all is set (state value is 0), then the engine is not
1707 * fully initialised yet.
1709 * The `BR_SSL_CLOSED` flag is exclusive; when it is set, no other flag
1710 * is set. To distinguish between a normal closure and an error, use
1711 * `br_ssl_engine_last_error()`.
1713 * Generally speaking, `BR_SSL_SENDREC` and `BR_SSL_SENDAPP` are mutually
1714 * exclusive: the input buffer, at any point, either accumulates
1715 * plaintext data, or contains an assembled record that is being sent.
1716 * Similarly, `BR_SSL_RECVREC` and `BR_SSL_RECVAPP` are mutually exclusive.
1717 * This may change in a future library version.
1719 * \param cc SSL engine context.
1720 * \return the current engine state.
1722 unsigned br_ssl_engine_current_state(const br_ssl_engine_context
*cc
);
1724 /** \brief SSL engine state: closed or failed. */
1725 #define BR_SSL_CLOSED 0x0001
1726 /** \brief SSL engine state: record data is ready to be sent to the peer. */
1727 #define BR_SSL_SENDREC 0x0002
1728 /** \brief SSL engine state: engine may receive records from the peer. */
1729 #define BR_SSL_RECVREC 0x0004
1730 /** \brief SSL engine state: engine may accept application data to send. */
1731 #define BR_SSL_SENDAPP 0x0008
1732 /** \brief SSL engine state: engine has received application data. */
1733 #define BR_SSL_RECVAPP 0x0010
1736 * \brief Get the engine error indicator.
1738 * The error indicator is `BR_ERR_OK` (0) if no error was encountered
1739 * since the last call to `br_ssl_client_reset()` or
1740 * `br_ssl_server_reset()`. Other status values are "sticky": they
1741 * remain set, and prevent all I/O activity, until cleared. Only the
1742 * reset calls clear the error indicator.
1744 * \param cc SSL engine context.
1745 * \return 0, or a non-zero error code.
1748 br_ssl_engine_last_error(const br_ssl_engine_context
*cc
)
1754 * There are four I/O operations, each identified by a symbolic name:
1756 * sendapp inject application data in the engine
1757 * recvapp retrieving application data from the engine
1758 * sendrec sending records on the transport medium
1759 * recvrec receiving records from the transport medium
1761 * Terminology works thus: in a layered model where the SSL engine sits
1762 * between the application and the network, "send" designates operations
1763 * where bytes flow from application to network, and "recv" for the
1764 * reverse operation. Application data (the plaintext that is to be
1765 * conveyed through SSL) is "app", while encrypted records are "rec".
1766 * Note that from the SSL engine point of view, "sendapp" and "recvrec"
1767 * designate bytes that enter the engine ("inject" operation), while
1768 * "recvapp" and "sendrec" designate bytes that exit the engine
1769 * ("extract" operation).
1771 * For the operation 'xxx', two functions are defined:
1773 * br_ssl_engine_xxx_buf
1774 * Returns a pointer and length to the buffer to use for that
1775 * operation. '*len' is set to the number of bytes that may be read
1776 * from the buffer (extract operation) or written to the buffer
1777 * (inject operation). If no byte may be exchanged for that operation
1778 * at that point, then '*len' is set to zero, and NULL is returned.
1779 * The engine state is unmodified by this call.
1781 * br_ssl_engine_xxx_ack
1782 * Informs the engine that 'len' bytes have been read from the buffer
1783 * (extract operation) or written to the buffer (inject operation).
1784 * The 'len' value MUST NOT be zero. The 'len' value MUST NOT exceed
1785 * that which was obtained from a preceeding br_ssl_engine_xxx_buf()
1790 * \brief Get buffer for application data to send.
1792 * If the engine is ready to accept application data to send to the
1793 * peer, then this call returns a pointer to the buffer where such
1794 * data shall be written, and its length is written in `*len`.
1795 * Otherwise, `*len` is set to 0 and `NULL` is returned.
1797 * \param cc SSL engine context.
1798 * \param len receives the application data output buffer length, or 0.
1799 * \return the application data output buffer, or `NULL`.
1801 unsigned char *br_ssl_engine_sendapp_buf(
1802 const br_ssl_engine_context
*cc
, size_t *len
);
1805 * \brief Inform the engine of some new application data.
1807 * After writing `len` bytes in the buffer returned by
1808 * `br_ssl_engine_sendapp_buf()`, the application shall call this
1809 * function to trigger any relevant processing. The `len` parameter
1810 * MUST NOT be 0, and MUST NOT exceed the value obtained in the
1811 * `br_ssl_engine_sendapp_buf()` call.
1813 * \param cc SSL engine context.
1814 * \param len number of bytes pushed (not zero).
1816 void br_ssl_engine_sendapp_ack(br_ssl_engine_context
*cc
, size_t len
);
1819 * \brief Get buffer for received application data.
1821 * If the engine has received application data from the peer, hen this
1822 * call returns a pointer to the buffer from where such data shall be
1823 * read, and its length is written in `*len`. Otherwise, `*len` is set
1824 * to 0 and `NULL` is returned.
1826 * \param cc SSL engine context.
1827 * \param len receives the application data input buffer length, or 0.
1828 * \return the application data input buffer, or `NULL`.
1830 unsigned char *br_ssl_engine_recvapp_buf(
1831 const br_ssl_engine_context
*cc
, size_t *len
);
1834 * \brief Acknowledge some received application data.
1836 * After reading `len` bytes from the buffer returned by
1837 * `br_ssl_engine_recvapp_buf()`, the application shall call this
1838 * function to trigger any relevant processing. The `len` parameter
1839 * MUST NOT be 0, and MUST NOT exceed the value obtained in the
1840 * `br_ssl_engine_recvapp_buf()` call.
1842 * \param cc SSL engine context.
1843 * \param len number of bytes read (not zero).
1845 void br_ssl_engine_recvapp_ack(br_ssl_engine_context
*cc
, size_t len
);
1848 * \brief Get buffer for record data to send.
1850 * If the engine has prepared some records to send to the peer, then this
1851 * call returns a pointer to the buffer from where such data shall be
1852 * read, and its length is written in `*len`. Otherwise, `*len` is set
1853 * to 0 and `NULL` is returned.
1855 * \param cc SSL engine context.
1856 * \param len receives the record data output buffer length, or 0.
1857 * \return the record data output buffer, or `NULL`.
1859 unsigned char *br_ssl_engine_sendrec_buf(
1860 const br_ssl_engine_context
*cc
, size_t *len
);
1863 * \brief Acknowledge some sent record data.
1865 * After reading `len` bytes from the buffer returned by
1866 * `br_ssl_engine_sendrec_buf()`, the application shall call this
1867 * function to trigger any relevant processing. The `len` parameter
1868 * MUST NOT be 0, and MUST NOT exceed the value obtained in the
1869 * `br_ssl_engine_sendrec_buf()` call.
1871 * \param cc SSL engine context.
1872 * \param len number of bytes read (not zero).
1874 void br_ssl_engine_sendrec_ack(br_ssl_engine_context
*cc
, size_t len
);
1877 * \brief Get buffer for incoming records.
1879 * If the engine is ready to accept records from the peer, then this
1880 * call returns a pointer to the buffer where such data shall be
1881 * written, and its length is written in `*len`. Otherwise, `*len` is
1882 * set to 0 and `NULL` is returned.
1884 * \param cc SSL engine context.
1885 * \param len receives the record data input buffer length, or 0.
1886 * \return the record data input buffer, or `NULL`.
1888 unsigned char *br_ssl_engine_recvrec_buf(
1889 const br_ssl_engine_context
*cc
, size_t *len
);
1892 * \brief Inform the engine of some new record data.
1894 * After writing `len` bytes in the buffer returned by
1895 * `br_ssl_engine_recvrec_buf()`, the application shall call this
1896 * function to trigger any relevant processing. The `len` parameter
1897 * MUST NOT be 0, and MUST NOT exceed the value obtained in the
1898 * `br_ssl_engine_recvrec_buf()` call.
1900 * \param cc SSL engine context.
1901 * \param len number of bytes pushed (not zero).
1903 void br_ssl_engine_recvrec_ack(br_ssl_engine_context
*cc
, size_t len
);
1906 * \brief Flush buffered application data.
1908 * If some application data has been buffered in the engine, then wrap
1909 * it into a record and mark it for sending. If no application data has
1910 * been buffered but the engine would be ready to accept some, AND the
1911 * `force` parameter is non-zero, then an empty record is assembled and
1912 * marked for sending. In all other cases, this function does nothing.
1914 * Empty records are technically legal, but not all existing SSL/TLS
1915 * implementations support them. Empty records can be useful as a
1916 * transparent "keep-alive" mechanism to maintain some low-level
1919 * \param cc SSL engine context.
1920 * \param force non-zero to force sending an empty record.
1922 void br_ssl_engine_flush(br_ssl_engine_context
*cc
, int force
);
1925 * \brief Initiate a closure.
1927 * If, at that point, the context is open and in ready state, then a
1928 * `close_notify` alert is assembled and marked for sending; this
1929 * triggers the closure protocol. Otherwise, no such alert is assembled.
1931 * \param cc SSL engine context.
1933 void br_ssl_engine_close(br_ssl_engine_context
*cc
);
1936 * \brief Initiate a renegotiation.
1938 * If the engine is failed or closed, or if the peer is known not to
1939 * support secure renegotiation (RFC 5746), or if renegotiations have
1940 * been disabled with the `BR_OPT_NO_RENEGOTIATION` flag, then this
1941 * function returns 0 and nothing else happens.
1943 * Otherwise, this function returns 1, and a renegotiation attempt is
1944 * triggered (if a handshake is already ongoing at that point, then
1945 * no new handshake is triggered).
1947 * \param cc SSL engine context.
1948 * \return 1 on success, 0 on error.
1950 int br_ssl_engine_renegotiate(br_ssl_engine_context
*cc
);
1953 * Pre-declaration for the SSL client context.
1955 typedef struct br_ssl_client_context_ br_ssl_client_context
;
1958 * \brief Type for the client certificate, if requested by the server.
1962 * \brief Authentication type.
1964 * This is either `BR_AUTH_RSA` (RSA signature), `BR_AUTH_ECDSA`
1965 * (ECDSA signature), or `BR_AUTH_ECDH` (static ECDH key exchange).
1970 * \brief Hash function for computing the CertificateVerify.
1972 * This is the symbolic identifier for the hash function that
1973 * will be used to produce the hash of handshake messages, to
1974 * be signed into the CertificateVerify. For full static ECDH
1975 * (client and server certificates are both EC in the same
1976 * curve, and static ECDH is used), this value is set to -1.
1978 * Take care that with TLS 1.0 and 1.1, that value MUST match
1979 * the protocol requirements: value must be 0 (MD5+SHA-1) for
1980 * a RSA signature, or 2 (SHA-1) for an ECDSA signature. Only
1981 * TLS 1.2 allows for other hash functions.
1986 * \brief Certificate chain to send to the server.
1988 * This is an array of `br_x509_certificate` objects, each
1989 * normally containing a DER-encoded certificate. The client
1990 * code does not try to decode these elements. If there is no
1991 * chain to send to the server, then this pointer shall be
1994 const br_x509_certificate
*chain
;
1997 * \brief Certificate chain length (number of certificates).
1999 * If there is no chain to send to the server, then this value
2000 * shall be set to 0.
2004 } br_ssl_client_certificate
;
2007 * Note: the constants below for signatures match the TLS constants.
2010 /** \brief Client authentication type: static ECDH. */
2011 #define BR_AUTH_ECDH 0
2012 /** \brief Client authentication type: RSA signature. */
2013 #define BR_AUTH_RSA 1
2014 /** \brief Client authentication type: ECDSA signature. */
2015 #define BR_AUTH_ECDSA 3
2018 * \brief Class type for a certificate handler (client side).
2020 * A certificate handler selects a client certificate chain to send to
2021 * the server, upon explicit request from that server. It receives
2022 * the list of trust anchor DN from the server, and supported types
2023 * of certificates and signatures, and returns the chain to use. It
2024 * is also invoked to perform the corresponding private key operation
2025 * (a signature, or an ECDH computation).
2027 * The SSL client engine will first push the trust anchor DN with
2028 * `start_name_list()`, `start_name()`, `append_name()`, `end_name()`
2029 * and `end_name_list()`. Then it will call `choose()`, to select the
2030 * actual chain (and signature/hash algorithms). Finally, it will call
2031 * either `do_sign()` or `do_keyx()`, depending on the algorithm choices.
2033 typedef struct br_ssl_client_certificate_class_ br_ssl_client_certificate_class
;
2034 struct br_ssl_client_certificate_class_
{
2036 * \brief Context size (in bytes).
2038 size_t context_size
;
2041 * \brief Begin reception of a list of trust anchor names. This
2042 * is called while parsing the incoming CertificateRequest.
2044 * \param pctx certificate handler context.
2046 void (*start_name_list
)(const br_ssl_client_certificate_class
**pctx
);
2049 * \brief Begin reception of a new trust anchor name.
2051 * The total encoded name length is provided; it is less than
2054 * \param pctx certificate handler context.
2055 * \param len encoded name length (in bytes).
2057 void (*start_name
)(const br_ssl_client_certificate_class
**pctx
,
2061 * \brief Receive some more bytes for the current trust anchor name.
2063 * The provided reference (`data`) points to a transient buffer
2064 * they may be reused as soon as this function returns. The chunk
2065 * length (`len`) is never zero.
2067 * \param pctx certificate handler context.
2068 * \param data anchor name chunk.
2069 * \param len anchor name chunk length (in bytes).
2071 void (*append_name
)(const br_ssl_client_certificate_class
**pctx
,
2072 const unsigned char *data
, size_t len
);
2075 * \brief End current trust anchor name.
2077 * This function is called when all the encoded anchor name data
2078 * has been provided.
2080 * \param pctx certificate handler context.
2082 void (*end_name
)(const br_ssl_client_certificate_class
**pctx
);
2085 * \brief End list of trust anchor names.
2087 * This function is called when all the anchor names in the
2088 * CertificateRequest message have been obtained.
2090 * \param pctx certificate handler context.
2092 void (*end_name_list
)(const br_ssl_client_certificate_class
**pctx
);
2095 * \brief Select client certificate and algorithms.
2097 * This callback function shall fill the provided `choices`
2098 * structure with the selected algorithms and certificate chain.
2099 * The `hash_id`, `chain` and `chain_len` fields must be set. If
2100 * the client cannot or does not wish to send a certificate,
2101 * then it shall set `chain` to `NULL` and `chain_len` to 0.
2103 * The `auth_types` parameter describes the authentication types,
2104 * signature algorithms and hash functions that are supported by
2105 * both the client context and the server, and compatible with
2106 * the current protocol version. This is a bit field with the
2107 * following contents:
2109 * - If RSA signatures with hash function x are supported, then
2112 * - If ECDSA signatures with hash function x are supported,
2113 * then bit 8+x is set.
2115 * - If static ECDH is supported, with a RSA-signed certificate,
2116 * then bit 16 is set.
2118 * - If static ECDH is supported, with an ECDSA-signed certificate,
2119 * then bit 17 is set.
2123 * - When using TLS 1.0 or 1.1, the hash function for RSA
2124 * signatures is always the special MD5+SHA-1 (id 0), and the
2125 * hash function for ECDSA signatures is always SHA-1 (id 2).
2127 * - When using TLS 1.2, the list of hash functions is trimmed
2128 * down to include only hash functions that the client context
2129 * can support. The actual server list can be obtained with
2130 * `br_ssl_client_get_server_hashes()`; that list may be used
2131 * to select the certificate chain to send to the server.
2133 * \param pctx certificate handler context.
2134 * \param cc SSL client context.
2135 * \param auth_types supported authentication types and algorithms.
2136 * \param choices destination structure for the policy choices.
2138 void (*choose
)(const br_ssl_client_certificate_class
**pctx
,
2139 const br_ssl_client_context
*cc
, uint32_t auth_types
,
2140 br_ssl_client_certificate
*choices
);
2143 * \brief Perform key exchange (client part).
2145 * This callback is invoked in case of a full static ECDH key
2148 * - the cipher suite uses `ECDH_RSA` or `ECDH_ECDSA`;
2150 * - the server requests a client certificate;
2152 * - the client has, and sends, a client certificate that
2153 * uses an EC key in the same curve as the server's key,
2154 * and chooses static ECDH (the `hash_id` field in the choice
2155 * structure was set to -1).
2157 * In that situation, this callback is invoked to compute the
2158 * client-side ECDH: the provided `data` (of length `*len` bytes)
2159 * is the server's public key point (as decoded from its
2160 * certificate), and the client shall multiply that point with
2161 * its own private key, and write back the X coordinate of the
2162 * resulting point in the same buffer, starting at offset 0.
2163 * The `*len` value shall be modified to designate the actual
2164 * length of the X coordinate.
2166 * The callback must uphold the following:
2168 * - If the input array does not have the proper length for
2169 * an encoded curve point, then an error (0) shall be reported.
2171 * - If the input array has the proper length, then processing
2172 * MUST be constant-time, even if the data is not a valid
2175 * - This callback MUST check that the input point is valid.
2177 * Returned value is 1 on success, 0 on error.
2179 * \param pctx certificate handler context.
2180 * \param data server public key point.
2181 * \param len public key point length / X coordinate length.
2182 * \return 1 on success, 0 on error.
2184 uint32_t (*do_keyx
)(const br_ssl_client_certificate_class
**pctx
,
2185 unsigned char *data
, size_t *len
);
2188 * \brief Perform a signature (client authentication).
2190 * This callback is invoked when a client certificate was sent,
2191 * and static ECDH is not used. It shall compute a signature,
2192 * using the client's private key, over the provided hash value
2193 * (which is the hash of all previous handshake messages).
2195 * On input, the hash value to sign is in `data`, of size
2196 * `hv_len`; the involved hash function is identified by
2197 * `hash_id`. The signature shall be computed and written
2198 * back into `data`; the total size of that buffer is `len`
2201 * This callback shall verify that the signature length does not
2202 * exceed `len` bytes, and abstain from writing the signature if
2205 * For RSA signatures, the `hash_id` may be 0, in which case
2206 * this is the special header-less signature specified in TLS 1.0
2207 * and 1.1, with a 36-byte hash value. Otherwise, normal PKCS#1
2208 * v1.5 signatures shall be computed.
2210 * For ECDSA signatures, the signature value shall use the ASN.1
2213 * Returned value is the signature length (in bytes), or 0 on error.
2215 * \param pctx certificate handler context.
2216 * \param hash_id hash function identifier.
2217 * \param hv_len hash value length (in bytes).
2218 * \param data input/output buffer (hash value, then signature).
2219 * \param len total buffer length (in bytes).
2220 * \return signature length (in bytes) on success, or 0 on error.
2222 size_t (*do_sign
)(const br_ssl_client_certificate_class
**pctx
,
2223 int hash_id
, size_t hv_len
, unsigned char *data
, size_t len
);
2227 * \brief A single-chain RSA client certificate handler.
2229 * This handler uses a single certificate chain, with a RSA
2230 * signature. The list of trust anchor DN is ignored.
2232 * Apart from the first field (vtable pointer), its contents are
2233 * opaque and shall not be accessed directly.
2236 /** \brief Pointer to vtable. */
2237 const br_ssl_client_certificate_class
*vtable
;
2238 #ifndef BR_DOXYGEN_IGNORE
2239 const br_x509_certificate
*chain
;
2241 const br_rsa_private_key
*sk
;
2242 br_rsa_pkcs1_sign irsasign
;
2244 } br_ssl_client_certificate_rsa_context
;
2247 * \brief A single-chain EC client certificate handler.
2249 * This handler uses a single certificate chain, with a RSA
2250 * signature. The list of trust anchor DN is ignored.
2252 * This handler may support both static ECDH, and ECDSA signatures
2253 * (either usage may be selectively disabled).
2255 * Apart from the first field (vtable pointer), its contents are
2256 * opaque and shall not be accessed directly.
2259 /** \brief Pointer to vtable. */
2260 const br_ssl_client_certificate_class
*vtable
;
2261 #ifndef BR_DOXYGEN_IGNORE
2262 const br_x509_certificate
*chain
;
2264 const br_ec_private_key
*sk
;
2265 unsigned allowed_usages
;
2266 unsigned issuer_key_type
;
2267 const br_multihash_context
*mhash
;
2268 const br_ec_impl
*iec
;
2269 br_ecdsa_sign iecdsa
;
2271 } br_ssl_client_certificate_ec_context
;
2274 * \brief Context structure for a SSL client.
2276 * The first field (called `eng`) is the SSL engine; all functions that
2277 * work on a `br_ssl_engine_context` structure shall take as parameter
2278 * a pointer to that field. The other structure fields are opaque and
2279 * must not be accessed directly.
2281 struct br_ssl_client_context_
{
2283 * \brief The encapsulated engine context.
2285 br_ssl_engine_context eng
;
2287 #ifndef BR_DOXYGEN_IGNORE
2289 * Minimum ClientHello length; padding with an extension (RFC
2290 * 7685) is added if necessary to match at least that length.
2291 * Such padding is nominally unnecessary, but it has been used
2292 * to work around some server implementation bugs.
2294 uint16_t min_clienthello_len
;
2297 * Bit field for algoithms (hash + signature) supported by the
2298 * server when requesting a client certificate.
2303 * Server's public key curve.
2308 * Context for certificate handler.
2310 const br_ssl_client_certificate_class
**client_auth_vtable
;
2313 * Client authentication type.
2315 unsigned char auth_type
;
2318 * Hash function to use for the client signature. This is 0xFF
2319 * if static ECDH is used.
2321 unsigned char hash_id
;
2324 * For the core certificate handlers, thus avoiding (in most
2325 * cases) the need for an externally provided policy context.
2328 const br_ssl_client_certificate_class
*vtable
;
2329 br_ssl_client_certificate_rsa_context single_rsa
;
2330 br_ssl_client_certificate_ec_context single_ec
;
2336 br_rsa_public irsapub
;
2341 * \brief Get the hash functions and signature algorithms supported by
2344 * This value is a bit field:
2346 * - If RSA (PKCS#1 v1.5) is supported with hash function of ID `x`,
2347 * then bit `x` is set (hash function ID is 0 for the special MD5+SHA-1,
2348 * or 2 to 6 for the SHA family).
2350 * - If ECDSA is suported with hash function of ID `x`, then bit `8+x`
2353 * - Newer algorithms are symbolic 16-bit identifiers that do not
2354 * represent signature algorithm and hash function separately. If
2355 * the TLS-level identifier is `0x0800+x` for a `x` in the 0..15
2356 * range, then bit `16+x` is set.
2358 * "New algorithms" are currently defined only in draft documents, so
2359 * this support is subject to possible change. Right now (early 2017),
2360 * this maps ed25519 (EdDSA on Curve25519) to bit 23, and ed448 (EdDSA
2361 * on Curve448) to bit 24. If the identifiers on the wire change in
2362 * future document, then the decoding mechanism in BearSSL will be
2363 * amended to keep mapping ed25519 and ed448 on bits 23 and 24,
2364 * respectively. Mapping of other new algorithms (e.g. RSA/PSS) is not
2367 * \param cc client context.
2368 * \return the server-supported hash functions and signature algorithms.
2370 static inline uint32_t
2371 br_ssl_client_get_server_hashes(const br_ssl_client_context
*cc
)
2377 * \brief Get the server key curve.
2379 * This function returns the ID for the curve used by the server's public
2380 * key. This is set when the server's certificate chain is processed;
2381 * this value is 0 if the server's key is not an EC key.
2383 * \return the server's public key curve ID, or 0.
2386 br_ssl_client_get_server_curve(const br_ssl_client_context
*cc
)
2388 return cc
->server_curve
;
2392 * Each br_ssl_client_init_xxx() function sets the list of supported
2393 * cipher suites and used implementations, as specified by the profile
2394 * name 'xxx'. Defined profile names are:
2396 * full all supported versions and suites; constant-time implementations
2397 * TODO: add other profiles
2401 * \brief SSL client profile: full.
2403 * This function initialises the provided SSL client context with
2404 * all supported algorithms and cipher suites. It also initialises
2405 * a companion X.509 validation engine with all supported algorithms,
2406 * and the provided trust anchors; the X.509 engine will be used by
2407 * the client context to validate the server's certificate.
2409 * \param cc client context to initialise.
2410 * \param xc X.509 validation context to initialise.
2411 * \param trust_anchors trust anchors to use.
2412 * \param trust_anchors_num number of trust anchors.
2414 void br_ssl_client_init_full(br_ssl_client_context
*cc
,
2415 br_x509_minimal_context
*xc
,
2416 const br_x509_trust_anchor
*trust_anchors
, size_t trust_anchors_num
);
2419 * \brief Clear the complete contents of a SSL client context.
2421 * Everything is cleared, including the reference to the configured buffer,
2422 * implementations, cipher suites and state. This is a preparatory step
2423 * to assembling a custom profile.
2425 * \param cc client context to clear.
2427 void br_ssl_client_zero(br_ssl_client_context
*cc
);
2430 * \brief Set an externally provided client certificate handler context.
2432 * The handler's methods are invoked when the server requests a client
2435 * \param cc client context.
2436 * \param pctx certificate handler context (pointer to its vtable field).
2439 br_ssl_client_set_client_certificate(br_ssl_client_context
*cc
,
2440 const br_ssl_client_certificate_class
**pctx
)
2442 cc
->client_auth_vtable
= pctx
;
2446 * \brief Set the RSA public-key operations implementation.
2448 * This will be used to encrypt the pre-master secret with the server's
2449 * RSA public key (RSA-encryption cipher suites only).
2451 * \param cc client context.
2452 * \param irsapub RSA public-key encryption implementation.
2455 br_ssl_client_set_rsapub(br_ssl_client_context
*cc
, br_rsa_public irsapub
)
2457 cc
->irsapub
= irsapub
;
2461 * \brief Set the minimum ClientHello length (RFC 7685 padding).
2463 * If this value is set and the ClientHello would be shorter, then
2464 * the Pad ClientHello extension will be added with enough padding bytes
2465 * to reach the target size. Because of the extension header, the resulting
2466 * size will sometimes be slightly more than `len` bytes if the target
2467 * size cannot be exactly met.
2469 * The target length relates to the _contents_ of the ClientHello, not
2470 * counting its 4-byte header. For instance, if `len` is set to 512,
2471 * then the padding will bring the ClientHello size to 516 bytes with its
2472 * header, and 521 bytes when counting the 5-byte record header.
2474 * \param cc client context.
2475 * \param len minimum ClientHello length (in bytes).
2478 br_ssl_client_set_min_clienthello_len(br_ssl_client_context
*cc
, uint16_t len
)
2480 cc
->min_clienthello_len
= len
;
2484 * \brief Prepare or reset a client context for a new connection.
2486 * The `server_name` parameter is used to fill the SNI extension; the
2487 * X.509 "minimal" engine will also match that name against the server
2488 * names included in the server's certificate. If the parameter is
2489 * `NULL` then no SNI extension will be sent, and the X.509 "minimal"
2490 * engine (if used for server certificate validation) will not check
2491 * presence of any specific name in the received certificate.
2493 * Therefore, setting the `server_name` to `NULL` shall be reserved
2494 * to cases where alternate or additional methods are used to ascertain
2495 * that the right server public key is used (e.g. a "known key" model).
2497 * If `resume_session` is non-zero and the context was previously used
2498 * then the session parameters may be reused (depending on whether the
2499 * server previously sent a non-empty session ID, and accepts the session
2500 * resumption). The session parameters for session resumption can also
2501 * be set explicitly with `br_ssl_engine_set_session_parameters()`.
2503 * On failure, the context is marked as failed, and this function
2504 * returns 0. A possible failure condition is when no initial entropy
2505 * was injected, and none could be obtained from the OS (either OS
2506 * randomness gathering is not supported, or it failed).
2508 * \param cc client context.
2509 * \param server_name target server name, or `NULL`.
2510 * \param resume_session non-zero to try session resumption.
2511 * \return 0 on failure, 1 on success.
2513 int br_ssl_client_reset(br_ssl_client_context
*cc
,
2514 const char *server_name
, int resume_session
);
2517 * \brief Forget any session in the context.
2519 * This means that the next handshake that uses this context will
2520 * necessarily be a full handshake (this applies both to new connections
2521 * and to renegotiations).
2523 * \param cc client context.
2526 br_ssl_client_forget_session(br_ssl_client_context
*cc
)
2528 cc
->eng
.session
.session_id_len
= 0;
2532 * \brief Set client certificate chain and key (single RSA case).
2534 * This function sets a client certificate chain, that the client will
2535 * send to the server whenever a client certificate is requested. This
2536 * certificate uses an RSA public key; the corresponding private key is
2537 * invoked for authentication. Trust anchor names sent by the server are
2540 * The provided chain and private key are linked in the client context;
2541 * they must remain valid as long as they may be used, i.e. normally
2542 * for the duration of the connection, since they might be invoked
2543 * again upon renegotiations.
2545 * \param cc SSL client context.
2546 * \param chain client certificate chain (SSL order: EE comes first).
2547 * \param chain_len client chain length (number of certificates).
2548 * \param sk client private key.
2549 * \param irsasign RSA signature implementation (PKCS#1 v1.5).
2551 void br_ssl_client_set_single_rsa(br_ssl_client_context
*cc
,
2552 const br_x509_certificate
*chain
, size_t chain_len
,
2553 const br_rsa_private_key
*sk
, br_rsa_pkcs1_sign irsasign
);
2556 * \brief Set the client certificate chain and key (single EC case).
2558 * This function sets a client certificate chain, that the client will
2559 * send to the server whenever a client certificate is requested. This
2560 * certificate uses an EC public key; the corresponding private key is
2561 * invoked for authentication. Trust anchor names sent by the server are
2564 * The provided chain and private key are linked in the client context;
2565 * they must remain valid as long as they may be used, i.e. normally
2566 * for the duration of the connection, since they might be invoked
2567 * again upon renegotiations.
2569 * The `allowed_usages` is a combination of usages, namely
2570 * `BR_KEYTYPE_KEYX` and/or `BR_KEYTYPE_SIGN`. The `BR_KEYTYPE_KEYX`
2571 * value allows full static ECDH, while the `BR_KEYTYPE_SIGN` value
2572 * allows ECDSA signatures. If ECDSA signatures are used, then an ECDSA
2573 * signature implementation must be provided; otherwise, the `iecdsa`
2574 * parameter may be 0.
2576 * The `cert_issuer_key_type` value is either `BR_KEYTYPE_RSA` or
2577 * `BR_KEYTYPE_EC`; it is the type of the public key used the the CA
2578 * that issued (signed) the client certificate. That value is used with
2579 * full static ECDH: support of the certificate by the server depends
2580 * on how the certificate was signed. (Note: when using TLS 1.2, this
2581 * parameter is ignored; but its value matters for TLS 1.0 and 1.1.)
2583 * \param cc server context.
2584 * \param chain server certificate chain to send.
2585 * \param chain_len chain length (number of certificates).
2586 * \param sk server private key (EC).
2587 * \param allowed_usages allowed private key usages.
2588 * \param cert_issuer_key_type issuing CA's key type.
2589 * \param iec EC core implementation.
2590 * \param iecdsa ECDSA signature implementation ("asn1" format).
2592 void br_ssl_client_set_single_ec(br_ssl_client_context
*cc
,
2593 const br_x509_certificate
*chain
, size_t chain_len
,
2594 const br_ec_private_key
*sk
, unsigned allowed_usages
,
2595 unsigned cert_issuer_key_type
,
2596 const br_ec_impl
*iec
, br_ecdsa_sign iecdsa
);
2599 * \brief Type for a "translated cipher suite", as an array of two
2602 * The first element is the cipher suite identifier (as used on the wire).
2603 * The second element is the concatenation of four 4-bit elements which
2604 * characterise the cipher suite contents. In most to least significant
2605 * order, these 4-bit elements are:
2607 * - Bits 12 to 15: key exchange + server key type
2609 * | val | symbolic constant | suite type | details |
2610 * | :-- | :----------------------- | :---------- | :----------------------------------------------- |
2611 * | 0 | `BR_SSLKEYX_RSA` | RSA | RSA key exchange, key is RSA (encryption) |
2612 * | 1 | `BR_SSLKEYX_ECDHE_RSA` | ECDHE_RSA | ECDHE key exchange, key is RSA (signature) |
2613 * | 2 | `BR_SSLKEYX_ECDHE_ECDSA` | ECDHE_ECDSA | ECDHE key exchange, key is EC (signature) |
2614 * | 3 | `BR_SSLKEYX_ECDH_RSA` | ECDH_RSA | Key is EC (key exchange), cert signed with RSA |
2615 * | 4 | `BR_SSLKEYX_ECDH_ECDSA` | ECDH_ECDSA | Key is EC (key exchange), cert signed with ECDSA |
2617 * - Bits 8 to 11: symmetric encryption algorithm
2619 * | val | symbolic constant | symmetric encryption | key strength (bits) |
2620 * | :-- | :--------------------- | :------------------- | :------------------ |
2621 * | 0 | `BR_SSLENC_3DES_CBC` | 3DES/CBC | 168 |
2622 * | 1 | `BR_SSLENC_AES128_CBC` | AES-128/CBC | 128 |
2623 * | 2 | `BR_SSLENC_AES256_CBC` | AES-256/CBC | 256 |
2624 * | 3 | `BR_SSLENC_AES128_GCM` | AES-128/GCM | 128 |
2625 * | 4 | `BR_SSLENC_AES256_GCM` | AES-256/GCM | 256 |
2626 * | 5 | `BR_SSLENC_CHACHA20` | ChaCha20/Poly1305 | 256 |
2628 * - Bits 4 to 7: MAC algorithm
2630 * | val | symbolic constant | MAC type | details |
2631 * | :-- | :----------------- | :----------- | :------------------------------------ |
2632 * | 0 | `BR_SSLMAC_AEAD` | AEAD | No dedicated MAC (encryption is AEAD) |
2633 * | 2 | `BR_SSLMAC_SHA1` | HMAC/SHA-1 | Value matches `br_sha1_ID` |
2634 * | 4 | `BR_SSLMAC_SHA256` | HMAC/SHA-256 | Value matches `br_sha256_ID` |
2635 * | 5 | `BR_SSLMAC_SHA384` | HMAC/SHA-384 | Value matches `br_sha384_ID` |
2637 * - Bits 0 to 3: hash function for PRF when used with TLS-1.2
2639 * | val | symbolic constant | hash function | details |
2640 * | :-- | :----------------- | :------------ | :----------------------------------- |
2641 * | 4 | `BR_SSLPRF_SHA256` | SHA-256 | Value matches `br_sha256_ID` |
2642 * | 5 | `BR_SSLPRF_SHA384` | SHA-384 | Value matches `br_sha384_ID` |
2644 * For instance, cipher suite `TLS_RSA_WITH_AES_128_GCM_SHA256` has
2645 * standard identifier 0x009C, and is translated to 0x0304, for, in
2646 * that order: RSA key exchange (0), AES-128/GCM (3), AEAD integrity (0),
2647 * SHA-256 in the TLS PRF (4).
2649 typedef uint16_t br_suite_translated
[2];
2651 #ifndef BR_DOXYGEN_IGNORE
2653 * Constants are already documented in the br_suite_translated type.
2656 #define BR_SSLKEYX_RSA 0
2657 #define BR_SSLKEYX_ECDHE_RSA 1
2658 #define BR_SSLKEYX_ECDHE_ECDSA 2
2659 #define BR_SSLKEYX_ECDH_RSA 3
2660 #define BR_SSLKEYX_ECDH_ECDSA 4
2662 #define BR_SSLENC_3DES_CBC 0
2663 #define BR_SSLENC_AES128_CBC 1
2664 #define BR_SSLENC_AES256_CBC 2
2665 #define BR_SSLENC_AES128_GCM 3
2666 #define BR_SSLENC_AES256_GCM 4
2667 #define BR_SSLENC_CHACHA20 5
2669 #define BR_SSLMAC_AEAD 0
2670 #define BR_SSLMAC_SHA1 br_sha1_ID
2671 #define BR_SSLMAC_SHA256 br_sha256_ID
2672 #define BR_SSLMAC_SHA384 br_sha384_ID
2674 #define BR_SSLPRF_SHA256 br_sha256_ID
2675 #define BR_SSLPRF_SHA384 br_sha384_ID
2680 * Pre-declaration for the SSL server context.
2682 typedef struct br_ssl_server_context_ br_ssl_server_context
;
2685 * \brief Type for the server policy choices, taken after analysis of
2686 * the client message (ClientHello).
2690 * \brief Cipher suite to use with that client.
2692 uint16_t cipher_suite
;
2695 * \brief Hash function or algorithm for signing the ServerKeyExchange.
2697 * This parameter is ignored for `TLS_RSA_*` and `TLS_ECDH_*`
2698 * cipher suites; it is used only for `TLS_ECDHE_*` suites, in
2699 * which the server _signs_ the ephemeral EC Diffie-Hellman
2700 * parameters sent to the client.
2702 * This identifier must be one of the following values:
2704 * - `0xFF00 + id`, where `id` is a hash function identifier
2705 * (0 for MD5+SHA-1, or 2 to 6 for one of the SHA functions);
2707 * - a full 16-bit identifier, lower than `0xFF00`.
2709 * If the first option is used, then the SSL engine will
2710 * compute the hash of the data that is to be signed, with the
2711 * designated hash function. The `do_sign()` method will be
2712 * invoked with that hash value provided in the the `data`
2715 * If the second option is used, then the SSL engine will NOT
2716 * compute a hash on the data; instead, it will provide the
2717 * to-be-signed data itself in `data`, i.e. the concatenation of
2718 * the client random, server random, and encoded ECDH
2719 * parameters. Furthermore, with TLS-1.2 and later, the 16-bit
2720 * identifier will be used "as is" in the protocol, in the
2721 * SignatureAndHashAlgorithm; for instance, `0x0401` stands for
2722 * RSA PKCS#1 v1.5 signature (the `01`) with SHA-256 as hash
2723 * function (the `04`).
2725 * Take care that with TLS 1.0 and 1.1, the hash function is
2726 * constrainted by the protocol: RSA signature must use
2727 * MD5+SHA-1 (so use `0xFF00`), while ECDSA must use SHA-1
2728 * (`0xFF02`). Since TLS 1.0 and 1.1 don't include a
2729 * SignatureAndHashAlgorithm field in their ServerKeyExchange
2730 * messages, any value below `0xFF00` will be usable to send the
2731 * raw ServerKeyExchange data to the `do_sign()` callback, but
2732 * that callback must still follow the protocol requirements
2733 * when generating the signature.
2738 * \brief Certificate chain to send to the client.
2740 * This is an array of `br_x509_certificate` objects, each
2741 * normally containing a DER-encoded certificate. The server
2742 * code does not try to decode these elements.
2744 const br_x509_certificate
*chain
;
2747 * \brief Certificate chain length (number of certificates).
2751 } br_ssl_server_choices
;
2754 * \brief Class type for a policy handler (server side).
2756 * A policy handler selects the policy parameters for a connection
2757 * (cipher suite and other algorithms, and certificate chain to send to
2758 * the client); it also performs the server-side computations involving
2759 * its permanent private key.
2761 * The SSL server engine will invoke first `choose()`, once the
2762 * ClientHello message has been received, then either `do_keyx()`
2763 * `do_sign()`, depending on the cipher suite.
2765 typedef struct br_ssl_server_policy_class_ br_ssl_server_policy_class
;
2766 struct br_ssl_server_policy_class_
{
2768 * \brief Context size (in bytes).
2770 size_t context_size
;
2773 * \brief Select algorithms and certificates for this connection.
2775 * This callback function shall fill the provided `choices`
2776 * structure with the policy choices for this connection. This
2777 * entails selecting the cipher suite, hash function for signing
2778 * the ServerKeyExchange (applicable only to ECDHE cipher suites),
2779 * and certificate chain to send.
2781 * The callback receives a pointer to the server context that
2782 * contains the relevant data. In particular, the functions
2783 * `br_ssl_server_get_client_suites()`,
2784 * `br_ssl_server_get_client_hashes()` and
2785 * `br_ssl_server_get_client_curves()` can be used to obtain
2786 * the cipher suites, hash functions and elliptic curves
2787 * supported by both the client and server, respectively. The
2788 * `br_ssl_engine_get_version()` and `br_ssl_engine_get_server_name()`
2789 * functions yield the protocol version and requested server name
2790 * (SNI), respectively.
2792 * This function may modify its context structure (`pctx`) in
2793 * arbitrary ways to keep track of its own choices.
2795 * This function shall return 1 if appropriate policy choices
2796 * could be made, or 0 if this connection cannot be pursued.
2798 * \param pctx policy context.
2799 * \param cc SSL server context.
2800 * \param choices destination structure for the policy choices.
2801 * \return 1 on success, 0 on error.
2803 int (*choose
)(const br_ssl_server_policy_class
**pctx
,
2804 const br_ssl_server_context
*cc
,
2805 br_ssl_server_choices
*choices
);
2808 * \brief Perform key exchange (server part).
2810 * This callback is invoked to perform the server-side cryptographic
2811 * operation for a key exchange that is not ECDHE. This callback
2812 * uses the private key.
2814 * **For RSA key exchange**, the provided `data` (of length `*len`
2815 * bytes) shall be decrypted with the server's private key, and
2816 * the 48-byte premaster secret copied back to the first 48 bytes
2819 * - The caller makes sure that `*len` is at least 59 bytes.
2821 * - This callback MUST check that the provided length matches
2822 * that of the key modulus; it shall report an error otherwise.
2824 * - If the length matches that of the RSA key modulus, then
2825 * processing MUST be constant-time, even if decryption fails,
2826 * or the padding is incorrect, or the plaintext message length
2827 * is not exactly 48 bytes.
2829 * - This callback needs not check the two first bytes of the
2830 * obtained pre-master secret (the caller will do that).
2832 * - If an error is reported (0), then what the callback put
2833 * in the first 48 bytes of `data` is unimportant (the caller
2834 * will use random bytes instead).
2836 * **For ECDH key exchange**, the provided `data` (of length `*len`
2837 * bytes) is the elliptic curve point from the client. The
2838 * callback shall multiply it with its private key, and store
2839 * the resulting X coordinate in `data`, starting at offset 0,
2840 * and set `*len` to the length of the X coordinate.
2842 * - If the input array does not have the proper length for
2843 * an encoded curve point, then an error (0) shall be reported.
2845 * - If the input array has the proper length, then processing
2846 * MUST be constant-time, even if the data is not a valid
2849 * - This callback MUST check that the input point is valid.
2851 * Returned value is 1 on success, 0 on error.
2853 * \param pctx policy context.
2854 * \param data key exchange data from the client.
2855 * \param len key exchange data length (in bytes).
2856 * \return 1 on success, 0 on error.
2858 uint32_t (*do_keyx
)(const br_ssl_server_policy_class
**pctx
,
2859 unsigned char *data
, size_t *len
);
2862 * \brief Perform a signature (for a ServerKeyExchange message).
2864 * This callback function is invoked for ECDHE cipher suites. On
2865 * input, the hash value or message to sign is in `data`, of
2866 * size `hv_len`; the involved hash function or algorithm is
2867 * identified by `algo_id`. The signature shall be computed and
2868 * written back into `data`; the total size of that buffer is
2871 * This callback shall verify that the signature length does not
2872 * exceed `len` bytes, and abstain from writing the signature if
2875 * The `algo_id` value matches that which was written in the
2876 * `choices` structures by the `choose()` callback. This will be
2877 * one of the following:
2879 * - `0xFF00 + id` for a hash function identifier `id`. In
2880 * that case, the `data` buffer contains a hash value
2881 * already computed over the data that is to be signed,
2882 * of length `hv_len`. The `id` may be 0 to designate the
2883 * special MD5+SHA-1 concatenation (old-style RSA signing).
2885 * - Another value, lower than `0xFF00`. The `data` buffer
2886 * then contains the raw, non-hashed data to be signed
2887 * (concatenation of the client and server randoms and
2888 * ECDH parameters). The callback is responsible to apply
2889 * any relevant hashing as part of the signing process.
2891 * Returned value is the signature length (in bytes), or 0 on error.
2893 * \param pctx policy context.
2894 * \param algo_id hash function / algorithm identifier.
2895 * \param data input/output buffer (message/hash, then signature).
2896 * \param hv_len hash value or message length (in bytes).
2897 * \param len total buffer length (in bytes).
2898 * \return signature length (in bytes) on success, or 0 on error.
2900 size_t (*do_sign
)(const br_ssl_server_policy_class
**pctx
,
2902 unsigned char *data
, size_t hv_len
, size_t len
);
2906 * \brief A single-chain RSA policy handler.
2908 * This policy context uses a single certificate chain, and a RSA
2909 * private key. The context can be restricted to only signatures or
2910 * only key exchange.
2912 * Apart from the first field (vtable pointer), its contents are
2913 * opaque and shall not be accessed directly.
2916 /** \brief Pointer to vtable. */
2917 const br_ssl_server_policy_class
*vtable
;
2918 #ifndef BR_DOXYGEN_IGNORE
2919 const br_x509_certificate
*chain
;
2921 const br_rsa_private_key
*sk
;
2922 unsigned allowed_usages
;
2923 br_rsa_private irsacore
;
2924 br_rsa_pkcs1_sign irsasign
;
2926 } br_ssl_server_policy_rsa_context
;
2929 * \brief A single-chain EC policy handler.
2931 * This policy context uses a single certificate chain, and an EC
2932 * private key. The context can be restricted to only signatures or
2933 * only key exchange.
2935 * Due to how TLS is defined, this context must be made aware whether
2936 * the server certificate was itself signed with RSA or ECDSA. The code
2937 * does not try to decode the certificate to obtain that information.
2939 * Apart from the first field (vtable pointer), its contents are
2940 * opaque and shall not be accessed directly.
2943 /** \brief Pointer to vtable. */
2944 const br_ssl_server_policy_class
*vtable
;
2945 #ifndef BR_DOXYGEN_IGNORE
2946 const br_x509_certificate
*chain
;
2948 const br_ec_private_key
*sk
;
2949 unsigned allowed_usages
;
2950 unsigned cert_issuer_key_type
;
2951 const br_multihash_context
*mhash
;
2952 const br_ec_impl
*iec
;
2953 br_ecdsa_sign iecdsa
;
2955 } br_ssl_server_policy_ec_context
;
2958 * \brief Class type for a session parameter cache.
2960 * Session parameters are saved in the cache with `save()`, and
2961 * retrieved with `load()`. The cache implementation can apply any
2962 * storage and eviction strategy that it sees fit. The SSL server
2963 * context that performs the request is provided, so that its
2964 * functionalities may be used by the implementation (e.g. hash
2965 * functions or random number generation).
2967 typedef struct br_ssl_session_cache_class_ br_ssl_session_cache_class
;
2968 struct br_ssl_session_cache_class_
{
2970 * \brief Context size (in bytes).
2972 size_t context_size
;
2975 * \brief Record a session.
2977 * This callback should record the provided session parameters.
2978 * The `params` structure is transient, so its contents shall
2979 * be copied into the cache. The session ID has been randomly
2980 * generated and always has length exactly 32 bytes.
2982 * \param ctx session cache context.
2983 * \param server_ctx SSL server context.
2984 * \param params session parameters to save.
2986 void (*save
)(const br_ssl_session_cache_class
**ctx
,
2987 br_ssl_server_context
*server_ctx
,
2988 const br_ssl_session_parameters
*params
);
2991 * \brief Lookup a session in the cache.
2993 * The session ID to lookup is in `params` and always has length
2994 * exactly 32 bytes. If the session parameters are found in the
2995 * cache, then the parameters shall be copied into the `params`
2996 * structure. Returned value is 1 on successful lookup, 0
2999 * \param ctx session cache context.
3000 * \param server_ctx SSL server context.
3001 * \param params destination for session parameters.
3002 * \return 1 if found, 0 otherwise.
3004 int (*load
)(const br_ssl_session_cache_class
**ctx
,
3005 br_ssl_server_context
*server_ctx
,
3006 br_ssl_session_parameters
*params
);
3010 * \brief Context for a basic cache system.
3012 * The system stores session parameters in a buffer provided at
3013 * initialisation time. Each entry uses exactly 100 bytes, and
3014 * buffer sizes up to 4294967295 bytes are supported.
3016 * Entries are evicted with a LRU (Least Recently Used) policy. A
3017 * search tree is maintained to keep lookups fast even with large
3020 * Apart from the first field (vtable pointer), the structure
3021 * contents are opaque and shall not be accessed directly.
3024 /** \brief Pointer to vtable. */
3025 const br_ssl_session_cache_class
*vtable
;
3026 #ifndef BR_DOXYGEN_IGNORE
3027 unsigned char *store
;
3028 size_t store_len
, store_ptr
;
3029 unsigned char index_key
[32];
3030 const br_hash_class
*hash
;
3032 uint32_t head
, tail
, root
;
3034 } br_ssl_session_cache_lru
;
3037 * \brief Initialise a LRU session cache with the provided storage space.
3039 * The provided storage space must remain valid as long as the cache
3040 * is used. Arbitrary lengths are supported, up to 4294967295 bytes;
3041 * each entry uses up exactly 100 bytes.
3043 * \param cc session cache context.
3044 * \param store storage space for cached entries.
3045 * \param store_len storage space length (in bytes).
3047 void br_ssl_session_cache_lru_init(br_ssl_session_cache_lru
*cc
,
3048 unsigned char *store
, size_t store_len
);
3051 * \brief Context structure for a SSL server.
3053 * The first field (called `eng`) is the SSL engine; all functions that
3054 * work on a `br_ssl_engine_context` structure shall take as parameter
3055 * a pointer to that field. The other structure fields are opaque and
3056 * must not be accessed directly.
3058 struct br_ssl_server_context_
{
3060 * \brief The encapsulated engine context.
3062 br_ssl_engine_context eng
;
3064 #ifndef BR_DOXYGEN_IGNORE
3066 * Maximum version from the client.
3068 uint16_t client_max_version
;
3073 const br_ssl_session_cache_class
**cache_vtable
;
3076 * Translated cipher suites supported by the client. The list
3077 * is trimmed to include only the cipher suites that the
3078 * server also supports; they are in the same order as in the
3081 br_suite_translated client_suites
[BR_MAX_CIPHER_SUITES
];
3082 unsigned char client_suites_num
;
3085 * Hash functions supported by the client, with ECDSA and RSA
3086 * (bit mask). For hash function with id 'x', set bit index is
3087 * x for RSA, x+8 for ECDSA. For newer algorithms, with ID
3088 * 0x08**, bit 16+k is set for algorithm 0x0800+k.
3093 * Curves supported by the client (bit mask, for named curves).
3098 * Context for chain handler.
3100 const br_ssl_server_policy_class
**policy_vtable
;
3101 uint16_t sign_hash_id
;
3104 * For the core handlers, thus avoiding (in most cases) the
3105 * need for an externally provided policy context.
3108 const br_ssl_server_policy_class
*vtable
;
3109 br_ssl_server_policy_rsa_context single_rsa
;
3110 br_ssl_server_policy_ec_context single_ec
;
3114 * Buffer for the ECDHE private key.
3116 unsigned char ecdhe_key
[70];
3117 size_t ecdhe_key_len
;
3120 * Trust anchor names for client authentication. "ta_names" and
3121 * "tas" cannot be both non-NULL.
3123 const br_x500_name
*ta_names
;
3124 const br_x509_trust_anchor
*tas
;
3126 size_t cur_dn_index
;
3127 const unsigned char *cur_dn
;
3131 * Buffer for the hash value computed over all handshake messages
3132 * prior to CertificateVerify, and identifier for the hash function.
3134 unsigned char hash_CV
[64];
3139 * Server-specific implementations.
3146 * Each br_ssl_server_init_xxx() function sets the list of supported
3147 * cipher suites and used implementations, as specified by the profile
3148 * name 'xxx'. Defined profile names are:
3150 * full_rsa all supported algorithm, server key type is RSA
3151 * full_ec all supported algorithm, server key type is EC
3152 * TODO: add other profiles
3154 * Naming scheme for "minimal" profiles: min123
3156 * -- character 1: key exchange
3162 * -- character 2: version / PRF
3163 * 0 = TLS 1.0 / 1.1 with MD5+SHA-1
3164 * 2 = TLS 1.2 with SHA-256
3165 * 3 = TLS 1.2 with SHA-384
3166 * -- character 3: encryption
3173 * \brief SSL server profile: full_rsa.
3175 * This function initialises the provided SSL server context with
3176 * all supported algorithms and cipher suites that rely on a RSA
3179 * \param cc server context to initialise.
3180 * \param chain server certificate chain.
3181 * \param chain_len certificate chain length (number of certificate).
3182 * \param sk RSA private key.
3184 void br_ssl_server_init_full_rsa(br_ssl_server_context
*cc
,
3185 const br_x509_certificate
*chain
, size_t chain_len
,
3186 const br_rsa_private_key
*sk
);
3189 * \brief SSL server profile: full_ec.
3191 * This function initialises the provided SSL server context with
3192 * all supported algorithms and cipher suites that rely on an EC
3195 * The key type of the CA that issued the server's certificate must
3196 * be provided, since it matters for ECDH cipher suites (ECDH_RSA
3197 * suites require a RSA-powered CA). The key type is either
3198 * `BR_KEYTYPE_RSA` or `BR_KEYTYPE_EC`.
3200 * \param cc server context to initialise.
3201 * \param chain server certificate chain.
3202 * \param chain_len chain length (number of certificates).
3203 * \param cert_issuer_key_type certificate issuer's key type.
3204 * \param sk EC private key.
3206 void br_ssl_server_init_full_ec(br_ssl_server_context
*cc
,
3207 const br_x509_certificate
*chain
, size_t chain_len
,
3208 unsigned cert_issuer_key_type
, const br_ec_private_key
*sk
);
3211 * \brief SSL server profile: minr2g.
3213 * This profile uses only TLS_RSA_WITH_AES_128_GCM_SHA256. Server key is
3214 * RSA, and RSA key exchange is used (not forward secure, but uses little
3215 * CPU in the client).
3217 * \param cc server context to initialise.
3218 * \param chain server certificate chain.
3219 * \param chain_len certificate chain length (number of certificate).
3220 * \param sk RSA private key.
3222 void br_ssl_server_init_minr2g(br_ssl_server_context
*cc
,
3223 const br_x509_certificate
*chain
, size_t chain_len
,
3224 const br_rsa_private_key
*sk
);
3227 * \brief SSL server profile: mine2g.
3229 * This profile uses only TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256. Server key
3230 * is RSA, and ECDHE key exchange is used. This suite provides forward
3231 * security, with a higher CPU expense on the client, and a somewhat
3232 * larger code footprint (compared to "minr2g").
3234 * \param cc server context to initialise.
3235 * \param chain server certificate chain.
3236 * \param chain_len certificate chain length (number of certificate).
3237 * \param sk RSA private key.
3239 void br_ssl_server_init_mine2g(br_ssl_server_context
*cc
,
3240 const br_x509_certificate
*chain
, size_t chain_len
,
3241 const br_rsa_private_key
*sk
);
3244 * \brief SSL server profile: minf2g.
3246 * This profile uses only TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256.
3247 * Server key is EC, and ECDHE key exchange is used. This suite provides
3248 * forward security, with a higher CPU expense on the client and server
3249 * (by a factor of about 3 to 4), and a somewhat larger code footprint
3250 * (compared to "minu2g" and "minv2g").
3252 * \param cc server context to initialise.
3253 * \param chain server certificate chain.
3254 * \param chain_len certificate chain length (number of certificate).
3255 * \param sk EC private key.
3257 void br_ssl_server_init_minf2g(br_ssl_server_context
*cc
,
3258 const br_x509_certificate
*chain
, size_t chain_len
,
3259 const br_ec_private_key
*sk
);
3262 * \brief SSL server profile: minu2g.
3264 * This profile uses only TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256.
3265 * Server key is EC, and ECDH key exchange is used; the issuing CA used
3268 * The "minu2g" and "minv2g" profiles do not provide forward secrecy,
3269 * but are the lightest on the server (for CPU usage), and are rather
3270 * inexpensive on the client as well.
3272 * \param cc server context to initialise.
3273 * \param chain server certificate chain.
3274 * \param chain_len certificate chain length (number of certificate).
3275 * \param sk EC private key.
3277 void br_ssl_server_init_minu2g(br_ssl_server_context
*cc
,
3278 const br_x509_certificate
*chain
, size_t chain_len
,
3279 const br_ec_private_key
*sk
);
3282 * \brief SSL server profile: minv2g.
3284 * This profile uses only TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256.
3285 * Server key is EC, and ECDH key exchange is used; the issuing CA used
3288 * The "minu2g" and "minv2g" profiles do not provide forward secrecy,
3289 * but are the lightest on the server (for CPU usage), and are rather
3290 * inexpensive on the client as well.
3292 * \param cc server context to initialise.
3293 * \param chain server certificate chain.
3294 * \param chain_len certificate chain length (number of certificate).
3295 * \param sk EC private key.
3297 void br_ssl_server_init_minv2g(br_ssl_server_context
*cc
,
3298 const br_x509_certificate
*chain
, size_t chain_len
,
3299 const br_ec_private_key
*sk
);
3302 * \brief SSL server profile: mine2c.
3304 * This profile uses only TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256.
3305 * Server key is RSA, and ECDHE key exchange is used. This suite
3306 * provides forward security.
3308 * \param cc server context to initialise.
3309 * \param chain server certificate chain.
3310 * \param chain_len certificate chain length (number of certificate).
3311 * \param sk RSA private key.
3313 void br_ssl_server_init_mine2c(br_ssl_server_context
*cc
,
3314 const br_x509_certificate
*chain
, size_t chain_len
,
3315 const br_rsa_private_key
*sk
);
3318 * \brief SSL server profile: minf2c.
3320 * This profile uses only TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256.
3321 * Server key is EC, and ECDHE key exchange is used. This suite provides
3324 * \param cc server context to initialise.
3325 * \param chain server certificate chain.
3326 * \param chain_len certificate chain length (number of certificate).
3327 * \param sk EC private key.
3329 void br_ssl_server_init_minf2c(br_ssl_server_context
*cc
,
3330 const br_x509_certificate
*chain
, size_t chain_len
,
3331 const br_ec_private_key
*sk
);
3334 * \brief Get the supported client suites.
3336 * This function shall be called only after the ClientHello has been
3337 * processed, typically from the policy engine. The returned array
3338 * contains the cipher suites that are supported by both the client
3339 * and the server; these suites are in client preference order, unless
3340 * the `BR_OPT_ENFORCE_SERVER_PREFERENCES` flag was set, in which case
3341 * they are in server preference order.
3343 * The suites are _translated_, which means that each suite is given
3344 * as two 16-bit integers: the standard suite identifier, and its
3345 * translated version, broken down into its individual components,
3346 * as explained with the `br_suite_translated` type.
3348 * The returned array is allocated in the context and will be rewritten
3349 * by each handshake.
3351 * \param cc server context.
3352 * \param num receives the array size (number of suites).
3353 * \return the translated common cipher suites, in preference order.
3355 static inline const br_suite_translated
*
3356 br_ssl_server_get_client_suites(const br_ssl_server_context
*cc
, size_t *num
)
3358 *num
= cc
->client_suites_num
;
3359 return cc
->client_suites
;
3363 * \brief Get the hash functions and signature algorithms supported by
3366 * This value is a bit field:
3368 * - If RSA (PKCS#1 v1.5) is supported with hash function of ID `x`,
3369 * then bit `x` is set (hash function ID is 0 for the special MD5+SHA-1,
3370 * or 2 to 6 for the SHA family).
3372 * - If ECDSA is suported with hash function of ID `x`, then bit `8+x`
3375 * - Newer algorithms are symbolic 16-bit identifiers that do not
3376 * represent signature algorithm and hash function separately. If
3377 * the TLS-level identifier is `0x0800+x` for a `x` in the 0..15
3378 * range, then bit `16+x` is set.
3380 * "New algorithms" are currently defined only in draft documents, so
3381 * this support is subject to possible change. Right now (early 2017),
3382 * this maps ed25519 (EdDSA on Curve25519) to bit 23, and ed448 (EdDSA
3383 * on Curve448) to bit 24. If the identifiers on the wire change in
3384 * future document, then the decoding mechanism in BearSSL will be
3385 * amended to keep mapping ed25519 and ed448 on bits 23 and 24,
3386 * respectively. Mapping of other new algorithms (e.g. RSA/PSS) is not
3389 * \param cc server context.
3390 * \return the client-supported hash functions and signature algorithms.
3392 static inline uint32_t
3393 br_ssl_server_get_client_hashes(const br_ssl_server_context
*cc
)
3399 * \brief Get the elliptic curves supported by the client.
3401 * This is a bit field (bit x is set if curve of ID x is supported).
3403 * \param cc server context.
3404 * \return the client-supported elliptic curves.
3406 static inline uint32_t
3407 br_ssl_server_get_client_curves(const br_ssl_server_context
*cc
)
3413 * \brief Clear the complete contents of a SSL server context.
3415 * Everything is cleared, including the reference to the configured buffer,
3416 * implementations, cipher suites and state. This is a preparatory step
3417 * to assembling a custom profile.
3419 * \param cc server context to clear.
3421 void br_ssl_server_zero(br_ssl_server_context
*cc
);
3424 * \brief Set an externally provided policy context.
3426 * The policy context's methods are invoked to decide the cipher suite
3427 * and certificate chain, and to perform operations involving the server's
3430 * \param cc server context.
3431 * \param pctx policy context (pointer to its vtable field).
3434 br_ssl_server_set_policy(br_ssl_server_context
*cc
,
3435 const br_ssl_server_policy_class
**pctx
)
3437 cc
->policy_vtable
= pctx
;
3441 * \brief Set the server certificate chain and key (single RSA case).
3443 * This function uses a policy context included in the server context.
3444 * It configures use of a single server certificate chain with a RSA
3445 * private key. The `allowed_usages` is a combination of usages, namely
3446 * `BR_KEYTYPE_KEYX` and/or `BR_KEYTYPE_SIGN`; this enables or disables
3447 * the corresponding cipher suites (i.e. `TLS_RSA_*` use the RSA key for
3448 * key exchange, while `TLS_ECDHE_RSA_*` use the RSA key for signatures).
3450 * \param cc server context.
3451 * \param chain server certificate chain to send to the client.
3452 * \param chain_len chain length (number of certificates).
3453 * \param sk server private key (RSA).
3454 * \param allowed_usages allowed private key usages.
3455 * \param irsacore RSA core implementation.
3456 * \param irsasign RSA signature implementation (PKCS#1 v1.5).
3458 void br_ssl_server_set_single_rsa(br_ssl_server_context
*cc
,
3459 const br_x509_certificate
*chain
, size_t chain_len
,
3460 const br_rsa_private_key
*sk
, unsigned allowed_usages
,
3461 br_rsa_private irsacore
, br_rsa_pkcs1_sign irsasign
);
3464 * \brief Set the server certificate chain and key (single EC case).
3466 * This function uses a policy context included in the server context.
3467 * It configures use of a single server certificate chain with an EC
3468 * private key. The `allowed_usages` is a combination of usages, namely
3469 * `BR_KEYTYPE_KEYX` and/or `BR_KEYTYPE_SIGN`; this enables or disables
3470 * the corresponding cipher suites (i.e. `TLS_ECDH_*` use the EC key for
3471 * key exchange, while `TLS_ECDHE_ECDSA_*` use the EC key for signatures).
3473 * In order to support `TLS_ECDH_*` cipher suites (non-ephemeral ECDH),
3474 * the algorithm type of the key used by the issuing CA to sign the
3475 * server's certificate must be provided, as `cert_issuer_key_type`
3476 * parameter (this value is either `BR_KEYTYPE_RSA` or `BR_KEYTYPE_EC`).
3478 * \param cc server context.
3479 * \param chain server certificate chain to send.
3480 * \param chain_len chain length (number of certificates).
3481 * \param sk server private key (EC).
3482 * \param allowed_usages allowed private key usages.
3483 * \param cert_issuer_key_type issuing CA's key type.
3484 * \param iec EC core implementation.
3485 * \param iecdsa ECDSA signature implementation ("asn1" format).
3487 void br_ssl_server_set_single_ec(br_ssl_server_context
*cc
,
3488 const br_x509_certificate
*chain
, size_t chain_len
,
3489 const br_ec_private_key
*sk
, unsigned allowed_usages
,
3490 unsigned cert_issuer_key_type
,
3491 const br_ec_impl
*iec
, br_ecdsa_sign iecdsa
);
3494 * \brief Activate client certificate authentication.
3496 * The trust anchor encoded X.500 names (DN) to send to the client are
3497 * provided. A client certificate will be requested and validated through
3498 * the X.509 validator configured in the SSL engine. If `num` is 0, then
3499 * client certificate authentication is disabled.
3501 * If the client does not send a certificate, or on validation failure,
3502 * the handshake aborts. Unauthenticated clients can be tolerated by
3503 * setting the `BR_OPT_TOLERATE_NO_CLIENT_AUTH` flag.
3505 * The provided array is linked in, not copied, so that pointer must
3506 * remain valid as long as anchor names may be used.
3508 * \param cc server context.
3509 * \param ta_names encoded trust anchor names.
3510 * \param num number of encoded trust anchor names.
3513 br_ssl_server_set_trust_anchor_names(br_ssl_server_context
*cc
,
3514 const br_x500_name
*ta_names
, size_t num
)
3516 cc
->ta_names
= ta_names
;
3522 * \brief Activate client certificate authentication.
3524 * This is a variant for `br_ssl_server_set_trust_anchor_names()`: the
3525 * trust anchor names are provided not as an array of stand-alone names
3526 * (`br_x500_name` structures), but as an array of trust anchors
3527 * (`br_x509_trust_anchor` structures). The server engine itself will
3528 * only use the `dn` field of each trust anchor. This is meant to allow
3529 * defining a single array of trust anchors, to be used here and in the
3530 * X.509 validation engine itself.
3532 * The provided array is linked in, not copied, so that pointer must
3533 * remain valid as long as anchor names may be used.
3535 * \param cc server context.
3536 * \param tas trust anchors (only names are used).
3537 * \param num number of trust anchors.
3540 br_ssl_server_set_trust_anchor_names_alt(br_ssl_server_context
*cc
,
3541 const br_x509_trust_anchor
*tas
, size_t num
)
3543 cc
->ta_names
= NULL
;
3549 * \brief Configure the cache for session parameters.
3551 * The cache context is provided as a pointer to its first field (vtable
3554 * \param cc server context.
3555 * \param vtable session cache context.
3558 br_ssl_server_set_cache(br_ssl_server_context
*cc
,
3559 const br_ssl_session_cache_class
**vtable
)
3561 cc
->cache_vtable
= vtable
;
3565 * \brief Prepare or reset a server context for handling an incoming client.
3567 * \param cc server context.
3568 * \return 1 on success, 0 on error.
3570 int br_ssl_server_reset(br_ssl_server_context
*cc
);
3572 /* ===================================================================== */
3575 * Context for the simplified I/O context. The transport medium is accessed
3576 * through the low_read() and low_write() callback functions, each with
3577 * its own opaque context pointer.
3579 * low_read() read some bytes, at most 'len' bytes, into data[]. The
3580 * returned value is the number of read bytes, or -1 on error.
3581 * The 'len' parameter is guaranteed never to exceed 20000,
3582 * so the length always fits in an 'int' on all platforms.
3584 * low_write() write up to 'len' bytes, to be read from data[]. The
3585 * returned value is the number of written bytes, or -1 on
3586 * error. The 'len' parameter is guaranteed never to exceed
3587 * 20000, so the length always fits in an 'int' on all
3590 * A socket closure (if the transport medium is a socket) should be reported
3591 * as an error (-1). The callbacks shall endeavour to block until at least
3592 * one byte can be read or written; a callback returning 0 at times is
3593 * acceptable, but this normally leads to the callback being immediately
3594 * called again, so the callback should at least always try to block for
3595 * some time if no I/O can take place.
3597 * The SSL engine naturally applies some buffering, so the callbacks need
3598 * not apply buffers of their own.
3601 * \brief Context structure for the simplified SSL I/O wrapper.
3603 * This structure is initialised with `br_sslio_init()`. Its contents
3604 * are opaque and shall not be accessed directly.
3607 #ifndef BR_DOXYGEN_IGNORE
3608 br_ssl_engine_context
*engine
;
3609 int (*low_read
)(void *read_context
,
3610 unsigned char *data
, size_t len
);
3612 int (*low_write
)(void *write_context
,
3613 const unsigned char *data
, size_t len
);
3614 void *write_context
;
3619 * \brief Initialise a simplified I/O wrapper context.
3621 * The simplified I/O wrapper offers a simpler read/write API for a SSL
3622 * engine (client or server), using the provided callback functions for
3623 * reading data from, or writing data to, the transport medium.
3625 * The callback functions have the following semantics:
3627 * - Each callback receives an opaque context value (of type `void *`)
3628 * that the callback may use arbitrarily (or possibly ignore).
3630 * - `low_read()` reads at least one byte, at most `len` bytes, from
3631 * the transport medium. Read bytes shall be written in `data`.
3633 * - `low_write()` writes at least one byte, at most `len` bytes, unto
3634 * the transport medium. The bytes to write are read from `data`.
3636 * - The `len` parameter is never zero, and is always lower than 20000.
3638 * - The number of processed bytes (read or written) is returned. Since
3639 * that number is less than 20000, it always fits on an `int`.
3641 * - On error, the callbacks return -1. Reaching end-of-stream is an
3642 * error. Errors are permanent: the SSL connection is terminated.
3644 * - Callbacks SHOULD NOT return 0. This is tolerated, as long as
3645 * callbacks endeavour to block for some non-negligible amount of
3646 * time until at least one byte can be sent or received (if a
3647 * callback returns 0, then the wrapper invokes it again
3650 * - Callbacks MAY return as soon as at least one byte is processed;
3651 * they MAY also insist on reading or writing _all_ requested bytes.
3652 * Since SSL is a self-terminated protocol (each record has a length
3653 * header), this does not change semantics.
3655 * - Callbacks need not apply any buffering (for performance) since SSL
3656 * itself uses buffers.
3658 * \param ctx wrapper context to initialise.
3659 * \param engine SSL engine to wrap.
3660 * \param low_read callback for reading data from the transport.
3661 * \param read_context context pointer for `low_read()`.
3662 * \param low_write callback for writing data on the transport.
3663 * \param write_context context pointer for `low_write()`.
3665 void br_sslio_init(br_sslio_context
*ctx
,
3666 br_ssl_engine_context
*engine
,
3667 int (*low_read
)(void *read_context
,
3668 unsigned char *data
, size_t len
),
3670 int (*low_write
)(void *write_context
,
3671 const unsigned char *data
, size_t len
),
3672 void *write_context
);
3675 * \brief Read some application data from a SSL connection.
3677 * If `len` is zero, then this function returns 0 immediately. In
3678 * all other cases, it never returns 0.
3680 * This call returns only when at least one byte has been obtained.
3681 * Returned value is the number of bytes read, or -1 on error. The
3682 * number of bytes always fits on an 'int' (data from a single SSL/TLS
3683 * record is returned).
3685 * On error or SSL closure, this function returns -1. The caller should
3686 * inspect the error status on the SSL engine to distinguish between
3687 * normal closure and error.
3689 * \param cc SSL wrapper context.
3690 * \param dst destination buffer for application data.
3691 * \param len maximum number of bytes to obtain.
3692 * \return number of bytes obtained, or -1 on error.
3694 int br_sslio_read(br_sslio_context
*cc
, void *dst
, size_t len
);
3697 * \brief Read application data from a SSL connection.
3699 * This calls returns only when _all_ requested `len` bytes are read,
3700 * or an error is reached. Returned value is 0 on success, -1 on error.
3701 * A normal (verified) SSL closure before that many bytes are obtained
3702 * is reported as an error by this function.
3704 * \param cc SSL wrapper context.
3705 * \param dst destination buffer for application data.
3706 * \param len number of bytes to obtain.
3707 * \return 0 on success, or -1 on error.
3709 int br_sslio_read_all(br_sslio_context
*cc
, void *dst
, size_t len
);
3712 * \brief Write some application data unto a SSL connection.
3714 * If `len` is zero, then this function returns 0 immediately. In
3715 * all other cases, it never returns 0.
3717 * This call returns only when at least one byte has been written.