xref: /freebsd/contrib/bearssl/inc/bearssl_ssl.h (revision a134ebd6e63f658f2d3d04ac0c60d23bcaa86dd7)
1 /*
2  * Copyright (c) 2016 Thomas Pornin <pornin@bolet.org>
3  *
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:
11  *
12  * The above copyright notice and this permission notice shall be
13  * included in all copies or substantial portions of the Software.
14  *
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
22  * SOFTWARE.
23  */
24 
25 #ifndef BR_BEARSSL_SSL_H__
26 #define BR_BEARSSL_SSL_H__
27 
28 #include <stddef.h>
29 #include <stdint.h>
30 
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"
37 
38 #ifdef __cplusplus
39 extern "C" {
40 #endif
41 
42 /** \file bearssl_ssl.h
43  *
44  * # SSL
45  *
46  * For an overview of the SSL/TLS API, see [the BearSSL Web
47  * site](https://www.bearssl.org/api1.html).
48  *
49  * The `BR_TLS_*` constants correspond to the standard cipher suites and
50  * their values in the [IANA
51  * registry](http://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-4).
52  *
53  * The `BR_ALERT_*` constants are for standard TLS alert messages. When
54  * a fatal alert message is sent of received, then the SSL engine context
55  * status is set to the sum of that alert value (an integer in the 0..255
56  * range) and a fixed offset (`BR_ERR_SEND_FATAL_ALERT` for a sent alert,
57  * `BR_ERR_RECV_FATAL_ALERT` for a received alert).
58  */
59 
60 /** \brief Optimal input buffer size. */
61 #define BR_SSL_BUFSIZE_INPUT    (16384 + 325)
62 
63 /** \brief Optimal output buffer size. */
64 #define BR_SSL_BUFSIZE_OUTPUT   (16384 + 85)
65 
66 /** \brief Optimal buffer size for monodirectional engine
67     (shared input/output buffer). */
68 #define BR_SSL_BUFSIZE_MONO     BR_SSL_BUFSIZE_INPUT
69 
70 /** \brief Optimal buffer size for bidirectional engine
71     (single buffer split into two separate input/output buffers). */
72 #define BR_SSL_BUFSIZE_BIDI     (BR_SSL_BUFSIZE_INPUT + BR_SSL_BUFSIZE_OUTPUT)
73 
74 /*
75  * Constants for known SSL/TLS protocol versions (SSL 3.0, TLS 1.0, TLS 1.1
76  * and TLS 1.2). Note that though there is a constant for SSL 3.0, that
77  * protocol version is not actually supported.
78  */
79 
80 /** \brief Protocol version: SSL 3.0 (unsupported). */
81 #define BR_SSL30   0x0300
82 /** \brief Protocol version: TLS 1.0. */
83 #define BR_TLS10   0x0301
84 /** \brief Protocol version: TLS 1.1. */
85 #define BR_TLS11   0x0302
86 /** \brief Protocol version: TLS 1.2. */
87 #define BR_TLS12   0x0303
88 
89 /*
90  * Error constants. They are used to report the reason why a context has
91  * been marked as failed.
92  *
93  * Implementation note: SSL-level error codes should be in the 1..31
94  * range. The 32..63 range is for certificate decoding and validation
95  * errors. Received fatal alerts imply an error code in the 256..511 range.
96  */
97 
98 /** \brief SSL status: no error so far (0). */
99 #define BR_ERR_OK                      0
100 
101 /** \brief SSL status: caller-provided parameter is incorrect. */
102 #define BR_ERR_BAD_PARAM               1
103 
104 /** \brief SSL status: operation requested by the caller cannot be applied
105     with the current context state (e.g. reading data while outgoing data
106     is waiting to be sent). */
107 #define BR_ERR_BAD_STATE               2
108 
109 /** \brief SSL status: incoming protocol or record version is unsupported. */
110 #define BR_ERR_UNSUPPORTED_VERSION     3
111 
112 /** \brief SSL status: incoming record version does not match the expected
113     version. */
114 #define BR_ERR_BAD_VERSION             4
115 
116 /** \brief SSL status: incoming record length is invalid. */
117 #define BR_ERR_BAD_LENGTH              5
118 
119 /** \brief SSL status: incoming record is too large to be processed, or
120     buffer is too small for the handshake message to send. */
121 #define BR_ERR_TOO_LARGE               6
122 
123 /** \brief SSL status: decryption found an invalid padding, or the record
124     MAC is not correct. */
125 #define BR_ERR_BAD_MAC                 7
126 
127 /** \brief SSL status: no initial entropy was provided, and none can be
128     obtained from the OS. */
129 #define BR_ERR_NO_RANDOM               8
130 
131 /** \brief SSL status: incoming record type is unknown. */
132 #define BR_ERR_UNKNOWN_TYPE            9
133 
134 /** \brief SSL status: incoming record or message has wrong type with
135     regards to the current engine state. */
136 #define BR_ERR_UNEXPECTED             10
137 
138 /** \brief SSL status: ChangeCipherSpec message from the peer has invalid
139     contents. */
140 #define BR_ERR_BAD_CCS                12
141 
142 /** \brief SSL status: alert message from the peer has invalid contents
143     (odd length). */
144 #define BR_ERR_BAD_ALERT              13
145 
146 /** \brief SSL status: incoming handshake message decoding failed. */
147 #define BR_ERR_BAD_HANDSHAKE          14
148 
149 /** \brief SSL status: ServerHello contains a session ID which is larger
150     than 32 bytes. */
151 #define BR_ERR_OVERSIZED_ID           15
152 
153 /** \brief SSL status: server wants to use a cipher suite that we did
154     not claim to support. This is also reported if we tried to advertise
155     a cipher suite that we do not support. */
156 #define BR_ERR_BAD_CIPHER_SUITE       16
157 
158 /** \brief SSL status: server wants to use a compression that we did not
159     claim to support. */
160 #define BR_ERR_BAD_COMPRESSION        17
161 
162 /** \brief SSL status: server's max fragment length does not match
163     client's. */
164 #define BR_ERR_BAD_FRAGLEN            18
165 
166 /** \brief SSL status: secure renegotiation failed. */
167 #define BR_ERR_BAD_SECRENEG           19
168 
169 /** \brief SSL status: server sent an extension type that we did not
170     announce, or used the same extension type several times in a single
171     ServerHello. */
172 #define BR_ERR_EXTRA_EXTENSION        20
173 
174 /** \brief SSL status: invalid Server Name Indication contents (when
175     used by the server, this extension shall be empty). */
176 #define BR_ERR_BAD_SNI                21
177 
178 /** \brief SSL status: invalid ServerHelloDone from the server (length
179     is not 0). */
180 #define BR_ERR_BAD_HELLO_DONE         22
181 
182 /** \brief SSL status: internal limit exceeded (e.g. server's public key
183     is too large). */
184 #define BR_ERR_LIMIT_EXCEEDED         23
185 
186 /** \brief SSL status: Finished message from peer does not match the
187     expected value. */
188 #define BR_ERR_BAD_FINISHED           24
189 
190 /** \brief SSL status: session resumption attempt with distinct version
191     or cipher suite. */
192 #define BR_ERR_RESUME_MISMATCH        25
193 
194 /** \brief SSL status: unsupported or invalid algorithm (ECDHE curve,
195     signature algorithm, hash function). */
196 #define BR_ERR_INVALID_ALGORITHM      26
197 
198 /** \brief SSL status: invalid signature (on ServerKeyExchange from
199     server, or in CertificateVerify from client). */
200 #define BR_ERR_BAD_SIGNATURE          27
201 
202 /** \brief SSL status: peer's public key does not have the proper type
203     or is not allowed for requested operation. */
204 #define BR_ERR_WRONG_KEY_USAGE        28
205 
206 /** \brief SSL status: client did not send a certificate upon request,
207     or the client certificate could not be validated. */
208 #define BR_ERR_NO_CLIENT_AUTH         29
209 
210 /** \brief SSL status: I/O error or premature close on underlying
211     transport stream. This error code is set only by the simplified
212     I/O API ("br_sslio_*"). */
213 #define BR_ERR_IO                     31
214 
215 /** \brief SSL status: base value for a received fatal alert.
216 
217     When a fatal alert is received from the peer, the alert value
218     is added to this constant. */
219 #define BR_ERR_RECV_FATAL_ALERT      256
220 
221 /** \brief SSL status: base value for a sent fatal alert.
222 
223     When a fatal alert is sent to the peer, the alert value is added
224     to this constant. */
225 #define BR_ERR_SEND_FATAL_ALERT      512
226 
227 /* ===================================================================== */
228 
229 /**
230  * \brief Decryption engine for SSL.
231  *
232  * When processing incoming records, the SSL engine will use a decryption
233  * engine that uses a specific context structure, and has a set of
234  * methods (a vtable) that follows this template.
235  *
236  * The decryption engine is responsible for applying decryption, verifying
237  * MAC, and keeping track of the record sequence number.
238  */
239 typedef struct br_sslrec_in_class_ br_sslrec_in_class;
240 struct br_sslrec_in_class_ {
241 	/**
242 	 * \brief Context size (in bytes).
243 	 */
244 	size_t context_size;
245 
246 	/**
247 	 * \brief Test validity of the incoming record length.
248 	 *
249 	 * This function returns 1 if the announced length for an
250 	 * incoming record is valid, 0 otherwise,
251 	 *
252 	 * \param ctx          decryption engine context.
253 	 * \param record_len   incoming record length.
254 	 * \return  1 of a valid length, 0 otherwise.
255 	 */
256 	int (*check_length)(const br_sslrec_in_class *const *ctx,
257 		size_t record_len);
258 
259 	/**
260 	 * \brief Decrypt the incoming record.
261 	 *
262 	 * This function may assume that the record length is valid
263 	 * (it has been previously tested with `check_length()`).
264 	 * Decryption is done in place; `*len` is updated with the
265 	 * cleartext length, and the address of the first plaintext
266 	 * byte is returned. If the record is correct but empty, then
267 	 * `*len` is set to 0 and a non-`NULL` pointer is returned.
268 	 *
269 	 * On decryption/MAC error, `NULL` is returned.
270 	 *
271 	 * \param ctx           decryption engine context.
272 	 * \param record_type   record type (23 for application data, etc).
273 	 * \param version       record version.
274 	 * \param payload       address of encrypted payload.
275 	 * \param len           pointer to payload length (updated).
276 	 * \return  pointer to plaintext, or `NULL` on error.
277 	 */
278 	unsigned char *(*decrypt)(const br_sslrec_in_class **ctx,
279 		int record_type, unsigned version,
280 		void *payload, size_t *len);
281 };
282 
283 /**
284  * \brief Encryption engine for SSL.
285  *
286  * When building outgoing records, the SSL engine will use an encryption
287  * engine that uses a specific context structure, and has a set of
288  * methods (a vtable) that follows this template.
289  *
290  * The encryption engine is responsible for applying encryption and MAC,
291  * and keeping track of the record sequence number.
292  */
293 typedef struct br_sslrec_out_class_ br_sslrec_out_class;
294 struct br_sslrec_out_class_ {
295 	/**
296 	 * \brief Context size (in bytes).
297 	 */
298 	size_t context_size;
299 
300 	/**
301 	 * \brief Compute maximum plaintext sizes and offsets.
302 	 *
303 	 * When this function is called, the `*start` and `*end`
304 	 * values contain offsets designating the free area in the
305 	 * outgoing buffer for plaintext data; that free area is
306 	 * preceded by a 5-byte space which will receive the record
307 	 * header.
308 	 *
309 	 * The `max_plaintext()` function is responsible for adjusting
310 	 * both `*start` and `*end` to make room for any record-specific
311 	 * header, MAC, padding, and possible split.
312 	 *
313 	 * \param ctx     encryption engine context.
314 	 * \param start   pointer to start of plaintext offset (updated).
315 	 * \param end     pointer to start of plaintext offset (updated).
316 	 */
317 	void (*max_plaintext)(const br_sslrec_out_class *const *ctx,
318 		size_t *start, size_t *end);
319 
320 	/**
321 	 * \brief Perform record encryption.
322 	 *
323 	 * This function encrypts the record. The plaintext address and
324 	 * length are provided. Returned value is the start of the
325 	 * encrypted record (or sequence of records, if a split was
326 	 * performed), _including_ the 5-byte header, and `*len` is
327 	 * adjusted to the total size of the record(s), there again
328 	 * including the header(s).
329 	 *
330 	 * \param ctx           decryption engine context.
331 	 * \param record_type   record type (23 for application data, etc).
332 	 * \param version       record version.
333 	 * \param plaintext     address of plaintext.
334 	 * \param len           pointer to plaintext length (updated).
335 	 * \return  pointer to start of built record.
336 	 */
337 	unsigned char *(*encrypt)(const br_sslrec_out_class **ctx,
338 		int record_type, unsigned version,
339 		void *plaintext, size_t *len);
340 };
341 
342 /**
343  * \brief Context for a no-encryption engine.
344  *
345  * The no-encryption engine processes outgoing records during the initial
346  * handshake, before encryption is applied.
347  */
348 typedef struct {
349 	/** \brief No-encryption engine vtable. */
350 	const br_sslrec_out_class *vtable;
351 } br_sslrec_out_clear_context;
352 
353 /** \brief Static, constant vtable for the no-encryption engine. */
354 extern const br_sslrec_out_class br_sslrec_out_clear_vtable;
355 
356 /* ===================================================================== */
357 
358 /**
359  * \brief Record decryption engine class, for CBC mode.
360  *
361  * This class type extends the decryption engine class with an
362  * initialisation method that receives the parameters needed
363  * for CBC processing: block cipher implementation, block cipher key,
364  * HMAC parameters (hash function, key, MAC length), and IV. If the
365  * IV is `NULL`, then a per-record IV will be used (TLS 1.1+).
366  */
367 typedef struct br_sslrec_in_cbc_class_ br_sslrec_in_cbc_class;
368 struct br_sslrec_in_cbc_class_ {
369 	/**
370 	 * \brief Superclass, as first vtable field.
371 	 */
372 	br_sslrec_in_class inner;
373 
374 	/**
375 	 * \brief Engine initialisation method.
376 	 *
377 	 * This method sets the vtable field in the context.
378 	 *
379 	 * \param ctx           context to initialise.
380 	 * \param bc_impl       block cipher implementation (CBC decryption).
381 	 * \param bc_key        block cipher key.
382 	 * \param bc_key_len    block cipher key length (in bytes).
383 	 * \param dig_impl      hash function for HMAC.
384 	 * \param mac_key       HMAC key.
385 	 * \param mac_key_len   HMAC key length (in bytes).
386 	 * \param mac_out_len   HMAC output length (in bytes).
387 	 * \param iv            initial IV (or `NULL`).
388 	 */
389 	void (*init)(const br_sslrec_in_cbc_class **ctx,
390 		const br_block_cbcdec_class *bc_impl,
391 		const void *bc_key, size_t bc_key_len,
392 		const br_hash_class *dig_impl,
393 		const void *mac_key, size_t mac_key_len, size_t mac_out_len,
394 		const void *iv);
395 };
396 
397 /**
398  * \brief Record encryption engine class, for CBC mode.
399  *
400  * This class type extends the encryption engine class with an
401  * initialisation method that receives the parameters needed
402  * for CBC processing: block cipher implementation, block cipher key,
403  * HMAC parameters (hash function, key, MAC length), and IV. If the
404  * IV is `NULL`, then a per-record IV will be used (TLS 1.1+).
405  */
406 typedef struct br_sslrec_out_cbc_class_ br_sslrec_out_cbc_class;
407 struct br_sslrec_out_cbc_class_ {
408 	/**
409 	 * \brief Superclass, as first vtable field.
410 	 */
411 	br_sslrec_out_class inner;
412 
413 	/**
414 	 * \brief Engine initialisation method.
415 	 *
416 	 * This method sets the vtable field in the context.
417 	 *
418 	 * \param ctx           context to initialise.
419 	 * \param bc_impl       block cipher implementation (CBC encryption).
420 	 * \param bc_key        block cipher key.
421 	 * \param bc_key_len    block cipher key length (in bytes).
422 	 * \param dig_impl      hash function for HMAC.
423 	 * \param mac_key       HMAC key.
424 	 * \param mac_key_len   HMAC key length (in bytes).
425 	 * \param mac_out_len   HMAC output length (in bytes).
426 	 * \param iv            initial IV (or `NULL`).
427 	 */
428 	void (*init)(const br_sslrec_out_cbc_class **ctx,
429 		const br_block_cbcenc_class *bc_impl,
430 		const void *bc_key, size_t bc_key_len,
431 		const br_hash_class *dig_impl,
432 		const void *mac_key, size_t mac_key_len, size_t mac_out_len,
433 		const void *iv);
434 };
435 
436 /**
437  * \brief Context structure for decrypting incoming records with
438  * CBC + HMAC.
439  *
440  * The first field points to the vtable. The other fields are opaque
441  * and shall not be accessed directly.
442  */
443 typedef struct {
444 	/** \brief Pointer to vtable. */
445 	const br_sslrec_in_cbc_class *vtable;
446 #ifndef BR_DOXYGEN_IGNORE
447 	uint64_t seq;
448 	union {
449 		const br_block_cbcdec_class *vtable;
450 		br_aes_gen_cbcdec_keys aes;
451 		br_des_gen_cbcdec_keys des;
452 	} bc;
453 	br_hmac_key_context mac;
454 	size_t mac_len;
455 	unsigned char iv[16];
456 	int explicit_IV;
457 #endif
458 } br_sslrec_in_cbc_context;
459 
460 /**
461  * \brief Static, constant vtable for record decryption with CBC.
462  */
463 extern const br_sslrec_in_cbc_class br_sslrec_in_cbc_vtable;
464 
465 /**
466  * \brief Context structure for encrypting outgoing records with
467  * CBC + HMAC.
468  *
469  * The first field points to the vtable. The other fields are opaque
470  * and shall not be accessed directly.
471  */
472 typedef struct {
473 	/** \brief Pointer to vtable. */
474 	const br_sslrec_out_cbc_class *vtable;
475 #ifndef BR_DOXYGEN_IGNORE
476 	uint64_t seq;
477 	union {
478 		const br_block_cbcenc_class *vtable;
479 		br_aes_gen_cbcenc_keys aes;
480 		br_des_gen_cbcenc_keys des;
481 	} bc;
482 	br_hmac_key_context mac;
483 	size_t mac_len;
484 	unsigned char iv[16];
485 	int explicit_IV;
486 #endif
487 } br_sslrec_out_cbc_context;
488 
489 /**
490  * \brief Static, constant vtable for record encryption with CBC.
491  */
492 extern const br_sslrec_out_cbc_class br_sslrec_out_cbc_vtable;
493 
494 /* ===================================================================== */
495 
496 /**
497  * \brief Record decryption engine class, for GCM mode.
498  *
499  * This class type extends the decryption engine class with an
500  * initialisation method that receives the parameters needed
501  * for GCM processing: block cipher implementation, block cipher key,
502  * GHASH implementation, and 4-byte IV.
503  */
504 typedef struct br_sslrec_in_gcm_class_ br_sslrec_in_gcm_class;
505 struct br_sslrec_in_gcm_class_ {
506 	/**
507 	 * \brief Superclass, as first vtable field.
508 	 */
509 	br_sslrec_in_class inner;
510 
511 	/**
512 	 * \brief Engine initialisation method.
513 	 *
514 	 * This method sets the vtable field in the context.
515 	 *
516 	 * \param ctx           context to initialise.
517 	 * \param bc_impl       block cipher implementation (CTR).
518 	 * \param key           block cipher key.
519 	 * \param key_len       block cipher key length (in bytes).
520 	 * \param gh_impl       GHASH implementation.
521 	 * \param iv            static IV (4 bytes).
522 	 */
523 	void (*init)(const br_sslrec_in_gcm_class **ctx,
524 		const br_block_ctr_class *bc_impl,
525 		const void *key, size_t key_len,
526 		br_ghash gh_impl,
527 		const void *iv);
528 };
529 
530 /**
531  * \brief Record encryption engine class, for GCM mode.
532  *
533  * This class type extends the encryption engine class with an
534  * initialisation method that receives the parameters needed
535  * for GCM processing: block cipher implementation, block cipher key,
536  * GHASH implementation, and 4-byte IV.
537  */
538 typedef struct br_sslrec_out_gcm_class_ br_sslrec_out_gcm_class;
539 struct br_sslrec_out_gcm_class_ {
540 	/**
541 	 * \brief Superclass, as first vtable field.
542 	 */
543 	br_sslrec_out_class inner;
544 
545 	/**
546 	 * \brief Engine initialisation method.
547 	 *
548 	 * This method sets the vtable field in the context.
549 	 *
550 	 * \param ctx           context to initialise.
551 	 * \param bc_impl       block cipher implementation (CTR).
552 	 * \param key           block cipher key.
553 	 * \param key_len       block cipher key length (in bytes).
554 	 * \param gh_impl       GHASH implementation.
555 	 * \param iv            static IV (4 bytes).
556 	 */
557 	void (*init)(const br_sslrec_out_gcm_class **ctx,
558 		const br_block_ctr_class *bc_impl,
559 		const void *key, size_t key_len,
560 		br_ghash gh_impl,
561 		const void *iv);
562 };
563 
564 /**
565  * \brief Context structure for processing records with GCM.
566  *
567  * The same context structure is used for encrypting and decrypting.
568  *
569  * The first field points to the vtable. The other fields are opaque
570  * and shall not be accessed directly.
571  */
572 typedef struct {
573 	/** \brief Pointer to vtable. */
574 	union {
575 		const void *gen;
576 		const br_sslrec_in_gcm_class *in;
577 		const br_sslrec_out_gcm_class *out;
578 	} vtable;
579 #ifndef BR_DOXYGEN_IGNORE
580 	uint64_t seq;
581 	union {
582 		const br_block_ctr_class *vtable;
583 		br_aes_gen_ctr_keys aes;
584 	} bc;
585 	br_ghash gh;
586 	unsigned char iv[4];
587 	unsigned char h[16];
588 #endif
589 } br_sslrec_gcm_context;
590 
591 /**
592  * \brief Static, constant vtable for record decryption with GCM.
593  */
594 extern const br_sslrec_in_gcm_class br_sslrec_in_gcm_vtable;
595 
596 /**
597  * \brief Static, constant vtable for record encryption with GCM.
598  */
599 extern const br_sslrec_out_gcm_class br_sslrec_out_gcm_vtable;
600 
601 /* ===================================================================== */
602 
603 /**
604  * \brief Record decryption engine class, for ChaCha20+Poly1305.
605  *
606  * This class type extends the decryption engine class with an
607  * initialisation method that receives the parameters needed
608  * for ChaCha20+Poly1305 processing: ChaCha20 implementation,
609  * Poly1305 implementation, key, and 12-byte IV.
610  */
611 typedef struct br_sslrec_in_chapol_class_ br_sslrec_in_chapol_class;
612 struct br_sslrec_in_chapol_class_ {
613 	/**
614 	 * \brief Superclass, as first vtable field.
615 	 */
616 	br_sslrec_in_class inner;
617 
618 	/**
619 	 * \brief Engine initialisation method.
620 	 *
621 	 * This method sets the vtable field in the context.
622 	 *
623 	 * \param ctx           context to initialise.
624 	 * \param ichacha       ChaCha20 implementation.
625 	 * \param ipoly         Poly1305 implementation.
626 	 * \param key           secret key (32 bytes).
627 	 * \param iv            static IV (12 bytes).
628 	 */
629 	void (*init)(const br_sslrec_in_chapol_class **ctx,
630 		br_chacha20_run ichacha,
631 		br_poly1305_run ipoly,
632 		const void *key, const void *iv);
633 };
634 
635 /**
636  * \brief Record encryption engine class, for ChaCha20+Poly1305.
637  *
638  * This class type extends the encryption engine class with an
639  * initialisation method that receives the parameters needed
640  * for ChaCha20+Poly1305 processing: ChaCha20 implementation,
641  * Poly1305 implementation, key, and 12-byte IV.
642  */
643 typedef struct br_sslrec_out_chapol_class_ br_sslrec_out_chapol_class;
644 struct br_sslrec_out_chapol_class_ {
645 	/**
646 	 * \brief Superclass, as first vtable field.
647 	 */
648 	br_sslrec_out_class inner;
649 
650 	/**
651 	 * \brief Engine initialisation method.
652 	 *
653 	 * This method sets the vtable field in the context.
654 	 *
655 	 * \param ctx           context to initialise.
656 	 * \param ichacha       ChaCha20 implementation.
657 	 * \param ipoly         Poly1305 implementation.
658 	 * \param key           secret key (32 bytes).
659 	 * \param iv            static IV (12 bytes).
660 	 */
661 	void (*init)(const br_sslrec_out_chapol_class **ctx,
662 		br_chacha20_run ichacha,
663 		br_poly1305_run ipoly,
664 		const void *key, const void *iv);
665 };
666 
667 /**
668  * \brief Context structure for processing records with ChaCha20+Poly1305.
669  *
670  * The same context structure is used for encrypting and decrypting.
671  *
672  * The first field points to the vtable. The other fields are opaque
673  * and shall not be accessed directly.
674  */
675 typedef struct {
676 	/** \brief Pointer to vtable. */
677 	union {
678 		const void *gen;
679 		const br_sslrec_in_chapol_class *in;
680 		const br_sslrec_out_chapol_class *out;
681 	} vtable;
682 #ifndef BR_DOXYGEN_IGNORE
683 	uint64_t seq;
684 	unsigned char key[32];
685 	unsigned char iv[12];
686 	br_chacha20_run ichacha;
687 	br_poly1305_run ipoly;
688 #endif
689 } br_sslrec_chapol_context;
690 
691 /**
692  * \brief Static, constant vtable for record decryption with ChaCha20+Poly1305.
693  */
694 extern const br_sslrec_in_chapol_class br_sslrec_in_chapol_vtable;
695 
696 /**
697  * \brief Static, constant vtable for record encryption with ChaCha20+Poly1305.
698  */
699 extern const br_sslrec_out_chapol_class br_sslrec_out_chapol_vtable;
700 
701 /* ===================================================================== */
702 
703 /**
704  * \brief Record decryption engine class, for CCM mode.
705  *
706  * This class type extends the decryption engine class with an
707  * initialisation method that receives the parameters needed
708  * for CCM processing: block cipher implementation, block cipher key,
709  * and 4-byte IV.
710  */
711 typedef struct br_sslrec_in_ccm_class_ br_sslrec_in_ccm_class;
712 struct br_sslrec_in_ccm_class_ {
713 	/**
714 	 * \brief Superclass, as first vtable field.
715 	 */
716 	br_sslrec_in_class inner;
717 
718 	/**
719 	 * \brief Engine initialisation method.
720 	 *
721 	 * This method sets the vtable field in the context.
722 	 *
723 	 * \param ctx           context to initialise.
724 	 * \param bc_impl       block cipher implementation (CTR+CBC).
725 	 * \param key           block cipher key.
726 	 * \param key_len       block cipher key length (in bytes).
727 	 * \param iv            static IV (4 bytes).
728 	 * \param tag_len       tag length (in bytes)
729 	 */
730 	void (*init)(const br_sslrec_in_ccm_class **ctx,
731 		const br_block_ctrcbc_class *bc_impl,
732 		const void *key, size_t key_len,
733 		const void *iv, size_t tag_len);
734 };
735 
736 /**
737  * \brief Record encryption engine class, for CCM mode.
738  *
739  * This class type extends the encryption engine class with an
740  * initialisation method that receives the parameters needed
741  * for CCM processing: block cipher implementation, block cipher key,
742  * and 4-byte IV.
743  */
744 typedef struct br_sslrec_out_ccm_class_ br_sslrec_out_ccm_class;
745 struct br_sslrec_out_ccm_class_ {
746 	/**
747 	 * \brief Superclass, as first vtable field.
748 	 */
749 	br_sslrec_out_class inner;
750 
751 	/**
752 	 * \brief Engine initialisation method.
753 	 *
754 	 * This method sets the vtable field in the context.
755 	 *
756 	 * \param ctx           context to initialise.
757 	 * \param bc_impl       block cipher implementation (CTR+CBC).
758 	 * \param key           block cipher key.
759 	 * \param key_len       block cipher key length (in bytes).
760 	 * \param iv            static IV (4 bytes).
761 	 * \param tag_len       tag length (in bytes)
762 	 */
763 	void (*init)(const br_sslrec_out_ccm_class **ctx,
764 		const br_block_ctrcbc_class *bc_impl,
765 		const void *key, size_t key_len,
766 		const void *iv, size_t tag_len);
767 };
768 
769 /**
770  * \brief Context structure for processing records with CCM.
771  *
772  * The same context structure is used for encrypting and decrypting.
773  *
774  * The first field points to the vtable. The other fields are opaque
775  * and shall not be accessed directly.
776  */
777 typedef struct {
778 	/** \brief Pointer to vtable. */
779 	union {
780 		const void *gen;
781 		const br_sslrec_in_ccm_class *in;
782 		const br_sslrec_out_ccm_class *out;
783 	} vtable;
784 #ifndef BR_DOXYGEN_IGNORE
785 	uint64_t seq;
786 	union {
787 		const br_block_ctrcbc_class *vtable;
788 		br_aes_gen_ctrcbc_keys aes;
789 	} bc;
790 	unsigned char iv[4];
791 	size_t tag_len;
792 #endif
793 } br_sslrec_ccm_context;
794 
795 /**
796  * \brief Static, constant vtable for record decryption with CCM.
797  */
798 extern const br_sslrec_in_ccm_class br_sslrec_in_ccm_vtable;
799 
800 /**
801  * \brief Static, constant vtable for record encryption with CCM.
802  */
803 extern const br_sslrec_out_ccm_class br_sslrec_out_ccm_vtable;
804 
805 /* ===================================================================== */
806 
807 /**
808  * \brief Type for session parameters, to be saved for session resumption.
809  */
810 typedef struct {
811 	/** \brief Session ID buffer. */
812 	unsigned char session_id[32];
813 	/** \brief Session ID length (in bytes, at most 32). */
814 	unsigned char session_id_len;
815 	/** \brief Protocol version. */
816 	uint16_t version;
817 	/** \brief Cipher suite. */
818 	uint16_t cipher_suite;
819 	/** \brief Master secret. */
820 	unsigned char master_secret[48];
821 } br_ssl_session_parameters;
822 
823 #ifndef BR_DOXYGEN_IGNORE
824 /*
825  * Maximum number of cipher suites supported by a client or server.
826  */
827 #define BR_MAX_CIPHER_SUITES   48
828 #endif
829 
830 /**
831  * \brief Context structure for SSL engine.
832  *
833  * This strucuture is common to the client and server; both the client
834  * context (`br_ssl_client_context`) and the server context
835  * (`br_ssl_server_context`) include a `br_ssl_engine_context` as their
836  * first field.
837  *
838  * The engine context manages records, including alerts, closures, and
839  * transitions to new encryption/MAC algorithms. Processing of handshake
840  * records is delegated to externally provided code. This structure
841  * should not be used directly.
842  *
843  * Structure contents are opaque and shall not be accessed directly.
844  */
845 typedef struct {
846 #ifndef BR_DOXYGEN_IGNORE
847 	/*
848 	 * The error code. When non-zero, then the state is "failed" and
849 	 * no I/O may occur until reset.
850 	 */
851 	int err;
852 
853 	/*
854 	 * Configured I/O buffers. They are either disjoint, or identical.
855 	 */
856 	unsigned char *ibuf, *obuf;
857 	size_t ibuf_len, obuf_len;
858 
859 	/*
860 	 * Maximum fragment length applies to outgoing records; incoming
861 	 * records can be processed as long as they fit in the input
862 	 * buffer. It is guaranteed that incoming records at least as big
863 	 * as max_frag_len can be processed.
864 	 */
865 	uint16_t max_frag_len;
866 	unsigned char log_max_frag_len;
867 	unsigned char peer_log_max_frag_len;
868 
869 	/*
870 	 * Buffering management registers.
871 	 */
872 	size_t ixa, ixb, ixc;
873 	size_t oxa, oxb, oxc;
874 	unsigned char iomode;
875 	unsigned char incrypt;
876 
877 	/*
878 	 * Shutdown flag: when set to non-zero, incoming record bytes
879 	 * will not be accepted anymore. This is used after a close_notify
880 	 * has been received: afterwards, the engine no longer claims that
881 	 * it could receive bytes from the transport medium.
882 	 */
883 	unsigned char shutdown_recv;
884 
885 	/*
886 	 * 'record_type_in' is set to the incoming record type when the
887 	 * record header has been received.
888 	 * 'record_type_out' is used to make the next outgoing record
889 	 * header when it is ready to go.
890 	 */
891 	unsigned char record_type_in, record_type_out;
892 
893 	/*
894 	 * When a record is received, its version is extracted:
895 	 * -- if 'version_in' is 0, then it is set to the received version;
896 	 * -- otherwise, if the received version is not identical to
897 	 *    the 'version_in' contents, then a failure is reported.
898 	 *
899 	 * This implements the SSL requirement that all records shall
900 	 * use the negotiated protocol version, once decided (in the
901 	 * ServerHello). It is up to the handshake handler to adjust this
902 	 * field when necessary.
903 	 */
904 	uint16_t version_in;
905 
906 	/*
907 	 * 'version_out' is used when the next outgoing record is ready
908 	 * to go.
909 	 */
910 	uint16_t version_out;
911 
912 	/*
913 	 * Record handler contexts.
914 	 */
915 	union {
916 		const br_sslrec_in_class *vtable;
917 		br_sslrec_in_cbc_context cbc;
918 		br_sslrec_gcm_context gcm;
919 		br_sslrec_chapol_context chapol;
920 		br_sslrec_ccm_context ccm;
921 	} in;
922 	union {
923 		const br_sslrec_out_class *vtable;
924 		br_sslrec_out_clear_context clear;
925 		br_sslrec_out_cbc_context cbc;
926 		br_sslrec_gcm_context gcm;
927 		br_sslrec_chapol_context chapol;
928 		br_sslrec_ccm_context ccm;
929 	} out;
930 
931 	/*
932 	 * The "application data" flag. Value:
933 	 *   0   handshake is in process, no application data acceptable
934 	 *   1   application data can be sent and received
935 	 *   2   closing, no application data can be sent, but some
936 	 *       can still be received (and discarded)
937 	 */
938 	unsigned char application_data;
939 
940 	/*
941 	 * Context RNG.
942 	 *
943 	 *   rng_init_done is initially 0. It is set to 1 when the
944 	 *   basic structure of the RNG is set, and 2 when some
945 	 *   entropy has been pushed in. The value 2 marks the RNG
946 	 *   as "properly seeded".
947 	 *
948 	 *   rng_os_rand_done is initially 0. It is set to 1 when
949 	 *   some seeding from the OS or hardware has been attempted.
950 	 */
951 	br_hmac_drbg_context rng;
952 	int rng_init_done;
953 	int rng_os_rand_done;
954 
955 	/*
956 	 * Supported minimum and maximum versions, and cipher suites.
957 	 */
958 	uint16_t version_min;
959 	uint16_t version_max;
960 	uint16_t suites_buf[BR_MAX_CIPHER_SUITES];
961 	unsigned char suites_num;
962 
963 	/*
964 	 * For clients, the server name to send as a SNI extension. For
965 	 * servers, the name received in the SNI extension (if any).
966 	 */
967 	char server_name[256];
968 
969 	/*
970 	 * "Security parameters". These are filled by the handshake
971 	 * handler, and used when switching encryption state.
972 	 */
973 	unsigned char client_random[32];
974 	unsigned char server_random[32];
975 	br_ssl_session_parameters session;
976 
977 	/*
978 	 * ECDHE elements: curve and point from the peer. The server also
979 	 * uses that buffer for the point to send to the client.
980 	 */
981 	unsigned char ecdhe_curve;
982 	unsigned char ecdhe_point[133];
983 	unsigned char ecdhe_point_len;
984 
985 	/*
986 	 * Secure renegotiation (RFC 5746): 'reneg' can be:
987 	 *   0   first handshake (server support is not known)
988 	 *   1   peer does not support secure renegotiation
989 	 *   2   peer supports secure renegotiation
990 	 *
991 	 * The saved_finished buffer contains the client and the
992 	 * server "Finished" values from the last handshake, in
993 	 * that order (12 bytes each).
994 	 */
995 	unsigned char reneg;
996 	unsigned char saved_finished[24];
997 
998 	/*
999 	 * Behavioural flags.
1000 	 */
1001 	uint32_t flags;
1002 
1003 	/*
1004 	 * Context variables for the handshake processor. The 'pad' must
1005 	 * be large enough to accommodate an RSA-encrypted pre-master
1006 	 * secret, or an RSA signature; since we want to support up to
1007 	 * RSA-4096, this means at least 512 bytes. (Other pad usages
1008 	 * require its length to be at least 256.)
1009 	 */
1010 	struct {
1011 		uint32_t *dp;
1012 		uint32_t *rp;
1013 		const unsigned char *ip;
1014 	} cpu;
1015 	uint32_t dp_stack[32];
1016 	uint32_t rp_stack[32];
1017 	unsigned char pad[512];
1018 	unsigned char *hbuf_in, *hbuf_out, *saved_hbuf_out;
1019 	size_t hlen_in, hlen_out;
1020 	void (*hsrun)(void *ctx);
1021 
1022 	/*
1023 	 * The 'action' value communicates OOB information between the
1024 	 * engine and the handshake processor.
1025 	 *
1026 	 * From the engine:
1027 	 *   0  invocation triggered by I/O
1028 	 *   1  invocation triggered by explicit close
1029 	 *   2  invocation triggered by explicit renegotiation
1030 	 */
1031 	unsigned char action;
1032 
1033 	/*
1034 	 * State for alert messages. Value is either 0, or the value of
1035 	 * the alert level byte (level is either 1 for warning, or 2 for
1036 	 * fatal; we convert all other values to 'fatal').
1037 	 */
1038 	unsigned char alert;
1039 
1040 	/*
1041 	 * Closure flags. This flag is set when a close_notify has been
1042 	 * received from the peer.
1043 	 */
1044 	unsigned char close_received;
1045 
1046 	/*
1047 	 * Multi-hasher for the handshake messages. The handshake handler
1048 	 * is responsible for resetting it when appropriate.
1049 	 */
1050 	br_multihash_context mhash;
1051 
1052 	/*
1053 	 * Pointer to the X.509 engine. The engine is supposed to be
1054 	 * already initialized. It is used to validate the peer's
1055 	 * certificate.
1056 	 */
1057 	const br_x509_class **x509ctx;
1058 
1059 	/*
1060 	 * Certificate chain to send. This is used by both client and
1061 	 * server, when they send their respective Certificate messages.
1062 	 * If chain_len is 0, then chain may be NULL.
1063 	 */
1064 	const br_x509_certificate *chain;
1065 	size_t chain_len;
1066 	const unsigned char *cert_cur;
1067 	size_t cert_len;
1068 
1069 	/*
1070 	 * List of supported protocol names (ALPN extension). If unset,
1071 	 * (number of names is 0), then:
1072 	 *  - the client sends no ALPN extension;
1073 	 *  - the server ignores any incoming ALPN extension.
1074 	 *
1075 	 * Otherwise:
1076 	 *  - the client sends an ALPN extension with all the names;
1077 	 *  - the server selects the first protocol in its list that
1078 	 *    the client also supports, or fails (fatal alert 120)
1079 	 *    if the client sends an ALPN extension and there is no
1080 	 *    match.
1081 	 *
1082 	 * The 'selected_protocol' field contains 1+n if the matching
1083 	 * name has index n in the list (the value is 0 if no match was
1084 	 * performed, e.g. the peer did not send an ALPN extension).
1085 	 */
1086 	const char **protocol_names;
1087 	uint16_t protocol_names_num;
1088 	uint16_t selected_protocol;
1089 
1090 	/*
1091 	 * Pointers to implementations; left to NULL for unsupported
1092 	 * functions. For the raw hash functions, implementations are
1093 	 * referenced from the multihasher (mhash field).
1094 	 */
1095 	br_tls_prf_impl prf10;
1096 	br_tls_prf_impl prf_sha256;
1097 	br_tls_prf_impl prf_sha384;
1098 	const br_block_cbcenc_class *iaes_cbcenc;
1099 	const br_block_cbcdec_class *iaes_cbcdec;
1100 	const br_block_ctr_class *iaes_ctr;
1101 	const br_block_ctrcbc_class *iaes_ctrcbc;
1102 	const br_block_cbcenc_class *ides_cbcenc;
1103 	const br_block_cbcdec_class *ides_cbcdec;
1104 	br_ghash ighash;
1105 	br_chacha20_run ichacha;
1106 	br_poly1305_run ipoly;
1107 	const br_sslrec_in_cbc_class *icbc_in;
1108 	const br_sslrec_out_cbc_class *icbc_out;
1109 	const br_sslrec_in_gcm_class *igcm_in;
1110 	const br_sslrec_out_gcm_class *igcm_out;
1111 	const br_sslrec_in_chapol_class *ichapol_in;
1112 	const br_sslrec_out_chapol_class *ichapol_out;
1113 	const br_sslrec_in_ccm_class *iccm_in;
1114 	const br_sslrec_out_ccm_class *iccm_out;
1115 	const br_ec_impl *iec;
1116 	br_rsa_pkcs1_vrfy irsavrfy;
1117 	br_ecdsa_vrfy iecdsa;
1118 #endif
1119 } br_ssl_engine_context;
1120 
1121 /**
1122  * \brief Get currently defined engine behavioural flags.
1123  *
1124  * \param cc   SSL engine context.
1125  * \return  the flags.
1126  */
1127 static inline uint32_t
1128 br_ssl_engine_get_flags(br_ssl_engine_context *cc)
1129 {
1130 	return cc->flags;
1131 }
1132 
1133 /**
1134  * \brief Set all engine behavioural flags.
1135  *
1136  * \param cc      SSL engine context.
1137  * \param flags   new value for all flags.
1138  */
1139 static inline void
1140 br_ssl_engine_set_all_flags(br_ssl_engine_context *cc, uint32_t flags)
1141 {
1142 	cc->flags = flags;
1143 }
1144 
1145 /**
1146  * \brief Set some engine behavioural flags.
1147  *
1148  * The flags set in the `flags` parameter are set in the context; other
1149  * flags are untouched.
1150  *
1151  * \param cc      SSL engine context.
1152  * \param flags   additional set flags.
1153  */
1154 static inline void
1155 br_ssl_engine_add_flags(br_ssl_engine_context *cc, uint32_t flags)
1156 {
1157 	cc->flags |= flags;
1158 }
1159 
1160 /**
1161  * \brief Clear some engine behavioural flags.
1162  *
1163  * The flags set in the `flags` parameter are cleared from the context; other
1164  * flags are untouched.
1165  *
1166  * \param cc      SSL engine context.
1167  * \param flags   flags to remove.
1168  */
1169 static inline void
1170 br_ssl_engine_remove_flags(br_ssl_engine_context *cc, uint32_t flags)
1171 {
1172 	cc->flags &= ~flags;
1173 }
1174 
1175 /**
1176  * \brief Behavioural flag: enforce server preferences.
1177  *
1178  * If this flag is set, then the server will enforce its own cipher suite
1179  * preference order; otherwise, it follows the client preferences.
1180  */
1181 #define BR_OPT_ENFORCE_SERVER_PREFERENCES      ((uint32_t)1 << 0)
1182 
1183 /**
1184  * \brief Behavioural flag: disable renegotiation.
1185  *
1186  * If this flag is set, then renegotiations are rejected unconditionally:
1187  * they won't be honoured if asked for programmatically, and requests from
1188  * the peer are rejected.
1189  */
1190 #define BR_OPT_NO_RENEGOTIATION                ((uint32_t)1 << 1)
1191 
1192 /**
1193  * \brief Behavioural flag: tolerate lack of client authentication.
1194  *
1195  * If this flag is set in a server and the server requests a client
1196  * certificate, but the authentication fails (the client does not send
1197  * a certificate, or the client's certificate chain cannot be validated),
1198  * then the connection keeps on. Without this flag, a failed client
1199  * authentication terminates the connection.
1200  *
1201  * Notes:
1202  *
1203  *   - If the client's certificate can be validated and its public key is
1204  *     supported, then a wrong signature value terminates the connection
1205  *     regardless of that flag.
1206  *
1207  *   - If using full-static ECDH, then a failure to validate the client's
1208  *     certificate prevents the handshake from succeeding.
1209  */
1210 #define BR_OPT_TOLERATE_NO_CLIENT_AUTH         ((uint32_t)1 << 2)
1211 
1212 /**
1213  * \brief Behavioural flag: fail on application protocol mismatch.
1214  *
1215  * The ALPN extension ([RFC 7301](https://tools.ietf.org/html/rfc7301))
1216  * allows the client to send a list of application protocol names, and
1217  * the server to select one. A mismatch is one of the following occurrences:
1218  *
1219  *   - On the client: the client sends a list of names, the server
1220  *     responds with a protocol name which is _not_ part of the list of
1221  *     names sent by the client.
1222  *
1223  *   - On the server: the client sends a list of names, and the server
1224  *     is also configured with a list of names, but there is no common
1225  *     protocol name between the two lists.
1226  *
1227  * Normal behaviour in case of mismatch is to report no matching name
1228  * (`br_ssl_engine_get_selected_protocol()` returns `NULL`) and carry on.
1229  * If the flag is set, then a mismatch implies a protocol failure (if
1230  * the mismatch is detected by the server, it will send a fatal alert).
1231  *
1232  * Note: even with this flag, `br_ssl_engine_get_selected_protocol()`
1233  * may still return `NULL` if the client or the server does not send an
1234  * ALPN extension at all.
1235  */
1236 #define BR_OPT_FAIL_ON_ALPN_MISMATCH           ((uint32_t)1 << 3)
1237 
1238 /**
1239  * \brief Set the minimum and maximum supported protocol versions.
1240  *
1241  * The two provided versions MUST be supported by the implementation
1242  * (i.e. TLS 1.0, 1.1 and 1.2), and `version_max` MUST NOT be lower
1243  * than `version_min`.
1244  *
1245  * \param cc            SSL engine context.
1246  * \param version_min   minimum supported TLS version.
1247  * \param version_max   maximum supported TLS version.
1248  */
1249 static inline void
1250 br_ssl_engine_set_versions(br_ssl_engine_context *cc,
1251 	unsigned version_min, unsigned version_max)
1252 {
1253 	cc->version_min = version_min;
1254 	cc->version_max = version_max;
1255 }
1256 
1257 /**
1258  * \brief Set the list of cipher suites advertised by this context.
1259  *
1260  * The provided array is copied into the context. It is the caller
1261  * responsibility to ensure that all provided suites will be supported
1262  * by the context. The engine context has enough room to receive _all_
1263  * suites supported by the implementation. The provided array MUST NOT
1264  * contain duplicates.
1265  *
1266  * If the engine is for a client, the "signaling" pseudo-cipher suite
1267  * `TLS_FALLBACK_SCSV` can be added at the end of the list, if the
1268  * calling application is performing a voluntary downgrade (voluntary
1269  * downgrades are not recommended, but if such a downgrade is done, then
1270  * adding the fallback pseudo-suite is a good idea).
1271  *
1272  * \param cc           SSL engine context.
1273  * \param suites       cipher suites.
1274  * \param suites_num   number of cipher suites.
1275  */
1276 void br_ssl_engine_set_suites(br_ssl_engine_context *cc,
1277 	const uint16_t *suites, size_t suites_num);
1278 
1279 /**
1280  * \brief Set the X.509 engine.
1281  *
1282  * The caller shall ensure that the X.509 engine is properly initialised.
1283  *
1284  * \param cc        SSL engine context.
1285  * \param x509ctx   X.509 certificate validation context.
1286  */
1287 static inline void
1288 br_ssl_engine_set_x509(br_ssl_engine_context *cc, const br_x509_class **x509ctx)
1289 {
1290 	cc->x509ctx = x509ctx;
1291 }
1292 
1293 /**
1294  * \brief Set the supported protocol names.
1295  *
1296  * Protocol names are part of the ALPN extension ([RFC
1297  * 7301](https://tools.ietf.org/html/rfc7301)). Each protocol name is a
1298  * character string, containing no more than 255 characters (256 with the
1299  * terminating zero). When names are set, then:
1300  *
1301  *   - The client will send an ALPN extension, containing the names. If
1302  *     the server responds with an ALPN extension, the client will verify
1303  *     that the response contains one of its name, and report that name
1304  *     through `br_ssl_engine_get_selected_protocol()`.
1305  *
1306  *   - The server will parse incoming ALPN extension (from clients), and
1307  *     try to find a common protocol; if none is found, the connection
1308  *     is aborted with a fatal alert. On match, a response ALPN extension
1309  *     is sent, and name is reported through
1310  *     `br_ssl_engine_get_selected_protocol()`.
1311  *
1312  * The provided array is linked in, and must remain valid while the
1313  * connection is live.
1314  *
1315  * Names MUST NOT be empty. Names MUST NOT be longer than 255 characters
1316  * (excluding the terminating 0).
1317  *
1318  * \param ctx     SSL engine context.
1319  * \param names   list of protocol names (zero-terminated).
1320  * \param num     number of protocol names (MUST be 1 or more).
1321  */
1322 static inline void
1323 br_ssl_engine_set_protocol_names(br_ssl_engine_context *ctx,
1324 	const char **names, size_t num)
1325 {
1326 	ctx->protocol_names = names;
1327 	ctx->protocol_names_num = num;
1328 }
1329 
1330 /**
1331  * \brief Get the selected protocol.
1332  *
1333  * If this context was initialised with a non-empty list of protocol
1334  * names, and both client and server sent ALPN extensions during the
1335  * handshake, and a common name was found, then that name is returned.
1336  * Otherwise, `NULL` is returned.
1337  *
1338  * The returned pointer is one of the pointers provided to the context
1339  * with `br_ssl_engine_set_protocol_names()`.
1340  *
1341  * \return  the selected protocol, or `NULL`.
1342  */
1343 static inline const char *
1344 br_ssl_engine_get_selected_protocol(br_ssl_engine_context *ctx)
1345 {
1346 	unsigned k;
1347 
1348 	k = ctx->selected_protocol;
1349 	return (k == 0 || k == 0xFFFF) ? NULL : ctx->protocol_names[k - 1];
1350 }
1351 
1352 /**
1353  * \brief Set a hash function implementation (by ID).
1354  *
1355  * Hash functions set with this call will be used for SSL/TLS specific
1356  * usages, not X.509 certificate validation. Only "standard" hash functions
1357  * may be set (MD5, SHA-1, SHA-224, SHA-256, SHA-384, SHA-512). If `impl`
1358  * is `NULL`, then the hash function support is removed, not added.
1359  *
1360  * \param ctx    SSL engine context.
1361  * \param id     hash function identifier.
1362  * \param impl   hash function implementation (or `NULL`).
1363  */
1364 static inline void
1365 br_ssl_engine_set_hash(br_ssl_engine_context *ctx,
1366 	int id, const br_hash_class *impl)
1367 {
1368 	br_multihash_setimpl(&ctx->mhash, id, impl);
1369 }
1370 
1371 /**
1372  * \brief Get a hash function implementation (by ID).
1373  *
1374  * This function retrieves a hash function implementation which was
1375  * set with `br_ssl_engine_set_hash()`.
1376  *
1377  * \param ctx   SSL engine context.
1378  * \param id    hash function identifier.
1379  * \return  the hash function implementation (or `NULL`).
1380  */
1381 static inline const br_hash_class *
1382 br_ssl_engine_get_hash(br_ssl_engine_context *ctx, int id)
1383 {
1384 	return br_multihash_getimpl(&ctx->mhash, id);
1385 }
1386 
1387 /**
1388  * \brief Set the PRF implementation (for TLS 1.0 and 1.1).
1389  *
1390  * This function sets (or removes, if `impl` is `NULL`) the implementation
1391  * for the PRF used in TLS 1.0 and 1.1.
1392  *
1393  * \param cc     SSL engine context.
1394  * \param impl   PRF implementation (or `NULL`).
1395  */
1396 static inline void
1397 br_ssl_engine_set_prf10(br_ssl_engine_context *cc, br_tls_prf_impl impl)
1398 {
1399 	cc->prf10 = impl;
1400 }
1401 
1402 /**
1403  * \brief Set the PRF implementation with SHA-256 (for TLS 1.2).
1404  *
1405  * This function sets (or removes, if `impl` is `NULL`) the implementation
1406  * for the SHA-256 variant of the PRF used in TLS 1.2.
1407  *
1408  * \param cc     SSL engine context.
1409  * \param impl   PRF implementation (or `NULL`).
1410  */
1411 static inline void
1412 br_ssl_engine_set_prf_sha256(br_ssl_engine_context *cc, br_tls_prf_impl impl)
1413 {
1414 	cc->prf_sha256 = impl;
1415 }
1416 
1417 /**
1418  * \brief Set the PRF implementation with SHA-384 (for TLS 1.2).
1419  *
1420  * This function sets (or removes, if `impl` is `NULL`) the implementation
1421  * for the SHA-384 variant of the PRF used in TLS 1.2.
1422  *
1423  * \param cc     SSL engine context.
1424  * \param impl   PRF implementation (or `NULL`).
1425  */
1426 static inline void
1427 br_ssl_engine_set_prf_sha384(br_ssl_engine_context *cc, br_tls_prf_impl impl)
1428 {
1429 	cc->prf_sha384 = impl;
1430 }
1431 
1432 /**
1433  * \brief Set the AES/CBC implementations.
1434  *
1435  * \param cc         SSL engine context.
1436  * \param impl_enc   AES/CBC encryption implementation (or `NULL`).
1437  * \param impl_dec   AES/CBC decryption implementation (or `NULL`).
1438  */
1439 static inline void
1440 br_ssl_engine_set_aes_cbc(br_ssl_engine_context *cc,
1441 	const br_block_cbcenc_class *impl_enc,
1442 	const br_block_cbcdec_class *impl_dec)
1443 {
1444 	cc->iaes_cbcenc = impl_enc;
1445 	cc->iaes_cbcdec = impl_dec;
1446 }
1447 
1448 /**
1449  * \brief Set the "default" AES/CBC implementations.
1450  *
1451  * This function configures in the engine the AES implementations that
1452  * should provide best runtime performance on the local system, while
1453  * still being safe (in particular, constant-time). It also sets the
1454  * handlers for CBC records.
1455  *
1456  * \param cc   SSL engine context.
1457  */
1458 void br_ssl_engine_set_default_aes_cbc(br_ssl_engine_context *cc);
1459 
1460 /**
1461  * \brief Set the AES/CTR implementation.
1462  *
1463  * \param cc     SSL engine context.
1464  * \param impl   AES/CTR encryption/decryption implementation (or `NULL`).
1465  */
1466 static inline void
1467 br_ssl_engine_set_aes_ctr(br_ssl_engine_context *cc,
1468 	const br_block_ctr_class *impl)
1469 {
1470 	cc->iaes_ctr = impl;
1471 }
1472 
1473 /**
1474  * \brief Set the "default" implementations for AES/GCM (AES/CTR + GHASH).
1475  *
1476  * This function configures in the engine the AES/CTR and GHASH
1477  * implementation that should provide best runtime performance on the local
1478  * system, while still being safe (in particular, constant-time). It also
1479  * sets the handlers for GCM records.
1480  *
1481  * \param cc   SSL engine context.
1482  */
1483 void br_ssl_engine_set_default_aes_gcm(br_ssl_engine_context *cc);
1484 
1485 /**
1486  * \brief Set the DES/CBC implementations.
1487  *
1488  * \param cc         SSL engine context.
1489  * \param impl_enc   DES/CBC encryption implementation (or `NULL`).
1490  * \param impl_dec   DES/CBC decryption implementation (or `NULL`).
1491  */
1492 static inline void
1493 br_ssl_engine_set_des_cbc(br_ssl_engine_context *cc,
1494 	const br_block_cbcenc_class *impl_enc,
1495 	const br_block_cbcdec_class *impl_dec)
1496 {
1497 	cc->ides_cbcenc = impl_enc;
1498 	cc->ides_cbcdec = impl_dec;
1499 }
1500 
1501 /**
1502  * \brief Set the "default" DES/CBC implementations.
1503  *
1504  * This function configures in the engine the DES implementations that
1505  * should provide best runtime performance on the local system, while
1506  * still being safe (in particular, constant-time). It also sets the
1507  * handlers for CBC records.
1508  *
1509  * \param cc   SSL engine context.
1510  */
1511 void br_ssl_engine_set_default_des_cbc(br_ssl_engine_context *cc);
1512 
1513 /**
1514  * \brief Set the GHASH implementation (used in GCM mode).
1515  *
1516  * \param cc     SSL engine context.
1517  * \param impl   GHASH implementation (or `NULL`).
1518  */
1519 static inline void
1520 br_ssl_engine_set_ghash(br_ssl_engine_context *cc, br_ghash impl)
1521 {
1522 	cc->ighash = impl;
1523 }
1524 
1525 /**
1526  * \brief Set the ChaCha20 implementation.
1527  *
1528  * \param cc        SSL engine context.
1529  * \param ichacha   ChaCha20 implementation (or `NULL`).
1530  */
1531 static inline void
1532 br_ssl_engine_set_chacha20(br_ssl_engine_context *cc,
1533 	br_chacha20_run ichacha)
1534 {
1535 	cc->ichacha = ichacha;
1536 }
1537 
1538 /**
1539  * \brief Set the Poly1305 implementation.
1540  *
1541  * \param cc      SSL engine context.
1542  * \param ipoly   Poly1305 implementation (or `NULL`).
1543  */
1544 static inline void
1545 br_ssl_engine_set_poly1305(br_ssl_engine_context *cc,
1546 	br_poly1305_run ipoly)
1547 {
1548 	cc->ipoly = ipoly;
1549 }
1550 
1551 /**
1552  * \brief Set the "default" ChaCha20 and Poly1305 implementations.
1553  *
1554  * This function configures in the engine the ChaCha20 and Poly1305
1555  * implementations that should provide best runtime performance on the
1556  * local system, while still being safe (in particular, constant-time).
1557  * It also sets the handlers for ChaCha20+Poly1305 records.
1558  *
1559  * \param cc   SSL engine context.
1560  */
1561 void br_ssl_engine_set_default_chapol(br_ssl_engine_context *cc);
1562 
1563 /**
1564  * \brief Set the AES/CTR+CBC implementation.
1565  *
1566  * \param cc     SSL engine context.
1567  * \param impl   AES/CTR+CBC encryption/decryption implementation (or `NULL`).
1568  */
1569 static inline void
1570 br_ssl_engine_set_aes_ctrcbc(br_ssl_engine_context *cc,
1571 	const br_block_ctrcbc_class *impl)
1572 {
1573 	cc->iaes_ctrcbc = impl;
1574 }
1575 
1576 /**
1577  * \brief Set the "default" implementations for AES/CCM.
1578  *
1579  * This function configures in the engine the AES/CTR+CBC
1580  * implementation that should provide best runtime performance on the local
1581  * system, while still being safe (in particular, constant-time). It also
1582  * sets the handlers for CCM records.
1583  *
1584  * \param cc   SSL engine context.
1585  */
1586 void br_ssl_engine_set_default_aes_ccm(br_ssl_engine_context *cc);
1587 
1588 /**
1589  * \brief Set the record encryption and decryption engines for CBC + HMAC.
1590  *
1591  * \param cc         SSL engine context.
1592  * \param impl_in    record CBC decryption implementation (or `NULL`).
1593  * \param impl_out   record CBC encryption implementation (or `NULL`).
1594  */
1595 static inline void
1596 br_ssl_engine_set_cbc(br_ssl_engine_context *cc,
1597 	const br_sslrec_in_cbc_class *impl_in,
1598 	const br_sslrec_out_cbc_class *impl_out)
1599 {
1600 	cc->icbc_in = impl_in;
1601 	cc->icbc_out = impl_out;
1602 }
1603 
1604 /**
1605  * \brief Set the record encryption and decryption engines for GCM.
1606  *
1607  * \param cc         SSL engine context.
1608  * \param impl_in    record GCM decryption implementation (or `NULL`).
1609  * \param impl_out   record GCM encryption implementation (or `NULL`).
1610  */
1611 static inline void
1612 br_ssl_engine_set_gcm(br_ssl_engine_context *cc,
1613 	const br_sslrec_in_gcm_class *impl_in,
1614 	const br_sslrec_out_gcm_class *impl_out)
1615 {
1616 	cc->igcm_in = impl_in;
1617 	cc->igcm_out = impl_out;
1618 }
1619 
1620 /**
1621  * \brief Set the record encryption and decryption engines for CCM.
1622  *
1623  * \param cc         SSL engine context.
1624  * \param impl_in    record CCM decryption implementation (or `NULL`).
1625  * \param impl_out   record CCM encryption implementation (or `NULL`).
1626  */
1627 static inline void
1628 br_ssl_engine_set_ccm(br_ssl_engine_context *cc,
1629 	const br_sslrec_in_ccm_class *impl_in,
1630 	const br_sslrec_out_ccm_class *impl_out)
1631 {
1632 	cc->iccm_in = impl_in;
1633 	cc->iccm_out = impl_out;
1634 }
1635 
1636 /**
1637  * \brief Set the record encryption and decryption engines for
1638  * ChaCha20+Poly1305.
1639  *
1640  * \param cc         SSL engine context.
1641  * \param impl_in    record ChaCha20 decryption implementation (or `NULL`).
1642  * \param impl_out   record ChaCha20 encryption implementation (or `NULL`).
1643  */
1644 static inline void
1645 br_ssl_engine_set_chapol(br_ssl_engine_context *cc,
1646 	const br_sslrec_in_chapol_class *impl_in,
1647 	const br_sslrec_out_chapol_class *impl_out)
1648 {
1649 	cc->ichapol_in = impl_in;
1650 	cc->ichapol_out = impl_out;
1651 }
1652 
1653 /**
1654  * \brief Set the EC implementation.
1655  *
1656  * The elliptic curve implementation will be used for ECDH and ECDHE
1657  * cipher suites, and for ECDSA support.
1658  *
1659  * \param cc    SSL engine context.
1660  * \param iec   EC implementation (or `NULL`).
1661  */
1662 static inline void
1663 br_ssl_engine_set_ec(br_ssl_engine_context *cc, const br_ec_impl *iec)
1664 {
1665 	cc->iec = iec;
1666 }
1667 
1668 /**
1669  * \brief Set the "default" EC implementation.
1670  *
1671  * This function sets the elliptic curve implementation for ECDH and
1672  * ECDHE cipher suites, and for ECDSA support. It selects the fastest
1673  * implementation on the current system.
1674  *
1675  * \param cc   SSL engine context.
1676  */
1677 void br_ssl_engine_set_default_ec(br_ssl_engine_context *cc);
1678 
1679 /**
1680  * \brief Get the EC implementation configured in the provided engine.
1681  *
1682  * \param cc   SSL engine context.
1683  * \return  the EC implementation.
1684  */
1685 static inline const br_ec_impl *
1686 br_ssl_engine_get_ec(br_ssl_engine_context *cc)
1687 {
1688 	return cc->iec;
1689 }
1690 
1691 /**
1692  * \brief Set the RSA signature verification implementation.
1693  *
1694  * On the client, this is used to verify the server's signature on its
1695  * ServerKeyExchange message (for ECDHE_RSA cipher suites). On the server,
1696  * this is used to verify the client's CertificateVerify message (if a
1697  * client certificate is requested, and that certificate contains a RSA key).
1698  *
1699  * \param cc         SSL engine context.
1700  * \param irsavrfy   RSA signature verification implementation.
1701  */
1702 static inline void
1703 br_ssl_engine_set_rsavrfy(br_ssl_engine_context *cc, br_rsa_pkcs1_vrfy irsavrfy)
1704 {
1705 	cc->irsavrfy = irsavrfy;
1706 }
1707 
1708 /**
1709  * \brief Set the "default" RSA implementation (signature verification).
1710  *
1711  * This function sets the RSA implementation (signature verification)
1712  * to the fastest implementation available on the current platform.
1713  *
1714  * \param cc   SSL engine context.
1715  */
1716 void br_ssl_engine_set_default_rsavrfy(br_ssl_engine_context *cc);
1717 
1718 /**
1719  * \brief Get the RSA implementation (signature verification) configured
1720  * in the provided engine.
1721  *
1722  * \param cc   SSL engine context.
1723  * \return  the RSA signature verification implementation.
1724  */
1725 static inline br_rsa_pkcs1_vrfy
1726 br_ssl_engine_get_rsavrfy(br_ssl_engine_context *cc)
1727 {
1728 	return cc->irsavrfy;
1729 }
1730 
1731 /*
1732  * \brief Set the ECDSA implementation (signature verification).
1733  *
1734  * On the client, this is used to verify the server's signature on its
1735  * ServerKeyExchange message (for ECDHE_ECDSA cipher suites). On the server,
1736  * this is used to verify the client's CertificateVerify message (if a
1737  * client certificate is requested, that certificate contains an EC key,
1738  * and full-static ECDH is not used).
1739  *
1740  * The ECDSA implementation will use the EC core implementation configured
1741  * in the engine context.
1742  *
1743  * \param cc       client context.
1744  * \param iecdsa   ECDSA verification implementation.
1745  */
1746 static inline void
1747 br_ssl_engine_set_ecdsa(br_ssl_engine_context *cc, br_ecdsa_vrfy iecdsa)
1748 {
1749 	cc->iecdsa = iecdsa;
1750 }
1751 
1752 /**
1753  * \brief Set the "default" ECDSA implementation (signature verification).
1754  *
1755  * This function sets the ECDSA implementation (signature verification)
1756  * to the fastest implementation available on the current platform. This
1757  * call also sets the elliptic curve implementation itself, there again
1758  * to the fastest EC implementation available.
1759  *
1760  * \param cc   SSL engine context.
1761  */
1762 void br_ssl_engine_set_default_ecdsa(br_ssl_engine_context *cc);
1763 
1764 /**
1765  * \brief Get the ECDSA implementation (signature verification) configured
1766  * in the provided engine.
1767  *
1768  * \param cc   SSL engine context.
1769  * \return  the ECDSA signature verification implementation.
1770  */
1771 static inline br_ecdsa_vrfy
1772 br_ssl_engine_get_ecdsa(br_ssl_engine_context *cc)
1773 {
1774 	return cc->iecdsa;
1775 }
1776 
1777 /**
1778  * \brief Set the I/O buffer for the SSL engine.
1779  *
1780  * Once this call has been made, `br_ssl_client_reset()` or
1781  * `br_ssl_server_reset()` MUST be called before using the context.
1782  *
1783  * The provided buffer will be used as long as the engine context is
1784  * used. The caller is responsible for keeping it available.
1785  *
1786  * If `bidi` is 0, then the engine will operate in half-duplex mode
1787  * (it won't be able to send data while there is unprocessed incoming
1788  * data in the buffer, and it won't be able to receive data while there
1789  * is unsent data in the buffer). The optimal buffer size in half-duplex
1790  * mode is `BR_SSL_BUFSIZE_MONO`; if the buffer is larger, then extra
1791  * bytes are ignored. If the buffer is smaller, then this limits the
1792  * capacity of the engine to support all allowed record sizes.
1793  *
1794  * If `bidi` is 1, then the engine will split the buffer into two
1795  * parts, for separate handling of outgoing and incoming data. This
1796  * enables full-duplex processing, but requires more RAM. The optimal
1797  * buffer size in full-duplex mode is `BR_SSL_BUFSIZE_BIDI`; if the
1798  * buffer is larger, then extra bytes are ignored. If the buffer is
1799  * smaller, then the split will favour the incoming part, so that
1800  * interoperability is maximised.
1801  *
1802  * \param cc          SSL engine context
1803  * \param iobuf       I/O buffer.
1804  * \param iobuf_len   I/O buffer length (in bytes).
1805  * \param bidi        non-zero for full-duplex mode.
1806  */
1807 void br_ssl_engine_set_buffer(br_ssl_engine_context *cc,
1808 	void *iobuf, size_t iobuf_len, int bidi);
1809 
1810 /**
1811  * \brief Set the I/O buffers for the SSL engine.
1812  *
1813  * Once this call has been made, `br_ssl_client_reset()` or
1814  * `br_ssl_server_reset()` MUST be called before using the context.
1815  *
1816  * This function is similar to `br_ssl_engine_set_buffer()`, except
1817  * that it enforces full-duplex mode, and the two I/O buffers are
1818  * provided as separate chunks.
1819  *
1820  * The macros `BR_SSL_BUFSIZE_INPUT` and `BR_SSL_BUFSIZE_OUTPUT`
1821  * evaluate to the optimal (maximum) sizes for the input and output
1822  * buffer, respectively.
1823  *
1824  * \param cc         SSL engine context
1825  * \param ibuf       input buffer.
1826  * \param ibuf_len   input buffer length (in bytes).
1827  * \param obuf       output buffer.
1828  * \param obuf_len   output buffer length (in bytes).
1829  */
1830 void br_ssl_engine_set_buffers_bidi(br_ssl_engine_context *cc,
1831 	void *ibuf, size_t ibuf_len, void *obuf, size_t obuf_len);
1832 
1833 /**
1834  * \brief Inject some "initial entropy" in the context.
1835  *
1836  * This entropy will be added to what can be obtained from the
1837  * underlying operating system, if that OS is supported.
1838  *
1839  * This function may be called several times; all injected entropy chunks
1840  * are cumulatively mixed.
1841  *
1842  * If entropy gathering from the OS is supported and compiled in, then this
1843  * step is optional. Otherwise, it is mandatory to inject randomness, and
1844  * the caller MUST take care to push (as one or several successive calls)
1845  * enough entropy to achieve cryptographic resistance (at least 80 bits,
1846  * preferably 128 or more). The engine will report an error if no entropy
1847  * was provided and none can be obtained from the OS.
1848  *
1849  * Take care that this function cannot assess the cryptographic quality of
1850  * the provided bytes.
1851  *
1852  * In all generality, "entropy" must here be considered to mean "that
1853  * which the attacker cannot predict". If your OS/architecture does not
1854  * have a suitable source of randomness, then you can make do with the
1855  * combination of a large enough secret value (possibly a copy of an
1856  * asymmetric private key that you also store on the system) AND a
1857  * non-repeating value (e.g. current time, provided that the local clock
1858  * cannot be reset or altered by the attacker).
1859  *
1860  * \param cc     SSL engine context.
1861  * \param data   extra entropy to inject.
1862  * \param len    length of the extra data (in bytes).
1863  */
1864 void br_ssl_engine_inject_entropy(br_ssl_engine_context *cc,
1865 	const void *data, size_t len);
1866 
1867 /**
1868  * \brief Get the "server name" in this engine.
1869  *
1870  * For clients, this is the name provided with `br_ssl_client_reset()`;
1871  * for servers, this is the name received from the client as part of the
1872  * ClientHello message. If there is no such name (e.g. the client did
1873  * not send an SNI extension) then the returned string is empty
1874  * (returned pointer points to a byte of value 0).
1875  *
1876  * The returned pointer refers to a buffer inside the context, which may
1877  * be overwritten as part of normal SSL activity (even within the same
1878  * connection, if a renegotiation occurs).
1879  *
1880  * \param cc   SSL engine context.
1881  * \return  the server name (possibly empty).
1882  */
1883 static inline const char *
1884 br_ssl_engine_get_server_name(const br_ssl_engine_context *cc)
1885 {
1886 	return cc->server_name;
1887 }
1888 
1889 /**
1890  * \brief Get the protocol version.
1891  *
1892  * This function returns the protocol version that is used by the
1893  * engine. That value is set after sending (for a server) or receiving
1894  * (for a client) the ServerHello message.
1895  *
1896  * \param cc   SSL engine context.
1897  * \return  the protocol version.
1898  */
1899 static inline unsigned
1900 br_ssl_engine_get_version(const br_ssl_engine_context *cc)
1901 {
1902 	return cc->session.version;
1903 }
1904 
1905 /**
1906  * \brief Get a copy of the session parameters.
1907  *
1908  * The session parameters are filled during the handshake, so this
1909  * function shall not be called before completion of the handshake.
1910  * The initial handshake is completed when the context first allows
1911  * application data to be injected.
1912  *
1913  * This function copies the current session parameters into the provided
1914  * structure. Beware that the session parameters include the master
1915  * secret, which is sensitive data, to handle with great care.
1916  *
1917  * \param cc   SSL engine context.
1918  * \param pp   destination structure for the session parameters.
1919  */
1920 static inline void
1921 br_ssl_engine_get_session_parameters(const br_ssl_engine_context *cc,
1922 	br_ssl_session_parameters *pp)
1923 {
1924 	memcpy(pp, &cc->session, sizeof *pp);
1925 }
1926 
1927 /**
1928  * \brief Set the session parameters to the provided values.
1929  *
1930  * This function is meant to be used in the client, before doing a new
1931  * handshake; a session resumption will be attempted with these
1932  * parameters. In the server, this function has no effect.
1933  *
1934  * \param cc   SSL engine context.
1935  * \param pp   source structure for the session parameters.
1936  */
1937 static inline void
1938 br_ssl_engine_set_session_parameters(br_ssl_engine_context *cc,
1939 	const br_ssl_session_parameters *pp)
1940 {
1941 	memcpy(&cc->session, pp, sizeof *pp);
1942 }
1943 
1944 /**
1945  * \brief Get identifier for the curve used for key exchange.
1946  *
1947  * If the cipher suite uses ECDHE, then this function returns the
1948  * identifier for the curve used for transient parameters. This is
1949  * defined during the course of the handshake, when the ServerKeyExchange
1950  * is sent (on the server) or received (on the client). If the
1951  * cipher suite does not use ECDHE (e.g. static ECDH, or RSA key
1952  * exchange), then this value is indeterminate.
1953  *
1954  * @param cc   SSL engine context.
1955  * @return  the ECDHE curve identifier.
1956  */
1957 static inline int
1958 br_ssl_engine_get_ecdhe_curve(br_ssl_engine_context *cc)
1959 {
1960 	return cc->ecdhe_curve;
1961 }
1962 
1963 /**
1964  * \brief Get the current engine state.
1965  *
1966  * An SSL engine (client or server) has, at any time, a state which is
1967  * the combination of zero, one or more of these flags:
1968  *
1969  *   - `BR_SSL_CLOSED`
1970  *
1971  *     Engine is finished, no more I/O (until next reset).
1972  *
1973  *   - `BR_SSL_SENDREC`
1974  *
1975  *     Engine has some bytes to send to the peer.
1976  *
1977  *   - `BR_SSL_RECVREC`
1978  *
1979  *     Engine expects some bytes from the peer.
1980  *
1981  *   - `BR_SSL_SENDAPP`
1982  *
1983  *     Engine may receive application data to send (or flush).
1984  *
1985  *   - `BR_SSL_RECVAPP`
1986  *
1987  *     Engine has obtained some application data from the peer,
1988  *     that should be read by the caller.
1989  *
1990  * If no flag at all is set (state value is 0), then the engine is not
1991  * fully initialised yet.
1992  *
1993  * The `BR_SSL_CLOSED` flag is exclusive; when it is set, no other flag
1994  * is set. To distinguish between a normal closure and an error, use
1995  * `br_ssl_engine_last_error()`.
1996  *
1997  * Generally speaking, `BR_SSL_SENDREC` and `BR_SSL_SENDAPP` are mutually
1998  * exclusive: the input buffer, at any point, either accumulates
1999  * plaintext data, or contains an assembled record that is being sent.
2000  * Similarly, `BR_SSL_RECVREC` and `BR_SSL_RECVAPP` are mutually exclusive.
2001  * This may change in a future library version.
2002  *
2003  * \param cc   SSL engine context.
2004  * \return  the current engine state.
2005  */
2006 unsigned br_ssl_engine_current_state(const br_ssl_engine_context *cc);
2007 
2008 /** \brief SSL engine state: closed or failed. */
2009 #define BR_SSL_CLOSED    0x0001
2010 /** \brief SSL engine state: record data is ready to be sent to the peer. */
2011 #define BR_SSL_SENDREC   0x0002
2012 /** \brief SSL engine state: engine may receive records from the peer. */
2013 #define BR_SSL_RECVREC   0x0004
2014 /** \brief SSL engine state: engine may accept application data to send. */
2015 #define BR_SSL_SENDAPP   0x0008
2016 /** \brief SSL engine state: engine has received application data. */
2017 #define BR_SSL_RECVAPP   0x0010
2018 
2019 /**
2020  * \brief Get the engine error indicator.
2021  *
2022  * The error indicator is `BR_ERR_OK` (0) if no error was encountered
2023  * since the last call to `br_ssl_client_reset()` or
2024  * `br_ssl_server_reset()`. Other status values are "sticky": they
2025  * remain set, and prevent all I/O activity, until cleared. Only the
2026  * reset calls clear the error indicator.
2027  *
2028  * \param cc   SSL engine context.
2029  * \return  0, or a non-zero error code.
2030  */
2031 static inline int
2032 br_ssl_engine_last_error(const br_ssl_engine_context *cc)
2033 {
2034 	return cc->err;
2035 }
2036 
2037 /*
2038  * There are four I/O operations, each identified by a symbolic name:
2039  *
2040  *   sendapp   inject application data in the engine
2041  *   recvapp   retrieving application data from the engine
2042  *   sendrec   sending records on the transport medium
2043  *   recvrec   receiving records from the transport medium
2044  *
2045  * Terminology works thus: in a layered model where the SSL engine sits
2046  * between the application and the network, "send" designates operations
2047  * where bytes flow from application to network, and "recv" for the
2048  * reverse operation. Application data (the plaintext that is to be
2049  * conveyed through SSL) is "app", while encrypted records are "rec".
2050  * Note that from the SSL engine point of view, "sendapp" and "recvrec"
2051  * designate bytes that enter the engine ("inject" operation), while
2052  * "recvapp" and "sendrec" designate bytes that exit the engine
2053  * ("extract" operation).
2054  *
2055  * For the operation 'xxx', two functions are defined:
2056  *
2057  *   br_ssl_engine_xxx_buf
2058  *      Returns a pointer and length to the buffer to use for that
2059  *      operation. '*len' is set to the number of bytes that may be read
2060  *      from the buffer (extract operation) or written to the buffer
2061  *      (inject operation). If no byte may be exchanged for that operation
2062  *      at that point, then '*len' is set to zero, and NULL is returned.
2063  *      The engine state is unmodified by this call.
2064  *
2065  *   br_ssl_engine_xxx_ack
2066  *      Informs the engine that 'len' bytes have been read from the buffer
2067  *      (extract operation) or written to the buffer (inject operation).
2068  *      The 'len' value MUST NOT be zero. The 'len' value MUST NOT exceed
2069  *      that which was obtained from a preceding br_ssl_engine_xxx_buf()
2070  *      call.
2071  */
2072 
2073 /**
2074  * \brief Get buffer for application data to send.
2075  *
2076  * If the engine is ready to accept application data to send to the
2077  * peer, then this call returns a pointer to the buffer where such
2078  * data shall be written, and its length is written in `*len`.
2079  * Otherwise, `*len` is set to 0 and `NULL` is returned.
2080  *
2081  * \param cc    SSL engine context.
2082  * \param len   receives the application data output buffer length, or 0.
2083  * \return  the application data output buffer, or `NULL`.
2084  */
2085 unsigned char *br_ssl_engine_sendapp_buf(
2086 	const br_ssl_engine_context *cc, size_t *len);
2087 
2088 /**
2089  * \brief Inform the engine of some new application data.
2090  *
2091  * After writing `len` bytes in the buffer returned by
2092  * `br_ssl_engine_sendapp_buf()`, the application shall call this
2093  * function to trigger any relevant processing. The `len` parameter
2094  * MUST NOT be 0, and MUST NOT exceed the value obtained in the
2095  * `br_ssl_engine_sendapp_buf()` call.
2096  *
2097  * \param cc    SSL engine context.
2098  * \param len   number of bytes pushed (not zero).
2099  */
2100 void br_ssl_engine_sendapp_ack(br_ssl_engine_context *cc, size_t len);
2101 
2102 /**
2103  * \brief Get buffer for received application data.
2104  *
2105  * If the engine has received application data from the peer, hen this
2106  * call returns a pointer to the buffer from where such data shall be
2107  * read, and its length is written in `*len`. Otherwise, `*len` is set
2108  * to 0 and `NULL` is returned.
2109  *
2110  * \param cc    SSL engine context.
2111  * \param len   receives the application data input buffer length, or 0.
2112  * \return  the application data input buffer, or `NULL`.
2113  */
2114 unsigned char *br_ssl_engine_recvapp_buf(
2115 	const br_ssl_engine_context *cc, size_t *len);
2116 
2117 /**
2118  * \brief Acknowledge some received application data.
2119  *
2120  * After reading `len` bytes from the buffer returned by
2121  * `br_ssl_engine_recvapp_buf()`, the application shall call this
2122  * function to trigger any relevant processing. The `len` parameter
2123  * MUST NOT be 0, and MUST NOT exceed the value obtained in the
2124  * `br_ssl_engine_recvapp_buf()` call.
2125  *
2126  * \param cc    SSL engine context.
2127  * \param len   number of bytes read (not zero).
2128  */
2129 void br_ssl_engine_recvapp_ack(br_ssl_engine_context *cc, size_t len);
2130 
2131 /**
2132  * \brief Get buffer for record data to send.
2133  *
2134  * If the engine has prepared some records to send to the peer, then this
2135  * call returns a pointer to the buffer from where such data shall be
2136  * read, and its length is written in `*len`. Otherwise, `*len` is set
2137  * to 0 and `NULL` is returned.
2138  *
2139  * \param cc    SSL engine context.
2140  * \param len   receives the record data output buffer length, or 0.
2141  * \return  the record data output buffer, or `NULL`.
2142  */
2143 unsigned char *br_ssl_engine_sendrec_buf(
2144 	const br_ssl_engine_context *cc, size_t *len);
2145 
2146 /**
2147  * \brief Acknowledge some sent record data.
2148  *
2149  * After reading `len` bytes from the buffer returned by
2150  * `br_ssl_engine_sendrec_buf()`, the application shall call this
2151  * function to trigger any relevant processing. The `len` parameter
2152  * MUST NOT be 0, and MUST NOT exceed the value obtained in the
2153  * `br_ssl_engine_sendrec_buf()` call.
2154  *
2155  * \param cc    SSL engine context.
2156  * \param len   number of bytes read (not zero).
2157  */
2158 void br_ssl_engine_sendrec_ack(br_ssl_engine_context *cc, size_t len);
2159 
2160 /**
2161  * \brief Get buffer for incoming records.
2162  *
2163  * If the engine is ready to accept records from the peer, then this
2164  * call returns a pointer to the buffer where such data shall be
2165  * written, and its length is written in `*len`. Otherwise, `*len` is
2166  * set to 0 and `NULL` is returned.
2167  *
2168  * \param cc    SSL engine context.
2169  * \param len   receives the record data input buffer length, or 0.
2170  * \return  the record data input buffer, or `NULL`.
2171  */
2172 unsigned char *br_ssl_engine_recvrec_buf(
2173 	const br_ssl_engine_context *cc, size_t *len);
2174 
2175 /**
2176  * \brief Inform the engine of some new record data.
2177  *
2178  * After writing `len` bytes in the buffer returned by
2179  * `br_ssl_engine_recvrec_buf()`, the application shall call this
2180  * function to trigger any relevant processing. The `len` parameter
2181  * MUST NOT be 0, and MUST NOT exceed the value obtained in the
2182  * `br_ssl_engine_recvrec_buf()` call.
2183  *
2184  * \param cc    SSL engine context.
2185  * \param len   number of bytes pushed (not zero).
2186  */
2187 void br_ssl_engine_recvrec_ack(br_ssl_engine_context *cc, size_t len);
2188 
2189 /**
2190  * \brief Flush buffered application data.
2191  *
2192  * If some application data has been buffered in the engine, then wrap
2193  * it into a record and mark it for sending. If no application data has
2194  * been buffered but the engine would be ready to accept some, AND the
2195  * `force` parameter is non-zero, then an empty record is assembled and
2196  * marked for sending. In all other cases, this function does nothing.
2197  *
2198  * Empty records are technically legal, but not all existing SSL/TLS
2199  * implementations support them. Empty records can be useful as a
2200  * transparent "keep-alive" mechanism to maintain some low-level
2201  * network activity.
2202  *
2203  * \param cc      SSL engine context.
2204  * \param force   non-zero to force sending an empty record.
2205  */
2206 void br_ssl_engine_flush(br_ssl_engine_context *cc, int force);
2207 
2208 /**
2209  * \brief Initiate a closure.
2210  *
2211  * If, at that point, the context is open and in ready state, then a
2212  * `close_notify` alert is assembled and marked for sending; this
2213  * triggers the closure protocol. Otherwise, no such alert is assembled.
2214  *
2215  * \param cc   SSL engine context.
2216  */
2217 void br_ssl_engine_close(br_ssl_engine_context *cc);
2218 
2219 /**
2220  * \brief Initiate a renegotiation.
2221  *
2222  * If the engine is failed or closed, or if the peer is known not to
2223  * support secure renegotiation (RFC 5746), or if renegotiations have
2224  * been disabled with the `BR_OPT_NO_RENEGOTIATION` flag, or if there
2225  * is buffered incoming application data, then this function returns 0
2226  * and nothing else happens.
2227  *
2228  * Otherwise, this function returns 1, and a renegotiation attempt is
2229  * triggered (if a handshake is already ongoing at that point, then
2230  * no new handshake is triggered).
2231  *
2232  * \param cc   SSL engine context.
2233  * \return  1 on success, 0 on error.
2234  */
2235 int br_ssl_engine_renegotiate(br_ssl_engine_context *cc);
2236 
2237 /**
2238  * \brief Export key material from a connected SSL engine (RFC 5705).
2239  *
2240  * This calls compute a secret key of arbitrary length from the master
2241  * secret of a connected SSL engine. If the provided context is not
2242  * currently in "application data" state (initial handshake is not
2243  * finished, another handshake is ongoing, or the connection failed or
2244  * was closed), then this function returns 0. Otherwise, a secret key of
2245  * length `len` bytes is computed and written in the buffer pointed to
2246  * by `dst`, and 1 is returned.
2247  *
2248  * The computed key follows the specification described in RFC 5705.
2249  * That RFC includes two key computations, with and without a "context
2250  * value". If `context` is `NULL`, then the variant without context is
2251  * used; otherwise, the `context_len` bytes located at the address
2252  * pointed to by `context` are used in the computation. Note that it
2253  * is possible to have a "with context" key with a context length of
2254  * zero bytes, by setting `context` to a non-`NULL` value but
2255  * `context_len` to 0.
2256  *
2257  * When context bytes are used, the context length MUST NOT exceed
2258  * 65535 bytes.
2259  *
2260  * \param cc            SSL engine context.
2261  * \param dst           destination buffer for exported key.
2262  * \param len           exported key length (in bytes).
2263  * \param label         disambiguation label.
2264  * \param context       context value (or `NULL`).
2265  * \param context_len   context length (in bytes).
2266  * \return  1 on success, 0 on error.
2267  */
2268 int br_ssl_key_export(br_ssl_engine_context *cc,
2269 	void *dst, size_t len, const char *label,
2270 	const void *context, size_t context_len);
2271 
2272 /*
2273  * Pre-declaration for the SSL client context.
2274  */
2275 typedef struct br_ssl_client_context_ br_ssl_client_context;
2276 
2277 /**
2278  * \brief Type for the client certificate, if requested by the server.
2279  */
2280 typedef struct {
2281 	/**
2282 	 * \brief Authentication type.
2283 	 *
2284 	 * This is either `BR_AUTH_RSA` (RSA signature), `BR_AUTH_ECDSA`
2285 	 * (ECDSA signature), or `BR_AUTH_ECDH` (static ECDH key exchange).
2286 	 */
2287 	int auth_type;
2288 
2289 	/**
2290 	 * \brief Hash function for computing the CertificateVerify.
2291 	 *
2292 	 * This is the symbolic identifier for the hash function that
2293 	 * will be used to produce the hash of handshake messages, to
2294 	 * be signed into the CertificateVerify. For full static ECDH
2295 	 * (client and server certificates are both EC in the same
2296 	 * curve, and static ECDH is used), this value is set to -1.
2297 	 *
2298 	 * Take care that with TLS 1.0 and 1.1, that value MUST match
2299 	 * the protocol requirements: value must be 0 (MD5+SHA-1) for
2300 	 * a RSA signature, or 2 (SHA-1) for an ECDSA signature. Only
2301 	 * TLS 1.2 allows for other hash functions.
2302 	 */
2303 	int hash_id;
2304 
2305 	/**
2306 	 * \brief Certificate chain to send to the server.
2307 	 *
2308 	 * This is an array of `br_x509_certificate` objects, each
2309 	 * normally containing a DER-encoded certificate. The client
2310 	 * code does not try to decode these elements. If there is no
2311 	 * chain to send to the server, then this pointer shall be
2312 	 * set to `NULL`.
2313 	 */
2314 	const br_x509_certificate *chain;
2315 
2316 	/**
2317 	 * \brief Certificate chain length (number of certificates).
2318 	 *
2319 	 * If there is no chain to send to the server, then this value
2320 	 * shall be set to 0.
2321 	 */
2322 	size_t chain_len;
2323 
2324 } br_ssl_client_certificate;
2325 
2326 /*
2327  * Note: the constants below for signatures match the TLS constants.
2328  */
2329 
2330 /** \brief Client authentication type: static ECDH. */
2331 #define BR_AUTH_ECDH    0
2332 /** \brief Client authentication type: RSA signature. */
2333 #define BR_AUTH_RSA     1
2334 /** \brief Client authentication type: ECDSA signature. */
2335 #define BR_AUTH_ECDSA   3
2336 
2337 /**
2338  * \brief Class type for a certificate handler (client side).
2339  *
2340  * A certificate handler selects a client certificate chain to send to
2341  * the server, upon explicit request from that server. It receives
2342  * the list of trust anchor DN from the server, and supported types
2343  * of certificates and signatures, and returns the chain to use. It
2344  * is also invoked to perform the corresponding private key operation
2345  * (a signature, or an ECDH computation).
2346  *
2347  * The SSL client engine will first push the trust anchor DN with
2348  * `start_name_list()`, `start_name()`, `append_name()`, `end_name()`
2349  * and `end_name_list()`. Then it will call `choose()`, to select the
2350  * actual chain (and signature/hash algorithms). Finally, it will call
2351  * either `do_sign()` or `do_keyx()`, depending on the algorithm choices.
2352  */
2353 typedef struct br_ssl_client_certificate_class_ br_ssl_client_certificate_class;
2354 struct br_ssl_client_certificate_class_ {
2355 	/**
2356 	 * \brief Context size (in bytes).
2357 	 */
2358 	size_t context_size;
2359 
2360 	/**
2361 	 * \brief Begin reception of a list of trust anchor names. This
2362 	 * is called while parsing the incoming CertificateRequest.
2363 	 *
2364 	 * \param pctx   certificate handler context.
2365 	 */
2366 	void (*start_name_list)(const br_ssl_client_certificate_class **pctx);
2367 
2368 	/**
2369 	 * \brief Begin reception of a new trust anchor name.
2370 	 *
2371 	 * The total encoded name length is provided; it is less than
2372 	 * 65535 bytes.
2373 	 *
2374 	 * \param pctx   certificate handler context.
2375 	 * \param len    encoded name length (in bytes).
2376 	 */
2377 	void (*start_name)(const br_ssl_client_certificate_class **pctx,
2378 		size_t len);
2379 
2380 	/**
2381 	 * \brief Receive some more bytes for the current trust anchor name.
2382 	 *
2383 	 * The provided reference (`data`) points to a transient buffer
2384 	 * they may be reused as soon as this function returns. The chunk
2385 	 * length (`len`) is never zero.
2386 	 *
2387 	 * \param pctx   certificate handler context.
2388 	 * \param data   anchor name chunk.
2389 	 * \param len    anchor name chunk length (in bytes).
2390 	 */
2391 	void (*append_name)(const br_ssl_client_certificate_class **pctx,
2392 		const unsigned char *data, size_t len);
2393 
2394 	/**
2395 	 * \brief End current trust anchor name.
2396 	 *
2397 	 * This function is called when all the encoded anchor name data
2398 	 * has been provided.
2399 	 *
2400 	 * \param pctx   certificate handler context.
2401 	 */
2402 	void (*end_name)(const br_ssl_client_certificate_class **pctx);
2403 
2404 	/**
2405 	 * \brief End list of trust anchor names.
2406 	 *
2407 	 * This function is called when all the anchor names in the
2408 	 * CertificateRequest message have been obtained.
2409 	 *
2410 	 * \param pctx   certificate handler context.
2411 	 */
2412 	void (*end_name_list)(const br_ssl_client_certificate_class **pctx);
2413 
2414 	/**
2415 	 * \brief Select client certificate and algorithms.
2416 	 *
2417 	 * This callback function shall fill the provided `choices`
2418 	 * structure with the selected algorithms and certificate chain.
2419 	 * The `hash_id`, `chain` and `chain_len` fields must be set. If
2420 	 * the client cannot or does not wish to send a certificate,
2421 	 * then it shall set `chain` to `NULL` and `chain_len` to 0.
2422 	 *
2423 	 * The `auth_types` parameter describes the authentication types,
2424 	 * signature algorithms and hash functions that are supported by
2425 	 * both the client context and the server, and compatible with
2426 	 * the current protocol version. This is a bit field with the
2427 	 * following contents:
2428 	 *
2429 	 *   - If RSA signatures with hash function x are supported, then
2430 	 *     bit x is set.
2431 	 *
2432 	 *   - If ECDSA signatures with hash function x are supported,
2433 	 *     then bit 8+x is set.
2434 	 *
2435 	 *   - If static ECDH is supported, with a RSA-signed certificate,
2436 	 *     then bit 16 is set.
2437 	 *
2438 	 *   - If static ECDH is supported, with an ECDSA-signed certificate,
2439 	 *     then bit 17 is set.
2440 	 *
2441 	 * Notes:
2442 	 *
2443 	 *   - When using TLS 1.0 or 1.1, the hash function for RSA
2444 	 *     signatures is always the special MD5+SHA-1 (id 0), and the
2445 	 *     hash function for ECDSA signatures is always SHA-1 (id 2).
2446 	 *
2447 	 *   - When using TLS 1.2, the list of hash functions is trimmed
2448 	 *     down to include only hash functions that the client context
2449 	 *     can support. The actual server list can be obtained with
2450 	 *     `br_ssl_client_get_server_hashes()`; that list may be used
2451 	 *     to select the certificate chain to send to the server.
2452 	 *
2453 	 * \param pctx         certificate handler context.
2454 	 * \param cc           SSL client context.
2455 	 * \param auth_types   supported authentication types and algorithms.
2456 	 * \param choices      destination structure for the policy choices.
2457 	 */
2458 	void (*choose)(const br_ssl_client_certificate_class **pctx,
2459 		const br_ssl_client_context *cc, uint32_t auth_types,
2460 		br_ssl_client_certificate *choices);
2461 
2462 	/**
2463 	 * \brief Perform key exchange (client part).
2464 	 *
2465 	 * This callback is invoked in case of a full static ECDH key
2466 	 * exchange:
2467 	 *
2468 	 *   - the cipher suite uses `ECDH_RSA` or `ECDH_ECDSA`;
2469 	 *
2470 	 *   - the server requests a client certificate;
2471 	 *
2472 	 *   - the client has, and sends, a client certificate that
2473 	 *     uses an EC key in the same curve as the server's key,
2474 	 *     and chooses static ECDH (the `hash_id` field in the choice
2475 	 *     structure was set to -1).
2476 	 *
2477 	 * In that situation, this callback is invoked to compute the
2478 	 * client-side ECDH: the provided `data` (of length `*len` bytes)
2479 	 * is the server's public key point (as decoded from its
2480 	 * certificate), and the client shall multiply that point with
2481 	 * its own private key, and write back the X coordinate of the
2482 	 * resulting point in the same buffer, starting at offset 0.
2483 	 * The `*len` value shall be modified to designate the actual
2484 	 * length of the X coordinate.
2485 	 *
2486 	 * The callback must uphold the following:
2487 	 *
2488 	 *   - If the input array does not have the proper length for
2489 	 *     an encoded curve point, then an error (0) shall be reported.
2490 	 *
2491 	 *   - If the input array has the proper length, then processing
2492 	 *     MUST be constant-time, even if the data is not a valid
2493 	 *     encoded point.
2494 	 *
2495 	 *   - This callback MUST check that the input point is valid.
2496 	 *
2497 	 * Returned value is 1 on success, 0 on error.
2498 	 *
2499 	 * \param pctx   certificate handler context.
2500 	 * \param data   server public key point.
2501 	 * \param len    public key point length / X coordinate length.
2502 	 * \return  1 on success, 0 on error.
2503 	 */
2504 	uint32_t (*do_keyx)(const br_ssl_client_certificate_class **pctx,
2505 		unsigned char *data, size_t *len);
2506 
2507 	/**
2508 	 * \brief Perform a signature (client authentication).
2509 	 *
2510 	 * This callback is invoked when a client certificate was sent,
2511 	 * and static ECDH is not used. It shall compute a signature,
2512 	 * using the client's private key, over the provided hash value
2513 	 * (which is the hash of all previous handshake messages).
2514 	 *
2515 	 * On input, the hash value to sign is in `data`, of size
2516 	 * `hv_len`; the involved hash function is identified by
2517 	 * `hash_id`. The signature shall be computed and written
2518 	 * back into `data`; the total size of that buffer is `len`
2519 	 * bytes.
2520 	 *
2521 	 * This callback shall verify that the signature length does not
2522 	 * exceed `len` bytes, and abstain from writing the signature if
2523 	 * it does not fit.
2524 	 *
2525 	 * For RSA signatures, the `hash_id` may be 0, in which case
2526 	 * this is the special header-less signature specified in TLS 1.0
2527 	 * and 1.1, with a 36-byte hash value. Otherwise, normal PKCS#1
2528 	 * v1.5 signatures shall be computed.
2529 	 *
2530 	 * For ECDSA signatures, the signature value shall use the ASN.1
2531 	 * based encoding.
2532 	 *
2533 	 * Returned value is the signature length (in bytes), or 0 on error.
2534 	 *
2535 	 * \param pctx      certificate handler context.
2536 	 * \param hash_id   hash function identifier.
2537 	 * \param hv_len    hash value length (in bytes).
2538 	 * \param data      input/output buffer (hash value, then signature).
2539 	 * \param len       total buffer length (in bytes).
2540 	 * \return  signature length (in bytes) on success, or 0 on error.
2541 	 */
2542 	size_t (*do_sign)(const br_ssl_client_certificate_class **pctx,
2543 		int hash_id, size_t hv_len, unsigned char *data, size_t len);
2544 };
2545 
2546 /**
2547  * \brief A single-chain RSA client certificate handler.
2548  *
2549  * This handler uses a single certificate chain, with a RSA
2550  * signature. The list of trust anchor DN is ignored.
2551  *
2552  * Apart from the first field (vtable pointer), its contents are
2553  * opaque and shall not be accessed directly.
2554  */
2555 typedef struct {
2556 	/** \brief Pointer to vtable. */
2557 	const br_ssl_client_certificate_class *vtable;
2558 #ifndef BR_DOXYGEN_IGNORE
2559 	const br_x509_certificate *chain;
2560 	size_t chain_len;
2561 	const br_rsa_private_key *sk;
2562 	br_rsa_pkcs1_sign irsasign;
2563 #endif
2564 } br_ssl_client_certificate_rsa_context;
2565 
2566 /**
2567  * \brief A single-chain EC client certificate handler.
2568  *
2569  * This handler uses a single certificate chain, with a RSA
2570  * signature. The list of trust anchor DN is ignored.
2571  *
2572  * This handler may support both static ECDH, and ECDSA signatures
2573  * (either usage may be selectively disabled).
2574  *
2575  * Apart from the first field (vtable pointer), its contents are
2576  * opaque and shall not be accessed directly.
2577  */
2578 typedef struct {
2579 	/** \brief Pointer to vtable. */
2580 	const br_ssl_client_certificate_class *vtable;
2581 #ifndef BR_DOXYGEN_IGNORE
2582 	const br_x509_certificate *chain;
2583 	size_t chain_len;
2584 	const br_ec_private_key *sk;
2585 	unsigned allowed_usages;
2586 	unsigned issuer_key_type;
2587 	const br_multihash_context *mhash;
2588 	const br_ec_impl *iec;
2589 	br_ecdsa_sign iecdsa;
2590 #endif
2591 } br_ssl_client_certificate_ec_context;
2592 
2593 /**
2594  * \brief Context structure for a SSL client.
2595  *
2596  * The first field (called `eng`) is the SSL engine; all functions that
2597  * work on a `br_ssl_engine_context` structure shall take as parameter
2598  * a pointer to that field. The other structure fields are opaque and
2599  * must not be accessed directly.
2600  */
2601 struct br_ssl_client_context_ {
2602 	/**
2603 	 * \brief The encapsulated engine context.
2604 	 */
2605 	br_ssl_engine_context eng;
2606 
2607 #ifndef BR_DOXYGEN_IGNORE
2608 	/*
2609 	 * Minimum ClientHello length; padding with an extension (RFC
2610 	 * 7685) is added if necessary to match at least that length.
2611 	 * Such padding is nominally unnecessary, but it has been used
2612 	 * to work around some server implementation bugs.
2613 	 */
2614 	uint16_t min_clienthello_len;
2615 
2616 	/*
2617 	 * Bit field for algoithms (hash + signature) supported by the
2618 	 * server when requesting a client certificate.
2619 	 */
2620 	uint32_t hashes;
2621 
2622 	/*
2623 	 * Server's public key curve.
2624 	 */
2625 	int server_curve;
2626 
2627 	/*
2628 	 * Context for certificate handler.
2629 	 */
2630 	const br_ssl_client_certificate_class **client_auth_vtable;
2631 
2632 	/*
2633 	 * Client authentication type.
2634 	 */
2635 	unsigned char auth_type;
2636 
2637 	/*
2638 	 * Hash function to use for the client signature. This is 0xFF
2639 	 * if static ECDH is used.
2640 	 */
2641 	unsigned char hash_id;
2642 
2643 	/*
2644 	 * For the core certificate handlers, thus avoiding (in most
2645 	 * cases) the need for an externally provided policy context.
2646 	 */
2647 	union {
2648 		const br_ssl_client_certificate_class *vtable;
2649 		br_ssl_client_certificate_rsa_context single_rsa;
2650 		br_ssl_client_certificate_ec_context single_ec;
2651 	} client_auth;
2652 
2653 	/*
2654 	 * Implementations.
2655 	 */
2656 	br_rsa_public irsapub;
2657 #endif
2658 };
2659 
2660 /**
2661  * \brief Get the hash functions and signature algorithms supported by
2662  * the server.
2663  *
2664  * This value is a bit field:
2665  *
2666  *   - If RSA (PKCS#1 v1.5) is supported with hash function of ID `x`,
2667  *     then bit `x` is set (hash function ID is 0 for the special MD5+SHA-1,
2668  *     or 2 to 6 for the SHA family).
2669  *
2670  *   - If ECDSA is supported with hash function of ID `x`, then bit `8+x`
2671  *     is set.
2672  *
2673  *   - Newer algorithms are symbolic 16-bit identifiers that do not
2674  *     represent signature algorithm and hash function separately. If
2675  *     the TLS-level identifier is `0x0800+x` for a `x` in the 0..15
2676  *     range, then bit `16+x` is set.
2677  *
2678  * "New algorithms" are currently defined only in draft documents, so
2679  * this support is subject to possible change. Right now (early 2017),
2680  * this maps ed25519 (EdDSA on Curve25519) to bit 23, and ed448 (EdDSA
2681  * on Curve448) to bit 24. If the identifiers on the wire change in
2682  * future document, then the decoding mechanism in BearSSL will be
2683  * amended to keep mapping ed25519 and ed448 on bits 23 and 24,
2684  * respectively. Mapping of other new algorithms (e.g. RSA/PSS) is not
2685  * guaranteed yet.
2686  *
2687  * \param cc   client context.
2688  * \return  the server-supported hash functions and signature algorithms.
2689  */
2690 static inline uint32_t
2691 br_ssl_client_get_server_hashes(const br_ssl_client_context *cc)
2692 {
2693 	return cc->hashes;
2694 }
2695 
2696 /**
2697  * \brief Get the server key curve.
2698  *
2699  * This function returns the ID for the curve used by the server's public
2700  * key. This is set when the server's certificate chain is processed;
2701  * this value is 0 if the server's key is not an EC key.
2702  *
2703  * \return  the server's public key curve ID, or 0.
2704  */
2705 static inline int
2706 br_ssl_client_get_server_curve(const br_ssl_client_context *cc)
2707 {
2708 	return cc->server_curve;
2709 }
2710 
2711 /*
2712  * Each br_ssl_client_init_xxx() function sets the list of supported
2713  * cipher suites and used implementations, as specified by the profile
2714  * name 'xxx'. Defined profile names are:
2715  *
2716  *    full    all supported versions and suites; constant-time implementations
2717  *    TODO: add other profiles
2718  */
2719 
2720 /**
2721  * \brief SSL client profile: full.
2722  *
2723  * This function initialises the provided SSL client context with
2724  * all supported algorithms and cipher suites. It also initialises
2725  * a companion X.509 validation engine with all supported algorithms,
2726  * and the provided trust anchors; the X.509 engine will be used by
2727  * the client context to validate the server's certificate.
2728  *
2729  * \param cc                  client context to initialise.
2730  * \param xc                  X.509 validation context to initialise.
2731  * \param trust_anchors       trust anchors to use.
2732  * \param trust_anchors_num   number of trust anchors.
2733  */
2734 void br_ssl_client_init_full(br_ssl_client_context *cc,
2735 	br_x509_minimal_context *xc,
2736 	const br_x509_trust_anchor *trust_anchors, size_t trust_anchors_num);
2737 
2738 /**
2739  * \brief Clear the complete contents of a SSL client context.
2740  *
2741  * Everything is cleared, including the reference to the configured buffer,
2742  * implementations, cipher suites and state. This is a preparatory step
2743  * to assembling a custom profile.
2744  *
2745  * \param cc   client context to clear.
2746  */
2747 void br_ssl_client_zero(br_ssl_client_context *cc);
2748 
2749 /**
2750  * \brief Set an externally provided client certificate handler context.
2751  *
2752  * The handler's methods are invoked when the server requests a client
2753  * certificate.
2754  *
2755  * \param cc     client context.
2756  * \param pctx   certificate handler context (pointer to its vtable field).
2757  */
2758 static inline void
2759 br_ssl_client_set_client_certificate(br_ssl_client_context *cc,
2760 	const br_ssl_client_certificate_class **pctx)
2761 {
2762 	cc->client_auth_vtable = pctx;
2763 }
2764 
2765 /**
2766  * \brief Set the RSA public-key operations implementation.
2767  *
2768  * This will be used to encrypt the pre-master secret with the server's
2769  * RSA public key (RSA-encryption cipher suites only).
2770  *
2771  * \param cc        client context.
2772  * \param irsapub   RSA public-key encryption implementation.
2773  */
2774 static inline void
2775 br_ssl_client_set_rsapub(br_ssl_client_context *cc, br_rsa_public irsapub)
2776 {
2777 	cc->irsapub = irsapub;
2778 }
2779 
2780 /**
2781  * \brief Set the "default" RSA implementation for public-key operations.
2782  *
2783  * This sets the RSA implementation in the client context (for encrypting
2784  * the pre-master secret, in `TLS_RSA_*` cipher suites) to the fastest
2785  * available on the current platform.
2786  *
2787  * \param cc   client context.
2788  */
2789 void br_ssl_client_set_default_rsapub(br_ssl_client_context *cc);
2790 
2791 /**
2792  * \brief Set the minimum ClientHello length (RFC 7685 padding).
2793  *
2794  * If this value is set and the ClientHello would be shorter, then
2795  * the Pad ClientHello extension will be added with enough padding bytes
2796  * to reach the target size. Because of the extension header, the resulting
2797  * size will sometimes be slightly more than `len` bytes if the target
2798  * size cannot be exactly met.
2799  *
2800  * The target length relates to the _contents_ of the ClientHello, not
2801  * counting its 4-byte header. For instance, if `len` is set to 512,
2802  * then the padding will bring the ClientHello size to 516 bytes with its
2803  * header, and 521 bytes when counting the 5-byte record header.
2804  *
2805  * \param cc    client context.
2806  * \param len   minimum ClientHello length (in bytes).
2807  */
2808 static inline void
2809 br_ssl_client_set_min_clienthello_len(br_ssl_client_context *cc, uint16_t len)
2810 {
2811 	cc->min_clienthello_len = len;
2812 }
2813 
2814 /**
2815  * \brief Prepare or reset a client context for a new connection.
2816  *
2817  * The `server_name` parameter is used to fill the SNI extension; the
2818  * X.509 "minimal" engine will also match that name against the server
2819  * names included in the server's certificate. If the parameter is
2820  * `NULL` then no SNI extension will be sent, and the X.509 "minimal"
2821  * engine (if used for server certificate validation) will not check
2822  * presence of any specific name in the received certificate.
2823  *
2824  * Therefore, setting the `server_name` to `NULL` shall be reserved
2825  * to cases where alternate or additional methods are used to ascertain
2826  * that the right server public key is used (e.g. a "known key" model).
2827  *
2828  * If `resume_session` is non-zero and the context was previously used
2829  * then the session parameters may be reused (depending on whether the
2830  * server previously sent a non-empty session ID, and accepts the session
2831  * resumption). The session parameters for session resumption can also
2832  * be set explicitly with `br_ssl_engine_set_session_parameters()`.
2833  *
2834  * On failure, the context is marked as failed, and this function
2835  * returns 0. A possible failure condition is when no initial entropy
2836  * was injected, and none could be obtained from the OS (either OS
2837  * randomness gathering is not supported, or it failed).
2838  *
2839  * \param cc               client context.
2840  * \param server_name      target server name, or `NULL`.
2841  * \param resume_session   non-zero to try session resumption.
2842  * \return  0 on failure, 1 on success.
2843  */
2844 int br_ssl_client_reset(br_ssl_client_context *cc,
2845 	const char *server_name, int resume_session);
2846 
2847 /**
2848  * \brief Forget any session in the context.
2849  *
2850  * This means that the next handshake that uses this context will
2851  * necessarily be a full handshake (this applies both to new connections
2852  * and to renegotiations).
2853  *
2854  * \param cc   client context.
2855  */
2856 static inline void
2857 br_ssl_client_forget_session(br_ssl_client_context *cc)
2858 {
2859 	cc->eng.session.session_id_len = 0;
2860 }
2861 
2862 /**
2863  * \brief Set client certificate chain and key (single RSA case).
2864  *
2865  * This function sets a client certificate chain, that the client will
2866  * send to the server whenever a client certificate is requested. This
2867  * certificate uses an RSA public key; the corresponding private key is
2868  * invoked for authentication. Trust anchor names sent by the server are
2869  * ignored.
2870  *
2871  * The provided chain and private key are linked in the client context;
2872  * they must remain valid as long as they may be used, i.e. normally
2873  * for the duration of the connection, since they might be invoked
2874  * again upon renegotiations.
2875  *
2876  * \param cc          SSL client context.
2877  * \param chain       client certificate chain (SSL order: EE comes first).
2878  * \param chain_len   client chain length (number of certificates).
2879  * \param sk          client private key.
2880  * \param irsasign    RSA signature implementation (PKCS#1 v1.5).
2881  */
2882 void br_ssl_client_set_single_rsa(br_ssl_client_context *cc,
2883 	const br_x509_certificate *chain, size_t chain_len,
2884 	const br_rsa_private_key *sk, br_rsa_pkcs1_sign irsasign);
2885 
2886 /*
2887  * \brief Set the client certificate chain and key (single EC case).
2888  *
2889  * This function sets a client certificate chain, that the client will
2890  * send to the server whenever a client certificate is requested. This
2891  * certificate uses an EC public key; the corresponding private key is
2892  * invoked for authentication. Trust anchor names sent by the server are
2893  * ignored.
2894  *
2895  * The provided chain and private key are linked in the client context;
2896  * they must remain valid as long as they may be used, i.e. normally
2897  * for the duration of the connection, since they might be invoked
2898  * again upon renegotiations.
2899  *
2900  * The `allowed_usages` is a combination of usages, namely
2901  * `BR_KEYTYPE_KEYX` and/or `BR_KEYTYPE_SIGN`. The `BR_KEYTYPE_KEYX`
2902  * value allows full static ECDH, while the `BR_KEYTYPE_SIGN` value
2903  * allows ECDSA signatures. If ECDSA signatures are used, then an ECDSA
2904  * signature implementation must be provided; otherwise, the `iecdsa`
2905  * parameter may be 0.
2906  *
2907  * The `cert_issuer_key_type` value is either `BR_KEYTYPE_RSA` or
2908  * `BR_KEYTYPE_EC`; it is the type of the public key used the the CA
2909  * that issued (signed) the client certificate. That value is used with
2910  * full static ECDH: support of the certificate by the server depends
2911  * on how the certificate was signed. (Note: when using TLS 1.2, this
2912  * parameter is ignored; but its value matters for TLS 1.0 and 1.1.)
2913  *
2914  * \param cc                     server context.
2915  * \param chain                  server certificate chain to send.
2916  * \param chain_len              chain length (number of certificates).
2917  * \param sk                     server private key (EC).
2918  * \param allowed_usages         allowed private key usages.
2919  * \param cert_issuer_key_type   issuing CA's key type.
2920  * \param iec                    EC core implementation.
2921  * \param iecdsa                 ECDSA signature implementation ("asn1" format).
2922  */
2923 void br_ssl_client_set_single_ec(br_ssl_client_context *cc,
2924 	const br_x509_certificate *chain, size_t chain_len,
2925 	const br_ec_private_key *sk, unsigned allowed_usages,
2926 	unsigned cert_issuer_key_type,
2927 	const br_ec_impl *iec, br_ecdsa_sign iecdsa);
2928 
2929 /**
2930  * \brief Type for a "translated cipher suite", as an array of two
2931  * 16-bit integers.
2932  *
2933  * The first element is the cipher suite identifier (as used on the wire).
2934  * The second element is the concatenation of four 4-bit elements which
2935  * characterise the cipher suite contents. In most to least significant
2936  * order, these 4-bit elements are:
2937  *
2938  *   - Bits 12 to 15: key exchange + server key type
2939  *
2940  *     | val | symbolic constant        | suite type  | details                                          |
2941  *     | :-- | :----------------------- | :---------- | :----------------------------------------------- |
2942  *     |  0  | `BR_SSLKEYX_RSA`         | RSA         | RSA key exchange, key is RSA (encryption)        |
2943  *     |  1  | `BR_SSLKEYX_ECDHE_RSA`   | ECDHE_RSA   | ECDHE key exchange, key is RSA (signature)       |
2944  *     |  2  | `BR_SSLKEYX_ECDHE_ECDSA` | ECDHE_ECDSA | ECDHE key exchange, key is EC (signature)        |
2945  *     |  3  | `BR_SSLKEYX_ECDH_RSA`    | ECDH_RSA    | Key is EC (key exchange), cert signed with RSA   |
2946  *     |  4  | `BR_SSLKEYX_ECDH_ECDSA`  | ECDH_ECDSA  | Key is EC (key exchange), cert signed with ECDSA |
2947  *
2948  *   - Bits 8 to 11: symmetric encryption algorithm
2949  *
2950  *     | val | symbolic constant      | symmetric encryption | key strength (bits) |
2951  *     | :-- | :--------------------- | :------------------- | :------------------ |
2952  *     |  0  | `BR_SSLENC_3DES_CBC`   | 3DES/CBC             | 168                 |
2953  *     |  1  | `BR_SSLENC_AES128_CBC` | AES-128/CBC          | 128                 |
2954  *     |  2  | `BR_SSLENC_AES256_CBC` | AES-256/CBC          | 256                 |
2955  *     |  3  | `BR_SSLENC_AES128_GCM` | AES-128/GCM          | 128                 |
2956  *     |  4  | `BR_SSLENC_AES256_GCM` | AES-256/GCM          | 256                 |
2957  *     |  5  | `BR_SSLENC_CHACHA20`   | ChaCha20/Poly1305    | 256                 |
2958  *
2959  *   - Bits 4 to 7: MAC algorithm
2960  *
2961  *     | val | symbolic constant  | MAC type     | details                               |
2962  *     | :-- | :----------------- | :----------- | :------------------------------------ |
2963  *     |  0  | `BR_SSLMAC_AEAD`   | AEAD         | No dedicated MAC (encryption is AEAD) |
2964  *     |  2  | `BR_SSLMAC_SHA1`   | HMAC/SHA-1   | Value matches `br_sha1_ID`            |
2965  *     |  4  | `BR_SSLMAC_SHA256` | HMAC/SHA-256 | Value matches `br_sha256_ID`          |
2966  *     |  5  | `BR_SSLMAC_SHA384` | HMAC/SHA-384 | Value matches `br_sha384_ID`          |
2967  *
2968  *   - Bits 0 to 3: hash function for PRF when used with TLS-1.2
2969  *
2970  *     | val | symbolic constant  | hash function | details                              |
2971  *     | :-- | :----------------- | :------------ | :----------------------------------- |
2972  *     |  4  | `BR_SSLPRF_SHA256` | SHA-256       | Value matches `br_sha256_ID`         |
2973  *     |  5  | `BR_SSLPRF_SHA384` | SHA-384       | Value matches `br_sha384_ID`         |
2974  *
2975  * For instance, cipher suite `TLS_RSA_WITH_AES_128_GCM_SHA256` has
2976  * standard identifier 0x009C, and is translated to 0x0304, for, in
2977  * that order: RSA key exchange (0), AES-128/GCM (3), AEAD integrity (0),
2978  * SHA-256 in the TLS PRF (4).
2979  */
2980 typedef uint16_t br_suite_translated[2];
2981 
2982 #ifndef BR_DOXYGEN_IGNORE
2983 /*
2984  * Constants are already documented in the br_suite_translated type.
2985  */
2986 
2987 #define BR_SSLKEYX_RSA           0
2988 #define BR_SSLKEYX_ECDHE_RSA     1
2989 #define BR_SSLKEYX_ECDHE_ECDSA   2
2990 #define BR_SSLKEYX_ECDH_RSA      3
2991 #define BR_SSLKEYX_ECDH_ECDSA    4
2992 
2993 #define BR_SSLENC_3DES_CBC       0
2994 #define BR_SSLENC_AES128_CBC     1
2995 #define BR_SSLENC_AES256_CBC     2
2996 #define BR_SSLENC_AES128_GCM     3
2997 #define BR_SSLENC_AES256_GCM     4
2998 #define BR_SSLENC_CHACHA20       5
2999 
3000 #define BR_SSLMAC_AEAD           0
3001 #define BR_SSLMAC_SHA1           br_sha1_ID
3002 #define BR_SSLMAC_SHA256         br_sha256_ID
3003 #define BR_SSLMAC_SHA384         br_sha384_ID
3004 
3005 #define BR_SSLPRF_SHA256         br_sha256_ID
3006 #define BR_SSLPRF_SHA384         br_sha384_ID
3007 
3008 #endif
3009 
3010 /*
3011  * Pre-declaration for the SSL server context.
3012  */
3013 typedef struct br_ssl_server_context_ br_ssl_server_context;
3014 
3015 /**
3016  * \brief Type for the server policy choices, taken after analysis of
3017  * the client message (ClientHello).
3018  */
3019 typedef struct {
3020 	/**
3021 	 * \brief Cipher suite to use with that client.
3022 	 */
3023 	uint16_t cipher_suite;
3024 
3025 	/**
3026 	 * \brief Hash function or algorithm for signing the ServerKeyExchange.
3027 	 *
3028 	 * This parameter is ignored for `TLS_RSA_*` and `TLS_ECDH_*`
3029 	 * cipher suites; it is used only for `TLS_ECDHE_*` suites, in
3030 	 * which the server _signs_ the ephemeral EC Diffie-Hellman
3031 	 * parameters sent to the client.
3032 	 *
3033 	 * This identifier must be one of the following values:
3034 	 *
3035 	 *   - `0xFF00 + id`, where `id` is a hash function identifier
3036 	 *     (0 for MD5+SHA-1, or 2 to 6 for one of the SHA functions);
3037 	 *
3038 	 *   - a full 16-bit identifier, lower than `0xFF00`.
3039 	 *
3040 	 * If the first option is used, then the SSL engine will
3041 	 * compute the hash of the data that is to be signed, with the
3042 	 * designated hash function. The `do_sign()` method will be
3043 	 * invoked with that hash value provided in the the `data`
3044 	 * buffer.
3045 	 *
3046 	 * If the second option is used, then the SSL engine will NOT
3047 	 * compute a hash on the data; instead, it will provide the
3048 	 * to-be-signed data itself in `data`, i.e. the concatenation of
3049 	 * the client random, server random, and encoded ECDH
3050 	 * parameters. Furthermore, with TLS-1.2 and later, the 16-bit
3051 	 * identifier will be used "as is" in the protocol, in the
3052 	 * SignatureAndHashAlgorithm; for instance, `0x0401` stands for
3053 	 * RSA PKCS#1 v1.5 signature (the `01`) with SHA-256 as hash
3054 	 * function (the `04`).
3055 	 *
3056 	 * Take care that with TLS 1.0 and 1.1, the hash function is
3057 	 * constrainted by the protocol: RSA signature must use
3058 	 * MD5+SHA-1 (so use `0xFF00`), while ECDSA must use SHA-1
3059 	 * (`0xFF02`). Since TLS 1.0 and 1.1 don't include a
3060 	 * SignatureAndHashAlgorithm field in their ServerKeyExchange
3061 	 * messages, any value below `0xFF00` will be usable to send the
3062 	 * raw ServerKeyExchange data to the `do_sign()` callback, but
3063 	 * that callback must still follow the protocol requirements
3064 	 * when generating the signature.
3065 	 */
3066 	unsigned algo_id;
3067 
3068 	/**
3069 	 * \brief Certificate chain to send to the client.
3070 	 *
3071 	 * This is an array of `br_x509_certificate` objects, each
3072 	 * normally containing a DER-encoded certificate. The server
3073 	 * code does not try to decode these elements.
3074 	 */
3075 	const br_x509_certificate *chain;
3076 
3077 	/**
3078 	 * \brief Certificate chain length (number of certificates).
3079 	 */
3080 	size_t chain_len;
3081 
3082 } br_ssl_server_choices;
3083 
3084 /**
3085  * \brief Class type for a policy handler (server side).
3086  *
3087  * A policy handler selects the policy parameters for a connection
3088  * (cipher suite and other algorithms, and certificate chain to send to
3089  * the client); it also performs the server-side computations involving
3090  * its permanent private key.
3091  *
3092  * The SSL server engine will invoke first `choose()`, once the
3093  * ClientHello message has been received, then either `do_keyx()`
3094  * `do_sign()`, depending on the cipher suite.
3095  */
3096 typedef struct br_ssl_server_policy_class_ br_ssl_server_policy_class;
3097 struct br_ssl_server_policy_class_ {
3098 	/**
3099 	 * \brief Context size (in bytes).
3100 	 */
3101 	size_t context_size;
3102 
3103 	/**
3104 	 * \brief Select algorithms and certificates for this connection.
3105 	 *
3106 	 * This callback function shall fill the provided `choices`
3107 	 * structure with the policy choices for this connection. This
3108 	 * entails selecting the cipher suite, hash function for signing
3109 	 * the ServerKeyExchange (applicable only to ECDHE cipher suites),
3110 	 * and certificate chain to send.
3111 	 *
3112 	 * The callback receives a pointer to the server context that
3113 	 * contains the relevant data. In particular, the functions
3114 	 * `br_ssl_server_get_client_suites()`,
3115 	 * `br_ssl_server_get_client_hashes()` and
3116 	 * `br_ssl_server_get_client_curves()` can be used to obtain
3117 	 * the cipher suites, hash functions and elliptic curves
3118 	 * supported by both the client and server, respectively. The
3119 	 * `br_ssl_engine_get_version()` and `br_ssl_engine_get_server_name()`
3120 	 * functions yield the protocol version and requested server name
3121 	 * (SNI), respectively.
3122 	 *
3123 	 * This function may modify its context structure (`pctx`) in
3124 	 * arbitrary ways to keep track of its own choices.
3125 	 *
3126 	 * This function shall return 1 if appropriate policy choices
3127 	 * could be made, or 0 if this connection cannot be pursued.
3128 	 *
3129 	 * \param pctx      policy context.
3130 	 * \param cc        SSL server context.
3131 	 * \param choices   destination structure for the policy choices.
3132 	 * \return  1 on success, 0 on error.
3133 	 */
3134 	int (*choose)(const br_ssl_server_policy_class **pctx,
3135 		const br_ssl_server_context *cc,
3136 		br_ssl_server_choices *choices);
3137 
3138 	/**
3139 	 * \brief Perform key exchange (server part).
3140 	 *
3141 	 * This callback is invoked to perform the server-side cryptographic
3142 	 * operation for a key exchange that is not ECDHE. This callback
3143 	 * uses the private key.
3144 	 *
3145 	 * **For RSA key exchange**, the provided `data` (of length `*len`
3146 	 * bytes) shall be decrypted with the server's private key, and
3147 	 * the 48-byte premaster secret copied back to the first 48 bytes
3148 	 * of `data`.
3149 	 *
3150 	 *   - The caller makes sure that `*len` is at least 59 bytes.
3151 	 *
3152 	 *   - This callback MUST check that the provided length matches
3153 	 *     that of the key modulus; it shall report an error otherwise.
3154 	 *
3155 	 *   - If the length matches that of the RSA key modulus, then
3156 	 *     processing MUST be constant-time, even if decryption fails,
3157 	 *     or the padding is incorrect, or the plaintext message length
3158 	 *     is not exactly 48 bytes.
3159 	 *
3160 	 *   - This callback needs not check the two first bytes of the
3161 	 *     obtained pre-master secret (the caller will do that).
3162 	 *
3163 	 *   - If an error is reported (0), then what the callback put
3164 	 *     in the first 48 bytes of `data` is unimportant (the caller
3165 	 *     will use random bytes instead).
3166 	 *
3167 	 * **For ECDH key exchange**, the provided `data` (of length `*len`
3168 	 * bytes) is the elliptic curve point from the client. The
3169 	 * callback shall multiply it with its private key, and store
3170 	 * the resulting X coordinate in `data`, starting at offset 0,
3171 	 * and set `*len` to the length of the X coordinate.
3172 	 *
3173 	 *   - If the input array does not have the proper length for
3174 	 *     an encoded curve point, then an error (0) shall be reported.
3175 	 *
3176 	 *   - If the input array has the proper length, then processing
3177 	 *     MUST be constant-time, even if the data is not a valid
3178 	 *     encoded point.
3179 	 *
3180 	 *   - This callback MUST check that the input point is valid.
3181 	 *
3182 	 * Returned value is 1 on success, 0 on error.
3183 	 *
3184 	 * \param pctx   policy context.
3185 	 * \param data   key exchange data from the client.
3186 	 * \param len    key exchange data length (in bytes).
3187 	 * \return  1 on success, 0 on error.
3188 	 */
3189 	uint32_t (*do_keyx)(const br_ssl_server_policy_class **pctx,
3190 		unsigned char *data, size_t *len);
3191 
3192 	/**
3193 	 * \brief Perform a signature (for a ServerKeyExchange message).
3194 	 *
3195 	 * This callback function is invoked for ECDHE cipher suites. On
3196 	 * input, the hash value or message to sign is in `data`, of
3197 	 * size `hv_len`; the involved hash function or algorithm is
3198 	 * identified by `algo_id`. The signature shall be computed and
3199 	 * written back into `data`; the total size of that buffer is
3200 	 * `len` bytes.
3201 	 *
3202 	 * This callback shall verify that the signature length does not
3203 	 * exceed `len` bytes, and abstain from writing the signature if
3204 	 * it does not fit.
3205 	 *
3206 	 * The `algo_id` value matches that which was written in the
3207 	 * `choices` structures by the `choose()` callback. This will be
3208 	 * one of the following:
3209 	 *
3210 	 *   - `0xFF00 + id` for a hash function identifier `id`. In
3211 	 *     that case, the `data` buffer contains a hash value
3212 	 *     already computed over the data that is to be signed,
3213 	 *     of length `hv_len`. The `id` may be 0 to designate the
3214 	 *     special MD5+SHA-1 concatenation (old-style RSA signing).
3215 	 *
3216 	 *   - Another value, lower than `0xFF00`. The `data` buffer
3217 	 *     then contains the raw, non-hashed data to be signed
3218 	 *     (concatenation of the client and server randoms and
3219 	 *     ECDH parameters). The callback is responsible to apply
3220 	 *     any relevant hashing as part of the signing process.
3221 	 *
3222 	 * Returned value is the signature length (in bytes), or 0 on error.
3223 	 *
3224 	 * \param pctx      policy context.
3225 	 * \param algo_id   hash function / algorithm identifier.
3226 	 * \param data      input/output buffer (message/hash, then signature).
3227 	 * \param hv_len    hash value or message length (in bytes).
3228 	 * \param len       total buffer length (in bytes).
3229 	 * \return  signature length (in bytes) on success, or 0 on error.
3230 	 */
3231 	size_t (*do_sign)(const br_ssl_server_policy_class **pctx,
3232 		unsigned algo_id,
3233 		unsigned char *data, size_t hv_len, size_t len);
3234 };
3235 
3236 /**
3237  * \brief A single-chain RSA policy handler.
3238  *
3239  * This policy context uses a single certificate chain, and a RSA
3240  * private key. The context can be restricted to only signatures or
3241  * only key exchange.
3242  *
3243  * Apart from the first field (vtable pointer), its contents are
3244  * opaque and shall not be accessed directly.
3245  */
3246 typedef struct {
3247 	/** \brief Pointer to vtable. */
3248 	const br_ssl_server_policy_class *vtable;
3249 #ifndef BR_DOXYGEN_IGNORE
3250 	const br_x509_certificate *chain;
3251 	size_t chain_len;
3252 	const br_rsa_private_key *sk;
3253 	unsigned allowed_usages;
3254 	br_rsa_private irsacore;
3255 	br_rsa_pkcs1_sign irsasign;
3256 #endif
3257 } br_ssl_server_policy_rsa_context;
3258 
3259 /**
3260  * \brief A single-chain EC policy handler.
3261  *
3262  * This policy context uses a single certificate chain, and an EC
3263  * private key. The context can be restricted to only signatures or
3264  * only key exchange.
3265  *
3266  * Due to how TLS is defined, this context must be made aware whether
3267  * the server certificate was itself signed with RSA or ECDSA. The code
3268  * does not try to decode the certificate to obtain that information.
3269  *
3270  * Apart from the first field (vtable pointer), its contents are
3271  * opaque and shall not be accessed directly.
3272  */
3273 typedef struct {
3274 	/** \brief Pointer to vtable. */
3275 	const br_ssl_server_policy_class *vtable;
3276 #ifndef BR_DOXYGEN_IGNORE
3277 	const br_x509_certificate *chain;
3278 	size_t chain_len;
3279 	const br_ec_private_key *sk;
3280 	unsigned allowed_usages;
3281 	unsigned cert_issuer_key_type;
3282 	const br_multihash_context *mhash;
3283 	const br_ec_impl *iec;
3284 	br_ecdsa_sign iecdsa;
3285 #endif
3286 } br_ssl_server_policy_ec_context;
3287 
3288 /**
3289  * \brief Class type for a session parameter cache.
3290  *
3291  * Session parameters are saved in the cache with `save()`, and
3292  * retrieved with `load()`. The cache implementation can apply any
3293  * storage and eviction strategy that it sees fit. The SSL server
3294  * context that performs the request is provided, so that its
3295  * functionalities may be used by the implementation (e.g. hash
3296  * functions or random number generation).
3297  */
3298 typedef struct br_ssl_session_cache_class_ br_ssl_session_cache_class;
3299 struct br_ssl_session_cache_class_ {
3300 	/**
3301 	 * \brief Context size (in bytes).
3302 	 */
3303 	size_t context_size;
3304 
3305 	/**
3306 	 * \brief Record a session.
3307 	 *
3308 	 * This callback should record the provided session parameters.
3309 	 * The `params` structure is transient, so its contents shall
3310 	 * be copied into the cache. The session ID has been randomly
3311 	 * generated and always has length exactly 32 bytes.
3312 	 *
3313 	 * \param ctx          session cache context.
3314 	 * \param server_ctx   SSL server context.
3315 	 * \param params       session parameters to save.
3316 	 */
3317 	void (*save)(const br_ssl_session_cache_class **ctx,
3318 		br_ssl_server_context *server_ctx,
3319 		const br_ssl_session_parameters *params);
3320 
3321 	/**
3322 	 * \brief Lookup a session in the cache.
3323 	 *
3324 	 * The session ID to lookup is in `params` and always has length
3325 	 * exactly 32 bytes. If the session parameters are found in the
3326 	 * cache, then the parameters shall be copied into the `params`
3327 	 * structure. Returned value is 1 on successful lookup, 0
3328 	 * otherwise.
3329 	 *
3330 	 * \param ctx          session cache context.
3331 	 * \param server_ctx   SSL server context.
3332 	 * \param params       destination for session parameters.
3333 	 * \return  1 if found, 0 otherwise.
3334 	 */
3335 	int (*load)(const br_ssl_session_cache_class **ctx,
3336 		br_ssl_server_context *server_ctx,
3337 		br_ssl_session_parameters *params);
3338 };
3339 
3340 /**
3341  * \brief Context for a basic cache system.
3342  *
3343  * The system stores session parameters in a buffer provided at
3344  * initialisation time. Each entry uses exactly 100 bytes, and
3345  * buffer sizes up to 4294967295 bytes are supported.
3346  *
3347  * Entries are evicted with a LRU (Least Recently Used) policy. A
3348  * search tree is maintained to keep lookups fast even with large
3349  * caches.
3350  *
3351  * Apart from the first field (vtable pointer), the structure
3352  * contents are opaque and shall not be accessed directly.
3353  */
3354 typedef struct {
3355 	/** \brief Pointer to vtable. */
3356 	const br_ssl_session_cache_class *vtable;
3357 #ifndef BR_DOXYGEN_IGNORE
3358 	unsigned char *store;
3359 	size_t store_len, store_ptr;
3360 	unsigned char index_key[32];
3361 	const br_hash_class *hash;
3362 	int init_done;
3363 	uint32_t head, tail, root;
3364 #endif
3365 } br_ssl_session_cache_lru;
3366 
3367 /**
3368  * \brief Initialise a LRU session cache with the provided storage space.
3369  *
3370  * The provided storage space must remain valid as long as the cache
3371  * is used. Arbitrary lengths are supported, up to 4294967295 bytes;
3372  * each entry uses up exactly 100 bytes.
3373  *
3374  * \param cc          session cache context.
3375  * \param store       storage space for cached entries.
3376  * \param store_len   storage space length (in bytes).
3377  */
3378 void br_ssl_session_cache_lru_init(br_ssl_session_cache_lru *cc,
3379 	unsigned char *store, size_t store_len);
3380 
3381 /**
3382  * \brief Forget an entry in an LRU session cache.
3383  *
3384  * The session cache context must have been initialised. The entry
3385  * with the provided session ID (of exactly 32 bytes) is looked for
3386  * in the cache; if located, it is disabled.
3387  *
3388  * \param cc   session cache context.
3389  * \param id   session ID to forget.
3390  */
3391 void br_ssl_session_cache_lru_forget(
3392 	br_ssl_session_cache_lru *cc, const unsigned char *id);
3393 
3394 /**
3395  * \brief Context structure for a SSL server.
3396  *
3397  * The first field (called `eng`) is the SSL engine; all functions that
3398  * work on a `br_ssl_engine_context` structure shall take as parameter
3399  * a pointer to that field. The other structure fields are opaque and
3400  * must not be accessed directly.
3401  */
3402 struct br_ssl_server_context_ {
3403 	/**
3404 	 * \brief The encapsulated engine context.
3405 	 */
3406 	br_ssl_engine_context eng;
3407 
3408 #ifndef BR_DOXYGEN_IGNORE
3409 	/*
3410 	 * Maximum version from the client.
3411 	 */
3412 	uint16_t client_max_version;
3413 
3414 	/*
3415 	 * Session cache.
3416 	 */
3417 	const br_ssl_session_cache_class **cache_vtable;
3418 
3419 	/*
3420 	 * Translated cipher suites supported by the client. The list
3421 	 * is trimmed to include only the cipher suites that the
3422 	 * server also supports; they are in the same order as in the
3423 	 * client message.
3424 	 */
3425 	br_suite_translated client_suites[BR_MAX_CIPHER_SUITES];
3426 	unsigned char client_suites_num;
3427 
3428 	/*
3429 	 * Hash functions supported by the client, with ECDSA and RSA
3430 	 * (bit mask). For hash function with id 'x', set bit index is
3431 	 * x for RSA, x+8 for ECDSA. For newer algorithms, with ID
3432 	 * 0x08**, bit 16+k is set for algorithm 0x0800+k.
3433 	 */
3434 	uint32_t hashes;
3435 
3436 	/*
3437 	 * Curves supported by the client (bit mask, for named curves).
3438 	 */
3439 	uint32_t curves;
3440 
3441 	/*
3442 	 * Context for chain handler.
3443 	 */
3444 	const br_ssl_server_policy_class **policy_vtable;
3445 	uint16_t sign_hash_id;
3446 
3447 	/*
3448 	 * For the core handlers, thus avoiding (in most cases) the
3449 	 * need for an externally provided policy context.
3450 	 */
3451 	union {
3452 		const br_ssl_server_policy_class *vtable;
3453 		br_ssl_server_policy_rsa_context single_rsa;
3454 		br_ssl_server_policy_ec_context single_ec;
3455 	} chain_handler;
3456 
3457 	/*
3458 	 * Buffer for the ECDHE private key.
3459 	 */
3460 	unsigned char ecdhe_key[70];
3461 	size_t ecdhe_key_len;
3462 
3463 	/*
3464 	 * Trust anchor names for client authentication. "ta_names" and
3465 	 * "tas" cannot be both non-NULL.
3466 	 */
3467 	const br_x500_name *ta_names;
3468 	const br_x509_trust_anchor *tas;
3469 	size_t num_tas;
3470 	size_t cur_dn_index;
3471 	const unsigned char *cur_dn;
3472 	size_t cur_dn_len;
3473 
3474 	/*
3475 	 * Buffer for the hash value computed over all handshake messages
3476 	 * prior to CertificateVerify, and identifier for the hash function.
3477 	 */
3478 	unsigned char hash_CV[64];
3479 	size_t hash_CV_len;
3480 	int hash_CV_id;
3481 
3482 	/*
3483 	 * Server-specific implementations.
3484 	 * (none for now)
3485 	 */
3486 #endif
3487 };
3488 
3489 /*
3490  * Each br_ssl_server_init_xxx() function sets the list of supported
3491  * cipher suites and used implementations, as specified by the profile
3492  * name 'xxx'. Defined profile names are:
3493  *
3494  *    full_rsa    all supported algorithm, server key type is RSA
3495  *    full_ec     all supported algorithm, server key type is EC
3496  *    TODO: add other profiles
3497  *
3498  * Naming scheme for "minimal" profiles: min123
3499  *
3500  * -- character 1: key exchange
3501  *      r = RSA
3502  *      e = ECDHE_RSA
3503  *      f = ECDHE_ECDSA
3504  *      u = ECDH_RSA
3505  *      v = ECDH_ECDSA
3506  * -- character 2: version / PRF
3507  *      0 = TLS 1.0 / 1.1 with MD5+SHA-1
3508  *      2 = TLS 1.2 with SHA-256
3509  *      3 = TLS 1.2 with SHA-384
3510  * -- character 3: encryption
3511  *      a = AES/CBC
3512  *      d = 3DES/CBC
3513  *      g = AES/GCM
3514  *      c = ChaCha20+Poly1305
3515  */
3516 
3517 /**
3518  * \brief SSL server profile: full_rsa.
3519  *
3520  * This function initialises the provided SSL server context with
3521  * all supported algorithms and cipher suites that rely on a RSA
3522  * key pair.
3523  *
3524  * \param cc          server context to initialise.
3525  * \param chain       server certificate chain.
3526  * \param chain_len   certificate chain length (number of certificate).
3527  * \param sk          RSA private key.
3528  */
3529 void br_ssl_server_init_full_rsa(br_ssl_server_context *cc,
3530 	const br_x509_certificate *chain, size_t chain_len,
3531 	const br_rsa_private_key *sk);
3532 
3533 /**
3534  * \brief SSL server profile: full_ec.
3535  *
3536  * This function initialises the provided SSL server context with
3537  * all supported algorithms and cipher suites that rely on an EC
3538  * key pair.
3539  *
3540  * The key type of the CA that issued the server's certificate must
3541  * be provided, since it matters for ECDH cipher suites (ECDH_RSA
3542  * suites require a RSA-powered CA). The key type is either
3543  * `BR_KEYTYPE_RSA` or `BR_KEYTYPE_EC`.
3544  *
3545  * \param cc                     server context to initialise.
3546  * \param chain                  server certificate chain.
3547  * \param chain_len              chain length (number of certificates).
3548  * \param cert_issuer_key_type   certificate issuer's key type.
3549  * \param sk                     EC private key.
3550  */
3551 void br_ssl_server_init_full_ec(br_ssl_server_context *cc,
3552 	const br_x509_certificate *chain, size_t chain_len,
3553 	unsigned cert_issuer_key_type, const br_ec_private_key *sk);
3554 
3555 /**
3556  * \brief SSL server profile: minr2g.
3557  *
3558  * This profile uses only TLS_RSA_WITH_AES_128_GCM_SHA256. Server key is
3559  * RSA, and RSA key exchange is used (not forward secure, but uses little
3560  * CPU in the client).
3561  *
3562  * \param cc          server context to initialise.
3563  * \param chain       server certificate chain.
3564  * \param chain_len   certificate chain length (number of certificate).
3565  * \param sk          RSA private key.
3566  */
3567 void br_ssl_server_init_minr2g(br_ssl_server_context *cc,
3568 	const br_x509_certificate *chain, size_t chain_len,
3569 	const br_rsa_private_key *sk);
3570 
3571 /**
3572  * \brief SSL server profile: mine2g.
3573  *
3574  * This profile uses only TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256. Server key
3575  * is RSA, and ECDHE key exchange is used. This suite provides forward
3576  * security, with a higher CPU expense on the client, and a somewhat
3577  * larger code footprint (compared to "minr2g").
3578  *
3579  * \param cc          server context to initialise.
3580  * \param chain       server certificate chain.
3581  * \param chain_len   certificate chain length (number of certificate).
3582  * \param sk          RSA private key.
3583  */
3584 void br_ssl_server_init_mine2g(br_ssl_server_context *cc,
3585 	const br_x509_certificate *chain, size_t chain_len,
3586 	const br_rsa_private_key *sk);
3587 
3588 /**
3589  * \brief SSL server profile: minf2g.
3590  *
3591  * This profile uses only TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256.
3592  * Server key is EC, and ECDHE key exchange is used. This suite provides
3593  * forward security, with a higher CPU expense on the client and server
3594  * (by a factor of about 3 to 4), and a somewhat larger code footprint
3595  * (compared to "minu2g" and "minv2g").
3596  *
3597  * \param cc          server context to initialise.
3598  * \param chain       server certificate chain.
3599  * \param chain_len   certificate chain length (number of certificate).
3600  * \param sk          EC private key.
3601  */
3602 void br_ssl_server_init_minf2g(br_ssl_server_context *cc,
3603 	const br_x509_certificate *chain, size_t chain_len,
3604 	const br_ec_private_key *sk);
3605 
3606 /**
3607  * \brief SSL server profile: minu2g.
3608  *
3609  * This profile uses only TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256.
3610  * Server key is EC, and ECDH key exchange is used; the issuing CA used
3611  * a RSA key.
3612  *
3613  * The "minu2g" and "minv2g" profiles do not provide forward secrecy,
3614  * but are the lightest on the server (for CPU usage), and are rather
3615  * inexpensive on the client as well.
3616  *
3617  * \param cc          server context to initialise.
3618  * \param chain       server certificate chain.
3619  * \param chain_len   certificate chain length (number of certificate).
3620  * \param sk          EC private key.
3621  */
3622 void br_ssl_server_init_minu2g(br_ssl_server_context *cc,
3623 	const br_x509_certificate *chain, size_t chain_len,
3624 	const br_ec_private_key *sk);
3625 
3626 /**
3627  * \brief SSL server profile: minv2g.
3628  *
3629  * This profile uses only TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256.
3630  * Server key is EC, and ECDH key exchange is used; the issuing CA used
3631  * an EC key.
3632  *
3633  * The "minu2g" and "minv2g" profiles do not provide forward secrecy,
3634  * but are the lightest on the server (for CPU usage), and are rather
3635  * inexpensive on the client as well.
3636  *
3637  * \param cc          server context to initialise.
3638  * \param chain       server certificate chain.
3639  * \param chain_len   certificate chain length (number of certificate).
3640  * \param sk          EC private key.
3641  */
3642 void br_ssl_server_init_minv2g(br_ssl_server_context *cc,
3643 	const br_x509_certificate *chain, size_t chain_len,
3644 	const br_ec_private_key *sk);
3645 
3646 /**
3647  * \brief SSL server profile: mine2c.
3648  *
3649  * This profile uses only TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256.
3650  * Server key is RSA, and ECDHE key exchange is used. This suite
3651  * provides forward security.
3652  *
3653  * \param cc          server context to initialise.
3654  * \param chain       server certificate chain.
3655  * \param chain_len   certificate chain length (number of certificate).
3656  * \param sk          RSA private key.
3657  */
3658 void br_ssl_server_init_mine2c(br_ssl_server_context *cc,
3659 	const br_x509_certificate *chain, size_t chain_len,
3660 	const br_rsa_private_key *sk);
3661 
3662 /**
3663  * \brief SSL server profile: minf2c.
3664  *
3665  * This profile uses only TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256.
3666  * Server key is EC, and ECDHE key exchange is used. This suite provides
3667  * forward security.
3668  *
3669  * \param cc          server context to initialise.
3670  * \param chain       server certificate chain.
3671  * \param chain_len   certificate chain length (number of certificate).
3672  * \param sk          EC private key.
3673  */
3674 void br_ssl_server_init_minf2c(br_ssl_server_context *cc,
3675 	const br_x509_certificate *chain, size_t chain_len,
3676 	const br_ec_private_key *sk);
3677 
3678 /**
3679  * \brief Get the supported client suites.
3680  *
3681  * This function shall be called only after the ClientHello has been
3682  * processed, typically from the policy engine. The returned array
3683  * contains the cipher suites that are supported by both the client
3684  * and the server; these suites are in client preference order, unless
3685  * the `BR_OPT_ENFORCE_SERVER_PREFERENCES` flag was set, in which case
3686  * they are in server preference order.
3687  *
3688  * The suites are _translated_, which means that each suite is given
3689  * as two 16-bit integers: the standard suite identifier, and its
3690  * translated version, broken down into its individual components,
3691  * as explained with the `br_suite_translated` type.
3692  *
3693  * The returned array is allocated in the context and will be rewritten
3694  * by each handshake.
3695  *
3696  * \param cc    server context.
3697  * \param num   receives the array size (number of suites).
3698  * \return  the translated common cipher suites, in preference order.
3699  */
3700 static inline const br_suite_translated *
3701 br_ssl_server_get_client_suites(const br_ssl_server_context *cc, size_t *num)
3702 {
3703 	*num = cc->client_suites_num;
3704 	return cc->client_suites;
3705 }
3706 
3707 /**
3708  * \brief Get the hash functions and signature algorithms supported by
3709  * the client.
3710  *
3711  * This value is a bit field:
3712  *
3713  *   - If RSA (PKCS#1 v1.5) is supported with hash function of ID `x`,
3714  *     then bit `x` is set (hash function ID is 0 for the special MD5+SHA-1,
3715  *     or 2 to 6 for the SHA family).
3716  *
3717  *   - If ECDSA is supported with hash function of ID `x`, then bit `8+x`
3718  *     is set.
3719  *
3720  *   - Newer algorithms are symbolic 16-bit identifiers that do not
3721  *     represent signature algorithm and hash function separately. If
3722  *     the TLS-level identifier is `0x0800+x` for a `x` in the 0..15
3723  *     range, then bit `16+x` is set.
3724  *
3725  * "New algorithms" are currently defined only in draft documents, so
3726  * this support is subject to possible change. Right now (early 2017),
3727  * this maps ed25519 (EdDSA on Curve25519) to bit 23, and ed448 (EdDSA
3728  * on Curve448) to bit 24. If the identifiers on the wire change in
3729  * future document, then the decoding mechanism in BearSSL will be
3730  * amended to keep mapping ed25519 and ed448 on bits 23 and 24,
3731  * respectively. Mapping of other new algorithms (e.g. RSA/PSS) is not
3732  * guaranteed yet.
3733  *
3734  * \param cc   server context.
3735  * \return  the client-supported hash functions and signature algorithms.
3736  */
3737 static inline uint32_t
3738 br_ssl_server_get_client_hashes(const br_ssl_server_context *cc)
3739 {
3740 	return cc->hashes;
3741 }
3742 
3743 /**
3744  * \brief Get the elliptic curves supported by the client.
3745  *
3746  * This is a bit field (bit x is set if curve of ID x is supported).
3747  *
3748  * \param cc   server context.
3749  * \return  the client-supported elliptic curves.
3750  */
3751 static inline uint32_t
3752 br_ssl_server_get_client_curves(const br_ssl_server_context *cc)
3753 {
3754 	return cc->curves;
3755 }
3756 
3757 /**
3758  * \brief Clear the complete contents of a SSL server context.
3759  *
3760  * Everything is cleared, including the reference to the configured buffer,
3761  * implementations, cipher suites and state. This is a preparatory step
3762  * to assembling a custom profile.
3763  *
3764  * \param cc   server context to clear.
3765  */
3766 void br_ssl_server_zero(br_ssl_server_context *cc);
3767 
3768 /**
3769  * \brief Set an externally provided policy context.
3770  *
3771  * The policy context's methods are invoked to decide the cipher suite
3772  * and certificate chain, and to perform operations involving the server's
3773  * private key.
3774  *
3775  * \param cc     server context.
3776  * \param pctx   policy context (pointer to its vtable field).
3777  */
3778 static inline void
3779 br_ssl_server_set_policy(br_ssl_server_context *cc,
3780 	const br_ssl_server_policy_class **pctx)
3781 {
3782 	cc->policy_vtable = pctx;
3783 }
3784 
3785 /**
3786  * \brief Set the server certificate chain and key (single RSA case).
3787  *
3788  * This function uses a policy context included in the server context.
3789  * It configures use of a single server certificate chain with a RSA
3790  * private key. The `allowed_usages` is a combination of usages, namely
3791  * `BR_KEYTYPE_KEYX` and/or `BR_KEYTYPE_SIGN`; this enables or disables
3792  * the corresponding cipher suites (i.e. `TLS_RSA_*` use the RSA key for
3793  * key exchange, while `TLS_ECDHE_RSA_*` use the RSA key for signatures).
3794  *
3795  * \param cc               server context.
3796  * \param chain            server certificate chain to send to the client.
3797  * \param chain_len        chain length (number of certificates).
3798  * \param sk               server private key (RSA).
3799  * \param allowed_usages   allowed private key usages.
3800  * \param irsacore         RSA core implementation.
3801  * \param irsasign         RSA signature implementation (PKCS#1 v1.5).
3802  */
3803 void br_ssl_server_set_single_rsa(br_ssl_server_context *cc,
3804 	const br_x509_certificate *chain, size_t chain_len,
3805 	const br_rsa_private_key *sk, unsigned allowed_usages,
3806 	br_rsa_private irsacore, br_rsa_pkcs1_sign irsasign);
3807 
3808 /**
3809  * \brief Set the server certificate chain and key (single EC case).
3810  *
3811  * This function uses a policy context included in the server context.
3812  * It configures use of a single server certificate chain with an EC
3813  * private key. The `allowed_usages` is a combination of usages, namely
3814  * `BR_KEYTYPE_KEYX` and/or `BR_KEYTYPE_SIGN`; this enables or disables
3815  * the corresponding cipher suites (i.e. `TLS_ECDH_*` use the EC key for
3816  * key exchange, while `TLS_ECDHE_ECDSA_*` use the EC key for signatures).
3817  *
3818  * In order to support `TLS_ECDH_*` cipher suites (non-ephemeral ECDH),
3819  * the algorithm type of the key used by the issuing CA to sign the
3820  * server's certificate must be provided, as `cert_issuer_key_type`
3821  * parameter (this value is either `BR_KEYTYPE_RSA` or `BR_KEYTYPE_EC`).
3822  *
3823  * \param cc                     server context.
3824  * \param chain                  server certificate chain to send.
3825  * \param chain_len              chain length (number of certificates).
3826  * \param sk                     server private key (EC).
3827  * \param allowed_usages         allowed private key usages.
3828  * \param cert_issuer_key_type   issuing CA's key type.
3829  * \param iec                    EC core implementation.
3830  * \param iecdsa                 ECDSA signature implementation ("asn1" format).
3831  */
3832 void br_ssl_server_set_single_ec(br_ssl_server_context *cc,
3833 	const br_x509_certificate *chain, size_t chain_len,
3834 	const br_ec_private_key *sk, unsigned allowed_usages,
3835 	unsigned cert_issuer_key_type,
3836 	const br_ec_impl *iec, br_ecdsa_sign iecdsa);
3837 
3838 /**
3839  * \brief Activate client certificate authentication.
3840  *
3841  * The trust anchor encoded X.500 names (DN) to send to the client are
3842  * provided. A client certificate will be requested and validated through
3843  * the X.509 validator configured in the SSL engine. If `num` is 0, then
3844  * client certificate authentication is disabled.
3845  *
3846  * If the client does not send a certificate, or on validation failure,
3847  * the handshake aborts. Unauthenticated clients can be tolerated by
3848  * setting the `BR_OPT_TOLERATE_NO_CLIENT_AUTH` flag.
3849  *
3850  * The provided array is linked in, not copied, so that pointer must
3851  * remain valid as long as anchor names may be used.
3852  *
3853  * \param cc         server context.
3854  * \param ta_names   encoded trust anchor names.
3855  * \param num        number of encoded trust anchor names.
3856  */
3857 static inline void
3858 br_ssl_server_set_trust_anchor_names(br_ssl_server_context *cc,
3859 	const br_x500_name *ta_names, size_t num)
3860 {
3861 	cc->ta_names = ta_names;
3862 	cc->tas = NULL;
3863 	cc->num_tas = num;
3864 }
3865 
3866 /**
3867  * \brief Activate client certificate authentication.
3868  *
3869  * This is a variant for `br_ssl_server_set_trust_anchor_names()`: the
3870  * trust anchor names are provided not as an array of stand-alone names
3871  * (`br_x500_name` structures), but as an array of trust anchors
3872  * (`br_x509_trust_anchor` structures). The server engine itself will
3873  * only use the `dn` field of each trust anchor. This is meant to allow
3874  * defining a single array of trust anchors, to be used here and in the
3875  * X.509 validation engine itself.
3876  *
3877  * The provided array is linked in, not copied, so that pointer must
3878  * remain valid as long as anchor names may be used.
3879  *
3880  * \param cc    server context.
3881  * \param tas   trust anchors (only names are used).
3882  * \param num   number of trust anchors.
3883  */
3884 static inline void
3885 br_ssl_server_set_trust_anchor_names_alt(br_ssl_server_context *cc,
3886 	const br_x509_trust_anchor *tas, size_t num)
3887 {
3888 	cc->ta_names = NULL;
3889 	cc->tas = tas;
3890 	cc->num_tas = num;
3891 }
3892 
3893 /**
3894  * \brief Configure the cache for session parameters.
3895  *
3896  * The cache context is provided as a pointer to its first field (vtable
3897  * pointer).
3898  *
3899  * \param cc       server context.
3900  * \param vtable   session cache context.
3901  */
3902 static inline void
3903 br_ssl_server_set_cache(br_ssl_server_context *cc,
3904 	const br_ssl_session_cache_class **vtable)
3905 {
3906 	cc->cache_vtable = vtable;
3907 }
3908 
3909 /**
3910  * \brief Prepare or reset a server context for handling an incoming client.
3911  *
3912  * \param cc   server context.
3913  * \return  1 on success, 0 on error.
3914  */
3915 int br_ssl_server_reset(br_ssl_server_context *cc);
3916 
3917 /* ===================================================================== */
3918 
3919 /*
3920  * Context for the simplified I/O context. The transport medium is accessed
3921  * through the low_read() and low_write() callback functions, each with
3922  * its own opaque context pointer.
3923  *
3924  *  low_read()    read some bytes, at most 'len' bytes, into data[]. The
3925  *                returned value is the number of read bytes, or -1 on error.
3926  *                The 'len' parameter is guaranteed never to exceed 20000,
3927  *                so the length always fits in an 'int' on all platforms.
3928  *
3929  *  low_write()   write up to 'len' bytes, to be read from data[]. The
3930  *                returned value is the number of written bytes, or -1 on
3931  *                error. The 'len' parameter is guaranteed never to exceed
3932  *                20000, so the length always fits in an 'int' on all
3933  *                parameters.
3934  *
3935  * A socket closure (if the transport medium is a socket) should be reported
3936  * as an error (-1). The callbacks shall endeavour to block until at least
3937  * one byte can be read or written; a callback returning 0 at times is
3938  * acceptable, but this normally leads to the callback being immediately
3939  * called again, so the callback should at least always try to block for
3940  * some time if no I/O can take place.
3941  *
3942  * The SSL engine naturally applies some buffering, so the callbacks need
3943  * not apply buffers of their own.
3944  */
3945 /**
3946  * \brief Context structure for the simplified SSL I/O wrapper.
3947  *
3948  * This structure is initialised with `br_sslio_init()`. Its contents
3949  * are opaque and shall not be accessed directly.
3950  */
3951 typedef struct {
3952 #ifndef BR_DOXYGEN_IGNORE
3953 	br_ssl_engine_context *engine;
3954 	int (*low_read)(void *read_context,
3955 		unsigned char *data, size_t len);
3956 	void *read_context;
3957 	int (*low_write)(void *write_context,
3958 		const unsigned char *data, size_t len);
3959 	void *write_context;
3960 #endif
3961 } br_sslio_context;
3962 
3963 /**
3964  * \brief Initialise a simplified I/O wrapper context.
3965  *
3966  * The simplified I/O wrapper offers a simpler read/write API for a SSL
3967  * engine (client or server), using the provided callback functions for
3968  * reading data from, or writing data to, the transport medium.
3969  *
3970  * The callback functions have the following semantics:
3971  *
3972  *   - Each callback receives an opaque context value (of type `void *`)
3973  *     that the callback may use arbitrarily (or possibly ignore).
3974  *
3975  *   - `low_read()` reads at least one byte, at most `len` bytes, from
3976  *     the transport medium. Read bytes shall be written in `data`.
3977  *
3978  *   - `low_write()` writes at least one byte, at most `len` bytes, unto
3979  *     the transport medium. The bytes to write are read from `data`.
3980  *
3981  *   - The `len` parameter is never zero, and is always lower than 20000.
3982  *
3983  *   - The number of processed bytes (read or written) is returned. Since
3984  *     that number is less than 20000, it always fits on an `int`.
3985  *
3986  *   - On error, the callbacks return -1. Reaching end-of-stream is an
3987  *     error. Errors are permanent: the SSL connection is terminated.
3988  *
3989  *   - Callbacks SHOULD NOT return 0. This is tolerated, as long as
3990  *     callbacks endeavour to block for some non-negligible amount of
3991  *     time until at least one byte can be sent or received (if a
3992  *     callback returns 0, then the wrapper invokes it again
3993  *     immediately).
3994  *
3995  *   - Callbacks MAY return as soon as at least one byte is processed;
3996  *     they MAY also insist on reading or writing _all_ requested bytes.
3997  *     Since SSL is a self-terminated protocol (each record has a length
3998  *     header), this does not change semantics.
3999  *
4000  *   - Callbacks need not apply any buffering (for performance) since SSL
4001  *     itself uses buffers.
4002  *
4003  * \param ctx             wrapper context to initialise.
4004  * \param engine          SSL engine to wrap.
4005  * \param low_read        callback for reading data from the transport.
4006  * \param read_context    context pointer for `low_read()`.
4007  * \param low_write       callback for writing data on the transport.
4008  * \param write_context   context pointer for `low_write()`.
4009  */
4010 void br_sslio_init(br_sslio_context *ctx,
4011 	br_ssl_engine_context *engine,
4012 	int (*low_read)(void *read_context,
4013 		unsigned char *data, size_t len),
4014 	void *read_context,
4015 	int (*low_write)(void *write_context,
4016 		const unsigned char *data, size_t len),
4017 	void *write_context);
4018 
4019 /**
4020  * \brief Read some application data from a SSL connection.
4021  *
4022  * If `len` is zero, then this function returns 0 immediately. In
4023  * all other cases, it never returns 0.
4024  *
4025  * This call returns only when at least one byte has been obtained.
4026  * Returned value is the number of bytes read, or -1 on error. The
4027  * number of bytes always fits on an 'int' (data from a single SSL/TLS
4028  * record is returned).
4029  *
4030  * On error or SSL closure, this function returns -1. The caller should
4031  * inspect the error status on the SSL engine to distinguish between
4032  * normal closure and error.
4033  *
4034  * \param cc    SSL wrapper context.
4035  * \param dst   destination buffer for application data.
4036  * \param len   maximum number of bytes to obtain.
4037  * \return  number of bytes obtained, or -1 on error.
4038  */
4039 int br_sslio_read(br_sslio_context *cc, void *dst, size_t len);
4040 
4041 /**
4042  * \brief Read application data from a SSL connection.
4043  *
4044  * This calls returns only when _all_ requested `len` bytes are read,
4045  * or an error is reached. Returned value is 0 on success, -1 on error.
4046  * A normal (verified) SSL closure before that many bytes are obtained
4047  * is reported as an error by this function.
4048  *
4049  * \param cc    SSL wrapper context.
4050  * \param dst   destination buffer for application data.
4051  * \param len   number of bytes to obtain.
4052  * \return  0 on success, or -1 on error.
4053  */
4054 int br_sslio_read_all(br_sslio_context *cc, void *dst, size_t len);
4055 
4056 /**
4057  * \brief Write some application data unto a SSL connection.
4058  *
4059  * If `len` is zero, then this function returns 0 immediately. In
4060  * all other cases, it never returns 0.
4061  *
4062  * This call returns only when at least one byte has been written.
4063  * Returned value is the number of bytes written, or -1 on error. The
4064  * number of bytes always fits on an 'int' (less than 20000).
4065  *
4066  * On error or SSL closure, this function returns -1. The caller should
4067  * inspect the error status on the SSL engine to distinguish between
4068  * normal closure and error.
4069  *
4070  * **Important:** SSL is buffered; a "written" byte is a byte that was
4071  * injected into the wrapped SSL engine, but this does not necessarily mean
4072  * that it has been scheduled for sending. Use `br_sslio_flush()` to
4073  * ensure that all pending data has been sent to the transport medium.
4074  *
4075  * \param cc    SSL wrapper context.
4076  * \param src   source buffer for application data.
4077  * \param len   maximum number of bytes to write.
4078  * \return  number of bytes written, or -1 on error.
4079  */
4080 int br_sslio_write(br_sslio_context *cc, const void *src, size_t len);
4081 
4082 /**
4083  * \brief Write application data unto a SSL connection.
4084  *
4085  * This calls returns only when _all_ requested `len` bytes have been
4086  * written, or an error is reached. Returned value is 0 on success, -1
4087  * on error. A normal (verified) SSL closure before that many bytes are
4088  * written is reported as an error by this function.
4089  *
4090  * **Important:** SSL is buffered; a "written" byte is a byte that was
4091  * injected into the wrapped SSL engine, but this does not necessarily mean
4092  * that it has been scheduled for sending. Use `br_sslio_flush()` to
4093  * ensure that all pending data has been sent to the transport medium.
4094  *
4095  * \param cc    SSL wrapper context.
4096  * \param src   source buffer for application data.
4097  * \param len   number of bytes to write.
4098  * \return  0 on success, or -1 on error.
4099  */
4100 int br_sslio_write_all(br_sslio_context *cc, const void *src, size_t len);
4101 
4102 /**
4103  * \brief Flush pending data.
4104  *
4105  * This call makes sure that any buffered application data in the
4106  * provided context (including the wrapped SSL engine) has been sent
4107  * to the transport medium (i.e. accepted by the `low_write()` callback
4108  * method). If there is no such pending data, then this function does
4109  * nothing (and returns a success, i.e. 0).
4110  *
4111  * If the underlying transport medium has its own buffers, then it is
4112  * up to the caller to ensure the corresponding flushing.
4113  *
4114  * Returned value is 0 on success, -1 on error.
4115  *
4116  * \param cc    SSL wrapper context.
4117  * \return  0 on success, or -1 on error.
4118  */
4119 int br_sslio_flush(br_sslio_context *cc);
4120 
4121 /**
4122  * \brief Close the SSL connection.
4123  *
4124  * This call runs the SSL closure protocol (sending a `close_notify`,
4125  * receiving the response `close_notify`). When it returns, the SSL
4126  * connection is finished. It is still up to the caller to manage the
4127  * possible transport-level termination, if applicable (alternatively,
4128  * the underlying transport stream may be reused for non-SSL messages).
4129  *
4130  * Returned value is 0 on success, -1 on error. A failure by the peer
4131  * to process the complete closure protocol (i.e. sending back the
4132  * `close_notify`) is an error.
4133  *
4134  * \param cc    SSL wrapper context.
4135  * \return  0 on success, or -1 on error.
4136  */
4137 int br_sslio_close(br_sslio_context *cc);
4138 
4139 /* ===================================================================== */
4140 
4141 /*
4142  * Symbolic constants for cipher suites.
4143  */
4144 
4145 /* From RFC 5246 */
4146 #define BR_TLS_NULL_WITH_NULL_NULL                   0x0000
4147 #define BR_TLS_RSA_WITH_NULL_MD5                     0x0001
4148 #define BR_TLS_RSA_WITH_NULL_SHA                     0x0002
4149 #define BR_TLS_RSA_WITH_NULL_SHA256                  0x003B
4150 #define BR_TLS_RSA_WITH_RC4_128_MD5                  0x0004
4151 #define BR_TLS_RSA_WITH_RC4_128_SHA                  0x0005
4152 #define BR_TLS_RSA_WITH_3DES_EDE_CBC_SHA             0x000A
4153 #define BR_TLS_RSA_WITH_AES_128_CBC_SHA              0x002F
4154 #define BR_TLS_RSA_WITH_AES_256_CBC_SHA              0x0035
4155 #define BR_TLS_RSA_WITH_AES_128_CBC_SHA256           0x003C
4156 #define BR_TLS_RSA_WITH_AES_256_CBC_SHA256           0x003D
4157 #define BR_TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA          0x000D
4158 #define BR_TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA          0x0010
4159 #define BR_TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA         0x0013
4160 #define BR_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA         0x0016
4161 #define BR_TLS_DH_DSS_WITH_AES_128_CBC_SHA           0x0030
4162 #define BR_TLS_DH_RSA_WITH_AES_128_CBC_SHA           0x0031
4163 #define BR_TLS_DHE_DSS_WITH_AES_128_CBC_SHA          0x0032
4164 #define BR_TLS_DHE_RSA_WITH_AES_128_CBC_SHA          0x0033
4165 #define BR_TLS_DH_DSS_WITH_AES_256_CBC_SHA           0x0036
4166 #define BR_TLS_DH_RSA_WITH_AES_256_CBC_SHA           0x0037
4167 #define BR_TLS_DHE_DSS_WITH_AES_256_CBC_SHA          0x0038
4168 #define BR_TLS_DHE_RSA_WITH_AES_256_CBC_SHA          0x0039
4169 #define BR_TLS_DH_DSS_WITH_AES_128_CBC_SHA256        0x003E
4170 #define BR_TLS_DH_RSA_WITH_AES_128_CBC_SHA256        0x003F
4171 #define BR_TLS_DHE_DSS_WITH_AES_128_CBC_SHA256       0x0040
4172 #define BR_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256       0x0067
4173 #define BR_TLS_DH_DSS_WITH_AES_256_CBC_SHA256        0x0068
4174 #define BR_TLS_DH_RSA_WITH_AES_256_CBC_SHA256        0x0069
4175 #define BR_TLS_DHE_DSS_WITH_AES_256_CBC_SHA256       0x006A
4176 #define BR_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256       0x006B
4177 #define BR_TLS_DH_anon_WITH_RC4_128_MD5              0x0018
4178 #define BR_TLS_DH_anon_WITH_3DES_EDE_CBC_SHA         0x001B
4179 #define BR_TLS_DH_anon_WITH_AES_128_CBC_SHA          0x0034
4180 #define BR_TLS_DH_anon_WITH_AES_256_CBC_SHA          0x003A
4181 #define BR_TLS_DH_anon_WITH_AES_128_CBC_SHA256       0x006C
4182 #define BR_TLS_DH_anon_WITH_AES_256_CBC_SHA256       0x006D
4183 
4184 /* From RFC 4492 */
4185 #define BR_TLS_ECDH_ECDSA_WITH_NULL_SHA              0xC001
4186 #define BR_TLS_ECDH_ECDSA_WITH_RC4_128_SHA           0xC002
4187 #define BR_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA      0xC003
4188 #define BR_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA       0xC004
4189 #define BR_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA       0xC005
4190 #define BR_TLS_ECDHE_ECDSA_WITH_NULL_SHA             0xC006
4191 #define BR_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA          0xC007
4192 #define BR_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA     0xC008
4193 #define BR_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA      0xC009
4194 #define BR_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA      0xC00A
4195 #define BR_TLS_ECDH_RSA_WITH_NULL_SHA                0xC00B
4196 #define BR_TLS_ECDH_RSA_WITH_RC4_128_SHA             0xC00C
4197 #define BR_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA        0xC00D
4198 #define BR_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA         0xC00E
4199 #define BR_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA         0xC00F
4200 #define BR_TLS_ECDHE_RSA_WITH_NULL_SHA               0xC010
4201 #define BR_TLS_ECDHE_RSA_WITH_RC4_128_SHA            0xC011
4202 #define BR_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA       0xC012
4203 #define BR_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA        0xC013
4204 #define BR_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA        0xC014
4205 #define BR_TLS_ECDH_anon_WITH_NULL_SHA               0xC015
4206 #define BR_TLS_ECDH_anon_WITH_RC4_128_SHA            0xC016
4207 #define BR_TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA       0xC017
4208 #define BR_TLS_ECDH_anon_WITH_AES_128_CBC_SHA        0xC018
4209 #define BR_TLS_ECDH_anon_WITH_AES_256_CBC_SHA        0xC019
4210 
4211 /* From RFC 5288 */
4212 #define BR_TLS_RSA_WITH_AES_128_GCM_SHA256           0x009C
4213 #define BR_TLS_RSA_WITH_AES_256_GCM_SHA384           0x009D
4214 #define BR_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256       0x009E
4215 #define BR_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384       0x009F
4216 #define BR_TLS_DH_RSA_WITH_AES_128_GCM_SHA256        0x00A0
4217 #define BR_TLS_DH_RSA_WITH_AES_256_GCM_SHA384        0x00A1
4218 #define BR_TLS_DHE_DSS_WITH_AES_128_GCM_SHA256       0x00A2
4219 #define BR_TLS_DHE_DSS_WITH_AES_256_GCM_SHA384       0x00A3
4220 #define BR_TLS_DH_DSS_WITH_AES_128_GCM_SHA256        0x00A4
4221 #define BR_TLS_DH_DSS_WITH_AES_256_GCM_SHA384        0x00A5
4222 #define BR_TLS_DH_anon_WITH_AES_128_GCM_SHA256       0x00A6
4223 #define BR_TLS_DH_anon_WITH_AES_256_GCM_SHA384       0x00A7
4224 
4225 /* From RFC 5289 */
4226 #define BR_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256   0xC023
4227 #define BR_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384   0xC024
4228 #define BR_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256    0xC025
4229 #define BR_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384    0xC026
4230 #define BR_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256     0xC027
4231 #define BR_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384     0xC028
4232 #define BR_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256      0xC029
4233 #define BR_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384      0xC02A
4234 #define BR_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256   0xC02B
4235 #define BR_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384   0xC02C
4236 #define BR_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256    0xC02D
4237 #define BR_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384    0xC02E
4238 #define BR_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256     0xC02F
4239 #define BR_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384     0xC030
4240 #define BR_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256      0xC031
4241 #define BR_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384      0xC032
4242 
4243 /* From RFC 6655 and 7251 */
4244 #define BR_TLS_RSA_WITH_AES_128_CCM                  0xC09C
4245 #define BR_TLS_RSA_WITH_AES_256_CCM                  0xC09D
4246 #define BR_TLS_RSA_WITH_AES_128_CCM_8                0xC0A0
4247 #define BR_TLS_RSA_WITH_AES_256_CCM_8                0xC0A1
4248 #define BR_TLS_ECDHE_ECDSA_WITH_AES_128_CCM          0xC0AC
4249 #define BR_TLS_ECDHE_ECDSA_WITH_AES_256_CCM          0xC0AD
4250 #define BR_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8        0xC0AE
4251 #define BR_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8        0xC0AF
4252 
4253 /* From RFC 7905 */
4254 #define BR_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256     0xCCA8
4255 #define BR_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256   0xCCA9
4256 #define BR_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256       0xCCAA
4257 #define BR_TLS_PSK_WITH_CHACHA20_POLY1305_SHA256           0xCCAB
4258 #define BR_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256     0xCCAC
4259 #define BR_TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256       0xCCAD
4260 #define BR_TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256       0xCCAE
4261 
4262 /* From RFC 7507 */
4263 #define BR_TLS_FALLBACK_SCSV                         0x5600
4264 
4265 /*
4266  * Symbolic constants for alerts.
4267  */
4268 #define BR_ALERT_CLOSE_NOTIFY                0
4269 #define BR_ALERT_UNEXPECTED_MESSAGE         10
4270 #define BR_ALERT_BAD_RECORD_MAC             20
4271 #define BR_ALERT_RECORD_OVERFLOW            22
4272 #define BR_ALERT_DECOMPRESSION_FAILURE      30
4273 #define BR_ALERT_HANDSHAKE_FAILURE          40
4274 #define BR_ALERT_BAD_CERTIFICATE            42
4275 #define BR_ALERT_UNSUPPORTED_CERTIFICATE    43
4276 #define BR_ALERT_CERTIFICATE_REVOKED        44
4277 #define BR_ALERT_CERTIFICATE_EXPIRED        45
4278 #define BR_ALERT_CERTIFICATE_UNKNOWN        46
4279 #define BR_ALERT_ILLEGAL_PARAMETER          47
4280 #define BR_ALERT_UNKNOWN_CA                 48
4281 #define BR_ALERT_ACCESS_DENIED              49
4282 #define BR_ALERT_DECODE_ERROR               50
4283 #define BR_ALERT_DECRYPT_ERROR              51
4284 #define BR_ALERT_PROTOCOL_VERSION           70
4285 #define BR_ALERT_INSUFFICIENT_SECURITY      71
4286 #define BR_ALERT_INTERNAL_ERROR             80
4287 #define BR_ALERT_USER_CANCELED              90
4288 #define BR_ALERT_NO_RENEGOTIATION          100
4289 #define BR_ALERT_UNSUPPORTED_EXTENSION     110
4290 #define BR_ALERT_NO_APPLICATION_PROTOCOL   120
4291 
4292 #ifdef __cplusplus
4293 }
4294 #endif
4295 
4296 #endif
4297