5ea257f9aa76e3e9d19fb011bfea4c1239ca4514
[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 AES/CTR implementation.
1326 *
1327 * \param cc SSL engine context.
1328 * \param impl AES/CTR encryption/decryption implementation (or `NULL`).
1329 */
1330 static inline void
1331 br_ssl_engine_set_aes_ctr(br_ssl_engine_context *cc,
1332 const br_block_ctr_class *impl)
1333 {
1334 cc->iaes_ctr = impl;
1335 }
1336
1337 /**
1338 * \brief Set the DES/CBC implementations.
1339 *
1340 * \param cc SSL engine context.
1341 * \param impl_enc DES/CBC encryption implementation (or `NULL`).
1342 * \param impl_dec DES/CBC decryption implementation (or `NULL`).
1343 */
1344 static inline void
1345 br_ssl_engine_set_des_cbc(br_ssl_engine_context *cc,
1346 const br_block_cbcenc_class *impl_enc,
1347 const br_block_cbcdec_class *impl_dec)
1348 {
1349 cc->ides_cbcenc = impl_enc;
1350 cc->ides_cbcdec = impl_dec;
1351 }
1352
1353 /**
1354 * \brief Set the GHASH implementation (used in GCM mode).
1355 *
1356 * \param cc SSL engine context.
1357 * \param impl GHASH implementation (or `NULL`).
1358 */
1359 static inline void
1360 br_ssl_engine_set_ghash(br_ssl_engine_context *cc, br_ghash impl)
1361 {
1362 cc->ighash = impl;
1363 }
1364
1365 /**
1366 * \brief Set the ChaCha20 implementation.
1367 *
1368 * \param cc SSL engine context.
1369 * \param ichacha ChaCha20 implementation (or `NULL`).
1370 */
1371 static inline void
1372 br_ssl_engine_set_chacha20(br_ssl_engine_context *cc,
1373 br_chacha20_run ichacha)
1374 {
1375 cc->ichacha = ichacha;
1376 }
1377
1378 /**
1379 * \brief Set the Poly1305 implementation.
1380 *
1381 * \param cc SSL engine context.
1382 * \param ipoly Poly1305 implementation (or `NULL`).
1383 */
1384 static inline void
1385 br_ssl_engine_set_poly1305(br_ssl_engine_context *cc,
1386 br_poly1305_run ipoly)
1387 {
1388 cc->ipoly = ipoly;
1389 }
1390
1391 /**
1392 * \brief Set the record encryption and decryption engines for CBC + HMAC.
1393 *
1394 * \param cc SSL engine context.
1395 * \param impl_in record CBC decryption implementation (or `NULL`).
1396 * \param impl_out record CBC encryption implementation (or `NULL`).
1397 */
1398 static inline void
1399 br_ssl_engine_set_cbc(br_ssl_engine_context *cc,
1400 const br_sslrec_in_cbc_class *impl_in,
1401 const br_sslrec_out_cbc_class *impl_out)
1402 {
1403 cc->icbc_in = impl_in;
1404 cc->icbc_out = impl_out;
1405 }
1406
1407 /**
1408 * \brief Set the record encryption and decryption engines for GCM.
1409 *
1410 * \param cc SSL engine context.
1411 * \param impl_in record GCM decryption implementation (or `NULL`).
1412 * \param impl_out record GCM encryption implementation (or `NULL`).
1413 */
1414 static inline void
1415 br_ssl_engine_set_gcm(br_ssl_engine_context *cc,
1416 const br_sslrec_in_gcm_class *impl_in,
1417 const br_sslrec_out_gcm_class *impl_out)
1418 {
1419 cc->igcm_in = impl_in;
1420 cc->igcm_out = impl_out;
1421 }
1422
1423 /**
1424 * \brief Set the record encryption and decryption engines for
1425 * ChaCha20+Poly1305.
1426 *
1427 * \param cc SSL engine context.
1428 * \param impl_in record ChaCha20 decryption implementation (or `NULL`).
1429 * \param impl_out record ChaCha20 encryption implementation (or `NULL`).
1430 */
1431 static inline void
1432 br_ssl_engine_set_chapol(br_ssl_engine_context *cc,
1433 const br_sslrec_in_chapol_class *impl_in,
1434 const br_sslrec_out_chapol_class *impl_out)
1435 {
1436 cc->ichapol_in = impl_in;
1437 cc->ichapol_out = impl_out;
1438 }
1439
1440 /**
1441 * \brief Set the EC implementation.
1442 *
1443 * The elliptic curve implementation will be used for ECDH and ECDHE
1444 * cipher suites, and for ECDSA support.
1445 *
1446 * \param cc SSL engine context.
1447 * \param iec EC implementation (or `NULL`).
1448 */
1449 static inline void
1450 br_ssl_engine_set_ec(br_ssl_engine_context *cc, const br_ec_impl *iec)
1451 {
1452 cc->iec = iec;
1453 }
1454
1455 /**
1456 * \brief Set the RSA signature verification implementation.
1457 *
1458 * On the client, this is used to verify the server's signature on its
1459 * ServerKeyExchange message (for ECDHE_RSA cipher suites). On the server,
1460 * this is used to verify the client's CertificateVerify message (if a
1461 * client certificate is requested, and that certificate contains a RSA key).
1462 *
1463 * \param cc SSL engine context.
1464 * \param irsavrfy RSA signature verification implementation.
1465 */
1466 static inline void
1467 br_ssl_engine_set_rsavrfy(br_ssl_engine_context *cc, br_rsa_pkcs1_vrfy irsavrfy)
1468 {
1469 cc->irsavrfy = irsavrfy;
1470 }
1471
1472 /*
1473 * \brief Set the ECDSA implementation (signature verification).
1474 *
1475 * On the client, this is used to verify the server's signature on its
1476 * ServerKeyExchange message (for ECDHE_ECDSA cipher suites). On the server,
1477 * this is used to verify the client's CertificateVerify message (if a
1478 * client certificate is requested, that certificate contains an EC key,
1479 * and full-static ECDH is not used).
1480 *
1481 * The ECDSA implementation will use the EC core implementation configured
1482 * in the engine context.
1483 *
1484 * \param cc client context.
1485 * \param iecdsa ECDSA verification implementation.
1486 */
1487 static inline void
1488 br_ssl_engine_set_ecdsa(br_ssl_engine_context *cc, br_ecdsa_vrfy iecdsa)
1489 {
1490 cc->iecdsa = iecdsa;
1491 }
1492
1493 /**
1494 * \brief Set the I/O buffer for the SSL engine.
1495 *
1496 * Once this call has been made, `br_ssl_client_reset()` or
1497 * `br_ssl_server_reset()` MUST be called before using the context.
1498 *
1499 * The provided buffer will be used as long as the engine context is
1500 * used. The caller is responsible for keeping it available.
1501 *
1502 * If `bidi` is 0, then the engine will operate in half-duplex mode
1503 * (it won't be able to send data while there is unprocessed incoming
1504 * data in the buffer, and it won't be able to receive data while there
1505 * is unsent data in the buffer). The optimal buffer size in half-duplex
1506 * mode is `BR_SSL_BUFSIZE_MONO`; if the buffer is larger, then extra
1507 * bytes are ignored. If the buffer is smaller, then this limits the
1508 * capacity of the engine to support all allowed record sizes.
1509 *
1510 * If `bidi` is 1, then the engine will split the buffer into two
1511 * parts, for separate handling of outgoing and incoming data. This
1512 * enables full-duplex processing, but requires more RAM. The optimal
1513 * buffer size in full-duplex mode is `BR_SSL_BUFSIZE_BIDI`; if the
1514 * buffer is larger, then extra bytes are ignored. If the buffer is
1515 * smaller, then the split will favour the incoming part, so that
1516 * interoperability is maximised.
1517 *
1518 * \param cc SSL engine context
1519 * \param iobuf I/O buffer.
1520 * \param iobuf_len I/O buffer length (in bytes).
1521 * \param bidi non-zero for full-duplex mode.
1522 */
1523 void br_ssl_engine_set_buffer(br_ssl_engine_context *cc,
1524 void *iobuf, size_t iobuf_len, int bidi);
1525
1526 /**
1527 * \brief Set the I/O buffers for the SSL engine.
1528 *
1529 * Once this call has been made, `br_ssl_client_reset()` or
1530 * `br_ssl_server_reset()` MUST be called before using the context.
1531 *
1532 * This function is similar to `br_ssl_engine_set_buffer()`, except
1533 * that it enforces full-duplex mode, and the two I/O buffers are
1534 * provided as separate chunks.
1535 *
1536 * The macros `BR_SSL_BUFSIZE_INPUT` and `BR_SSL_BUFSIZE_OUTPUT`
1537 * evaluate to the optimal (maximum) sizes for the input and output
1538 * buffer, respectively.
1539 *
1540 * \param cc SSL engine context
1541 * \param ibuf input buffer.
1542 * \param ibuf_len input buffer length (in bytes).
1543 * \param obuf output buffer.
1544 * \param obuf_len output buffer length (in bytes).
1545 */
1546 void br_ssl_engine_set_buffers_bidi(br_ssl_engine_context *cc,
1547 void *ibuf, size_t ibuf_len, void *obuf, size_t obuf_len);
1548
1549 /**
1550 * \brief Inject some "initial entropy" in the context.
1551 *
1552 * This entropy will be added to what can be obtained from the
1553 * underlying operating system, if that OS is supported.
1554 *
1555 * This function may be called several times; all injected entropy chunks
1556 * are cumulatively mixed.
1557 *
1558 * If entropy gathering from the OS is supported and compiled in, then this
1559 * step is optional. Otherwise, it is mandatory to inject randomness, and
1560 * the caller MUST take care to push (as one or several successive calls)
1561 * enough entropy to achieve cryptographic resistance (at least 80 bits,
1562 * preferably 128 or more). The engine will report an error if no entropy
1563 * was provided and none can be obtained from the OS.
1564 *
1565 * Take care that this function cannot assess the cryptographic quality of
1566 * the provided bytes.
1567 *
1568 * In all generality, "entropy" must here be considered to mean "that
1569 * which the attacker cannot predict". If your OS/architecture does not
1570 * have a suitable source of randomness, then you can make do with the
1571 * combination of a large enough secret value (possibly a copy of an
1572 * asymmetric private key that you also store on the system) AND a
1573 * non-repeating value (e.g. current time, provided that the local clock
1574 * cannot be reset or altered by the attacker).
1575 *
1576 * \param cc SSL engine context.
1577 * \param data extra entropy to inject.
1578 * \param len length of the extra data (in bytes).
1579 */
1580 void br_ssl_engine_inject_entropy(br_ssl_engine_context *cc,
1581 const void *data, size_t len);
1582
1583 /**
1584 * \brief Get the "server name" in this engine.
1585 *
1586 * For clients, this is the name provided with `br_ssl_client_reset()`;
1587 * for servers, this is the name received from the client as part of the
1588 * ClientHello message. If there is no such name (e.g. the client did
1589 * not send an SNI extension) then the returned string is empty
1590 * (returned pointer points to a byte of value 0).
1591 *
1592 * The returned pointer refers to a buffer inside the context, which may
1593 * be overwritten as part of normal SSL activity (even within the same
1594 * connection, if a renegotiation occurs).
1595 *
1596 * \param cc SSL engine context.
1597 * \return the server name (possibly empty).
1598 */
1599 static inline const char *
1600 br_ssl_engine_get_server_name(const br_ssl_engine_context *cc)
1601 {
1602 return cc->server_name;
1603 }
1604
1605 /**
1606 * \brief Get the protocol version.
1607 *
1608 * This function returns the protocol version that is used by the
1609 * engine. That value is set after sending (for a server) or receiving
1610 * (for a client) the ServerHello message.
1611 *
1612 * \param cc SSL engine context.
1613 * \return the protocol version.
1614 */
1615 static inline unsigned
1616 br_ssl_engine_get_version(const br_ssl_engine_context *cc)
1617 {
1618 return cc->session.version;
1619 }
1620
1621 /**
1622 * \brief Get a copy of the session parameters.
1623 *
1624 * The session parameters are filled during the handshake, so this
1625 * function shall not be called before completion of the handshake.
1626 * The initial handshake is completed when the context first allows
1627 * application data to be injected.
1628 *
1629 * This function copies the current session parameters into the provided
1630 * structure. Beware that the session parameters include the master
1631 * secret, which is sensitive data, to handle with great care.
1632 *
1633 * \param cc SSL engine context.
1634 * \param pp destination structure for the session parameters.
1635 */
1636 static inline void
1637 br_ssl_engine_get_session_parameters(const br_ssl_engine_context *cc,
1638 br_ssl_session_parameters *pp)
1639 {
1640 memcpy(pp, &cc->session, sizeof *pp);
1641 }
1642
1643 /**
1644 * \brief Set the session parameters to the provided values.
1645 *
1646 * This function is meant to be used in the client, before doing a new
1647 * handshake; a session resumption will be attempted with these
1648 * parameters. In the server, this function has no effect.
1649 *
1650 * \param cc SSL engine context.
1651 * \param pp source structure for the session parameters.
1652 */
1653 static inline void
1654 br_ssl_engine_set_session_parameters(br_ssl_engine_context *cc,
1655 const br_ssl_session_parameters *pp)
1656 {
1657 memcpy(&cc->session, pp, sizeof *pp);
1658 }
1659
1660 /**
1661 * \brief Get the current engine state.
1662 *
1663 * An SSL engine (client or server) has, at any time, a state which is
1664 * the combination of zero, one or more of these flags:
1665 *
1666 * - `BR_SSL_CLOSED`
1667 *
1668 * Engine is finished, no more I/O (until next reset).
1669 *
1670 * - `BR_SSL_SENDREC`
1671 *
1672 * Engine has some bytes to send to the peer.
1673 *
1674 * - `BR_SSL_RECVREC`
1675 *
1676 * Engine expects some bytes from the peer.
1677 *
1678 * - `BR_SSL_SENDAPP`
1679 *
1680 * Engine may receive application data to send (or flush).
1681 *
1682 * - `BR_SSL_RECVAPP`
1683 *
1684 * Engine has obtained some application data from the peer,
1685 * that should be read by the caller.
1686 *
1687 * If no flag at all is set (state value is 0), then the engine is not
1688 * fully initialised yet.
1689 *
1690 * The `BR_SSL_CLOSED` flag is exclusive; when it is set, no other flag
1691 * is set. To distinguish between a normal closure and an error, use
1692 * `br_ssl_engine_last_error()`.
1693 *
1694 * Generally speaking, `BR_SSL_SENDREC` and `BR_SSL_SENDAPP` are mutually
1695 * exclusive: the input buffer, at any point, either accumulates
1696 * plaintext data, or contains an assembled record that is being sent.
1697 * Similarly, `BR_SSL_RECVREC` and `BR_SSL_RECVAPP` are mutually exclusive.
1698 * This may change in a future library version.
1699 *
1700 * \param cc SSL engine context.
1701 * \return the current engine state.
1702 */
1703 unsigned br_ssl_engine_current_state(const br_ssl_engine_context *cc);
1704
1705 /** \brief SSL engine state: closed or failed. */
1706 #define BR_SSL_CLOSED 0x0001
1707 /** \brief SSL engine state: record data is ready to be sent to the peer. */
1708 #define BR_SSL_SENDREC 0x0002
1709 /** \brief SSL engine state: engine may receive records from the peer. */
1710 #define BR_SSL_RECVREC 0x0004
1711 /** \brief SSL engine state: engine may accept application data to send. */
1712 #define BR_SSL_SENDAPP 0x0008
1713 /** \brief SSL engine state: engine has received application data. */
1714 #define BR_SSL_RECVAPP 0x0010
1715
1716 /**
1717 * \brief Get the engine error indicator.
1718 *
1719 * The error indicator is `BR_ERR_OK` (0) if no error was encountered
1720 * since the last call to `br_ssl_client_reset()` or
1721 * `br_ssl_server_reset()`. Other status values are "sticky": they
1722 * remain set, and prevent all I/O activity, until cleared. Only the
1723 * reset calls clear the error indicator.
1724 *
1725 * \param cc SSL engine context.
1726 * \return 0, or a non-zero error code.
1727 */
1728 static inline int
1729 br_ssl_engine_last_error(const br_ssl_engine_context *cc)
1730 {
1731 return cc->err;
1732 }
1733
1734 /*
1735 * There are four I/O operations, each identified by a symbolic name:
1736 *
1737 * sendapp inject application data in the engine
1738 * recvapp retrieving application data from the engine
1739 * sendrec sending records on the transport medium
1740 * recvrec receiving records from the transport medium
1741 *
1742 * Terminology works thus: in a layered model where the SSL engine sits
1743 * between the application and the network, "send" designates operations
1744 * where bytes flow from application to network, and "recv" for the
1745 * reverse operation. Application data (the plaintext that is to be
1746 * conveyed through SSL) is "app", while encrypted records are "rec".
1747 * Note that from the SSL engine point of view, "sendapp" and "recvrec"
1748 * designate bytes that enter the engine ("inject" operation), while
1749 * "recvapp" and "sendrec" designate bytes that exit the engine
1750 * ("extract" operation).
1751 *
1752 * For the operation 'xxx', two functions are defined:
1753 *
1754 * br_ssl_engine_xxx_buf
1755 * Returns a pointer and length to the buffer to use for that
1756 * operation. '*len' is set to the number of bytes that may be read
1757 * from the buffer (extract operation) or written to the buffer
1758 * (inject operation). If no byte may be exchanged for that operation
1759 * at that point, then '*len' is set to zero, and NULL is returned.
1760 * The engine state is unmodified by this call.
1761 *
1762 * br_ssl_engine_xxx_ack
1763 * Informs the engine that 'len' bytes have been read from the buffer
1764 * (extract operation) or written to the buffer (inject operation).
1765 * The 'len' value MUST NOT be zero. The 'len' value MUST NOT exceed
1766 * that which was obtained from a preceeding br_ssl_engine_xxx_buf()
1767 * call.
1768 */
1769
1770 /**
1771 * \brief Get buffer for application data to send.
1772 *
1773 * If the engine is ready to accept application data to send to the
1774 * peer, then this call returns a pointer to the buffer where such
1775 * data shall be written, and its length is written in `*len`.
1776 * Otherwise, `*len` is set to 0 and `NULL` is returned.
1777 *
1778 * \param cc SSL engine context.
1779 * \param len receives the application data output buffer length, or 0.
1780 * \return the application data output buffer, or `NULL`.
1781 */
1782 unsigned char *br_ssl_engine_sendapp_buf(
1783 const br_ssl_engine_context *cc, size_t *len);
1784
1785 /**
1786 * \brief Inform the engine of some new application data.
1787 *
1788 * After writing `len` bytes in the buffer returned by
1789 * `br_ssl_engine_sendapp_buf()`, the application shall call this
1790 * function to trigger any relevant processing. The `len` parameter
1791 * MUST NOT be 0, and MUST NOT exceed the value obtained in the
1792 * `br_ssl_engine_sendapp_buf()` call.
1793 *
1794 * \param cc SSL engine context.
1795 * \param len number of bytes pushed (not zero).
1796 */
1797 void br_ssl_engine_sendapp_ack(br_ssl_engine_context *cc, size_t len);
1798
1799 /**
1800 * \brief Get buffer for received application data.
1801 *
1802 * If the engine has received application data from the peer, hen this
1803 * call returns a pointer to the buffer from where such data shall be
1804 * read, and its length is written in `*len`. Otherwise, `*len` is set
1805 * to 0 and `NULL` is returned.
1806 *
1807 * \param cc SSL engine context.
1808 * \param len receives the application data input buffer length, or 0.
1809 * \return the application data input buffer, or `NULL`.
1810 */
1811 unsigned char *br_ssl_engine_recvapp_buf(
1812 const br_ssl_engine_context *cc, size_t *len);
1813
1814 /**
1815 * \brief Acknowledge some received application data.
1816 *
1817 * After reading `len` bytes from the buffer returned by
1818 * `br_ssl_engine_recvapp_buf()`, the application shall call this
1819 * function to trigger any relevant processing. The `len` parameter
1820 * MUST NOT be 0, and MUST NOT exceed the value obtained in the
1821 * `br_ssl_engine_recvapp_buf()` call.
1822 *
1823 * \param cc SSL engine context.
1824 * \param len number of bytes read (not zero).
1825 */
1826 void br_ssl_engine_recvapp_ack(br_ssl_engine_context *cc, size_t len);
1827
1828 /**
1829 * \brief Get buffer for record data to send.
1830 *
1831 * If the engine has prepared some records to send to the peer, then this
1832 * call returns a pointer to the buffer from where such data shall be
1833 * read, and its length is written in `*len`. Otherwise, `*len` is set
1834 * to 0 and `NULL` is returned.
1835 *
1836 * \param cc SSL engine context.
1837 * \param len receives the record data output buffer length, or 0.
1838 * \return the record data output buffer, or `NULL`.
1839 */
1840 unsigned char *br_ssl_engine_sendrec_buf(
1841 const br_ssl_engine_context *cc, size_t *len);
1842
1843 /**
1844 * \brief Acknowledge some sent record data.
1845 *
1846 * After reading `len` bytes from the buffer returned by
1847 * `br_ssl_engine_sendrec_buf()`, the application shall call this
1848 * function to trigger any relevant processing. The `len` parameter
1849 * MUST NOT be 0, and MUST NOT exceed the value obtained in the
1850 * `br_ssl_engine_sendrec_buf()` call.
1851 *
1852 * \param cc SSL engine context.
1853 * \param len number of bytes read (not zero).
1854 */
1855 void br_ssl_engine_sendrec_ack(br_ssl_engine_context *cc, size_t len);
1856
1857 /**
1858 * \brief Get buffer for incoming records.
1859 *
1860 * If the engine is ready to accept records from the peer, then this
1861 * call returns a pointer to the buffer where such data shall be
1862 * written, and its length is written in `*len`. Otherwise, `*len` is
1863 * set to 0 and `NULL` is returned.
1864 *
1865 * \param cc SSL engine context.
1866 * \param len receives the record data input buffer length, or 0.
1867 * \return the record data input buffer, or `NULL`.
1868 */
1869 unsigned char *br_ssl_engine_recvrec_buf(
1870 const br_ssl_engine_context *cc, size_t *len);
1871
1872 /**
1873 * \brief Inform the engine of some new record data.
1874 *
1875 * After writing `len` bytes in the buffer returned by
1876 * `br_ssl_engine_recvrec_buf()`, the application shall call this
1877 * function to trigger any relevant processing. The `len` parameter
1878 * MUST NOT be 0, and MUST NOT exceed the value obtained in the
1879 * `br_ssl_engine_recvrec_buf()` call.
1880 *
1881 * \param cc SSL engine context.
1882 * \param len number of bytes pushed (not zero).
1883 */
1884 void br_ssl_engine_recvrec_ack(br_ssl_engine_context *cc, size_t len);
1885
1886 /**
1887 * \brief Flush buffered application data.
1888 *
1889 * If some application data has been buffered in the engine, then wrap
1890 * it into a record and mark it for sending. If no application data has
1891 * been buffered but the engine would be ready to accept some, AND the
1892 * `force` parameter is non-zero, then an empty record is assembled and
1893 * marked for sending. In all other cases, this function does nothing.
1894 *
1895 * Empty records are technically legal, but not all existing SSL/TLS
1896 * implementations support them. Empty records can be useful as a
1897 * transparent "keep-alive" mechanism to maintain some low-level
1898 * network activity.
1899 *
1900 * \param cc SSL engine context.
1901 * \param force non-zero to force sending an empty record.
1902 */
1903 void br_ssl_engine_flush(br_ssl_engine_context *cc, int force);
1904
1905 /**
1906 * \brief Initiate a closure.
1907 *
1908 * If, at that point, the context is open and in ready state, then a
1909 * `close_notify` alert is assembled and marked for sending; this
1910 * triggers the closure protocol. Otherwise, no such alert is assembled.
1911 *
1912 * \param cc SSL engine context.
1913 */
1914 void br_ssl_engine_close(br_ssl_engine_context *cc);
1915
1916 /**
1917 * \brief Initiate a renegotiation.
1918 *
1919 * If the engine is failed or closed, or if the peer is known not to
1920 * support secure renegotiation (RFC 5746), or if renegotiations have
1921 * been disabled with the `BR_OPT_NO_RENEGOTIATION` flag, then this
1922 * function returns 0 and nothing else happens.
1923 *
1924 * Otherwise, this function returns 1, and a renegotiation attempt is
1925 * triggered (if a handshake is already ongoing at that point, then
1926 * no new handshake is triggered).
1927 *
1928 * \param cc SSL engine context.
1929 * \return 1 on success, 0 on error.
1930 */
1931 int br_ssl_engine_renegotiate(br_ssl_engine_context *cc);
1932
1933 /*
1934 * Pre-declaration for the SSL client context.
1935 */
1936 typedef struct br_ssl_client_context_ br_ssl_client_context;
1937
1938 /**
1939 * \brief Type for the client certificate, if requested by the server.
1940 */
1941 typedef struct {
1942 /**
1943 * \brief Authentication type.
1944 *
1945 * This is either `BR_AUTH_RSA` (RSA signature), `BR_AUTH_ECDSA`
1946 * (ECDSA signature), or `BR_AUTH_ECDH` (static ECDH key exchange).
1947 */
1948 int auth_type;
1949
1950 /**
1951 * \brief Hash function for computing the CertificateVerify.
1952 *
1953 * This is the symbolic identifier for the hash function that
1954 * will be used to produce the hash of handshake messages, to
1955 * be signed into the CertificateVerify. For full static ECDH
1956 * (client and server certificates are both EC in the same
1957 * curve, and static ECDH is used), this value is set to -1.
1958 *
1959 * Take care that with TLS 1.0 and 1.1, that value MUST match
1960 * the protocol requirements: value must be 0 (MD5+SHA-1) for
1961 * a RSA signature, or 2 (SHA-1) for an ECDSA signature. Only
1962 * TLS 1.2 allows for other hash functions.
1963 */
1964 int hash_id;
1965
1966 /**
1967 * \brief Certificate chain to send to the server.
1968 *
1969 * This is an array of `br_x509_certificate` objects, each
1970 * normally containing a DER-encoded certificate. The client
1971 * code does not try to decode these elements. If there is no
1972 * chain to send to the server, then this pointer shall be
1973 * set to `NULL`.
1974 */
1975 const br_x509_certificate *chain;
1976
1977 /**
1978 * \brief Certificate chain length (number of certificates).
1979 *
1980 * If there is no chain to send to the server, then this value
1981 * shall be set to 0.
1982 */
1983 size_t chain_len;
1984
1985 } br_ssl_client_certificate;
1986
1987 /*
1988 * Note: the constants below for signatures match the TLS constants.
1989 */
1990
1991 /** \brief Client authentication type: static ECDH. */
1992 #define BR_AUTH_ECDH 0
1993 /** \brief Client authentication type: RSA signature. */
1994 #define BR_AUTH_RSA 1
1995 /** \brief Client authentication type: ECDSA signature. */
1996 #define BR_AUTH_ECDSA 3
1997
1998 /**
1999 * \brief Class type for a certificate handler (client side).
2000 *
2001 * A certificate handler selects a client certificate chain to send to
2002 * the server, upon explicit request from that server. It receives
2003 * the list of trust anchor DN from the server, and supported types
2004 * of certificates and signatures, and returns the chain to use. It
2005 * is also invoked to perform the corresponding private key operation
2006 * (a signature, or an ECDH computation).
2007 *
2008 * The SSL client engine will first push the trust anchor DN with
2009 * `start_name_list()`, `start_name()`, `append_name()`, `end_name()`
2010 * and `end_name_list()`. Then it will call `choose()`, to select the
2011 * actual chain (and signature/hash algorithms). Finally, it will call
2012 * either `do_sign()` or `do_keyx()`, depending on the algorithm choices.
2013 */
2014 typedef struct br_ssl_client_certificate_class_ br_ssl_client_certificate_class;
2015 struct br_ssl_client_certificate_class_ {
2016 /**
2017 * \brief Context size (in bytes).
2018 */
2019 size_t context_size;
2020
2021 /**
2022 * \brief Begin reception of a list of trust anchor names. This
2023 * is called while parsing the incoming CertificateRequest.
2024 *
2025 * \param pctx certificate handler context.
2026 */
2027 void (*start_name_list)(const br_ssl_client_certificate_class **pctx);
2028
2029 /**
2030 * \brief Begin reception of a new trust anchor name.
2031 *
2032 * The total encoded name length is provided; it is less than
2033 * 65535 bytes.
2034 *
2035 * \param pctx certificate handler context.
2036 * \param len encoded name length (in bytes).
2037 */
2038 void (*start_name)(const br_ssl_client_certificate_class **pctx,
2039 size_t len);
2040
2041 /**
2042 * \brief Receive some more bytes for the current trust anchor name.
2043 *
2044 * The provided reference (`data`) points to a transient buffer
2045 * they may be reused as soon as this function returns. The chunk
2046 * length (`len`) is never zero.
2047 *
2048 * \param pctx certificate handler context.
2049 * \param data anchor name chunk.
2050 * \param len anchor name chunk length (in bytes).
2051 */
2052 void (*append_name)(const br_ssl_client_certificate_class **pctx,
2053 const unsigned char *data, size_t len);
2054
2055 /**
2056 * \brief End current trust anchor name.
2057 *
2058 * This function is called when all the encoded anchor name data
2059 * has been provided.
2060 *
2061 * \param pctx certificate handler context.
2062 */
2063 void (*end_name)(const br_ssl_client_certificate_class **pctx);
2064
2065 /**
2066 * \brief End list of trust anchor names.
2067 *
2068 * This function is called when all the anchor names in the
2069 * CertificateRequest message have been obtained.
2070 *
2071 * \param pctx certificate handler context.
2072 */
2073 void (*end_name_list)(const br_ssl_client_certificate_class **pctx);
2074
2075 /**
2076 * \brief Select client certificate and algorithms.
2077 *
2078 * This callback function shall fill the provided `choices`
2079 * structure with the selected algorithms and certificate chain.
2080 * The `hash_id`, `chain` and `chain_len` fields must be set. If
2081 * the client cannot or does not wish to send a certificate,
2082 * then it shall set `chain` to `NULL` and `chain_len` to 0.
2083 *
2084 * The `auth_types` parameter describes the authentication types,
2085 * signature algorithms and hash functions that are supported by
2086 * both the client context and the server, and compatible with
2087 * the current protocol version. This is a bit field with the
2088 * following contents:
2089 *
2090 * - If RSA signatures with hash function x are supported, then
2091 * bit x is set.
2092 *
2093 * - If ECDSA signatures with hash function x are supported,
2094 * then bit 8+x is set.
2095 *
2096 * - If static ECDH is supported, with a RSA-signed certificate,
2097 * then bit 16 is set.
2098 *
2099 * - If static ECDH is supported, with an ECDSA-signed certificate,
2100 * then bit 17 is set.
2101 *
2102 * Notes:
2103 *
2104 * - When using TLS 1.0 or 1.1, the hash function for RSA
2105 * signatures is always the special MD5+SHA-1 (id 0), and the
2106 * hash function for ECDSA signatures is always SHA-1 (id 2).
2107 *
2108 * - When using TLS 1.2, the list of hash functions is trimmed
2109 * down to include only hash functions that the client context
2110 * can support. The actual server list can be obtained with
2111 * `br_ssl_client_get_server_hashes()`; that list may be used
2112 * to select the certificate chain to send to the server.
2113 *
2114 * \param pctx certificate handler context.
2115 * \param cc SSL client context.
2116 * \param auth_types supported authentication types and algorithms.
2117 * \param choices destination structure for the policy choices.
2118 */
2119 void (*choose)(const br_ssl_client_certificate_class **pctx,
2120 const br_ssl_client_context *cc, uint32_t auth_types,
2121 br_ssl_client_certificate *choices);
2122
2123 /**
2124 * \brief Perform key exchange (client part).
2125 *
2126 * This callback is invoked in case of a full static ECDH key
2127 * exchange:
2128 *
2129 * - the cipher suite uses `ECDH_RSA` or `ECDH_ECDSA`;
2130 *
2131 * - the server requests a client certificate;
2132 *
2133 * - the client has, and sends, a client certificate that
2134 * uses an EC key in the same curve as the server's key,
2135 * and chooses static ECDH (the `hash_id` field in the choice
2136 * structure was set to -1).
2137 *
2138 * In that situation, this callback is invoked to compute the
2139 * client-side ECDH: the provided `data` (of length `len` bytes)
2140 * is the server's public key point (as decoded from its
2141 * certificate), and the client shall multiply that point with
2142 * its own private key, and write back the X coordinate of the
2143 * resulting point in the same buffer, starting at offset 1
2144 * (therefore, writing back the complete encoded point works).
2145 *
2146 * The callback must uphold the following:
2147 *
2148 * - If the input array does not have the proper length for
2149 * an encoded curve point, then an error (0) shall be reported.
2150 *
2151 * - If the input array has the proper length, then processing
2152 * MUST be constant-time, even if the data is not a valid
2153 * encoded point.
2154 *
2155 * - This callback MUST check that the input point is valid.
2156 *
2157 * Returned value is 1 on success, 0 on error.
2158 *
2159 * \param pctx certificate handler context.
2160 * \param data server public key point.
2161 * \param len server public key point length (in bytes).
2162 * \return 1 on success, 0 on error.
2163 */
2164 uint32_t (*do_keyx)(const br_ssl_client_certificate_class **pctx,
2165 unsigned char *data, size_t len);
2166
2167 /**
2168 * \brief Perform a signature (client authentication).
2169 *
2170 * This callback is invoked when a client certificate was sent,
2171 * and static ECDH is not used. It shall compute a signature,
2172 * using the client's private key, over the provided hash value
2173 * (which is the hash of all previous handshake messages).
2174 *
2175 * On input, the hash value to sign is in `data`, of size
2176 * `hv_len`; the involved hash function is identified by
2177 * `hash_id`. The signature shall be computed and written
2178 * back into `data`; the total size of that buffer is `len`
2179 * bytes.
2180 *
2181 * This callback shall verify that the signature length does not
2182 * exceed `len` bytes, and abstain from writing the signature if
2183 * it does not fit.
2184 *
2185 * For RSA signatures, the `hash_id` may be 0, in which case
2186 * this is the special header-less signature specified in TLS 1.0
2187 * and 1.1, with a 36-byte hash value. Otherwise, normal PKCS#1
2188 * v1.5 signatures shall be computed.
2189 *
2190 * For ECDSA signatures, the signature value shall use the ASN.1
2191 * based encoding.
2192 *
2193 * Returned value is the signature length (in bytes), or 0 on error.
2194 *
2195 * \param pctx certificate handler context.
2196 * \param hash_id hash function identifier.
2197 * \param hv_len hash value length (in bytes).
2198 * \param data input/output buffer (hash value, then signature).
2199 * \param len total buffer length (in bytes).
2200 * \return signature length (in bytes) on success, or 0 on error.
2201 */
2202 size_t (*do_sign)(const br_ssl_client_certificate_class **pctx,
2203 int hash_id, size_t hv_len, unsigned char *data, size_t len);
2204 };
2205
2206 /**
2207 * \brief A single-chain RSA client certificate handler.
2208 *
2209 * This handler uses a single certificate chain, with a RSA
2210 * signature. The list of trust anchor DN is ignored.
2211 *
2212 * Apart from the first field (vtable pointer), its contents are
2213 * opaque and shall not be accessed directly.
2214 */
2215 typedef struct {
2216 /** \brief Pointer to vtable. */
2217 const br_ssl_client_certificate_class *vtable;
2218 #ifndef BR_DOXYGEN_IGNORE
2219 const br_x509_certificate *chain;
2220 size_t chain_len;
2221 const br_rsa_private_key *sk;
2222 br_rsa_pkcs1_sign irsasign;
2223 #endif
2224 } br_ssl_client_certificate_rsa_context;
2225
2226 /**
2227 * \brief A single-chain EC client certificate handler.
2228 *
2229 * This handler uses a single certificate chain, with a RSA
2230 * signature. The list of trust anchor DN is ignored.
2231 *
2232 * This handler may support both static ECDH, and ECDSA signatures
2233 * (either usage may be selectively disabled).
2234 *
2235 * Apart from the first field (vtable pointer), its contents are
2236 * opaque and shall not be accessed directly.
2237 */
2238 typedef struct {
2239 /** \brief Pointer to vtable. */
2240 const br_ssl_client_certificate_class *vtable;
2241 #ifndef BR_DOXYGEN_IGNORE
2242 const br_x509_certificate *chain;
2243 size_t chain_len;
2244 const br_ec_private_key *sk;
2245 unsigned allowed_usages;
2246 unsigned issuer_key_type;
2247 const br_multihash_context *mhash;
2248 const br_ec_impl *iec;
2249 br_ecdsa_sign iecdsa;
2250 #endif
2251 } br_ssl_client_certificate_ec_context;
2252
2253 /**
2254 * \brief Context structure for a SSL client.
2255 *
2256 * The first field (called `eng`) is the SSL engine; all functions that
2257 * work on a `br_ssl_engine_context` structure shall take as parameter
2258 * a pointer to that field. The other structure fields are opaque and
2259 * must not be accessed directly.
2260 */
2261 struct br_ssl_client_context_ {
2262 /**
2263 * \brief The encapsulated engine context.
2264 */
2265 br_ssl_engine_context eng;
2266
2267 #ifndef BR_DOXYGEN_IGNORE
2268 /*
2269 * Minimum ClientHello length; padding with an extension (RFC
2270 * 7685) is added if necessary to match at least that length.
2271 * Such padding is nominally unnecessary, but it has been used
2272 * to work around some server implementation bugs.
2273 */
2274 uint16_t min_clienthello_len;
2275
2276 /*
2277 * Bit field for algoithms (hash + signature) supported by the
2278 * server when requesting a client certificate.
2279 */
2280 uint16_t hashes;
2281
2282 /*
2283 * Server's public key curve.
2284 */
2285 int server_curve;
2286
2287 /*
2288 * Context for certificate handler.
2289 */
2290 const br_ssl_client_certificate_class **client_auth_vtable;
2291
2292 /*
2293 * Client authentication type.
2294 */
2295 unsigned char auth_type;
2296
2297 /*
2298 * Hash function to use for the client signature. This is 0xFF
2299 * if static ECDH is used.
2300 */
2301 unsigned char hash_id;
2302
2303 /*
2304 * For the core certificate handlers, thus avoiding (in most
2305 * cases) the need for an externally provided policy context.
2306 */
2307 union {
2308 const br_ssl_client_certificate_class *vtable;
2309 br_ssl_client_certificate_rsa_context single_rsa;
2310 br_ssl_client_certificate_ec_context single_ec;
2311 } client_auth;
2312
2313 /*
2314 * Implementations.
2315 */
2316 br_rsa_public irsapub;
2317 #endif
2318 };
2319
2320 /**
2321 * \brief Get the hash functions and signature algorithms supported by
2322 * the server.
2323 *
2324 * This is a field of bits: for hash function of ID x, bit x is set if
2325 * the hash function is supported in RSA signatures, 8+x if it is supported
2326 * with ECDSA. This information is conveyed by the server when requesting
2327 * a client certificate.
2328 *
2329 * \param cc client context.
2330 * \return the server-supported hash functions (for signatures).
2331 */
2332 static inline uint16_t
2333 br_ssl_client_get_server_hashes(const br_ssl_client_context *cc)
2334 {
2335 return cc->hashes;
2336 }
2337
2338 /**
2339 * \brief Get the server key curve.
2340 *
2341 * This function returns the ID for the curve used by the server's public
2342 * key. This is set when the server's certificate chain is processed;
2343 * this value is 0 if the server's key is not an EC key.
2344 *
2345 * \return the server's public key curve ID, or 0.
2346 */
2347 static inline int
2348 br_ssl_client_get_server_curve(const br_ssl_client_context *cc)
2349 {
2350 return cc->server_curve;
2351 }
2352
2353 /*
2354 * Each br_ssl_client_init_xxx() function sets the list of supported
2355 * cipher suites and used implementations, as specified by the profile
2356 * name 'xxx'. Defined profile names are:
2357 *
2358 * full all supported versions and suites; constant-time implementations
2359 * TODO: add other profiles
2360 */
2361
2362 /**
2363 * \brief SSL client profile: full.
2364 *
2365 * This function initialises the provided SSL client context with
2366 * all supported algorithms and cipher suites. It also initialises
2367 * a companion X.509 validation engine with all supported algorithms,
2368 * and the provided trust anchors; the X.509 engine will be used by
2369 * the client context to validate the server's certificate.
2370 *
2371 * \param cc client context to initialise.
2372 * \param xc X.509 validation context to initialise.
2373 * \param trust_anchors trust anchors to use.
2374 * \param trust_anchors_num number of trust anchors.
2375 */
2376 void br_ssl_client_init_full(br_ssl_client_context *cc,
2377 br_x509_minimal_context *xc,
2378 const br_x509_trust_anchor *trust_anchors, size_t trust_anchors_num);
2379
2380 /**
2381 * \brief Clear the complete contents of a SSL client context.
2382 *
2383 * Everything is cleared, including the reference to the configured buffer,
2384 * implementations, cipher suites and state. This is a preparatory step
2385 * to assembling a custom profile.
2386 *
2387 * \param cc client context to clear.
2388 */
2389 void br_ssl_client_zero(br_ssl_client_context *cc);
2390
2391 /**
2392 * \brief Set an externally provided client certificate handler context.
2393 *
2394 * The handler's methods are invoked when the server requests a client
2395 * certificate.
2396 *
2397 * \param cc client context.
2398 * \param pctx certificate handler context (pointer to its vtable field).
2399 */
2400 static inline void
2401 br_ssl_client_set_client_certificate(br_ssl_client_context *cc,
2402 const br_ssl_client_certificate_class **pctx)
2403 {
2404 cc->client_auth_vtable = pctx;
2405 }
2406
2407 /**
2408 * \brief Set the RSA public-key operations implementation.
2409 *
2410 * This will be used to encrypt the pre-master secret with the server's
2411 * RSA public key (RSA-encryption cipher suites only).
2412 *
2413 * \param cc client context.
2414 * \param irsapub RSA public-key encryption implementation.
2415 */
2416 static inline void
2417 br_ssl_client_set_rsapub(br_ssl_client_context *cc, br_rsa_public irsapub)
2418 {
2419 cc->irsapub = irsapub;
2420 }
2421
2422 /**
2423 * \brief Set the minimum ClientHello length (RFC 7685 padding).
2424 *
2425 * If this value is set and the ClientHello would be shorter, then
2426 * the Pad ClientHello extension will be added with enough padding bytes
2427 * to reach the target size. Because of the extension header, the resulting
2428 * size will sometimes be slightly more than `len` bytes if the target
2429 * size cannot be exactly met.
2430 *
2431 * The target length relates to the _contents_ of the ClientHello, not
2432 * counting its 4-byte header. For instance, if `len` is set to 512,
2433 * then the padding will bring the ClientHello size to 516 bytes with its
2434 * header, and 521 bytes when counting the 5-byte record header.
2435 *
2436 * \param cc client context.
2437 * \param len minimum ClientHello length (in bytes).
2438 */
2439 static inline void
2440 br_ssl_client_set_min_clienthello_len(br_ssl_client_context *cc, uint16_t len)
2441 {
2442 cc->min_clienthello_len = len;
2443 }
2444
2445 /**
2446 * \brief Prepare or reset a client context for a new connection.
2447 *
2448 * The `server_name` parameter is used to fill the SNI extension; the
2449 * X.509 "minimal" engine will also match that name against the server
2450 * names included in the server's certificate. If the parameter is
2451 * `NULL` then no SNI extension will be sent, and the X.509 "minimal"
2452 * engine (if used for server certificate validation) will not check
2453 * presence of any specific name in the received certificate.
2454 *
2455 * Therefore, setting the `server_name` to `NULL` shall be reserved
2456 * to cases where alternate or additional methods are used to ascertain
2457 * that the right server public key is used (e.g. a "known key" model).
2458 *
2459 * If `resume_session` is non-zero and the context was previously used
2460 * then the session parameters may be reused (depending on whether the
2461 * server previously sent a non-empty session ID, and accepts the session
2462 * resumption). The session parameters for session resumption can also
2463 * be set explicitly with `br_ssl_engine_set_session_parameters()`.
2464 *
2465 * On failure, the context is marked as failed, and this function
2466 * returns 0. A possible failure condition is when no initial entropy
2467 * was injected, and none could be obtained from the OS (either OS
2468 * randomness gathering is not supported, or it failed).
2469 *
2470 * \param cc client context.
2471 * \param server_name target server name, or `NULL`.
2472 * \param resume_session non-zero to try session resumption.
2473 * \return 0 on failure, 1 on success.
2474 */
2475 int br_ssl_client_reset(br_ssl_client_context *cc,
2476 const char *server_name, int resume_session);
2477
2478 /**
2479 * \brief Forget any session in the context.
2480 *
2481 * This means that the next handshake that uses this context will
2482 * necessarily be a full handshake (this applies both to new connections
2483 * and to renegotiations).
2484 *
2485 * \param cc client context.
2486 */
2487 static inline void
2488 br_ssl_client_forget_session(br_ssl_client_context *cc)
2489 {
2490 cc->eng.session.session_id_len = 0;
2491 }
2492
2493 /**
2494 * \brief Set client certificate chain and key (single RSA case).
2495 *
2496 * This function sets a client certificate chain, that the client will
2497 * send to the server whenever a client certificate is requested. This
2498 * certificate uses an RSA public key; the corresponding private key is
2499 * invoked for authentication. Trust anchor names sent by the server are
2500 * ignored.
2501 *
2502 * The provided chain and private key are linked in the client context;
2503 * they must remain valid as long as they may be used, i.e. normally
2504 * for the duration of the connection, since they might be invoked
2505 * again upon renegotiations.
2506 *
2507 * \param cc SSL client context.
2508 * \param chain client certificate chain (SSL order: EE comes first).
2509 * \param chain_len client chain length (number of certificates).
2510 * \param sk client private key.
2511 * \param irsasign RSA signature implementation (PKCS#1 v1.5).
2512 */
2513 void br_ssl_client_set_single_rsa(br_ssl_client_context *cc,
2514 const br_x509_certificate *chain, size_t chain_len,
2515 const br_rsa_private_key *sk, br_rsa_pkcs1_sign irsasign);
2516
2517 /*
2518 * \brief Set the client certificate chain and key (single EC case).
2519 *
2520 * This function sets a client certificate chain, that the client will
2521 * send to the server whenever a client certificate is requested. This
2522 * certificate uses an EC public key; the corresponding private key is
2523 * invoked for authentication. Trust anchor names sent by the server are
2524 * ignored.
2525 *
2526 * The provided chain and private key are linked in the client context;
2527 * they must remain valid as long as they may be used, i.e. normally
2528 * for the duration of the connection, since they might be invoked
2529 * again upon renegotiations.
2530 *
2531 * The `allowed_usages` is a combination of usages, namely
2532 * `BR_KEYTYPE_KEYX` and/or `BR_KEYTYPE_SIGN`. The `BR_KEYTYPE_KEYX`
2533 * value allows full static ECDH, while the `BR_KEYTYPE_SIGN` value
2534 * allows ECDSA signatures. If ECDSA signatures are used, then an ECDSA
2535 * signature implementation must be provided; otherwise, the `iecdsa`
2536 * parameter may be 0.
2537 *
2538 * The `cert_issuer_key_type` value is either `BR_KEYTYPE_RSA` or
2539 * `BR_KEYTYPE_EC`; it is the type of the public key used the the CA
2540 * that issued (signed) the client certificate. That value is used with
2541 * full static ECDH: support of the certificate by the server depends
2542 * on how the certificate was signed. (Note: when using TLS 1.2, this
2543 * parameter is ignored; but its value matters for TLS 1.0 and 1.1.)
2544 *
2545 * \param cc server context.
2546 * \param chain server certificate chain to send.
2547 * \param chain_len chain length (number of certificates).
2548 * \param sk server private key (EC).
2549 * \param allowed_usages allowed private key usages.
2550 * \param cert_issuer_key_type issuing CA's key type.
2551 * \param iec EC core implementation.
2552 * \param iecdsa ECDSA signature implementation ("asn1" format).
2553 */
2554 void br_ssl_client_set_single_ec(br_ssl_client_context *cc,
2555 const br_x509_certificate *chain, size_t chain_len,
2556 const br_ec_private_key *sk, unsigned allowed_usages,
2557 unsigned cert_issuer_key_type,
2558 const br_ec_impl *iec, br_ecdsa_sign iecdsa);
2559
2560 /**
2561 * \brief Type for a "translated cipher suite", as an array of two
2562 * 16-bit integers.
2563 *
2564 * The first element is the cipher suite identifier (as used on the wire).
2565 * The second element is the concatenation of four 4-bit elements which
2566 * characterise the cipher suite contents. In most to least significant
2567 * order, these 4-bit elements are:
2568 *
2569 * - Bits 12 to 15: key exchange + server key type
2570 *
2571 * | val | symbolic constant | suite type | details |
2572 * | :-- | :----------------------- | :---------- | :----------------------------------------------- |
2573 * | 0 | `BR_SSLKEYX_RSA` | RSA | RSA key exchange, key is RSA (encryption) |
2574 * | 1 | `BR_SSLKEYX_ECDHE_RSA` | ECDHE_RSA | ECDHE key exchange, key is RSA (signature) |
2575 * | 2 | `BR_SSLKEYX_ECDHE_ECDSA` | ECDHE_ECDSA | ECDHE key exchange, key is EC (signature) |
2576 * | 3 | `BR_SSLKEYX_ECDH_RSA` | ECDH_RSA | Key is EC (key exchange), cert signed with RSA |
2577 * | 4 | `BR_SSLKEYX_ECDH_ECDSA` | ECDH_ECDSA | Key is EC (key exchange), cert signed with ECDSA |
2578 *
2579 * - Bits 8 to 11: symmetric encryption algorithm
2580 *
2581 * | val | symbolic constant | symmetric encryption | key strength (bits) |
2582 * | :-- | :--------------------- | :------------------- | :------------------ |
2583 * | 0 | `BR_SSLENC_3DES_CBC` | 3DES/CBC | 168 |
2584 * | 1 | `BR_SSLENC_AES128_CBC` | AES-128/CBC | 128 |
2585 * | 2 | `BR_SSLENC_AES256_CBC` | AES-256/CBC | 256 |
2586 * | 3 | `BR_SSLENC_AES128_GCM` | AES-128/GCM | 128 |
2587 * | 4 | `BR_SSLENC_AES256_GCM` | AES-256/GCM | 256 |
2588 * | 5 | `BR_SSLENC_CHACHA20` | ChaCha20/Poly1305 | 256 |
2589 *
2590 * - Bits 4 to 7: MAC algorithm
2591 *
2592 * | val | symbolic constant | MAC type | details |
2593 * | :-- | :----------------- | :----------- | :------------------------------------ |
2594 * | 0 | `BR_SSLMAC_AEAD` | AEAD | No dedicated MAC (encryption is AEAD) |
2595 * | 2 | `BR_SSLMAC_SHA1` | HMAC/SHA-1 | Value matches `br_sha1_ID` |
2596 * | 4 | `BR_SSLMAC_SHA256` | HMAC/SHA-256 | Value matches `br_sha256_ID` |
2597 * | 5 | `BR_SSLMAC_SHA384` | HMAC/SHA-384 | Value matches `br_sha384_ID` |
2598 *
2599 * - Bits 0 to 3: hash function for PRF when used with TLS-1.2
2600 *
2601 * | val | symbolic constant | hash function | details |
2602 * | :-- | :----------------- | :------------ | :----------------------------------- |
2603 * | 4 | `BR_SSLPRF_SHA256` | SHA-256 | Value matches `br_sha256_ID` |
2604 * | 5 | `BR_SSLPRF_SHA384` | SHA-384 | Value matches `br_sha384_ID` |
2605 *
2606 * For instance, cipher suite `TLS_RSA_WITH_AES_128_GCM_SHA256` has
2607 * standard identifier 0x009C, and is translated to 0x0304, for, in
2608 * that order: RSA key exchange (0), AES-128/GCM (3), AEAD integrity (0),
2609 * SHA-256 in the TLS PRF (4).
2610 */
2611 typedef uint16_t br_suite_translated[2];
2612
2613 #ifndef BR_DOXYGEN_IGNORE
2614 /*
2615 * Constants are already documented in the br_suite_translated type.
2616 */
2617
2618 #define BR_SSLKEYX_RSA 0
2619 #define BR_SSLKEYX_ECDHE_RSA 1
2620 #define BR_SSLKEYX_ECDHE_ECDSA 2
2621 #define BR_SSLKEYX_ECDH_RSA 3
2622 #define BR_SSLKEYX_ECDH_ECDSA 4
2623
2624 #define BR_SSLENC_3DES_CBC 0
2625 #define BR_SSLENC_AES128_CBC 1
2626 #define BR_SSLENC_AES256_CBC 2
2627 #define BR_SSLENC_AES128_GCM 3
2628 #define BR_SSLENC_AES256_GCM 4
2629 #define BR_SSLENC_CHACHA20 5
2630
2631 #define BR_SSLMAC_AEAD 0
2632 #define BR_SSLMAC_SHA1 br_sha1_ID
2633 #define BR_SSLMAC_SHA256 br_sha256_ID
2634 #define BR_SSLMAC_SHA384 br_sha384_ID
2635
2636 #define BR_SSLPRF_SHA256 br_sha256_ID
2637 #define BR_SSLPRF_SHA384 br_sha384_ID
2638
2639 #endif
2640
2641 /*
2642 * Pre-declaration for the SSL server context.
2643 */
2644 typedef struct br_ssl_server_context_ br_ssl_server_context;
2645
2646 /**
2647 * \brief Type for the server policy choices, taken after analysis of
2648 * the client message (ClientHello).
2649 */
2650 typedef struct {
2651 /**
2652 * \brief Cipher suite to use with that client.
2653 */
2654 uint16_t cipher_suite;
2655
2656 /**
2657 * \brief Hash function for signing the ServerKeyExchange.
2658 *
2659 * This is the symbolic identifier for the hash function that
2660 * will be used to sign the ServerKeyExchange message, for ECDHE
2661 * cipher suites. This is ignored for RSA and ECDH cipher suites.
2662 *
2663 * Take care that with TLS 1.0 and 1.1, that value MUST match
2664 * the protocol requirements: value must be 0 (MD5+SHA-1) for
2665 * a RSA signature, or 2 (SHA-1) for an ECDSA signature. Only
2666 * TLS 1.2 allows for other hash functions.
2667 */
2668 int hash_id;
2669
2670 /**
2671 * \brief Certificate chain to send to the client.
2672 *
2673 * This is an array of `br_x509_certificate` objects, each
2674 * normally containing a DER-encoded certificate. The server
2675 * code does not try to decode these elements.
2676 */
2677 const br_x509_certificate *chain;
2678
2679 /**
2680 * \brief Certificate chain length (number of certificates).
2681 */
2682 size_t chain_len;
2683
2684 } br_ssl_server_choices;
2685
2686 /**
2687 * \brief Class type for a policy handler (server side).
2688 *
2689 * A policy handler selects the policy parameters for a connection
2690 * (cipher suite and other algorithms, and certificate chain to send to
2691 * the client); it also performs the server-side computations involving
2692 * its permanent private key.
2693 *
2694 * The SSL server engine will invoke first `choose()`, once the
2695 * ClientHello message has been received, then either `do_keyx()`
2696 * `do_sign()`, depending on the cipher suite.
2697 */
2698 typedef struct br_ssl_server_policy_class_ br_ssl_server_policy_class;
2699 struct br_ssl_server_policy_class_ {
2700 /**
2701 * \brief Context size (in bytes).
2702 */
2703 size_t context_size;
2704
2705 /**
2706 * \brief Select algorithms and certificates for this connection.
2707 *
2708 * This callback function shall fill the provided `choices`
2709 * structure with the policy choices for this connection. This
2710 * entails selecting the cipher suite, hash function for signing
2711 * the ServerKeyExchange (applicable only to ECDHE cipher suites),
2712 * and certificate chain to send.
2713 *
2714 * The callback receives a pointer to the server context that
2715 * contains the relevant data. In particular, the functions
2716 * `br_ssl_server_get_client_suites()`,
2717 * `br_ssl_server_get_client_hashes()` and
2718 * `br_ssl_server_get_client_curves()` can be used to obtain
2719 * the cipher suites, hash functions and elliptic curves
2720 * supported by both the client and server, respectively. The
2721 * `br_ssl_engine_get_version()` and `br_ssl_engine_get_server_name()`
2722 * functions yield the protocol version and requested server name
2723 * (SNI), respectively.
2724 *
2725 * This function may modify its context structure (`pctx`) in
2726 * arbitrary ways to keep track of its own choices.
2727 *
2728 * This function shall return 1 if appropriate policy choices
2729 * could be made, or 0 if this connection cannot be pursued.
2730 *
2731 * \param pctx policy context.
2732 * \param cc SSL server context.
2733 * \param choices destination structure for the policy choices.
2734 * \return 1 on success, 0 on error.
2735 */
2736 int (*choose)(const br_ssl_server_policy_class **pctx,
2737 const br_ssl_server_context *cc,
2738 br_ssl_server_choices *choices);
2739
2740 /**
2741 * \brief Perform key exchange (server part).
2742 *
2743 * This callback is invoked to perform the server-side cryptographic
2744 * operation for a key exchange that is not ECDHE. This callback
2745 * uses the private key.
2746 *
2747 * **For RSA key exchange**, the provided `data` (of length `len`
2748 * bytes) shall be decrypted with the server's private key, and
2749 * the 48-byte premaster secret copied back to the first 48 bytes
2750 * of `data`.
2751 *
2752 * - The caller makes sure that `len` is at least 59 bytes.
2753 *
2754 * - This callback MUST check that the provided length matches
2755 * that of the key modulus; it shall report an error otherwise.
2756 *
2757 * - If the length matches that of the RSA key modulus, then
2758 * processing MUST be constant-time, even if decryption fails,
2759 * or the padding is incorrect, or the plaintext message length
2760 * is not exactly 48 bytes.
2761 *
2762 * - This callback needs not check the two first bytes of the
2763 * obtained pre-master secret (the caller will do that).
2764 *
2765 * - If an error is reported (0), then what the callback put
2766 * in the first 48 bytes of `data` is unimportant (the caller
2767 * will use random bytes instead).
2768 *
2769 * **For ECDH key exchange**, the provided `data` (of length `len`
2770 * bytes) is the elliptic curve point from the client. The
2771 * callback shall multiply it with its private key, and store
2772 * the resulting X coordinate in `data`, starting at offset 1
2773 * (thus, simply encoding the point in compressed or uncompressed
2774 * format in `data` is fine).
2775 *
2776 * - If the input array does not have the proper length for
2777 * an encoded curve point, then an error (0) shall be reported.
2778 *
2779 * - If the input array has the proper length, then processing
2780 * MUST be constant-time, even if the data is not a valid
2781 * encoded point.
2782 *
2783 * - This callback MUST check that the input point is valid.
2784 *
2785 * Returned value is 1 on success, 0 on error.
2786 *
2787 * \param pctx policy context.
2788 * \param data key exchange data from the client.
2789 * \param len key exchange data length (in bytes).
2790 * \return 1 on success, 0 on error.
2791 */
2792 uint32_t (*do_keyx)(const br_ssl_server_policy_class **pctx,
2793 unsigned char *data, size_t len);
2794
2795 /**
2796 * \brief Perform a signature (for a ServerKeyExchange message).
2797 *
2798 * This callback function is invoked for ECDHE cipher suites.
2799 * On input, the hash value to sign is in `data`, of size
2800 * `hv_len`; the involved hash function is identified by
2801 * `hash_id`. The signature shall be computed and written
2802 * back into `data`; the total size of that buffer is `len`
2803 * bytes.
2804 *
2805 * This callback shall verify that the signature length does not
2806 * exceed `len` bytes, and abstain from writing the signature if
2807 * it does not fit.
2808 *
2809 * For RSA signatures, the `hash_id` may be 0, in which case
2810 * this is the special header-less signature specified in TLS 1.0
2811 * and 1.1, with a 36-byte hash value. Otherwise, normal PKCS#1
2812 * v1.5 signatures shall be computed.
2813 *
2814 * Returned value is the signature length (in bytes), or 0 on error.
2815 *
2816 * \param pctx policy context.
2817 * \param hash_id hash function identifier.
2818 * \param hv_len hash value length (in bytes).
2819 * \param data input/output buffer (hash value, then signature).
2820 * \param len total buffer length (in bytes).
2821 * \return signature length (in bytes) on success, or 0 on error.
2822 */
2823 size_t (*do_sign)(const br_ssl_server_policy_class **pctx,
2824 int hash_id, size_t hv_len, unsigned char *data, size_t len);
2825 };
2826
2827 /**
2828 * \brief A single-chain RSA policy handler.
2829 *
2830 * This policy context uses a single certificate chain, and a RSA
2831 * private key. The context can be restricted to only signatures or
2832 * only key exchange.
2833 *
2834 * Apart from the first field (vtable pointer), its contents are
2835 * opaque and shall not be accessed directly.
2836 */
2837 typedef struct {
2838 /** \brief Pointer to vtable. */
2839 const br_ssl_server_policy_class *vtable;
2840 #ifndef BR_DOXYGEN_IGNORE
2841 const br_x509_certificate *chain;
2842 size_t chain_len;
2843 const br_rsa_private_key *sk;
2844 unsigned allowed_usages;
2845 br_rsa_private irsacore;
2846 br_rsa_pkcs1_sign irsasign;
2847 #endif
2848 } br_ssl_server_policy_rsa_context;
2849
2850 /**
2851 * \brief A single-chain EC policy handler.
2852 *
2853 * This policy context uses a single certificate chain, and an EC
2854 * private key. The context can be restricted to only signatures or
2855 * only key exchange.
2856 *
2857 * Due to how TLS is defined, this context must be made aware whether
2858 * the server certificate was itself signed with RSA or ECDSA. The code
2859 * does not try to decode the certificate to obtain that information.
2860 *
2861 * Apart from the first field (vtable pointer), its contents are
2862 * opaque and shall not be accessed directly.
2863 */
2864 typedef struct {
2865 /** \brief Pointer to vtable. */
2866 const br_ssl_server_policy_class *vtable;
2867 #ifndef BR_DOXYGEN_IGNORE
2868 const br_x509_certificate *chain;
2869 size_t chain_len;
2870 const br_ec_private_key *sk;
2871 unsigned allowed_usages;
2872 unsigned cert_issuer_key_type;
2873 const br_multihash_context *mhash;
2874 const br_ec_impl *iec;
2875 br_ecdsa_sign iecdsa;
2876 #endif
2877 } br_ssl_server_policy_ec_context;
2878
2879 /**
2880 * \brief Class type for a session parameter cache.
2881 *
2882 * Session parameters are saved in the cache with `save()`, and
2883 * retrieved with `load()`. The cache implementation can apply any
2884 * storage and eviction strategy that it sees fit. The SSL server
2885 * context that performs the request is provided, so that its
2886 * functionalities may be used by the implementation (e.g. hash
2887 * functions or random number generation).
2888 */
2889 typedef struct br_ssl_session_cache_class_ br_ssl_session_cache_class;
2890 struct br_ssl_session_cache_class_ {
2891 /**
2892 * \brief Context size (in bytes).
2893 */
2894 size_t context_size;
2895
2896 /**
2897 * \brief Record a session.
2898 *
2899 * This callback should record the provided session parameters.
2900 * The `params` structure is transient, so its contents shall
2901 * be copied into the cache. The session ID has been randomly
2902 * generated and always has length exactly 32 bytes.
2903 *
2904 * \param ctx session cache context.
2905 * \param server_ctx SSL server context.
2906 * \param params session parameters to save.
2907 */
2908 void (*save)(const br_ssl_session_cache_class **ctx,
2909 br_ssl_server_context *server_ctx,
2910 const br_ssl_session_parameters *params);
2911
2912 /**
2913 * \brief Lookup a session in the cache.
2914 *
2915 * The session ID to lookup is in `params` and always has length
2916 * exactly 32 bytes. If the session parameters are found in the
2917 * cache, then the parameters shall be copied into the `params`
2918 * structure. Returned value is 1 on successful lookup, 0
2919 * otherwise.
2920 *
2921 * \param ctx session cache context.
2922 * \param server_ctx SSL server context.
2923 * \param params destination for session parameters.
2924 * \return 1 if found, 0 otherwise.
2925 */
2926 int (*load)(const br_ssl_session_cache_class **ctx,
2927 br_ssl_server_context *server_ctx,
2928 br_ssl_session_parameters *params);
2929 };
2930
2931 /**
2932 * \brief Context for a basic cache system.
2933 *
2934 * The system stores session parameters in a buffer provided at
2935 * initialisation time. Each entry uses exactly 100 bytes, and
2936 * buffer sizes up to 4294967295 bytes are supported.
2937 *
2938 * Entries are evicted with a LRU (Least Recently Used) policy. A
2939 * search tree is maintained to keep lookups fast even with large
2940 * caches.
2941 *
2942 * Apart from the first field (vtable pointer), the structure
2943 * contents are opaque and shall not be accessed directly.
2944 */
2945 typedef struct {
2946 /** \brief Pointer to vtable. */
2947 const br_ssl_session_cache_class *vtable;
2948 #ifndef BR_DOXYGEN_IGNORE
2949 unsigned char *store;
2950 size_t store_len, store_ptr;
2951 unsigned char index_key[32];
2952 const br_hash_class *hash;
2953 int init_done;
2954 uint32_t head, tail, root;
2955 #endif
2956 } br_ssl_session_cache_lru;
2957
2958 /**
2959 * \brief Initialise a LRU session cache with the provided storage space.
2960 *
2961 * The provided storage space must remain valid as long as the cache
2962 * is used. Arbitrary lengths are supported, up to 4294967295 bytes;
2963 * each entry uses up exactly 100 bytes.
2964 *
2965 * \param cc session cache context.
2966 * \param store storage space for cached entries.
2967 * \param store_len storage space length (in bytes).
2968 */
2969 void br_ssl_session_cache_lru_init(br_ssl_session_cache_lru *cc,
2970 unsigned char *store, size_t store_len);
2971
2972 /**
2973 * \brief Context structure for a SSL server.
2974 *
2975 * The first field (called `eng`) is the SSL engine; all functions that
2976 * work on a `br_ssl_engine_context` structure shall take as parameter
2977 * a pointer to that field. The other structure fields are opaque and
2978 * must not be accessed directly.
2979 */
2980 struct br_ssl_server_context_ {
2981 /**
2982 * \brief The encapsulated engine context.
2983 */
2984 br_ssl_engine_context eng;
2985
2986 #ifndef BR_DOXYGEN_IGNORE
2987 /*
2988 * Maximum version from the client.
2989 */
2990 uint16_t client_max_version;
2991
2992 /*
2993 * Session cache.
2994 */
2995 const br_ssl_session_cache_class **cache_vtable;
2996
2997 /*
2998 * Translated cipher suites supported by the client. The list
2999 * is trimmed to include only the cipher suites that the
3000 * server also supports; they are in the same order as in the
3001 * client message.
3002 */
3003 br_suite_translated client_suites[BR_MAX_CIPHER_SUITES];
3004 unsigned char client_suites_num;
3005
3006 /*
3007 * Hash functions supported by the client, with ECDSA and RSA
3008 * (bit mask). For hash function with id 'x', set bit index is
3009 * x for RSA, x+8 for ECDSA.
3010 */
3011 uint16_t hashes;
3012
3013 /*
3014 * Curves supported by the client (bit mask, for named curves).
3015 */
3016 uint32_t curves;
3017
3018 /*
3019 * Context for chain handler.
3020 */
3021 const br_ssl_server_policy_class **policy_vtable;
3022 unsigned char sign_hash_id;
3023
3024 /*
3025 * For the core handlers, thus avoiding (in most cases) the
3026 * need for an externally provided policy context.
3027 */
3028 union {
3029 const br_ssl_server_policy_class *vtable;
3030 br_ssl_server_policy_rsa_context single_rsa;
3031 br_ssl_server_policy_ec_context single_ec;
3032 } chain_handler;
3033
3034 /*
3035 * Buffer for the ECDHE private key.
3036 */
3037 unsigned char ecdhe_key[70];
3038 size_t ecdhe_key_len;
3039
3040 /*
3041 * Trust anchor names for client authentication. "ta_names" and
3042 * "tas" cannot be both non-NULL.
3043 */
3044 const br_x500_name *ta_names;
3045 const br_x509_trust_anchor *tas;
3046 size_t num_tas;
3047 size_t cur_dn_index;
3048 const unsigned char *cur_dn;
3049 size_t cur_dn_len;
3050
3051 /*
3052 * Buffer for the hash value computed over all handshake messages
3053 * prior to CertificateVerify, and identifier for the hash function.
3054 */
3055 unsigned char hash_CV[64];
3056 size_t hash_CV_len;
3057 int hash_CV_id;
3058
3059 /*
3060 * Server-specific implementations.
3061 * (none for now)
3062 */
3063 #endif
3064 };
3065
3066 /*
3067 * Each br_ssl_server_init_xxx() function sets the list of supported
3068 * cipher suites and used implementations, as specified by the profile
3069 * name 'xxx'. Defined profile names are:
3070 *
3071 * full_rsa all supported algorithm, server key type is RSA
3072 * full_ec all supported algorithm, server key type is EC
3073 * TODO: add other profiles
3074 *
3075 * Naming scheme for "minimal" profiles: min123
3076 *
3077 * -- character 1: key exchange
3078 * r = RSA
3079 * e = ECDHE_RSA
3080 * f = ECDHE_ECDSA
3081 * u = ECDH_RSA
3082 * v = ECDH_ECDSA
3083 * -- character 2: version / PRF
3084 * 0 = TLS 1.0 / 1.1 with MD5+SHA-1
3085 * 2 = TLS 1.2 with SHA-256
3086 * 3 = TLS 1.2 with SHA-384
3087 * -- character 3: encryption
3088 * a = AES/CBC
3089 * g = AES/GCM
3090 * d = 3DES/CBC
3091 */
3092
3093 /**
3094 * \brief SSL server profile: full_rsa.
3095 *
3096 * This function initialises the provided SSL server context with
3097 * all supported algorithms and cipher suites that rely on a RSA
3098 * key pair.
3099 *
3100 * \param cc server context to initialise.
3101 * \param chain server certificate chain.
3102 * \param chain_len certificate chain length (number of certificate).
3103 * \param sk RSA private key.
3104 */
3105 void br_ssl_server_init_full_rsa(br_ssl_server_context *cc,
3106 const br_x509_certificate *chain, size_t chain_len,
3107 const br_rsa_private_key *sk);
3108
3109 /**
3110 * \brief SSL server profile: full_ec.
3111 *
3112 * This function initialises the provided SSL server context with
3113 * all supported algorithms and cipher suites that rely on an EC
3114 * key pair.
3115 *
3116 * The key type of the CA that issued the server's certificate must
3117 * be provided, since it matters for ECDH cipher suites (ECDH_RSA
3118 * suites require a RSA-powered CA). The key type is either
3119 * `BR_KEYTYPE_RSA` or `BR_KEYTYPE_EC`.
3120 *
3121 * \param cc server context to initialise.
3122 * \param chain server certificate chain.
3123 * \param chain_len chain length (number of certificates).
3124 * \param cert_issuer_key_type certificate issuer's key type.
3125 * \param sk EC private key.
3126 */
3127 void br_ssl_server_init_full_ec(br_ssl_server_context *cc,
3128 const br_x509_certificate *chain, size_t chain_len,
3129 unsigned cert_issuer_key_type, const br_ec_private_key *sk);
3130
3131 /**
3132 * \brief SSL server profile: minr2g.
3133 *
3134 * This profile uses only TLS_RSA_WITH_AES_128_GCM_SHA256. Server key is
3135 * RSA, and RSA key exchange is used (not forward secure, but uses little
3136 * CPU in the client).
3137 *
3138 * \param cc server context to initialise.
3139 * \param chain server certificate chain.
3140 * \param chain_len certificate chain length (number of certificate).
3141 * \param sk RSA private key.
3142 */
3143 void br_ssl_server_init_minr2g(br_ssl_server_context *cc,
3144 const br_x509_certificate *chain, size_t chain_len,
3145 const br_rsa_private_key *sk);
3146
3147 /**
3148 * \brief SSL server profile: mine2g.
3149 *
3150 * This profile uses only TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256. Server key
3151 * is RSA, and ECDHE key exchange is used. This suite provides forward
3152 * security, with a higher CPU expense on the client, and a somewhat
3153 * larger code footprint (compared to "minr2g").
3154 *
3155 * \param cc server context to initialise.
3156 * \param chain server certificate chain.
3157 * \param chain_len certificate chain length (number of certificate).
3158 * \param sk RSA private key.
3159 */
3160 void br_ssl_server_init_mine2g(br_ssl_server_context *cc,
3161 const br_x509_certificate *chain, size_t chain_len,
3162 const br_rsa_private_key *sk);
3163
3164 /**
3165 * \brief SSL server profile: minf2g.
3166 *
3167 * This profile uses only TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256.
3168 * Server key is EC, and ECDHE key exchange is used. This suite provides
3169 * forward security, with a higher CPU expense on the client and server
3170 * (by a factor of about 3 to 4), and a somewhat larger code footprint
3171 * (compared to "minu2g" and "minv2g").
3172 *
3173 * \param cc server context to initialise.
3174 * \param chain server certificate chain.
3175 * \param chain_len certificate chain length (number of certificate).
3176 * \param sk EC private key.
3177 */
3178 void br_ssl_server_init_minf2g(br_ssl_server_context *cc,
3179 const br_x509_certificate *chain, size_t chain_len,
3180 const br_ec_private_key *sk);
3181
3182 /**
3183 * \brief SSL server profile: minu2g.
3184 *
3185 * This profile uses only TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256.
3186 * Server key is EC, and ECDH key exchange is used; the issuing CA used
3187 * a RSA key.
3188 *
3189 * The "minu2g" and "minv2g" profiles do not provide forward secrecy,
3190 * but are the lightest on the server (for CPU usage), and are rather
3191 * inexpensive on the client as well.
3192 *
3193 * \param cc server context to initialise.
3194 * \param chain server certificate chain.
3195 * \param chain_len certificate chain length (number of certificate).
3196 * \param sk EC private key.
3197 */
3198 void br_ssl_server_init_minu2g(br_ssl_server_context *cc,
3199 const br_x509_certificate *chain, size_t chain_len,
3200 const br_ec_private_key *sk);
3201
3202 /**
3203 * \brief SSL server profile: minv2g.
3204 *
3205 * This profile uses only TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256.
3206 * Server key is EC, and ECDH key exchange is used; the issuing CA used
3207 * an EC key.
3208 *
3209 * The "minu2g" and "minv2g" profiles do not provide forward secrecy,
3210 * but are the lightest on the server (for CPU usage), and are rather
3211 * inexpensive on the client as well.
3212 *
3213 * \param cc server context to initialise.
3214 * \param chain server certificate chain.
3215 * \param chain_len certificate chain length (number of certificate).
3216 * \param sk EC private key.
3217 */
3218 void br_ssl_server_init_minv2g(br_ssl_server_context *cc,
3219 const br_x509_certificate *chain, size_t chain_len,
3220 const br_ec_private_key *sk);
3221
3222 /**
3223 * \brief SSL server profile: mine2c.
3224 *
3225 * This profile uses only TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256.
3226 * Server key is RSA, and ECDHE key exchange is used. This suite
3227 * provides forward security.
3228 *
3229 * \param cc server context to initialise.
3230 * \param chain server certificate chain.
3231 * \param chain_len certificate chain length (number of certificate).
3232 * \param sk RSA private key.
3233 */
3234 void br_ssl_server_init_mine2c(br_ssl_server_context *cc,
3235 const br_x509_certificate *chain, size_t chain_len,
3236 const br_rsa_private_key *sk);
3237
3238 /**
3239 * \brief SSL server profile: minf2c.
3240 *
3241 * This profile uses only TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256.
3242 * Server key is EC, and ECDHE key exchange is used. This suite provides
3243 * forward security.
3244 *
3245 * \param cc server context to initialise.
3246 * \param chain server certificate chain.
3247 * \param chain_len certificate chain length (number of certificate).
3248 * \param sk EC private key.
3249 */
3250 void br_ssl_server_init_minf2c(br_ssl_server_context *cc,
3251 const br_x509_certificate *chain, size_t chain_len,
3252 const br_ec_private_key *sk);
3253
3254 /**
3255 * \brief Get the supported client suites.
3256 *
3257 * This function shall be called only after the ClientHello has been
3258 * processed, typically from the policy engine. The returned array
3259 * contains the cipher suites that are supported by both the client
3260 * and the server; these suites are in client preference order, unless
3261 * the `BR_OPT_ENFORCE_SERVER_PREFERENCES` flag was set, in which case
3262 * they are in server preference order.
3263 *
3264 * The suites are _translated_, which means that each suite is given
3265 * as two 16-bit integers: the standard suite identifier, and its
3266 * translated version, broken down into its individual components,
3267 * as explained with the `br_suite_translated` type.
3268 *
3269 * The returned array is allocated in the context and will be rewritten
3270 * by each handshake.
3271 *
3272 * \param cc server context.
3273 * \param num receives the array size (number of suites).
3274 * \return the translated common cipher suites, in preference order.
3275 */
3276 static inline const br_suite_translated *
3277 br_ssl_server_get_client_suites(const br_ssl_server_context *cc, size_t *num)
3278 {
3279 *num = cc->client_suites_num;
3280 return cc->client_suites;
3281 }
3282
3283 /**
3284 * \brief Get the hash functions supported by the client.
3285 *
3286 * This is a field of bits: for hash function of ID x, bit x is set if
3287 * the hash function is supported in RSA signatures, 8+x if it is supported
3288 * with ECDSA.
3289 *
3290 * \param cc server context.
3291 * \return the client-supported hash functions (for signatures).
3292 */
3293 static inline uint16_t
3294 br_ssl_server_get_client_hashes(const br_ssl_server_context *cc)
3295 {
3296 return cc->hashes;
3297 }
3298
3299 /**
3300 * \brief Get the elliptic curves supported by the client.
3301 *
3302 * This is a bit field (bit x is set if curve of ID x is supported).
3303 *
3304 * \param cc server context.
3305 * \return the client-supported elliptic curves.
3306 */
3307 static inline uint32_t
3308 br_ssl_server_get_client_curves(const br_ssl_server_context *cc)
3309 {
3310 return cc->curves;
3311 }
3312
3313 /**
3314 * \brief Clear the complete contents of a SSL server context.
3315 *
3316 * Everything is cleared, including the reference to the configured buffer,
3317 * implementations, cipher suites and state. This is a preparatory step
3318 * to assembling a custom profile.
3319 *
3320 * \param cc server context to clear.
3321 */
3322 void br_ssl_server_zero(br_ssl_server_context *cc);
3323
3324 /**
3325 * \brief Set an externally provided policy context.
3326 *
3327 * The policy context's methods are invoked to decide the cipher suite
3328 * and certificate chain, and to perform operations involving the server's
3329 * private key.
3330 *
3331 * \param cc server context.
3332 * \param pctx policy context (pointer to its vtable field).
3333 */
3334 static inline void
3335 br_ssl_server_set_policy(br_ssl_server_context *cc,
3336 const br_ssl_server_policy_class **pctx)
3337 {
3338 cc->policy_vtable = pctx;
3339 }
3340
3341 /**
3342 * \brief Set the server certificate chain and key (single RSA case).
3343 *
3344 * This function uses a policy context included in the server context.
3345 * It configures use of a single server certificate chain with a RSA
3346 * private key. The `allowed_usages` is a combination of usages, namely
3347 * `BR_KEYTYPE_KEYX` and/or `BR_KEYTYPE_SIGN`; this enables or disables
3348 * the corresponding cipher suites (i.e. `TLS_RSA_*` use the RSA key for
3349 * key exchange, while `TLS_ECDHE_RSA_*` use the RSA key for signatures).
3350 *
3351 * \param cc server context.
3352 * \param chain server certificate chain to send to the client.
3353 * \param chain_len chain length (number of certificates).
3354 * \param sk server private key (RSA).
3355 * \param allowed_usages allowed private key usages.
3356 * \param irsacore RSA core implementation.
3357 * \param irsasign RSA signature implementation (PKCS#1 v1.5).
3358 */
3359 void br_ssl_server_set_single_rsa(br_ssl_server_context *cc,
3360 const br_x509_certificate *chain, size_t chain_len,
3361 const br_rsa_private_key *sk, unsigned allowed_usages,
3362 br_rsa_private irsacore, br_rsa_pkcs1_sign irsasign);
3363
3364 /**
3365 * \brief Set the server certificate chain and key (single EC case).
3366 *
3367 * This function uses a policy context included in the server context.
3368 * It configures use of a single server certificate chain with an EC
3369 * private key. The `allowed_usages` is a combination of usages, namely
3370 * `BR_KEYTYPE_KEYX` and/or `BR_KEYTYPE_SIGN`; this enables or disables
3371 * the corresponding cipher suites (i.e. `TLS_ECDH_*` use the EC key for
3372 * key exchange, while `TLS_ECDHE_ECDSA_*` use the EC key for signatures).
3373 *
3374 * In order to support `TLS_ECDH_*` cipher suites (non-ephemeral ECDH),
3375 * the algorithm type of the key used by the issuing CA to sign the
3376 * server's certificate must be provided, as `cert_issuer_key_type`
3377 * parameter (this value is either `BR_KEYTYPE_RSA` or `BR_KEYTYPE_EC`).
3378 *
3379 * \param cc server context.
3380 * \param chain server certificate chain to send.
3381 * \param chain_len chain length (number of certificates).
3382 * \param sk server private key (EC).
3383 * \param allowed_usages allowed private key usages.
3384 * \param cert_issuer_key_type issuing CA's key type.
3385 * \param iec EC core implementation.
3386 * \param iecdsa ECDSA signature implementation ("asn1" format).
3387 */
3388 void br_ssl_server_set_single_ec(br_ssl_server_context *cc,
3389 const br_x509_certificate *chain, size_t chain_len,
3390 const br_ec_private_key *sk, unsigned allowed_usages,
3391 unsigned cert_issuer_key_type,
3392 const br_ec_impl *iec, br_ecdsa_sign iecdsa);
3393
3394 /**
3395 * \brief Activate client certificate authentication.
3396 *
3397 * The trust anchor encoded X.500 names (DN) to send to the client are
3398 * provided. A client certificate will be requested and validated through
3399 * the X.509 validator configured in the SSL engine. If `num` is 0, then
3400 * client certificate authentication is disabled.
3401 *
3402 * If the client does not send a certificate, or on validation failure,
3403 * the handshake aborts. Unauthenticated clients can be tolerated by
3404 * setting the `BR_OPT_TOLERATE_NO_CLIENT_AUTH` flag.
3405 *
3406 * The provided array is linked in, not copied, so that pointer must
3407 * remain valid as long as anchor names may be used.
3408 *
3409 * \param cc server context.
3410 * \param ta_names encoded trust anchor names.
3411 * \param num number of encoded trust anchor names.
3412 */
3413 static inline void
3414 br_ssl_server_set_trust_anchor_names(br_ssl_server_context *cc,
3415 const br_x500_name *ta_names, size_t num)
3416 {
3417 cc->ta_names = ta_names;
3418 cc->tas = NULL;
3419 cc->num_tas = num;
3420 }
3421
3422 /**
3423 * \brief Activate client certificate authentication.
3424 *
3425 * This is a variant for `br_ssl_server_set_trust_anchor_names()`: the
3426 * trust anchor names are provided not as an array of stand-alone names
3427 * (`br_x500_name` structures), but as an array of trust anchors
3428 * (`br_x509_trust_anchor` structures). The server engine itself will
3429 * only use the `dn` field of each trust anchor. This is meant to allow
3430 * defining a single array of trust anchors, to be used here and in the
3431 * X.509 validation engine itself.
3432 *
3433 * The provided array is linked in, not copied, so that pointer must
3434 * remain valid as long as anchor names may be used.
3435 *
3436 * \param cc server context.
3437 * \param tas trust anchors (only names are used).
3438 * \param num number of trust anchors.
3439 */
3440 static inline void
3441 br_ssl_server_set_trust_anchor_names_alt(br_ssl_server_context *cc,
3442 const br_x509_trust_anchor *tas, size_t num)
3443 {
3444 cc->ta_names = NULL;
3445 cc->tas = tas;
3446 cc->num_tas = num;
3447 }
3448
3449 /**
3450 * \brief Configure the cache for session parameters.
3451 *
3452 * The cache context is provided as a pointer to its first field (vtable
3453 * pointer).
3454 *
3455 * \param cc server context.
3456 * \param vtable session cache context.
3457 */
3458 static inline void
3459 br_ssl_server_set_cache(br_ssl_server_context *cc,
3460 const br_ssl_session_cache_class **vtable)
3461 {
3462 cc->cache_vtable = vtable;
3463 }
3464
3465 /**
3466 * \brief Prepare or reset a server context for handling an incoming client.
3467 *
3468 * \param cc server context.
3469 * \return 1 on success, 0 on error.
3470 */
3471 int br_ssl_server_reset(br_ssl_server_context *cc);
3472
3473 /* ===================================================================== */
3474
3475 /*
3476 * Context for the simplified I/O context. The transport medium is accessed
3477 * through the low_read() and low_write() callback functions, each with
3478 * its own opaque context pointer.
3479 *
3480 * low_read() read some bytes, at most 'len' bytes, into data[]. The
3481 * returned value is the number of read bytes, or -1 on error.
3482 * The 'len' parameter is guaranteed never to exceed 20000,
3483 * so the length always fits in an 'int' on all platforms.
3484 *
3485 * low_write() write up to 'len' bytes, to be read from data[]. The
3486 * returned value is the number of written bytes, or -1 on
3487 * error. The 'len' parameter is guaranteed never to exceed
3488 * 20000, so the length always fits in an 'int' on all
3489 * parameters.
3490 *
3491 * A socket closure (if the transport medium is a socket) should be reported
3492 * as an error (-1). The callbacks shall endeavour to block until at least
3493 * one byte can be read or written; a callback returning 0 at times is
3494 * acceptable, but this normally leads to the callback being immediately
3495 * called again, so the callback should at least always try to block for
3496 * some time if no I/O can take place.
3497 *
3498 * The SSL engine naturally applies some buffering, so the callbacks need
3499 * not apply buffers of their own.
3500 */
3501 /**
3502 * \brief Context structure for the simplified SSL I/O wrapper.
3503 *
3504 * This structure is initialised with `br_sslio_init()`. Its contents
3505 * are opaque and shall not be accessed directly.
3506 */
3507 typedef struct {
3508 #ifndef BR_DOXYGEN_IGNORE
3509 br_ssl_engine_context *engine;
3510 int (*low_read)(void *read_context,
3511 unsigned char *data, size_t len);
3512 void *read_context;
3513 int (*low_write)(void *write_context,
3514 const unsigned char *data, size_t len);
3515 void *write_context;
3516 #endif
3517 } br_sslio_context;
3518
3519 /**
3520 * \brief Initialise a simplified I/O wrapper context.
3521 *
3522 * The simplified I/O wrapper offers a simpler read/write API for a SSL
3523 * engine (client or server), using the provided callback functions for
3524 * reading data from, or writing data to, the transport medium.
3525 *
3526 * The callback functions have the following semantics:
3527 *
3528 * - Each callback receives an opaque context value (of type `void *`)
3529 * that the callback may use arbitrarily (or possibly ignore).
3530 *
3531 * - `low_read()` reads at least one byte, at most `len` bytes, from
3532 * the transport medium. Read bytes shall be written in `data`.
3533 *
3534 * - `low_write()` writes at least one byte, at most `len` bytes, unto
3535 * the transport medium. The bytes to write are read from `data`.
3536 *
3537 * - The `len` parameter is never zero, and is always lower than 20000.
3538 *
3539 * - The number of processed bytes (read or written) is returned. Since
3540 * that number is less than 20000, it always fits on an `int`.
3541 *
3542 * - On error, the callbacks return -1. Reaching end-of-stream is an
3543 * error. Errors are permanent: the SSL connection is terminated.
3544 *
3545 * - Callbacks SHOULD NOT return 0. This is tolerated, as long as
3546 * callbacks endeavour to block for some non-negligible amount of
3547 * time until at least one byte can be sent or received (if a
3548 * callback returns 0, then the wrapper invokes it again
3549 * immediately).
3550 *
3551 * - Callbacks MAY return as soon as at least one byte is processed;
3552 * they MAY also insist on reading or writing _all_ requested bytes.
3553 * Since SSL is a self-terminated protocol (each record has a length
3554 * header), this does not change semantics.
3555 *
3556 * - Callbacks need not apply any buffering (for performance) since SSL
3557 * itself uses buffers.
3558 *
3559 * \param ctx wrapper context to initialise.
3560 * \param engine SSL engine to wrap.
3561 * \param low_read callback for reading data from the transport.
3562 * \param read_context context pointer for `low_read()`.
3563 * \param low_write callback for writing data on the transport.
3564 * \param write_context context pointer for `low_write()`.
3565 */
3566 void br_sslio_init(br_sslio_context *ctx,
3567 br_ssl_engine_context *engine,
3568 int (*low_read)(void *read_context,
3569 unsigned char *data, size_t len),
3570 void *read_context,
3571 int (*low_write)(void *write_context,
3572 const unsigned char *data, size_t len),
3573 void *write_context);
3574
3575 /**
3576 * \brief Read some application data from a SSL connection.
3577 *
3578 * If `len` is zero, then this function returns 0 immediately. In
3579 * all other cases, it never returns 0.
3580 *
3581 * This call returns only when at least one byte has been obtained.
3582 * Returned value is the number of bytes read, or -1 on error. The
3583 * number of bytes always fits on an 'int' (data from a single SSL/TLS
3584 * record is returned).
3585 *
3586 * On error or SSL closure, this function returns -1. The caller should
3587 * inspect the error status on the SSL engine to distinguish between
3588 * normal closure and error.
3589 *
3590 * \param cc SSL wrapper context.
3591 * \param dst destination buffer for application data.
3592 * \param len maximum number of bytes to obtain.
3593 * \return number of bytes obtained, or -1 on error.
3594 */
3595 int br_sslio_read(br_sslio_context *cc, void *dst, size_t len);
3596
3597 /**
3598 * \brief Read application data from a SSL connection.
3599 *
3600 * This calls returns only when _all_ requested `len` bytes are read,
3601 * or an error is reached. Returned value is 0 on success, -1 on error.
3602 * A normal (verified) SSL closure before that many bytes are obtained
3603 * is reported as an error by this function.
3604 *
3605 * \param cc SSL wrapper context.
3606 * \param dst destination buffer for application data.
3607 * \param len number of bytes to obtain.
3608 * \return 0 on success, or -1 on error.
3609 */
3610 int br_sslio_read_all(br_sslio_context *cc, void *dst, size_t len);
3611
3612 /**
3613 * \brief Write some application data unto a SSL connection.
3614 *
3615 * If `len` is zero, then this function returns 0 immediately. In
3616 * all other cases, it never returns 0.
3617 *
3618 * This call returns only when at least one byte has been written.
3619 * Returned value is the number of bytes written, or -1 on error. The
3620 * number of bytes always fits on an 'int' (less than 20000).
3621 *
3622 * On error or SSL closure, this function returns -1. The caller should
3623 * inspect the error status on the SSL engine to distinguish between
3624 * normal closure and error.
3625 *
3626 * **Important:** SSL is buffered; a "written" byte is a byte that was
3627 * injected into the wrapped SSL engine, but this does not necessarily mean
3628 * that it has been scheduled for sending. Use `br_sslio_flush()` to
3629 * ensure that all pending data has been sent to the transport medium.
3630 *
3631 * \param cc SSL wrapper context.
3632 * \param src source buffer for application data.
3633 * \param len maximum number of bytes to write.
3634 * \return number of bytes written, or -1 on error.
3635 */
3636 int br_sslio_write(br_sslio_context *cc, const void *src, size_t len);
3637
3638 /**
3639 * \brief Write application data unto a SSL connection.
3640 *
3641 * This calls returns only when _all_ requested `len` bytes have been
3642 * written, or an error is reached. Returned value is 0 on success, -1
3643 * on error. A normal (verified) SSL closure before that many bytes are
3644 * written is reported as an error by this function.
3645 *
3646 * **Important:** SSL is buffered; a "written" byte is a byte that was
3647 * injected into the wrapped SSL engine, but this does not necessarily mean
3648 * that it has been scheduled for sending. Use `br_sslio_flush()` to
3649 * ensure that all pending data has been sent to the transport medium.
3650 *
3651 * \param cc SSL wrapper context.
3652 * \param src source buffer for application data.
3653 * \param len number of bytes to write.
3654 * \return 0 on success, or -1 on error.
3655 */
3656 int br_sslio_write_all(br_sslio_context *cc, const void *src, size_t len);
3657
3658 /**
3659 * \brief Flush pending data.
3660 *
3661 * This call makes sure that any buffered application data in the
3662 * provided context (including the wrapped SSL engine) has been sent
3663 * to the transport medium (i.e. accepted by the `low_write()` callback
3664 * method). If there is no such pending data, then this function does
3665 * nothing (and returns a success, i.e. 0).
3666 *
3667 * If the underlying transport medium has its own buffers, then it is
3668 * up to the caller to ensure the corresponding flushing.
3669 *
3670 * Returned value is 0 on success, -1 on error.
3671 *
3672 * \param cc SSL wrapper context.
3673 * \return 0 on success, or -1 on error.
3674 */
3675 int br_sslio_flush(br_sslio_context *cc);
3676
3677 /**
3678 * \brief Close the SSL connection.
3679 *
3680 * This call runs the SSL closure protocol (sending a `close_notify`,
3681 * receiving the response `close_notify`). When it returns, the SSL
3682 * connection is finished. It is still up to the caller to manage the
3683 * possible transport-level termination, if applicable (alternatively,
3684 * the underlying transport stream may be reused for non-SSL messages).
3685 *
3686 * Returned value is 0 on success, -1 on error. A failure by the peer
3687 * to process the complete closure protocol (i.e. sending back the
3688 * `close_notify`) is an error.
3689 *
3690 * \param cc SSL wrapper context.
3691 * \return 0 on success, or -1 on error.
3692 */
3693 int br_sslio_close(br_sslio_context *cc);
3694
3695 /* ===================================================================== */
3696
3697 /*
3698 * Symbolic constants for cipher suites.
3699 */
3700
3701 /* From RFC 5246 */
3702 #define BR_TLS_NULL_WITH_NULL_NULL 0x0000
3703 #define BR_TLS_RSA_WITH_NULL_MD5 0x0001
3704 #define BR_TLS_RSA_WITH_NULL_SHA 0x0002
3705 #define BR_TLS_RSA_WITH_NULL_SHA256 0x003B
3706 #define BR_TLS_RSA_WITH_RC4_128_MD5 0x0004
3707 #define BR_TLS_RSA_WITH_RC4_128_SHA 0x0005
3708 #define BR_TLS_RSA_WITH_3DES_EDE_CBC_SHA 0x000A
3709 #define BR_TLS_RSA_WITH_AES_128_CBC_SHA 0x002F
3710 #define BR_TLS_RSA_WITH_AES_256_CBC_SHA 0x0035
3711 #define BR_TLS_RSA_WITH_AES_128_CBC_SHA256 0x003C
3712 #define BR_TLS_RSA_WITH_AES_256_CBC_SHA256 0x003D
3713 #define BR_TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA 0x000D
3714 #define BR_TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA 0x0010
3715 #define BR_TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA 0x0013
3716 #define BR_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA 0x0016
3717 #define BR_TLS_DH_DSS_WITH_AES_128_CBC_SHA 0x0030
3718 #define BR_TLS_DH_RSA_WITH_AES_128_CBC_SHA 0x0031