Added API for external hashing of ServerKeyExchange, and signature algorithm identifi...
[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 uint32_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 value is a bit field:
2325 *
2326 * - If RSA (PKCS#1 v1.5) is supported with hash function of ID `x`,
2327 * then bit `x` is set (hash function ID is 0 for the special MD5+SHA-1,
2328 * or 2 to 6 for the SHA family).
2329 *
2330 * - If ECDSA is suported with hash function of ID `x`, then bit `8+x`
2331 * is set.
2332 *
2333 * - Newer algorithms are symbolic 16-bit identifiers that do not
2334 * represent signature algorithm and hash function separately. If
2335 * the TLS-level identifier is `0x0800+x` for a `x` in the 0..15
2336 * range, then bit `16+x` is set.
2337 *
2338 * "New algorithms" are currently defined only in draft documents, so
2339 * this support is subject to possible change. Right now (early 2017),
2340 * this maps ed25519 (EdDSA on Curve25519) to bit 23, and ed448 (EdDSA
2341 * on Curve448) to bit 24. If the identifiers on the wire change in
2342 * future document, then the decoding mechanism in BearSSL will be
2343 * amended to keep mapping ed25519 and ed448 on bits 23 and 24,
2344 * respectively. Mapping of other new algorithms (e.g. RSA/PSS) is not
2345 * guaranteed yet.
2346 *
2347 * \param cc client context.
2348 * \return the server-supported hash functions and signature algorithms.
2349 */
2350 static inline uint32_t
2351 br_ssl_client_get_server_hashes(const br_ssl_client_context *cc)
2352 {
2353 return cc->hashes;
2354 }
2355
2356 /**
2357 * \brief Get the server key curve.
2358 *
2359 * This function returns the ID for the curve used by the server's public
2360 * key. This is set when the server's certificate chain is processed;
2361 * this value is 0 if the server's key is not an EC key.
2362 *
2363 * \return the server's public key curve ID, or 0.
2364 */
2365 static inline int
2366 br_ssl_client_get_server_curve(const br_ssl_client_context *cc)
2367 {
2368 return cc->server_curve;
2369 }
2370
2371 /*
2372 * Each br_ssl_client_init_xxx() function sets the list of supported
2373 * cipher suites and used implementations, as specified by the profile
2374 * name 'xxx'. Defined profile names are:
2375 *
2376 * full all supported versions and suites; constant-time implementations
2377 * TODO: add other profiles
2378 */
2379
2380 /**
2381 * \brief SSL client profile: full.
2382 *
2383 * This function initialises the provided SSL client context with
2384 * all supported algorithms and cipher suites. It also initialises
2385 * a companion X.509 validation engine with all supported algorithms,
2386 * and the provided trust anchors; the X.509 engine will be used by
2387 * the client context to validate the server's certificate.
2388 *
2389 * \param cc client context to initialise.
2390 * \param xc X.509 validation context to initialise.
2391 * \param trust_anchors trust anchors to use.
2392 * \param trust_anchors_num number of trust anchors.
2393 */
2394 void br_ssl_client_init_full(br_ssl_client_context *cc,
2395 br_x509_minimal_context *xc,
2396 const br_x509_trust_anchor *trust_anchors, size_t trust_anchors_num);
2397
2398 /**
2399 * \brief Clear the complete contents of a SSL client context.
2400 *
2401 * Everything is cleared, including the reference to the configured buffer,
2402 * implementations, cipher suites and state. This is a preparatory step
2403 * to assembling a custom profile.
2404 *
2405 * \param cc client context to clear.
2406 */
2407 void br_ssl_client_zero(br_ssl_client_context *cc);
2408
2409 /**
2410 * \brief Set an externally provided client certificate handler context.
2411 *
2412 * The handler's methods are invoked when the server requests a client
2413 * certificate.
2414 *
2415 * \param cc client context.
2416 * \param pctx certificate handler context (pointer to its vtable field).
2417 */
2418 static inline void
2419 br_ssl_client_set_client_certificate(br_ssl_client_context *cc,
2420 const br_ssl_client_certificate_class **pctx)
2421 {
2422 cc->client_auth_vtable = pctx;
2423 }
2424
2425 /**
2426 * \brief Set the RSA public-key operations implementation.
2427 *
2428 * This will be used to encrypt the pre-master secret with the server's
2429 * RSA public key (RSA-encryption cipher suites only).
2430 *
2431 * \param cc client context.
2432 * \param irsapub RSA public-key encryption implementation.
2433 */
2434 static inline void
2435 br_ssl_client_set_rsapub(br_ssl_client_context *cc, br_rsa_public irsapub)
2436 {
2437 cc->irsapub = irsapub;
2438 }
2439
2440 /**
2441 * \brief Set the minimum ClientHello length (RFC 7685 padding).
2442 *
2443 * If this value is set and the ClientHello would be shorter, then
2444 * the Pad ClientHello extension will be added with enough padding bytes
2445 * to reach the target size. Because of the extension header, the resulting
2446 * size will sometimes be slightly more than `len` bytes if the target
2447 * size cannot be exactly met.
2448 *
2449 * The target length relates to the _contents_ of the ClientHello, not
2450 * counting its 4-byte header. For instance, if `len` is set to 512,
2451 * then the padding will bring the ClientHello size to 516 bytes with its
2452 * header, and 521 bytes when counting the 5-byte record header.
2453 *
2454 * \param cc client context.
2455 * \param len minimum ClientHello length (in bytes).
2456 */
2457 static inline void
2458 br_ssl_client_set_min_clienthello_len(br_ssl_client_context *cc, uint16_t len)
2459 {
2460 cc->min_clienthello_len = len;
2461 }
2462
2463 /**
2464 * \brief Prepare or reset a client context for a new connection.
2465 *
2466 * The `server_name` parameter is used to fill the SNI extension; the
2467 * X.509 "minimal" engine will also match that name against the server
2468 * names included in the server's certificate. If the parameter is
2469 * `NULL` then no SNI extension will be sent, and the X.509 "minimal"
2470 * engine (if used for server certificate validation) will not check
2471 * presence of any specific name in the received certificate.
2472 *
2473 * Therefore, setting the `server_name` to `NULL` shall be reserved
2474 * to cases where alternate or additional methods are used to ascertain
2475 * that the right server public key is used (e.g. a "known key" model).
2476 *
2477 * If `resume_session` is non-zero and the context was previously used
2478 * then the session parameters may be reused (depending on whether the
2479 * server previously sent a non-empty session ID, and accepts the session
2480 * resumption). The session parameters for session resumption can also
2481 * be set explicitly with `br_ssl_engine_set_session_parameters()`.
2482 *
2483 * On failure, the context is marked as failed, and this function
2484 * returns 0. A possible failure condition is when no initial entropy
2485 * was injected, and none could be obtained from the OS (either OS
2486 * randomness gathering is not supported, or it failed).
2487 *
2488 * \param cc client context.
2489 * \param server_name target server name, or `NULL`.
2490 * \param resume_session non-zero to try session resumption.
2491 * \return 0 on failure, 1 on success.
2492 */
2493 int br_ssl_client_reset(br_ssl_client_context *cc,
2494 const char *server_name, int resume_session);
2495
2496 /**
2497 * \brief Forget any session in the context.
2498 *
2499 * This means that the next handshake that uses this context will
2500 * necessarily be a full handshake (this applies both to new connections
2501 * and to renegotiations).
2502 *
2503 * \param cc client context.
2504 */
2505 static inline void
2506 br_ssl_client_forget_session(br_ssl_client_context *cc)
2507 {
2508 cc->eng.session.session_id_len = 0;
2509 }
2510
2511 /**
2512 * \brief Set client certificate chain and key (single RSA case).
2513 *
2514 * This function sets a client certificate chain, that the client will
2515 * send to the server whenever a client certificate is requested. This
2516 * certificate uses an RSA public key; the corresponding private key is
2517 * invoked for authentication. Trust anchor names sent by the server are
2518 * ignored.
2519 *
2520 * The provided chain and private key are linked in the client context;
2521 * they must remain valid as long as they may be used, i.e. normally
2522 * for the duration of the connection, since they might be invoked
2523 * again upon renegotiations.
2524 *
2525 * \param cc SSL client context.
2526 * \param chain client certificate chain (SSL order: EE comes first).
2527 * \param chain_len client chain length (number of certificates).
2528 * \param sk client private key.
2529 * \param irsasign RSA signature implementation (PKCS#1 v1.5).
2530 */
2531 void br_ssl_client_set_single_rsa(br_ssl_client_context *cc,
2532 const br_x509_certificate *chain, size_t chain_len,
2533 const br_rsa_private_key *sk, br_rsa_pkcs1_sign irsasign);
2534
2535 /*
2536 * \brief Set the client certificate chain and key (single EC case).
2537 *
2538 * This function sets a client certificate chain, that the client will
2539 * send to the server whenever a client certificate is requested. This
2540 * certificate uses an EC public key; the corresponding private key is
2541 * invoked for authentication. Trust anchor names sent by the server are
2542 * ignored.
2543 *
2544 * The provided chain and private key are linked in the client context;
2545 * they must remain valid as long as they may be used, i.e. normally
2546 * for the duration of the connection, since they might be invoked
2547 * again upon renegotiations.
2548 *
2549 * The `allowed_usages` is a combination of usages, namely
2550 * `BR_KEYTYPE_KEYX` and/or `BR_KEYTYPE_SIGN`. The `BR_KEYTYPE_KEYX`
2551 * value allows full static ECDH, while the `BR_KEYTYPE_SIGN` value
2552 * allows ECDSA signatures. If ECDSA signatures are used, then an ECDSA
2553 * signature implementation must be provided; otherwise, the `iecdsa`
2554 * parameter may be 0.
2555 *
2556 * The `cert_issuer_key_type` value is either `BR_KEYTYPE_RSA` or
2557 * `BR_KEYTYPE_EC`; it is the type of the public key used the the CA
2558 * that issued (signed) the client certificate. That value is used with
2559 * full static ECDH: support of the certificate by the server depends
2560 * on how the certificate was signed. (Note: when using TLS 1.2, this
2561 * parameter is ignored; but its value matters for TLS 1.0 and 1.1.)
2562 *
2563 * \param cc server context.
2564 * \param chain server certificate chain to send.
2565 * \param chain_len chain length (number of certificates).
2566 * \param sk server private key (EC).
2567 * \param allowed_usages allowed private key usages.
2568 * \param cert_issuer_key_type issuing CA's key type.
2569 * \param iec EC core implementation.
2570 * \param iecdsa ECDSA signature implementation ("asn1" format).
2571 */
2572 void br_ssl_client_set_single_ec(br_ssl_client_context *cc,
2573 const br_x509_certificate *chain, size_t chain_len,
2574 const br_ec_private_key *sk, unsigned allowed_usages,
2575 unsigned cert_issuer_key_type,
2576 const br_ec_impl *iec, br_ecdsa_sign iecdsa);
2577
2578 /**
2579 * \brief Type for a "translated cipher suite", as an array of two
2580 * 16-bit integers.
2581 *
2582 * The first element is the cipher suite identifier (as used on the wire).
2583 * The second element is the concatenation of four 4-bit elements which
2584 * characterise the cipher suite contents. In most to least significant
2585 * order, these 4-bit elements are:
2586 *
2587 * - Bits 12 to 15: key exchange + server key type
2588 *
2589 * | val | symbolic constant | suite type | details |
2590 * | :-- | :----------------------- | :---------- | :----------------------------------------------- |
2591 * | 0 | `BR_SSLKEYX_RSA` | RSA | RSA key exchange, key is RSA (encryption) |
2592 * | 1 | `BR_SSLKEYX_ECDHE_RSA` | ECDHE_RSA | ECDHE key exchange, key is RSA (signature) |
2593 * | 2 | `BR_SSLKEYX_ECDHE_ECDSA` | ECDHE_ECDSA | ECDHE key exchange, key is EC (signature) |
2594 * | 3 | `BR_SSLKEYX_ECDH_RSA` | ECDH_RSA | Key is EC (key exchange), cert signed with RSA |
2595 * | 4 | `BR_SSLKEYX_ECDH_ECDSA` | ECDH_ECDSA | Key is EC (key exchange), cert signed with ECDSA |
2596 *
2597 * - Bits 8 to 11: symmetric encryption algorithm
2598 *
2599 * | val | symbolic constant | symmetric encryption | key strength (bits) |
2600 * | :-- | :--------------------- | :------------------- | :------------------ |
2601 * | 0 | `BR_SSLENC_3DES_CBC` | 3DES/CBC | 168 |
2602 * | 1 | `BR_SSLENC_AES128_CBC` | AES-128/CBC | 128 |
2603 * | 2 | `BR_SSLENC_AES256_CBC` | AES-256/CBC | 256 |
2604 * | 3 | `BR_SSLENC_AES128_GCM` | AES-128/GCM | 128 |
2605 * | 4 | `BR_SSLENC_AES256_GCM` | AES-256/GCM | 256 |
2606 * | 5 | `BR_SSLENC_CHACHA20` | ChaCha20/Poly1305 | 256 |
2607 *
2608 * - Bits 4 to 7: MAC algorithm
2609 *
2610 * | val | symbolic constant | MAC type | details |
2611 * | :-- | :----------------- | :----------- | :------------------------------------ |
2612 * | 0 | `BR_SSLMAC_AEAD` | AEAD | No dedicated MAC (encryption is AEAD) |
2613 * | 2 | `BR_SSLMAC_SHA1` | HMAC/SHA-1 | Value matches `br_sha1_ID` |
2614 * | 4 | `BR_SSLMAC_SHA256` | HMAC/SHA-256 | Value matches `br_sha256_ID` |
2615 * | 5 | `BR_SSLMAC_SHA384` | HMAC/SHA-384 | Value matches `br_sha384_ID` |
2616 *
2617 * - Bits 0 to 3: hash function for PRF when used with TLS-1.2
2618 *
2619 * | val | symbolic constant | hash function | details |
2620 * | :-- | :----------------- | :------------ | :----------------------------------- |
2621 * | 4 | `BR_SSLPRF_SHA256` | SHA-256 | Value matches `br_sha256_ID` |
2622 * | 5 | `BR_SSLPRF_SHA384` | SHA-384 | Value matches `br_sha384_ID` |
2623 *
2624 * For instance, cipher suite `TLS_RSA_WITH_AES_128_GCM_SHA256` has
2625 * standard identifier 0x009C, and is translated to 0x0304, for, in
2626 * that order: RSA key exchange (0), AES-128/GCM (3), AEAD integrity (0),
2627 * SHA-256 in the TLS PRF (4).
2628 */
2629 typedef uint16_t br_suite_translated[2];
2630
2631 #ifndef BR_DOXYGEN_IGNORE
2632 /*
2633 * Constants are already documented in the br_suite_translated type.
2634 */
2635
2636 #define BR_SSLKEYX_RSA 0
2637 #define BR_SSLKEYX_ECDHE_RSA 1
2638 #define BR_SSLKEYX_ECDHE_ECDSA 2
2639 #define BR_SSLKEYX_ECDH_RSA 3
2640 #define BR_SSLKEYX_ECDH_ECDSA 4
2641
2642 #define BR_SSLENC_3DES_CBC 0
2643 #define BR_SSLENC_AES128_CBC 1
2644 #define BR_SSLENC_AES256_CBC 2
2645 #define BR_SSLENC_AES128_GCM 3
2646 #define BR_SSLENC_AES256_GCM 4
2647 #define BR_SSLENC_CHACHA20 5
2648
2649 #define BR_SSLMAC_AEAD 0
2650 #define BR_SSLMAC_SHA1 br_sha1_ID
2651 #define BR_SSLMAC_SHA256 br_sha256_ID
2652 #define BR_SSLMAC_SHA384 br_sha384_ID
2653
2654 #define BR_SSLPRF_SHA256 br_sha256_ID
2655 #define BR_SSLPRF_SHA384 br_sha384_ID
2656
2657 #endif
2658
2659 /*
2660 * Pre-declaration for the SSL server context.
2661 */
2662 typedef struct br_ssl_server_context_ br_ssl_server_context;
2663
2664 /**
2665 * \brief Type for the server policy choices, taken after analysis of
2666 * the client message (ClientHello).
2667 */
2668 typedef struct {
2669 /**
2670 * \brief Cipher suite to use with that client.
2671 */
2672 uint16_t cipher_suite;
2673
2674 /**
2675 * \brief Hash function or algorithm for signing the ServerKeyExchange.
2676 *
2677 * This parameter is ignored for `TLS_RSA_*` and `TLS_ECDH_*`
2678 * cipher suites; it is used only for `TLS_ECDHE_*` suites, in
2679 * which the server _signs_ the ephemeral EC Diffie-Hellman
2680 * parameters sent to the client.
2681 *
2682 * This identifier must be one of the following values:
2683 *
2684 * - `0xFF00 + id`, where `id` is a hash function identifier
2685 * (0 for MD5+SHA-1, or 2 to 6 for one of the SHA functions);
2686 *
2687 * - a full 16-bit identifier, lower than `0xFF00`.
2688 *
2689 * If the first option is used, then the SSL engine will
2690 * compute the hash of the data that is to be signed, with the
2691 * designated hash function. The `do_sign()` method will be
2692 * invoked with that hash value provided in the the `data`
2693 * buffer.
2694 *
2695 * If the second option is used, then the SSL engine will NOT
2696 * compute a hash on the data; instead, it will provide the
2697 * to-be-signed data itself in `data`, i.e. the concatenation of
2698 * the client random, server random, and encoded ECDH
2699 * parameters. Furthermore, with TLS-1.2 and later, the 16-bit
2700 * identifier will be used "as is" in the protocol, in the
2701 * SignatureAndHashAlgorithm; for instance, `0x0401` stands for
2702 * RSA PKCS#1 v1.5 signature (the `01`) with SHA-256 as hash
2703 * function (the `04`).
2704 *
2705 * Take care that with TLS 1.0 and 1.1, the hash function is
2706 * constrainted by the protocol: RSA signature must use
2707 * MD5+SHA-1 (so use `0xFF00`), while ECDSA must use SHA-1
2708 * (`0xFF02`). Since TLS 1.0 and 1.1 don't include a
2709 * SignatureAndHashAlgorithm field in their ServerKeyExchange
2710 * messages, any value below `0xFF00` will be usable to send the
2711 * raw ServerKeyExchange data to the `do_sign()` callback, but
2712 * that callback must still follow the protocol requirements
2713 * when generating the signature.
2714 */
2715 unsigned algo_id;
2716
2717 /**
2718 * \brief Certificate chain to send to the client.
2719 *
2720 * This is an array of `br_x509_certificate` objects, each
2721 * normally containing a DER-encoded certificate. The server
2722 * code does not try to decode these elements.
2723 */
2724 const br_x509_certificate *chain;
2725
2726 /**
2727 * \brief Certificate chain length (number of certificates).
2728 */
2729 size_t chain_len;
2730
2731 } br_ssl_server_choices;
2732
2733 /**
2734 * \brief Class type for a policy handler (server side).
2735 *
2736 * A policy handler selects the policy parameters for a connection
2737 * (cipher suite and other algorithms, and certificate chain to send to
2738 * the client); it also performs the server-side computations involving
2739 * its permanent private key.
2740 *
2741 * The SSL server engine will invoke first `choose()`, once the
2742 * ClientHello message has been received, then either `do_keyx()`
2743 * `do_sign()`, depending on the cipher suite.
2744 */
2745 typedef struct br_ssl_server_policy_class_ br_ssl_server_policy_class;
2746 struct br_ssl_server_policy_class_ {
2747 /**
2748 * \brief Context size (in bytes).
2749 */
2750 size_t context_size;
2751
2752 /**
2753 * \brief Select algorithms and certificates for this connection.
2754 *
2755 * This callback function shall fill the provided `choices`
2756 * structure with the policy choices for this connection. This
2757 * entails selecting the cipher suite, hash function for signing
2758 * the ServerKeyExchange (applicable only to ECDHE cipher suites),
2759 * and certificate chain to send.
2760 *
2761 * The callback receives a pointer to the server context that
2762 * contains the relevant data. In particular, the functions
2763 * `br_ssl_server_get_client_suites()`,
2764 * `br_ssl_server_get_client_hashes()` and
2765 * `br_ssl_server_get_client_curves()` can be used to obtain
2766 * the cipher suites, hash functions and elliptic curves
2767 * supported by both the client and server, respectively. The
2768 * `br_ssl_engine_get_version()` and `br_ssl_engine_get_server_name()`
2769 * functions yield the protocol version and requested server name
2770 * (SNI), respectively.
2771 *
2772 * This function may modify its context structure (`pctx`) in
2773 * arbitrary ways to keep track of its own choices.
2774 *
2775 * This function shall return 1 if appropriate policy choices
2776 * could be made, or 0 if this connection cannot be pursued.
2777 *
2778 * \param pctx policy context.
2779 * \param cc SSL server context.
2780 * \param choices destination structure for the policy choices.
2781 * \return 1 on success, 0 on error.
2782 */
2783 int (*choose)(const br_ssl_server_policy_class **pctx,
2784 const br_ssl_server_context *cc,
2785 br_ssl_server_choices *choices);
2786
2787 /**
2788 * \brief Perform key exchange (server part).
2789 *
2790 * This callback is invoked to perform the server-side cryptographic
2791 * operation for a key exchange that is not ECDHE. This callback
2792 * uses the private key.
2793 *
2794 * **For RSA key exchange**, the provided `data` (of length `len`
2795 * bytes) shall be decrypted with the server's private key, and
2796 * the 48-byte premaster secret copied back to the first 48 bytes
2797 * of `data`.
2798 *
2799 * - The caller makes sure that `len` is at least 59 bytes.
2800 *
2801 * - This callback MUST check that the provided length matches
2802 * that of the key modulus; it shall report an error otherwise.
2803 *
2804 * - If the length matches that of the RSA key modulus, then
2805 * processing MUST be constant-time, even if decryption fails,
2806 * or the padding is incorrect, or the plaintext message length
2807 * is not exactly 48 bytes.
2808 *
2809 * - This callback needs not check the two first bytes of the
2810 * obtained pre-master secret (the caller will do that).
2811 *
2812 * - If an error is reported (0), then what the callback put
2813 * in the first 48 bytes of `data` is unimportant (the caller
2814 * will use random bytes instead).
2815 *
2816 * **For ECDH key exchange**, the provided `data` (of length `len`
2817 * bytes) is the elliptic curve point from the client. The
2818 * callback shall multiply it with its private key, and store
2819 * the resulting X coordinate in `data`, starting at offset 1
2820 * (thus, simply encoding the point in compressed or uncompressed
2821 * format in `data` is fine).
2822 *
2823 * - If the input array does not have the proper length for
2824 * an encoded curve point, then an error (0) shall be reported.
2825 *
2826 * - If the input array has the proper length, then processing
2827 * MUST be constant-time, even if the data is not a valid
2828 * encoded point.
2829 *
2830 * - This callback MUST check that the input point is valid.
2831 *
2832 * Returned value is 1 on success, 0 on error.
2833 *
2834 * \param pctx policy context.
2835 * \param data key exchange data from the client.
2836 * \param len key exchange data length (in bytes).
2837 * \return 1 on success, 0 on error.
2838 */
2839 uint32_t (*do_keyx)(const br_ssl_server_policy_class **pctx,
2840 unsigned char *data, size_t len);
2841
2842 /**
2843 * \brief Perform a signature (for a ServerKeyExchange message).
2844 *
2845 * This callback function is invoked for ECDHE cipher suites. On
2846 * input, the hash value or message to sign is in `data`, of
2847 * size `hv_len`; the involved hash function or algorithm is
2848 * identified by `algo_id`. The signature shall be computed and
2849 * written back into `data`; the total size of that buffer is
2850 * `len` bytes.
2851 *
2852 * This callback shall verify that the signature length does not
2853 * exceed `len` bytes, and abstain from writing the signature if
2854 * it does not fit.
2855 *
2856 * The `algo_id` value matches that which was written in the
2857 * `choices` structures by the `choose()` callback. This will be
2858 * one of the following:
2859 *
2860 * - `0xFF00 + id` for a hash function identifier `id`. In
2861 * that case, the `data` buffer contains a hash value
2862 * already computed over the data that is to be signed,
2863 * of length `hv_len`. The `id` may be 0 to designate the
2864 * special MD5+SHA-1 concatenation (old-style RSA signing).
2865 *
2866 * - Another value, lower than `0xFF00`. The `data` buffer
2867 * then contains the raw, non-hashed data to be signed
2868 * (concatenation of the client and server randoms and
2869 * ECDH parameters). The callback is responsible to apply
2870 * any relevant hashing as part of the signing process.
2871 *
2872 * Returned value is the signature length (in bytes), or 0 on error.
2873 *
2874 * \param pctx policy context.
2875 * \param algo_id hash function / algorithm identifier.
2876 * \param data input/output buffer (message/hash, then signature).
2877 * \param hv_len hash value or message length (in bytes).
2878 * \param len total buffer length (in bytes).
2879 * \return signature length (in bytes) on success, or 0 on error.
2880 */
2881 size_t (*do_sign)(const br_ssl_server_policy_class **pctx,
2882 unsigned algo_id,
2883 unsigned char *data, size_t hv_len, size_t len);
2884 };
2885
2886 /**
2887 * \brief A single-chain RSA policy handler.
2888 *
2889 * This policy context uses a single certificate chain, and a RSA
2890 * private key. The context can be restricted to only signatures or
2891 * only key exchange.
2892 *
2893 * Apart from the first field (vtable pointer), its contents are
2894 * opaque and shall not be accessed directly.
2895 */
2896 typedef struct {
2897 /** \brief Pointer to vtable. */
2898 const br_ssl_server_policy_class *vtable;
2899 #ifndef BR_DOXYGEN_IGNORE
2900 const br_x509_certificate *chain;
2901 size_t chain_len;
2902 const br_rsa_private_key *sk;
2903 unsigned allowed_usages;
2904 br_rsa_private irsacore;
2905 br_rsa_pkcs1_sign irsasign;
2906 #endif
2907 } br_ssl_server_policy_rsa_context;
2908
2909 /**
2910 * \brief A single-chain EC policy handler.
2911 *
2912 * This policy context uses a single certificate chain, and an EC
2913 * private key. The context can be restricted to only signatures or
2914 * only key exchange.
2915 *
2916 * Due to how TLS is defined, this context must be made aware whether
2917 * the server certificate was itself signed with RSA or ECDSA. The code
2918 * does not try to decode the certificate to obtain that information.
2919 *
2920 * Apart from the first field (vtable pointer), its contents are
2921 * opaque and shall not be accessed directly.
2922 */
2923 typedef struct {
2924 /** \brief Pointer to vtable. */
2925 const br_ssl_server_policy_class *vtable;
2926 #ifndef BR_DOXYGEN_IGNORE
2927 const br_x509_certificate *chain;
2928 size_t chain_len;
2929 const br_ec_private_key *sk;
2930 unsigned allowed_usages;
2931 unsigned cert_issuer_key_type;
2932 const br_multihash_context *mhash;
2933 const br_ec_impl *iec;
2934 br_ecdsa_sign iecdsa;
2935 #endif
2936 } br_ssl_server_policy_ec_context;
2937
2938 /**
2939 * \brief Class type for a session parameter cache.
2940 *
2941 * Session parameters are saved in the cache with `save()`, and
2942 * retrieved with `load()`. The cache implementation can apply any
2943 * storage and eviction strategy that it sees fit. The SSL server
2944 * context that performs the request is provided, so that its
2945 * functionalities may be used by the implementation (e.g. hash
2946 * functions or random number generation).
2947 */
2948 typedef struct br_ssl_session_cache_class_ br_ssl_session_cache_class;
2949 struct br_ssl_session_cache_class_ {
2950 /**
2951 * \brief Context size (in bytes).
2952 */
2953 size_t context_size;
2954
2955 /**
2956 * \brief Record a session.
2957 *
2958 * This callback should record the provided session parameters.
2959 * The `params` structure is transient, so its contents shall
2960 * be copied into the cache. The session ID has been randomly
2961 * generated and always has length exactly 32 bytes.
2962 *
2963 * \param ctx session cache context.
2964 * \param server_ctx SSL server context.
2965 * \param params session parameters to save.
2966 */
2967 void (*save)(const br_ssl_session_cache_class **ctx,
2968 br_ssl_server_context *server_ctx,
2969 const br_ssl_session_parameters *params);
2970
2971 /**
2972 * \brief Lookup a session in the cache.
2973 *
2974 * The session ID to lookup is in `params` and always has length
2975 * exactly 32 bytes. If the session parameters are found in the
2976 * cache, then the parameters shall be copied into the `params`
2977 * structure. Returned value is 1 on successful lookup, 0
2978 * otherwise.
2979 *
2980 * \param ctx session cache context.
2981 * \param server_ctx SSL server context.
2982 * \param params destination for session parameters.
2983 * \return 1 if found, 0 otherwise.
2984 */
2985 int (*load)(const br_ssl_session_cache_class **ctx,
2986 br_ssl_server_context *server_ctx,
2987 br_ssl_session_parameters *params);
2988 };
2989
2990 /**
2991 * \brief Context for a basic cache system.
2992 *
2993 * The system stores session parameters in a buffer provided at
2994 * initialisation time. Each entry uses exactly 100 bytes, and
2995 * buffer sizes up to 4294967295 bytes are supported.
2996 *
2997 * Entries are evicted with a LRU (Least Recently Used) policy. A
2998 * search tree is maintained to keep lookups fast even with large
2999 * caches.
3000 *
3001 * Apart from the first field (vtable pointer), the structure
3002 * contents are opaque and shall not be accessed directly.
3003 */
3004 typedef struct {
3005 /** \brief Pointer to vtable. */
3006 const br_ssl_session_cache_class *vtable;
3007 #ifndef BR_DOXYGEN_IGNORE
3008 unsigned char *store;
3009 size_t store_len, store_ptr;
3010 unsigned char index_key[32];
3011 const br_hash_class *hash;
3012 int init_done;
3013 uint32_t head, tail, root;
3014 #endif
3015 } br_ssl_session_cache_lru;
3016
3017 /**
3018 * \brief Initialise a LRU session cache with the provided storage space.
3019 *
3020 * The provided storage space must remain valid as long as the cache
3021 * is used. Arbitrary lengths are supported, up to 4294967295 bytes;
3022 * each entry uses up exactly 100 bytes.
3023 *
3024 * \param cc session cache context.
3025 * \param store storage space for cached entries.
3026 * \param store_len storage space length (in bytes).
3027 */
3028 void br_ssl_session_cache_lru_init(br_ssl_session_cache_lru *cc,
3029 unsigned char *store, size_t store_len);
3030
3031 /**
3032 * \brief Context structure for a SSL server.
3033 *
3034 * The first field (called `eng`) is the SSL engine; all functions that
3035 * work on a `br_ssl_engine_context` structure shall take as parameter
3036 * a pointer to that field. The other structure fields are opaque and
3037 * must not be accessed directly.
3038 */
3039 struct br_ssl_server_context_ {
3040 /**
3041 * \brief The encapsulated engine context.
3042 */
3043 br_ssl_engine_context eng;
3044
3045 #ifndef BR_DOXYGEN_IGNORE
3046 /*
3047 * Maximum version from the client.
3048 */
3049 uint16_t client_max_version;
3050
3051 /*
3052 * Session cache.
3053 */
3054 const br_ssl_session_cache_class **cache_vtable;
3055
3056 /*
3057 * Translated cipher suites supported by the client. The list
3058 * is trimmed to include only the cipher suites that the
3059 * server also supports; they are in the same order as in the
3060 * client message.
3061 */
3062 br_suite_translated client_suites[BR_MAX_CIPHER_SUITES];
3063 unsigned char client_suites_num;
3064
3065 /*
3066 * Hash functions supported by the client, with ECDSA and RSA
3067 * (bit mask). For hash function with id 'x', set bit index is
3068 * x for RSA, x+8 for ECDSA. For newer algorithms, with ID
3069 * 0x08**, bit 16+k is set for algorithm 0x0800+k.
3070 */
3071 uint32_t hashes;
3072
3073 /*
3074 * Curves supported by the client (bit mask, for named curves).
3075 */
3076 uint32_t curves;
3077
3078 /*
3079 * Context for chain handler.
3080 */
3081 const br_ssl_server_policy_class **policy_vtable;
3082 uint16_t sign_hash_id;
3083
3084 /*
3085 * For the core handlers, thus avoiding (in most cases) the
3086 * need for an externally provided policy context.
3087 */
3088 union {
3089 const br_ssl_server_policy_class *vtable;
3090 br_ssl_server_policy_rsa_context single_rsa;
3091 br_ssl_server_policy_ec_context single_ec;
3092 } chain_handler;
3093
3094 /*
3095 * Buffer for the ECDHE private key.
3096 */
3097 unsigned char ecdhe_key[70];
3098 size_t ecdhe_key_len;
3099
3100 /*
3101 * Trust anchor names for client authentication. "ta_names" and
3102 * "tas" cannot be both non-NULL.
3103 */
3104 const br_x500_name *ta_names;
3105 const br_x509_trust_anchor *tas;
3106 size_t num_tas;
3107 size_t cur_dn_index;
3108 const unsigned char *cur_dn;
3109 size_t cur_dn_len;
3110
3111 /*
3112 * Buffer for the hash value computed over all handshake messages
3113 * prior to CertificateVerify, and identifier for the hash function.
3114 */
3115 unsigned char hash_CV[64];
3116 size_t hash_CV_len;
3117 int hash_CV_id;
3118
3119 /*
3120 * Server-specific implementations.
3121 * (none for now)
3122 */
3123 #endif
3124 };
3125
3126 /*
3127 * Each br_ssl_server_init_xxx() function sets the list of supported
3128 * cipher suites and used implementations, as specified by the profile
3129 * name 'xxx'. Defined profile names are:
3130 *
3131 * full_rsa all supported algorithm, server key type is RSA
3132 * full_ec all supported algorithm, server key type is EC
3133 * TODO: add other profiles
3134 *
3135 * Naming scheme for "minimal" profiles: min123
3136 *
3137 * -- character 1: key exchange
3138 * r = RSA
3139 * e = ECDHE_RSA
3140 * f = ECDHE_ECDSA
3141 * u = ECDH_RSA
3142 * v = ECDH_ECDSA
3143 * -- character 2: version / PRF
3144 * 0 = TLS 1.0 / 1.1 with MD5+SHA-1
3145 * 2 = TLS 1.2 with SHA-256
3146 * 3 = TLS 1.2 with SHA-384
3147 * -- character 3: encryption
3148 * a = AES/CBC
3149 * g = AES/GCM
3150 * d = 3DES/CBC
3151 */
3152
3153 /**
3154 * \brief SSL server profile: full_rsa.
3155 *
3156 * This function initialises the provided SSL server context with
3157 * all supported algorithms and cipher suites that rely on a RSA
3158 * key pair.
3159 *
3160 * \param cc server context to initialise.
3161 * \param chain server certificate chain.
3162 * \param chain_len certificate chain length (number of certificate).
3163 * \param sk RSA private key.
3164 */
3165 void br_ssl_server_init_full_rsa(br_ssl_server_context *cc,
3166 const br_x509_certificate *chain, size_t chain_len,
3167 const br_rsa_private_key *sk);
3168
3169 /**
3170 * \brief SSL server profile: full_ec.
3171 *
3172 * This function initialises the provided SSL server context with
3173 * all supported algorithms and cipher suites that rely on an EC
3174 * key pair.
3175 *
3176 * The key type of the CA that issued the server's certificate must
3177 * be provided, since it matters for ECDH cipher suites (ECDH_RSA
3178 * suites require a RSA-powered CA). The key type is either
3179 * `BR_KEYTYPE_RSA` or `BR_KEYTYPE_EC`.
3180 *
3181 * \param cc server context to initialise.
3182 * \param chain server certificate chain.
3183 * \param chain_len chain length (number of certificates).
3184 * \param cert_issuer_key_type certificate issuer's key type.
3185 * \param sk EC private key.
3186 */
3187 void br_ssl_server_init_full_ec(br_ssl_server_context *cc,
3188 const br_x509_certificate *chain, size_t chain_len,
3189 unsigned cert_issuer_key_type, const br_ec_private_key *sk);
3190
3191 /**
3192 * \brief SSL server profile: minr2g.
3193 *
3194 * This profile uses only TLS_RSA_WITH_AES_128_GCM_SHA256. Server key is
3195 * RSA, and RSA key exchange is used (not forward secure, but uses little
3196 * CPU in the client).
3197 *
3198 * \param cc server context to initialise.
3199 * \param chain server certificate chain.
3200 * \param chain_len certificate chain length (number of certificate).
3201 * \param sk RSA private key.
3202 */
3203 void br_ssl_server_init_minr2g(br_ssl_server_context *cc,
3204 const br_x509_certificate *chain, size_t chain_len,
3205 const br_rsa_private_key *sk);
3206
3207 /**
3208 * \brief SSL server profile: mine2g.
3209 *
3210 * This profile uses only TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256. Server key
3211 * is RSA, and ECDHE key exchange is used. This suite provides forward
3212 * security, with a higher CPU expense on the client, and a somewhat
3213 * larger code footprint (compared to "minr2g").
3214 *
3215 * \param cc server context to initialise.
3216 * \param chain server certificate chain.
3217 * \param chain_len certificate chain length (number of certificate).
3218 * \param sk RSA private key.
3219 */
3220 void br_ssl_server_init_mine2g(br_ssl_server_context *cc,
3221 const br_x509_certificate *chain, size_t chain_len,
3222 const br_rsa_private_key *sk);
3223
3224 /**
3225 * \brief SSL server profile: minf2g.
3226 *
3227 * This profile uses only TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256.
3228 * Server key is EC, and ECDHE key exchange is used. This suite provides
3229 * forward security, with a higher CPU expense on the client and server
3230 * (by a factor of about 3 to 4), and a somewhat larger code footprint
3231 * (compared to "minu2g" and "minv2g").
3232 *
3233 * \param cc server context to initialise.
3234 * \param chain server certificate chain.
3235 * \param chain_len certificate chain length (number of certificate).
3236 * \param sk EC private key.
3237 */
3238 void br_ssl_server_init_minf2g(br_ssl_server_context *cc,
3239 const br_x509_certificate *chain, size_t chain_len,
3240 const br_ec_private_key *sk);
3241
3242 /**
3243 * \brief SSL server profile: minu2g.
3244 *
3245 * This profile uses only TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256.
3246 * Server key is EC, and ECDH key exchange is used; the issuing CA used
3247 * a RSA key.
3248 *
3249 * The "minu2g" and "minv2g" profiles do not provide forward secrecy,
3250 * but are the lightest on the server (for CPU usage), and are rather
3251 * inexpensive on the client as well.
3252 *
3253 * \param cc server context to initialise.
3254 * \param chain server certificate chain.
3255 * \param chain_len certificate chain length (number of certificate).
3256 * \param sk EC private key.
3257 */
3258 void br_ssl_server_init_minu2g(br_ssl_server_context *cc,
3259 const br_x509_certificate *chain, size_t chain_len,
3260 const br_ec_private_key *sk);
3261
3262 /**
3263 * \brief SSL server profile: minv2g.
3264 *
3265 * This profile uses only TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256.
3266 * Server key is EC, and ECDH key exchange is used; the issuing CA used
3267 * an EC key.
3268 *
3269 * The "minu2g" and "minv2g" profiles do not provide forward secrecy,
3270 * but are the lightest on the server (for CPU usage), and are rather
3271 * inexpensive on the client as well.
3272 *
3273 * \param cc server context to initialise.
3274 * \param chain server certificate chain.
3275 * \param chain_len certificate chain length (number of certificate).
3276 * \param sk EC private key.
3277 */
3278 void br_ssl_server_init_minv2g(br_ssl_server_context *cc,
3279 const br_x509_certificate *chain, size_t chain_len,
3280 const br_ec_private_key *sk);
3281
3282 /**
3283 * \brief SSL server profile: mine2c.
3284 *
3285 * This profile uses only TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256.
3286 * Server key is RSA, and ECDHE key exchange is used. This suite
3287 * provides forward security.
3288 *
3289 * \param cc server context to initialise.
3290 * \param chain server certificate chain.
3291 * \param chain_len certificate chain length (number of certificate).
3292 * \param sk RSA private key.
3293 */
3294 void br_ssl_server_init_mine2c(br_ssl_server_context *cc,
3295 const br_x509_certificate *chain, size_t chain_len,
3296 const br_rsa_private_key *sk);
3297
3298 /**
3299 * \brief SSL server profile: minf2c.
3300 *
3301 * This profile uses only TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256.
3302 * Server key is EC, and ECDHE key exchange is used. This suite provides
3303 * forward security.
3304 *
3305 * \param cc server context to initialise.
3306 * \param chain server certificate chain.
3307 * \param chain_len certificate chain length (number of certificate).
3308 * \param sk EC private key.
3309 */
3310 void br_ssl_server_init_minf2c(br_ssl_server_context *cc,
3311 const br_x509_certificate *chain, size_t chain_len,
3312 const br_ec_private_key *sk);
3313
3314 /**
3315 * \brief Get the supported client suites.
3316 *
3317 * This function shall be called only after the ClientHello has been
3318 * processed, typically from the policy engine. The returned array
3319 * contains the cipher suites that are supported by both the client
3320 * and the server; these suites are in client preference order, unless
3321 * the `BR_OPT_ENFORCE_SERVER_PREFERENCES` flag was set, in which case
3322 * they are in server preference order.
3323 *
3324 * The suites are _translated_, which means that each suite is given
3325 * as two 16-bit integers: the standard suite identifier, and its
3326 * translated version, broken down into its individual components,
3327 * as explained with the `br_suite_translated` type.
3328 *
3329 * The returned array is allocated in the context and will be rewritten
3330 * by each handshake.
3331 *
3332 * \param cc server context.
3333 * \param num receives the array size (number of suites).
3334 * \return the translated common cipher suites, in preference order.
3335 */
3336 static inline const br_suite_translated *
3337 br_ssl_server_get_client_suites(const br_ssl_server_context *cc, size_t *num)
3338 {
3339 *num = cc->client_suites_num;
3340 return cc->client_suites;
3341 }
3342
3343 /**
3344 * \brief Get the hash functions and signature algorithms supported by
3345 * the client.
3346 *
3347 * This value is a bit field:
3348 *
3349 * - If RSA (PKCS#1 v1.5) is supported with hash function of ID `x`,
3350 * then bit `x` is set (hash function ID is 0 for the special MD5+SHA-1,
3351 * or 2 to 6 for the SHA family).
3352 *
3353 * - If ECDSA is suported with hash function of ID `x`, then bit `8+x`
3354 * is set.
3355 *
3356 * - Newer algorithms are symbolic 16-bit identifiers that do not
3357 * represent signature algorithm and hash function separately. If
3358 * the TLS-level identifier is `0x0800+x` for a `x` in the 0..15
3359 * range, then bit `16+x` is set.
3360 *
3361 * "New algorithms" are currently defined only in draft documents, so
3362 * this support is subject to possible change. Right now (early 2017),
3363 * this maps ed25519 (EdDSA on Curve25519) to bit 23, and ed448 (EdDSA
3364 * on Curve448) to bit 24. If the identifiers on the wire change in
3365 * future document, then the decoding mechanism in BearSSL will be
3366 * amended to keep mapping ed25519 and ed448 on bits 23 and 24,
3367 * respectively. Mapping of other new algorithms (e.g. RSA/PSS) is not
3368 * guaranteed yet.
3369 *
3370 * \param cc server context.
3371 * \return the client-supported hash functions and signature algorithms.
3372 */
3373 static inline uint32_t
3374 br_ssl_server_get_client_hashes(const br_ssl_server_context *cc)
3375 {
3376 return cc->hashes;
3377 }
3378
3379 /**
3380 * \brief Get the elliptic curves supported by the client.
3381 *
3382 * This is a bit field (bit x is set if curve of ID x is supported).
3383 *
3384 * \param cc server context.
3385 * \return the client-supported elliptic curves.
3386 */
3387 static inline uint32_t
3388 br_ssl_server_get_client_curves(const br_ssl_server_context *cc)
3389 {
3390 return cc->curves;
3391 }
3392
3393 /**
3394 * \brief Clear the complete contents of a SSL server context.
3395 *
3396 * Everything is cleared, including the reference to the configured buffer,
3397 * implementations, cipher suites and state. This is a preparatory step
3398 * to assembling a custom profile.
3399 *
3400 * \param cc server context to clear.
3401 */
3402 void br_ssl_server_zero(br_ssl_server_context *cc);
3403
3404 /**
3405 * \brief Set an externally provided policy context.
3406 *
3407 * The policy context's methods are invoked to decide the cipher suite
3408 * and certificate chain, and to perform operations involving the server's
3409 * private key.
3410 *
3411 * \param cc server context.
3412 * \param pctx policy context (pointer to its vtable field).
3413 */
3414 static inline void
3415 br_ssl_server_set_policy(br_ssl_server_context *cc,
3416 const br_ssl_server_policy_class **pctx)
3417 {
3418 cc->policy_vtable = pctx;
3419 }
3420
3421 /**
3422 * \brief Set the server certificate chain and key (single RSA case).
3423 *
3424 * This function uses a policy context included in the server context.
3425 * It configures use of a single server certificate chain with a RSA
3426 * private key. The `allowed_usages` is a combination of usages, namely
3427 * `BR_KEYTYPE_KEYX` and/or `BR_KEYTYPE_SIGN`; this enables or disables
3428 * the corresponding cipher suites (i.e. `TLS_RSA_*` use the RSA key for
3429 * key exchange, while `TLS_ECDHE_RSA_*` use the RSA key for signatures).
3430 *
3431 * \param cc server context.
3432 * \param chain server certificate chain to send to the client.
3433 * \param chain_len chain length (number of certificates).
3434 * \param sk server private key (RSA).
3435 * \param allowed_usages allowed private key usages.
3436 * \param irsacore RSA core implementation.
3437 * \param irsasign RSA signature implementation (PKCS#1 v1.5).
3438 */
3439 void br_ssl_server_set_single_rsa(br_ssl_server_context *cc,
3440 const br_x509_certificate *chain, size_t chain_len,
3441 const br_rsa_private_key *sk, unsigned allowed_usages,
3442 br_rsa_private irsacore, br_rsa_pkcs1_sign irsasign);
3443
3444 /**
3445 * \brief Set the server certificate chain and key (single EC case).
3446 *
3447 * This function uses a policy context included in the server context.
3448 * It configures use of a single server certificate chain with an EC
3449 * private key. The `allowed_usages` is a combination of usages, namely
3450 * `BR_KEYTYPE_KEYX` and/or `BR_KEYTYPE_SIGN`; this enables or disables
3451 * the corresponding cipher suites (i.e. `TLS_ECDH_*` use the EC key for
3452 * key exchange, while `TLS_ECDHE_ECDSA_*` use the EC key for signatures).
3453 *
3454 * In order to support `TLS_ECDH_*` cipher suites (non-ephemeral ECDH),
3455 * the algorithm type of the key used by the issuing CA to sign the
3456 * server's certificate must be provided, as `cert_issuer_key_type`
3457 * parameter (this value is either `BR_KEYTYPE_RSA` or `BR_KEYTYPE_EC`).
3458 *
3459 * \param cc server context.
3460 * \param chain server certificate chain to send.
3461 * \param chain_len chain length (number of certificates).
3462 * \param sk server private key (EC).
3463 * \param allowed_usages allowed private key usages.
3464 * \param cert_issuer_key_type issuing CA's key type.
3465 * \param iec EC core implementation.
3466 * \param iecdsa ECDSA signature implementation ("asn1" format).
3467 */
3468 void br_ssl_server_set_single_ec(br_ssl_server_context *cc,
3469 const br_x509_certificate *chain, size_t chain_len,
3470 const br_ec_private_key *sk, unsigned allowed_usages,
3471 unsigned cert_issuer_key_type,
3472 const br_ec_impl *iec, br_ecdsa_sign iecdsa);
3473
3474 /**
3475 * \brief Activate client certificate authentication.
3476 *
3477 * The trust anchor encoded X.500 names (DN) to send to the client are
3478 * provided. A client certificate will be requested and validated through
3479 * the X.509 validator configured in the SSL engine. If `num` is 0, then
3480 * client certificate authentication is disabled.
3481 *
3482 * If the client does not send a certificate, or on validation failure,
3483 * the handshake aborts. Unauthenticated clients can be tolerated by
3484 * setting the `BR_OPT_TOLERATE_NO_CLIENT_AUTH` flag.
3485 *
3486 * The provided array is linked in, not copied, so that pointer must
3487 * remain valid as long as anchor names may be used.
3488 *
3489 * \param cc server context.
3490 * \param ta_names encoded trust anchor names.
3491 * \param num number of encoded trust anchor names.
3492 */
3493 static inline void
3494 br_ssl_server_set_trust_anchor_names(br_ssl_server_context *cc,
3495 const br_x500_name *ta_names, size_t num)
3496 {
3497 cc->ta_names = ta_names;
3498 cc->tas = NULL;
3499 cc->num_tas = num;
3500 }
3501
3502 /**
3503 * \brief Activate client certificate authentication.
3504 *
3505 * This is a variant for `br_ssl_server_set_trust_anchor_names()`: the
3506 * trust anchor names are provided not as an array of stand-alone names
3507 * (`br_x500_name` structures), but as an array of trust anchors
3508 * (`br_x509_trust_anchor` structures). The server engine itself will
3509 * only use the `dn` field of each trust anchor. This is meant to allow
3510 * defining a single array of trust anchors, to be used here and in the
3511 * X.509 validation engine itself.
3512 *
3513 * The provided array is linked in, not copied, so that pointer must
3514 * remain valid as long as anchor names may be used.
3515 *
3516 * \param cc server context.
3517 * \param tas trust anchors (only names are used).
3518 * \param num number of trust anchors.
3519 */
3520 static inline void
3521 br_ssl_server_set_trust_anchor_names_alt(br_ssl_server_context *cc,
3522 const br_x509_trust_anchor *tas, size_t num)
3523 {
3524 cc->ta_names = NULL;
3525 cc->tas = tas;
3526 cc->num_tas = num;
3527 }
3528
3529 /**
3530 * \brief Configure the cache for session parameters.
3531 *
3532 * The cache context is provided as a pointer to its first field (vtable
3533 * pointer).
3534 *
3535 * \param cc server context.
3536 * \param vtable session cache context.
3537 */
3538 static inline void
3539 br_ssl_server_set_cache(br_ssl_server_context *cc,
3540 const br_ssl_session_cache_class **vtable)
3541 {
3542 cc->cache_vtable = vtable;
3543 }
3544
3545 /**
3546 * \brief Prepare or reset a server context for handling an incoming client.
3547 *
3548 * \param cc server context.
3549 * \return 1 on success, 0 on error.
3550 */
3551 int br_ssl_server_reset(br_ssl_server_context *cc);
3552
3553 /* ===================================================================== */
3554
3555 /*
3556 * Context for the simplified I/O context. The transport medium is accessed
3557 * through the low_read() and low_write() callback functions, each with
3558 * its own opaque context pointer.
3559 *
3560 * low_read() read some bytes, at most 'len' bytes, into data[]. The
3561 * returned value is the number of read bytes, or -1 on error.
3562 * The 'len' parameter is guaranteed never to exceed 20000,
3563 * so the length always fits in an 'int' on all platforms.
3564 *
3565 * low_write() write up to 'len' bytes, to be read from data[]. The
3566 * returned value is the number of written bytes, or -1 on
3567 * error. The 'len' parameter is guaranteed never to exceed
3568 * 20000, so the length always fits in an 'int' on all
3569 * parameters.
3570 *
3571 * A socket closure (if the transport medium is a socket) should be reported
3572 * as an error (-1). The callbacks shall endeavour to block until at least
3573 * one byte can be read or written; a callback returning 0 at times is
3574 * acceptable, but this normally leads to the callback being immediately
3575 * called again, so the callback should at least always try to block for
3576 * some time if no I/O can take place.
3577 *
3578 * The SSL engine naturally applies some buffering, so the callbacks need
3579 * not apply buffers of their own.
3580 */
3581 /**
3582 * \brief Context structure for the simplified SSL I/O wrapper.
3583 *
3584 * This structure is initialised with `br_sslio_init()`. Its contents
3585 * are opaque and shall not be accessed directly.
3586 */
3587 typedef struct {
3588 #ifndef BR_DOXYGEN_IGNORE
3589 br_ssl_engine_context *engine;
3590 int (*low_read)(void *read_context,
3591 unsigned char *data, size_t len);
3592 void *read_context;
3593 int (*low_write)(void *write_context,
3594 const unsigned char *data, size_t len);
3595 void *write_context;
3596 #endif
3597 } br_sslio_context;
3598
3599 /**
3600 * \brief Initialise a simplified I/O wrapper context.
3601 *
3602 * The simplified I/O wrapper offers a simpler read/write API for a SSL
3603 * engine (client or server), using the provided callback functions for
3604 * reading data from, or writing data to, the transport medium.
3605 *
3606 * The callback functions have the following semantics:
3607 *
3608 * - Each callback receives an opaque context value (of type `void *`)
3609 * that the callback may use arbitrarily (or possibly ignore).
3610 *
3611 * - `low_read()` reads at least one byte, at most `len` bytes, from
3612 * the transport medium. Read bytes shall be written in `data`.
3613 *
3614 * - `low_write()` writes at least one byte, at most `len` bytes, unto
3615 * the transport medium. The bytes to write are read from `data`.
3616 *
3617 * - The `len` parameter is never zero, and is always lower than 20000.
3618 *
3619 * - The number of processed bytes (read or written) is returned. Since
3620 * that number is less than 20000, it always fits on an `int`.
3621 *
3622 * - On error, the callbacks return -1. Reaching end-of-stream is an
3623 * error. Errors are permanent: the SSL connection is terminated.
3624 *
3625 * - Callbacks SHOULD NOT return 0. This is tolerated, as long as
3626 * callbacks endeavour to block for some non-negligible amount of
3627 * time until at least one byte can be sent or received (if a
3628 * callback returns 0, then the wrapper invokes it again
3629 * immediately).
3630 *
3631 * - Callbacks MAY return as soon as at least one byte is processed;
3632 * they MAY also insist on reading or writing _all_ requested bytes.
3633 * Since SSL is a self-terminated protocol (each record has a length
3634 * header), this does not change semantics.
3635 *
3636 * - Callbacks need not apply any buffering (for performance) since SSL
3637 * itself uses buffers.
3638 *
3639 * \param ctx wrapper context to initialise.
3640 * \param engine SSL engine to wrap.
3641 * \param low_read callback for reading data from the transport.
3642 * \param read_context context pointer for `low_read()`.
3643 * \param low_write callback for writing data on the transport.
3644 * \param write_context context pointer for `low_write()`.
3645 */
3646 void br_sslio_init(br_sslio_context *ctx,
3647 br_ssl_engine_context *engine,
3648 int (*low_read)(void *read_context,
3649 unsigned char *data, size_t len),
3650 void *read_context,
3651 int (*low_write)(void *write_context,
3652 const unsigned char *data, size_t len),
3653 void *write_context);
3654
3655 /**
3656 * \brief Read some application data from a SSL connection.
3657 *
3658 * If `len` is zero, then this function returns 0 immediately. In
3659 * all other cases, it never returns 0.
3660 *
3661 * This call returns only when at least one byte has been obtained.
3662 * Returned value is the number of bytes read, or -1 on error. The
3663 * number of bytes always fits on an 'int' (data from a single SSL/TLS
3664 * record is returned).
3665 *
3666 * On error or SSL closure, this function returns -1. The caller should
3667 * inspect the error status on the SSL engine to distinguish between
3668 * normal closure and error.
3669 *
3670 * \param cc SSL wrapper context.
3671 * \param dst destination buffer for application data.
3672 * \param len maximum number of bytes to obtain.
3673 * \return number of bytes obtained, or -1 on error.
3674 */
3675 int br_sslio_read(br_sslio_context *cc, void *dst, size_t len);
3676
3677 /**
3678 * \brief Read application data from a SSL connection.
3679 *
3680 * This calls returns only when _all_ requested `len` bytes are read,
3681 * or an error is reached. Returned value is 0 on success, -1 on error.
3682 * A normal (verified) SSL closure before that many bytes are obtained
3683 * is reported as an error by this function.
3684 *
3685 * \param cc SSL wrapper context.
3686 * \param dst destination buffer for application data.
3687 * \param len number of bytes to obtain.
3688 * \return 0 on success, or -1 on error.
3689 */
3690 int br_sslio_read_all(br_sslio_context *cc, void *dst, size_t len);
3691
3692 /**
3693 * \brief Write some application data unto a SSL connection.
3694 *
3695 * If `len` is zero, then this function returns 0 immediately. In
3696 * all other cases, it never returns 0.
3697 *
3698 * This call returns only when at least one byte has been written.
3699 * Returned value is the number of bytes written, or -1 on error. The
3700 * number of bytes always fits on an 'int' (less than 20000).
3701 *
3702 * On error or SSL closure, this function returns -1. The caller should
3703 * inspect the error status on the SSL engine to distinguish between
3704 * normal closure and error.
3705 *
3706 * **Important:** SSL is buffered; a "written" byte is a byte that was
3707 * injected into the wrapped SSL engine, but this does not necessarily mean
3708 * that it has been scheduled for sending. Use `br_sslio_flush()` to
3709 * ensure that all pending data has been sent to the transport medium.
3710 *
3711 * \param cc SSL wrapper context.
3712 * \param src source buffer for application data.
3713 * \param len maximum number of bytes to write.
3714 * \return nu