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