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