463e6161e6764a150d0720086ac07377d9baf238
[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 message. */
195 #define BR_ERR_BAD_SIGNATURE 27
196
197 /** \brief SSL status: I/O error or premature close on underlying
198 transport stream. This error code is set only by the simplified
199 I/O API ("br_sslio_*"). */
200 #define BR_ERR_IO 31
201
202 /** \brief SSL status: base value for a received fatal alert.
203
204 When a fatal alert is received from the peer, the alert value
205 is added to this constant. */
206 #define BR_ERR_RECV_FATAL_ALERT 256
207
208 /** \brief SSL status: base value for a sent fatal alert.
209
210 When a fatal alert is sent to the peer, the alert value is added
211 to this constant. */
212 #define BR_ERR_SEND_FATAL_ALERT 512
213
214 /* ===================================================================== */
215
216 /**
217 * \brief Decryption engine for SSL.
218 *
219 * When processing incoming records, the SSL engine will use a decryption
220 * engine that uses a specific context structure, and has a set of
221 * methods (a vtable) that follows this template.
222 *
223 * The decryption engine is responsible for applying decryption, verifying
224 * MAC, and keeping track of the record sequence number.
225 */
226 typedef struct br_sslrec_in_class_ br_sslrec_in_class;
227 struct br_sslrec_in_class_ {
228 /**
229 * \brief Context size (in bytes).
230 */
231 size_t context_size;
232
233 /**
234 * \brief Test validity of the incoming record length.
235 *
236 * This function returns 1 if the announced length for an
237 * incoming record is valid, 0 otherwise,
238 *
239 * \param ctx decryption engine context.
240 * \param record_len incoming record length.
241 * \return 1 of a valid length, 0 otherwise.
242 */
243 int (*check_length)(const br_sslrec_in_class *const *ctx,
244 size_t record_len);
245
246 /**
247 * \brief Decrypt the incoming record.
248 *
249 * This function may assume that the record length is valid
250 * (it has been previously tested with `check_length()`).
251 * Decryption is done in place; `*len` is updated with the
252 * cleartext length, and the address of the first plaintext
253 * byte is returned. If the record is correct but empty, then
254 * `*len` is set to 0 and a non-`NULL` pointer is returned.
255 *
256 * On decryption/MAC error, `NULL` is returned.
257 *
258 * \param ctx decryption engine context.
259 * \param record_type record type (23 for application data, etc).
260 * \param version record version.
261 * \param payload address of encrypted payload.
262 * \param len pointer to payload length (updated).
263 * \return pointer to plaintext, or `NULL` on error.
264 */
265 unsigned char *(*decrypt)(const br_sslrec_in_class **ctx,
266 int record_type, unsigned version,
267 void *payload, size_t *len);
268 };
269
270 /**
271 * \brief Encryption engine for SSL.
272 *
273 * When building outgoing records, the SSL engine will use an encryption
274 * engine that uses a specific context structure, and has a set of
275 * methods (a vtable) that follows this template.
276 *
277 * The encryption engine is responsible for applying encryption and MAC,
278 * and keeping track of the record sequence number.
279 */
280 typedef struct br_sslrec_out_class_ br_sslrec_out_class;
281 struct br_sslrec_out_class_ {
282 /**
283 * \brief Context size (in bytes).
284 */
285 size_t context_size;
286
287 /**
288 * \brief Compute maximum plaintext sizes and offsets.
289 *
290 * When this function is called, the `*start` and `*end`
291 * values contain offsets designating the free area in the
292 * outgoing buffer for plaintext data; that free area is
293 * preceded by a 5-byte space which will receive the record
294 * header.
295 *
296 * The `max_plaintext()` function is responsible for adjusting
297 * both `*start` and `*end` to make room for any record-specific
298 * header, MAC, padding, and possible split.
299 *
300 * \param ctx encryption engine context.
301 * \param start pointer to start of plaintext offset (updated).
302 * \param end pointer to start of plaintext offset (updated).
303 */
304 void (*max_plaintext)(const br_sslrec_out_class *const *ctx,
305 size_t *start, size_t *end);
306
307 /**
308 * \brief Perform record encryption.
309 *
310 * This function encrypts the record. The plaintext address and
311 * length are provided. Returned value is the start of the
312 * encrypted record (or sequence of records, if a split was
313 * performed), _including_ the 5-byte header, and `*len` is
314 * adjusted to the total size of the record(s), there again
315 * including the header(s).
316 *
317 * \param ctx decryption engine context.
318 * \param record_type record type (23 for application data, etc).
319 * \param version record version.
320 * \param plaintext address of plaintext.
321 * \param len pointer to plaintext length (updated).
322 * \return pointer to start of built record.
323 */
324 unsigned char *(*encrypt)(const br_sslrec_out_class **ctx,
325 int record_type, unsigned version,
326 void *plaintext, size_t *len);
327 };
328
329 /**
330 * \brief Context for a no-encryption engine.
331 *
332 * The no-encryption engine processes outgoing records during the initial
333 * handshake, before encryption is applied.
334 */
335 typedef struct {
336 /** \brief No-encryption engine vtable. */
337 const br_sslrec_out_class *vtable;
338 } br_sslrec_out_clear_context;
339
340 /** \brief Static, constant vtable for the no-encryption engine. */
341 extern const br_sslrec_out_class br_sslrec_out_clear_vtable;
342
343 /* ===================================================================== */
344
345 /**
346 * \brief Record decryption engine class, for CBC mode.
347 *
348 * This class type extends the decryption engine class with an
349 * initialisation method that receives the parameters needed
350 * for CBC processing: block cipher implementation, block cipher key,
351 * HMAC parameters (hash function, key, MAC length), and IV. If the
352 * IV is `NULL`, then a per-record IV will be used (TLS 1.1+).
353 */
354 typedef struct br_sslrec_in_cbc_class_ br_sslrec_in_cbc_class;
355 struct br_sslrec_in_cbc_class_ {
356 /**
357 * \brief Superclass, as first vtable field.
358 */
359 br_sslrec_in_class inner;
360
361 /**
362 * \brief Engine initialisation method.
363 *
364 * This method sets the vtable field in the context.
365 *
366 * \param ctx context to initialise.
367 * \param bc_impl block cipher implementation (CBC decryption).
368 * \param bc_key block cipher key.
369 * \param bc_key_len block cipher key length (in bytes).
370 * \param dig_impl hash function for HMAC.
371 * \param mac_key HMAC key.
372 * \param mac_key_len HMAC key length (in bytes).
373 * \param mac_out_len HMAC output length (in bytes).
374 * \param iv initial IV (or `NULL`).
375 */
376 void (*init)(const br_sslrec_in_cbc_class **ctx,
377 const br_block_cbcdec_class *bc_impl,
378 const void *bc_key, size_t bc_key_len,
379 const br_hash_class *dig_impl,
380 const void *mac_key, size_t mac_key_len, size_t mac_out_len,
381 const void *iv);
382 };
383
384 /**
385 * \brief Record encryption engine class, for CBC mode.
386 *
387 * This class type extends the encryption engine class with an
388 * initialisation method that receives the parameters needed
389 * for CBC processing: block cipher implementation, block cipher key,
390 * HMAC parameters (hash function, key, MAC length), and IV. If the
391 * IV is `NULL`, then a per-record IV will be used (TLS 1.1+).
392 */
393 typedef struct br_sslrec_out_cbc_class_ br_sslrec_out_cbc_class;
394 struct br_sslrec_out_cbc_class_ {
395 /**
396 * \brief Superclass, as first vtable field.
397 */
398 br_sslrec_out_class inner;
399
400 /**
401 * \brief Engine initialisation method.
402 *
403 * This method sets the vtable field in the context.
404 *
405 * \param ctx context to initialise.
406 * \param bc_impl block cipher implementation (CBC encryption).
407 * \param bc_key block cipher key.
408 * \param bc_key_len block cipher key length (in bytes).
409 * \param dig_impl hash function for HMAC.
410 * \param mac_key HMAC key.
411 * \param mac_key_len HMAC key length (in bytes).
412 * \param mac_out_len HMAC output length (in bytes).
413 * \param iv initial IV (or `NULL`).
414 */
415 void (*init)(const br_sslrec_out_cbc_class **ctx,
416 const br_block_cbcenc_class *bc_impl,
417 const void *bc_key, size_t bc_key_len,
418 const br_hash_class *dig_impl,
419 const void *mac_key, size_t mac_key_len, size_t mac_out_len,
420 const void *iv);
421 };
422
423 /**
424 * \brief Context structure for decrypting incoming records with
425 * CBC + HMAC.
426 *
427 * The first field points to the vtable. The other fields are opaque
428 * and shall not be accessed directly.
429 */
430 typedef struct {
431 /** \brief Pointer to vtable. */
432 const br_sslrec_in_cbc_class *vtable;
433 #ifndef BR_DOXYGEN_IGNORE
434 uint64_t seq;
435 union {
436 const br_block_cbcdec_class *vtable;
437 br_aes_gen_cbcdec_keys aes;
438 br_des_gen_cbcdec_keys des;
439 } bc;
440 br_hmac_key_context mac;
441 size_t mac_len;
442 unsigned char iv[16];
443 int explicit_IV;
444 #endif
445 } br_sslrec_in_cbc_context;
446
447 /**
448 * \brief Static, constant vtable for record decryption with CBC.
449 */
450 extern const br_sslrec_in_cbc_class br_sslrec_in_cbc_vtable;
451
452 /**
453 * \brief Context structure for encrypting outgoing records with
454 * CBC + HMAC.
455 *
456 * The first field points to the vtable. The other fields are opaque
457 * and shall not be accessed directly.
458 */
459 typedef struct {
460 /** \brief Pointer to vtable. */
461 const br_sslrec_out_cbc_class *vtable;
462 #ifndef BR_DOXYGEN_IGNORE
463 uint64_t seq;
464 union {
465 const br_block_cbcenc_class *vtable;
466 br_aes_gen_cbcenc_keys aes;
467 br_des_gen_cbcenc_keys des;
468 } bc;
469 br_hmac_key_context mac;
470 size_t mac_len;
471 unsigned char iv[16];
472 int explicit_IV;
473 #endif
474 } br_sslrec_out_cbc_context;
475
476 /**
477 * \brief Static, constant vtable for record encryption with CBC.
478 */
479 extern const br_sslrec_out_cbc_class br_sslrec_out_cbc_vtable;
480
481 /* ===================================================================== */
482
483 /**
484 * \brief Record decryption engine class, for GCM mode.
485 *
486 * This class type extends the decryption engine class with an
487 * initialisation method that receives the parameters needed
488 * for GCM processing: block cipher implementation, block cipher key,
489 * GHASH implementtion, and 4-byte IV.
490 */
491 typedef struct br_sslrec_in_gcm_class_ br_sslrec_in_gcm_class;
492 struct br_sslrec_in_gcm_class_ {
493 /**
494 * \brief Superclass, as first vtable field.
495 */
496 br_sslrec_in_class inner;
497
498 /**
499 * \brief Engine initialisation method.
500 *
501 * This method sets the vtable field in the context.
502 *
503 * \param ctx context to initialise.
504 * \param bc_impl block cipher implementation (CTR).
505 * \param key block cipher key.
506 * \param key_len block cipher key length (in bytes).
507 * \param gh_impl GHASH implementation.
508 * \param iv static IV (4 bytes).
509 */
510 void (*init)(const br_sslrec_in_gcm_class **ctx,
511 const br_block_ctr_class *bc_impl,
512 const void *key, size_t key_len,
513 br_ghash gh_impl,
514 const void *iv);
515 };
516
517 /**
518 * \brief Record decryption engine class, for GCM mode.
519 *
520 * This class type extends the decryption engine class with an
521 * initialisation method that receives the parameters needed
522 * for GCM processing: block cipher implementation, block cipher key,
523 * GHASH implementtion, and 4-byte IV.
524 */
525 typedef struct br_sslrec_out_gcm_class_ br_sslrec_out_gcm_class;
526 struct br_sslrec_out_gcm_class_ {
527 /**
528 * \brief Superclass, as first vtable field.
529 */
530 br_sslrec_out_class inner;
531
532 /**
533 * \brief Engine initialisation method.
534 *
535 * This method sets the vtable field in the context.
536 *
537 * \param ctx context to initialise.
538 * \param bc_impl block cipher implementation (CTR).
539 * \param key block cipher key.
540 * \param key_len block cipher key length (in bytes).
541 * \param gh_impl GHASH implementation.
542 * \param iv static IV (4 bytes).
543 */
544 void (*init)(const br_sslrec_out_gcm_class **ctx,
545 const br_block_ctr_class *bc_impl,
546 const void *key, size_t key_len,
547 br_ghash gh_impl,
548 const void *iv);
549 };
550
551 /**
552 * \brief Context structure for processing records with GCM.
553 *
554 * The same context structure is used for encrypting and decrypting.
555 *
556 * The first field points to the vtable. The other fields are opaque
557 * and shall not be accessed directly.
558 */
559 typedef struct {
560 /** \brief Pointer to vtable. */
561 union {
562 const void *gen;
563 const br_sslrec_in_gcm_class *in;
564 const br_sslrec_out_gcm_class *out;
565 } vtable;
566 #ifndef BR_DOXYGEN_IGNORE
567 uint64_t seq;
568 union {
569 const br_block_ctr_class *vtable;
570 br_aes_gen_ctr_keys aes;
571 } bc;
572 br_ghash gh;
573 unsigned char iv[4];
574 unsigned char h[16];
575 #endif
576 } br_sslrec_gcm_context;
577
578 /**
579 * \brief Static, constant vtable for record decryption with GCM.
580 */
581 extern const br_sslrec_in_gcm_class br_sslrec_in_gcm_vtable;
582
583 /**
584 * \brief Static, constant vtable for record encryption with GCM.
585 */
586 extern const br_sslrec_out_gcm_class br_sslrec_out_gcm_vtable;
587
588 /* ===================================================================== */
589
590 /**
591 * \brief Type for session parameters, to be saved for session resumption.
592 */
593 typedef struct {
594 /** \brief Session ID buffer. */
595 unsigned char session_id[32];
596 /** \brief Session ID length (in bytes, at most 32). */
597 unsigned char session_id_len;
598 /** \brief Protocol version. */
599 uint16_t version;
600 /** \brief Cipher suite. */
601 uint16_t cipher_suite;
602 /** \brief Master secret. */
603 unsigned char master_secret[48];
604 } br_ssl_session_parameters;
605
606 #ifndef BR_DOXYGEN_IGNORE
607 /*
608 * Maximum numnber of cipher suites supported by a client or server.
609 */
610 #define BR_MAX_CIPHER_SUITES 40
611 #endif
612
613 /**
614 * \brief Context structure for SSL engine.
615 *
616 * This strucuture is common to the client and server; both the client
617 * context (`br_ssl_client_context`) and the server context
618 * (`br_ssl_server_context`) include a `br_ssl_engine_context` as their
619 * first field.
620 *
621 * The engine context manages records, including alerts, closures, and
622 * transitions to new encryption/MAC algorithms. Processing of handshake
623 * records is delegated to externally provided code. This structure
624 * should not be used directly.
625 *
626 * Structure contents are opaque and shall not be accessed directly.
627 */
628 typedef struct {
629 #ifndef BR_DOXYGEN_IGNORE
630 /*
631 * The error code. When non-zero, then the state is "failed" and
632 * no I/O may occur until reset.
633 */
634 int err;
635
636 /*
637 * Configured I/O buffers. They are either disjoint, or identical.
638 */
639 unsigned char *ibuf, *obuf;
640 size_t ibuf_len, obuf_len;
641
642 /*
643 * Maximum fragment length applies to outgoing records; incoming
644 * records can be processed as long as they fit in the input
645 * buffer. It is guaranteed that incoming records at least as big
646 * as max_frag_len can be processed.
647 */
648 uint16_t max_frag_len;
649 unsigned char log_max_frag_len;
650 unsigned char peer_log_max_frag_len;
651
652 /*
653 * Buffering management registers.
654 */
655 size_t ixa, ixb, ixc;
656 size_t oxa, oxb, oxc;
657 unsigned char iomode;
658 unsigned char incrypt;
659
660 /*
661 * Shutdown flag: when set to non-zero, incoming record bytes
662 * will not be accepted anymore. This is used after a close_notify
663 * has been received: afterwards, the engine no longer claims that
664 * it could receive bytes from the transport medium.
665 */
666 unsigned char shutdown_recv;
667
668 /*
669 * 'record_type_in' is set to the incoming record type when the
670 * record header has been received.
671 * 'record_type_out' is used to make the next outgoing record
672 * header when it is ready to go.
673 */
674 unsigned char record_type_in, record_type_out;
675
676 /*
677 * When a record is received, its version is extracted:
678 * -- if 'version_in' is 0, then it is set to the received version;
679 * -- otherwise, if the received version is not identical to
680 * the 'version_in' contents, then a failure is reported.
681 *
682 * This implements the SSL requirement that all records shall
683 * use the negotiated protocol version, once decided (in the
684 * ServerHello). It is up to the handshake handler to adjust this
685 * field when necessary.
686 */
687 uint16_t version_in;
688
689 /*
690 * 'version_out' is used when the next outgoing record is ready
691 * to go.
692 */
693 uint16_t version_out;
694
695 /*
696 * Record handler contexts.
697 */
698 union {
699 const br_sslrec_in_class *vtable;
700 br_sslrec_in_cbc_context cbc;
701 br_sslrec_gcm_context gcm;
702 } in;
703 union {
704 const br_sslrec_out_class *vtable;
705 br_sslrec_out_clear_context clear;
706 br_sslrec_out_cbc_context cbc;
707 br_sslrec_gcm_context gcm;
708 } out;
709
710 /*
711 * The "application data" flag. It is set when application data
712 * can be exchanged, cleared otherwise.
713 */
714 unsigned char application_data;
715
716 /*
717 * Context RNG.
718 */
719 br_hmac_drbg_context rng;
720 int rng_init_done;
721 int rng_os_rand_done;
722
723 /*
724 * Supported minimum and maximum versions, and cipher suites.
725 */
726 uint16_t version_min;
727 uint16_t version_max;
728 uint16_t suites_buf[BR_MAX_CIPHER_SUITES];
729 unsigned char suites_num;
730
731 /*
732 * For clients, the server name to send as a SNI extension. For
733 * servers, the name received in the SNI extension (if any).
734 */
735 char server_name[256];
736
737 /*
738 * "Security parameters". These are filled by the handshake
739 * handler, and used when switching encryption state.
740 */
741 unsigned char client_random[32];
742 unsigned char server_random[32];
743 br_ssl_session_parameters session;
744
745 /*
746 * ECDHE elements: curve and point from the peer. The server also
747 * uses that buffer for the point to send to the client.
748 */
749 unsigned char ecdhe_curve;
750 unsigned char ecdhe_point[133];
751 unsigned char ecdhe_point_len;
752
753 /*
754 * Secure renegotiation (RFC 5746): 'reneg' can be:
755 * 0 first handshake (server support is not known)
756 * 1 server does not support secure renegotiation
757 * 2 server supports secure renegotiation
758 *
759 * The saved_finished buffer contains the client and the
760 * server "Finished" values from the last handshake, in
761 * that order (12 bytes each).
762 */
763 unsigned char reneg;
764 unsigned char saved_finished[24];
765
766 /*
767 * Behavioural flags.
768 */
769 uint32_t flags;
770
771 /*
772 * Context variables for the handshake processor.
773 * The 'pad' must be large enough to accommodate an
774 * RSA-encrypted pre-master secret, or a RSA signature on
775 * key exchange parameters; since we want to support up to
776 * RSA-4096, this means at least 512 bytes.
777 * (Other pad usages require its length to be at least 256.)
778 */
779 struct {
780 uint32_t *dp;
781 uint32_t *rp;
782 const unsigned char *ip;
783 } cpu;
784 uint32_t dp_stack[32];
785 uint32_t rp_stack[32];
786 unsigned char pad[512];
787 unsigned char *hbuf_in, *hbuf_out, *saved_hbuf_out;
788 size_t hlen_in, hlen_out;
789 void (*hsrun)(void *ctx);
790
791 /*
792 * The 'action' value communicates OOB information between the
793 * engine and the handshake processor.
794 *
795 * From the engine:
796 * 0 invocation triggered by I/O
797 * 1 invocation triggered by explicit close
798 * 2 invocation triggered by explicit renegotiation
799 */
800 unsigned char action;
801
802 /*
803 * State for alert messages. Value is either 0, or the value of
804 * the alert level byte (level is either 1 for warning, or 2 for
805 * fatal; we convert all other values to 'fatal').
806 */
807 unsigned char alert;
808
809 /*
810 * Closure flags. This flag is set when a close_notify has been
811 * received from the peer.
812 */
813 unsigned char close_received;
814
815 /*
816 * Multi-hasher for the handshake messages. The handshake handler
817 * is responsible for resetting it when appropriate.
818 */
819 br_multihash_context mhash;
820
821 /*
822 * Pointer to the X.509 engine. The engine is supposed to be
823 * already initialized. It is used to validate the peer's
824 * certificate.
825 */
826 const br_x509_class **x509ctx;
827
828 /*
829 * Pointers to implementations; left to NULL for unsupported
830 * functions. For the raw hash functions, implementations are
831 * referenced from the multihasher (mhash field).
832 */
833 br_tls_prf_impl prf10;
834 br_tls_prf_impl prf_sha256;
835 br_tls_prf_impl prf_sha384;
836 const br_block_cbcenc_class *iaes_cbcenc;
837 const br_block_cbcdec_class *iaes_cbcdec;
838 const br_block_ctr_class *iaes_ctr;
839 const br_block_cbcenc_class *ides_cbcenc;
840 const br_block_cbcdec_class *ides_cbcdec;
841 br_ghash ighash;
842 const br_sslrec_in_cbc_class *icbc_in;
843 const br_sslrec_out_cbc_class *icbc_out;
844 const br_sslrec_in_gcm_class *igcm_in;
845 const br_sslrec_out_gcm_class *igcm_out;
846 const br_ec_impl *iec;
847 #endif
848 } br_ssl_engine_context;
849
850 /**
851 * \brief Get currently defined engine behavioural flags.
852 *
853 * \param cc SSL engine context.
854 * \return the flags.
855 */
856 static inline uint32_t
857 br_ssl_engine_get_flags(br_ssl_engine_context *cc)
858 {
859 return cc->flags;
860 }
861
862 /**
863 * \brief Set all engine behavioural flags.
864 *
865 * \param cc SSL engine context.
866 * \param flags new value for all flags.
867 */
868 static inline void
869 br_ssl_engine_set_all_flags(br_ssl_engine_context *cc, uint32_t flags)
870 {
871 cc->flags = flags;
872 }
873
874 /**
875 * \brief Set some engine behavioural flags.
876 *
877 * The flags set in the `flags` parameter are set in the context; other
878 * flags are untouched.
879 *
880 * \param cc SSL engine context.
881 * \param flags additional set flags.
882 */
883 static inline void
884 br_ssl_engine_add_flags(br_ssl_engine_context *cc, uint32_t flags)
885 {
886 cc->flags |= flags;
887 }
888
889 /**
890 * \brief Clear some engine behavioural flags.
891 *
892 * The flags set in the `flags` parameter are cleared from the context; other
893 * flags are untouched.
894 *
895 * \param cc SSL engine context.
896 * \param flags flags to remove.
897 */
898 static inline void
899 br_ssl_engine_remove_flags(br_ssl_engine_context *cc, uint32_t flags)
900 {
901 cc->flags &= ~flags;
902 }
903
904 /**
905 * \brief Behavioural flag: enforce server preferences.
906 *
907 * If this flag is set, then the server will enforce its own cipher suite
908 * preference order; otherwise, it follows the client preferences.
909 */
910 #define BR_OPT_ENFORCE_SERVER_PREFERENCES ((uint32_t)1 << 0)
911
912 /*
913 * \brief Behavioural flag: disable renegotiation.
914 *
915 * If this flag is set, then renegotiations are rejected unconditionally:
916 * they won't be honoured if asked for programmatically, and requests from
917 * the peer are rejected.
918 */
919 #define BR_OPT_NO_RENEGOTIATION ((uint32_t)1 << 1)
920
921 /**
922 * \brief Set the minimum and maximum supported protocol versions.
923 *
924 * The two provided versions MUST be supported by the implementation
925 * (i.e. TLS 1.0, 1.1 and 1.2), and `version_max` MUST NOT be lower
926 * than `version_min`.
927 *
928 * \param cc SSL engine context.
929 * \param version_min minimum supported TLS version.
930 * \param version_max maximum supported TLS version.
931 */
932 static inline void
933 br_ssl_engine_set_versions(br_ssl_engine_context *cc,
934 unsigned version_min, unsigned version_max)
935 {
936 cc->version_min = version_min;
937 cc->version_max = version_max;
938 }
939
940 /**
941 * \brief Set the list of cipher suites advertised by this context.
942 *
943 * The provided array is copied into the context. It is the caller
944 * responsibility to ensure that all provided suites will be supported
945 * by the context. The engine context has enough room to receive _all_
946 * suites supported by the implementation. The provided array MUST NOT
947 * contain duplicates.
948 *
949 * If the engine is for a client, the "signaling" pseudo-cipher suite
950 * `TLS_FALLBACK_SCSV` can be added at the end of the list, if the
951 * calling application is performing a voluntary downgrade (voluntary
952 * downgrades are not recommended, but if such a downgrade is done, then
953 * adding the fallback pseudo-suite is a good idea).
954 *
955 * \param cc SSL engine context.
956 * \param suites cipher suites.
957 * \param suites_num number of cipher suites.
958 */
959 void br_ssl_engine_set_suites(br_ssl_engine_context *cc,
960 const uint16_t *suites, size_t suites_num);
961
962 /**
963 * \brief Set the X.509 engine.
964 *
965 * The caller shall ensure that the X.509 engine is properly initialised.
966 *
967 * \param cc SSL engine context.
968 * \param x509ctx X.509 certificate validation context.
969 */
970 static inline void
971 br_ssl_engine_set_x509(br_ssl_engine_context *cc, const br_x509_class **x509ctx)
972 {
973 cc->x509ctx = x509ctx;
974 }
975
976 /**
977 * \brief Set a hash function implementation (by ID).
978 *
979 * Hash functions set with this call will be used for SSL/TLS specific
980 * usages, not X.509 certificate validation. Only "standard" hash functions
981 * may be set (MD5, SHA-1, SHA-224, SHA-256, SHA-384, SHA-512). If `impl`
982 * is `NULL`, then the hash function support is removed, not added.
983 *
984 * \param ctx SSL engine context.
985 * \param id hash function identifier.
986 * \param impl hash function implementation (or `NULL`).
987 */
988 static inline void
989 br_ssl_engine_set_hash(br_ssl_engine_context *ctx,
990 int id, const br_hash_class *impl)
991 {
992 br_multihash_setimpl(&ctx->mhash, id, impl);
993 }
994
995 /**
996 * \brief Get a hash function implementation (by ID).
997 *
998 * This function retrieves a hash function implementation which was
999 * set with `br_ssl_engine_set_hash()`.
1000 *
1001 * \param ctx SSL engine context.
1002 * \param id hash function identifier.
1003 * \return the hash function implementation (or `NULL`).
1004 */
1005 static inline const br_hash_class *
1006 br_ssl_engine_get_hash(br_ssl_engine_context *ctx, int id)
1007 {
1008 return br_multihash_getimpl(&ctx->mhash, id);
1009 }
1010
1011 /**
1012 * \brief Set the PRF implementation (for TLS 1.0 and 1.1).
1013 *
1014 * This function sets (or removes, if `impl` is `NULL`) the implemenation
1015 * for the PRF used in TLS 1.0 and 1.1.
1016 *
1017 * \param cc SSL engine context.
1018 * \param impl PRF implementation (or `NULL`).
1019 */
1020 static inline void
1021 br_ssl_engine_set_prf10(br_ssl_engine_context *cc, br_tls_prf_impl impl)
1022 {
1023 cc->prf10 = impl;
1024 }
1025
1026 /**
1027 * \brief Set the PRF implementation with SHA-256 (for TLS 1.2).
1028 *
1029 * This function sets (or removes, if `impl` is `NULL`) the implemenation
1030 * for the SHA-256 variant of the PRF used in TLS 1.2.
1031 *
1032 * \param cc SSL engine context.
1033 * \param impl PRF implementation (or `NULL`).
1034 */
1035 static inline void
1036 br_ssl_engine_set_prf_sha256(br_ssl_engine_context *cc, br_tls_prf_impl impl)
1037 {
1038 cc->prf_sha256 = impl;
1039 }
1040
1041 /**
1042 * \brief Set the PRF implementation with SHA-384 (for TLS 1.2).
1043 *
1044 * This function sets (or removes, if `impl` is `NULL`) the implemenation
1045 * for the SHA-384 variant of the PRF used in TLS 1.2.
1046 *
1047 * \param cc SSL engine context.
1048 * \param impl PRF implementation (or `NULL`).
1049 */
1050 static inline void
1051 br_ssl_engine_set_prf_sha384(br_ssl_engine_context *cc, br_tls_prf_impl impl)
1052 {
1053 cc->prf_sha384 = impl;
1054 }
1055
1056 /**
1057 * \brief Set the AES/CBC implementations.
1058 *
1059 * \param cc SSL engine context.
1060 * \param impl_enc AES/CBC encryption implementation (or `NULL`).
1061 * \param impl_dec AES/CBC decryption implementation (or `NULL`).
1062 */
1063 static inline void
1064 br_ssl_engine_set_aes_cbc(br_ssl_engine_context *cc,
1065 const br_block_cbcenc_class *impl_enc,
1066 const br_block_cbcdec_class *impl_dec)
1067 {
1068 cc->iaes_cbcenc = impl_enc;
1069 cc->iaes_cbcdec = impl_dec;
1070 }
1071
1072 /**
1073 * \brief Set the AES/CTR implementation.
1074 *
1075 * \param cc SSL engine context.
1076 * \param impl AES/CTR encryption/decryption implementation (or `NULL`).
1077 */
1078 static inline void
1079 br_ssl_engine_set_aes_ctr(br_ssl_engine_context *cc,
1080 const br_block_ctr_class *impl)
1081 {
1082 cc->iaes_ctr = impl;
1083 }
1084
1085 /**
1086 * \brief Set the DES/CBC implementations.
1087 *
1088 * \param cc SSL engine context.
1089 * \param impl_enc DES/CBC encryption implementation (or `NULL`).
1090 * \param impl_dec DES/CBC decryption implementation (or `NULL`).
1091 */
1092 static inline void
1093 br_ssl_engine_set_des_cbc(br_ssl_engine_context *cc,
1094 const br_block_cbcenc_class *impl_enc,
1095 const br_block_cbcdec_class *impl_dec)
1096 {
1097 cc->ides_cbcenc = impl_enc;
1098 cc->ides_cbcdec = impl_dec;
1099 }
1100
1101 /**
1102 * \brief Set the GHASH implementation (used in GCM mode).
1103 *
1104 * \param cc SSL engine context.
1105 * \param impl GHASH implementation (or `NULL`).
1106 */
1107 static inline void
1108 br_ssl_engine_set_ghash(br_ssl_engine_context *cc, br_ghash impl)
1109 {
1110 cc->ighash = impl;
1111 }
1112
1113 /**
1114 * \brief Set the record encryption and decryption engines for CBC + HMAC.
1115 *
1116 * \param cc SSL engine context.
1117 * \param impl_in record CBC decryption implementation (or `NULL`).
1118 * \param impl_out record CBC encryption implementation (or `NULL`).
1119 */
1120 static inline void
1121 br_ssl_engine_set_cbc(br_ssl_engine_context *cc,
1122 const br_sslrec_in_cbc_class *impl_in,
1123 const br_sslrec_out_cbc_class *impl_out)
1124 {
1125 cc->icbc_in = impl_in;
1126 cc->icbc_out = impl_out;
1127 }
1128
1129 /**
1130 * \brief Set the record encryption and decryption engines for GCM.
1131 *
1132 * \param cc SSL engine context.
1133 * \param impl_in record GCM decryption implementation (or `NULL`).
1134 * \param impl_out record GCM encryption implementation (or `NULL`).
1135 */
1136 static inline void
1137 br_ssl_engine_set_gcm(br_ssl_engine_context *cc,
1138 const br_sslrec_in_gcm_class *impl_in,
1139 const br_sslrec_out_gcm_class *impl_out)
1140 {
1141 cc->igcm_in = impl_in;
1142 cc->igcm_out = impl_out;
1143 }
1144
1145 /**
1146 * \brief Set the EC implementation.
1147 *
1148 * The elliptic curve implementation will be used for ECDH and ECDHE
1149 * cipher suites, and for ECDSA support.
1150 *
1151 * \param cc SSL engine context.
1152 * \param iec EC implementation (or `NULL`).
1153 */
1154 static inline void
1155 br_ssl_engine_set_ec(br_ssl_engine_context *cc, const br_ec_impl *iec)
1156 {
1157 cc->iec = iec;
1158 }
1159
1160 /**
1161 * \brief Set the I/O buffer for the SSL engine.
1162 *
1163 * Once this call has been made, `br_ssl_client_reset()` or
1164 * `br_ssl_server_reset()` MUST be called before using the context.
1165 *
1166 * The provided buffer will be used as long as the engine context is
1167 * used. The caller is responsible for keeping it available.
1168 *
1169 * If `bidi` is 0, then the engine will operate in half-duplex mode
1170 * (it won't be able to send data while there is unprocessed incoming
1171 * data in the buffer, and it won't be able to receive data while there
1172 * is unsent data in the buffer). The optimal buffer size in half-duplex
1173 * mode is `BR_SSL_BUFSIZE_MONO`; if the buffer is larger, then extra
1174 * bytes are ignored. If the buffer is smaller, then this limits the
1175 * capacity of the engine to support all allowed record sizes.
1176 *
1177 * If `bidi` is 1, then the engine will split the buffer into two
1178 * parts, for separate handling of outgoing and incoming data. This
1179 * enables full-duplex processing, but requires more RAM. The optimal
1180 * buffer size in full-duplex mode is `BR_SSL_BUFSIZE_BIDI`; if the
1181 * buffer is larger, then extra bytes are ignored. If the buffer is
1182 * smaller, then the split will favour the incoming part, so that
1183 * interoperability is maximised.
1184 *
1185 * \param cc SSL engine context
1186 * \param iobuf I/O buffer.
1187 * \param iobuf_len I/O buffer length (in bytes).
1188 * \param bidi non-zero for full-duplex mode.
1189 */
1190 void br_ssl_engine_set_buffer(br_ssl_engine_context *cc,
1191 void *iobuf, size_t iobuf_len, int bidi);
1192
1193 /**
1194 * \brief Set the I/O buffers for the SSL engine.
1195 *
1196 * Once this call has been made, `br_ssl_client_reset()` or
1197 * `br_ssl_server_reset()` MUST be called before using the context.
1198 *
1199 * This function is similar to `br_ssl_engine_set_buffer()`, except
1200 * that it enforces full-duplex mode, and the two I/O buffers are
1201 * provided as separate chunks.
1202 *
1203 * The macros `BR_SSL_BUFSIZE_INPUT` and `BR_SSL_BUFSIZE_OUTPUT`
1204 * evaluate to the optimal (maximum) sizes for the input and output
1205 * buffer, respectively.
1206 *
1207 * \param cc SSL engine context
1208 * \param ibuf input buffer.
1209 * \param ibuf_len input buffer length (in bytes).
1210 * \param obuf output buffer.
1211 * \param obuf_len output buffer length (in bytes).
1212 */
1213 void br_ssl_engine_set_buffers_bidi(br_ssl_engine_context *cc,
1214 void *ibuf, size_t ibuf_len, void *obuf, size_t obuf_len);
1215
1216 /**
1217 * \brief Inject some "initial entropy" in the context.
1218 *
1219 * This entropy will be added to what can be obtained from the
1220 * underlying operating system, if that OS is supported.
1221 *
1222 * This function may be called several times; all injected entropy chunks
1223 * are cumulatively mixed.
1224 *
1225 * If entropy gathering from the OS is supported and compiled in, then this
1226 * step is optional. Otherwise, it is mandatory to inject randomness, and
1227 * the caller MUST take care to push (as one or several successive calls)
1228 * enough entropy to achieve cryptographic resistance (at least 80 bits,
1229 * preferably 128 or more). The engine will report an error if no entropy
1230 * was provided and none can be obtained from the OS.
1231 *
1232 * Take care that this function cannot assess the cryptographic quality of
1233 * the provided bytes.
1234 *
1235 * In all generality, "entropy" must here be considered to mean "that
1236 * which the attacker cannot predict". If your OS/architecture does not
1237 * have a suitable source of randomness, then you can make do with the
1238 * combination of a large enough secret value (possibly a copy of an
1239 * asymmetric private key that you also store on the system) AND a
1240 * non-repeating value (e.g. current time, provided that the local clock
1241 * cannot be reset or altered by the attacker).
1242 *
1243 * \param cc SSL engine context.
1244 * \param data extra entropy to inject.
1245 * \param len length of the extra data (in bytes).
1246 */
1247 void br_ssl_engine_inject_entropy(br_ssl_engine_context *cc,
1248 const void *data, size_t len);
1249
1250 /**
1251 * \brief Get the "server name" in this engine.
1252 *
1253 * For clients, this is the name provided with `br_ssl_client_reset()`;
1254 * for servers, this is the name received from the client as part of the
1255 * ClientHello message. If there is no such name (e.g. the client did
1256 * not send an SNI extension) then the returned string is empty
1257 * (returned pointer points to a byte of value 0).
1258 *
1259 * The returned pointer refers to a buffer inside the context, which may
1260 * be overwritten as part of normal SSL activity (even within the same
1261 * connection, if a renegotiation occurs).
1262 *
1263 * \param cc SSL engine context.
1264 * \return the server name (possibly empty).
1265 */
1266 static inline const char *
1267 br_ssl_engine_get_server_name(const br_ssl_engine_context *cc)
1268 {
1269 return cc->server_name;
1270 }
1271
1272 /**
1273 * \brief Get the protocol version.
1274 *
1275 * This function returns the protocol version that is used by the
1276 * engine. That value is set after sending (for a server) or receiving
1277 * (for a client) the ServerHello message.
1278 *
1279 * \param cc SSL engine context.
1280 * \return the protocol version.
1281 */
1282 static inline unsigned
1283 br_ssl_engine_get_version(const br_ssl_engine_context *cc)
1284 {
1285 return cc->session.version;
1286 }
1287
1288 /**
1289 * \brief Get a copy of the session parameters.
1290 *
1291 * The session parameters are filled during the handshake, so this
1292 * function shall not be called before completion of the handshake.
1293 * The initial handshake is completed when the context first allows
1294 * application data to be injected.
1295 *
1296 * This function copies the current session parameters into the provided
1297 * structure. Beware that the session parameters include the master
1298 * secret, which is sensitive data, to handle with great care.
1299 *
1300 * \param cc SSL engine context.
1301 * \param pp destination structure for the session parameters.
1302 */
1303 static inline void
1304 br_ssl_engine_get_session_parameters(const br_ssl_engine_context *cc,
1305 br_ssl_session_parameters *pp)
1306 {
1307 memcpy(pp, &cc->session, sizeof *pp);
1308 }
1309
1310 /**
1311 * \brief Set the session parameters to the provided values.
1312 *
1313 * This function is meant to be used in the client, before doing a new
1314 * handshake; a session resumption will be attempted with these
1315 * parameters. In the server, this function has no effect.
1316 *
1317 * \param cc SSL engine context.
1318 * \param pp source structure for the session parameters.
1319 */
1320 static inline void
1321 br_ssl_engine_set_session_parameters(br_ssl_engine_context *cc,
1322 const br_ssl_session_parameters *pp)
1323 {
1324 memcpy(&cc->session, pp, sizeof *pp);
1325 }
1326
1327 /**
1328 * \brief Get the current engine state.
1329 *
1330 * An SSL engine (client or server) has, at any time, a state which is
1331 * the combination of zero, one or more of these flags:
1332 *
1333 * - `BR_SSL_CLOSED`
1334 *
1335 * Engine is finished, no more I/O (until next reset).
1336 *
1337 * - `BR_SSL_SENDREC`
1338 *
1339 * Engine has some bytes to send to the peer.
1340 *
1341 * - `BR_SSL_RECVREC`
1342 *
1343 * Engine expects some bytes from the peer.
1344 *
1345 * - `BR_SSL_SENDAPP`
1346 *
1347 * Engine may receive application data to send (or flush).
1348 *
1349 * - `BR_SSL_RECVAPP`
1350 *
1351 * Engine has obtained some application data from the peer,
1352 * that should be read by the caller.
1353 *
1354 * If no flag at all is set (state value is 0), then the engine is not
1355 * fully initialised yet.
1356 *
1357 * The `BR_SSL_CLOSED` flag is exclusive; when it is set, no other flag
1358 * is set. To distinguish between a normal closure and an error, use
1359 * `br_ssl_engine_last_error()`.
1360 *
1361 * Generally speaking, `BR_SSL_SENDREC` and `BR_SSL_SENDAPP` are mutually
1362 * exclusive: the input buffer, at any point, either accumulates
1363 * plaintext data, or contains an assembled record that is being sent.
1364 * Similarly, `BR_SSL_RECVREC` and `BR_SSL_RECVAPP` are mutually exclusive.
1365 * This may change in a future library version.
1366 *
1367 * \param cc SSL engine context.
1368 * \return the current engine state.
1369 */
1370 unsigned br_ssl_engine_current_state(const br_ssl_engine_context *cc);
1371
1372 /** \brief SSL engine state: closed or failed. */
1373 #define BR_SSL_CLOSED 0x0001
1374 /** \brief SSL engine state: record data is ready to be sent to the peer. */
1375 #define BR_SSL_SENDREC 0x0002
1376 /** \brief SSL engine state: engine may receive records from the peer. */
1377 #define BR_SSL_RECVREC 0x0004
1378 /** \brief SSL engine state: engine may accept application data to send. */
1379 #define BR_SSL_SENDAPP 0x0008
1380 /** \brief SSL engine state: engine has received application data. */
1381 #define BR_SSL_RECVAPP 0x0010
1382
1383 /**
1384 * \brief Get the engine error indicator.
1385 *
1386 * The error indicator is `BR_ERR_OK` (0) if no error was encountered
1387 * since the last call to `br_ssl_client_reset()` or
1388 * `br_ssl_server_reset()`. Other status values are "sticky": they
1389 * remain set, and prevent all I/O activity, until cleared. Only the
1390 * reset calls clear the error indicator.
1391 *
1392 * \param cc SSL engine context.
1393 * \return 0, or a non-zero error code.
1394 */
1395 static inline int
1396 br_ssl_engine_last_error(const br_ssl_engine_context *cc)
1397 {
1398 return cc->err;
1399 }
1400
1401 /*
1402 * There are four I/O operations, each identified by a symbolic name:
1403 *
1404 * sendapp inject application data in the engine
1405 * recvapp retrieving application data from the engine
1406 * sendrec sending records on the transport medium
1407 * recvrec receiving records from the transport medium
1408 *
1409 * Terminology works thus: in a layered model where the SSL engine sits
1410 * between the application and the network, "send" designates operations
1411 * where bytes flow from application to network, and "recv" for the
1412 * reverse operation. Application data (the plaintext that is to be
1413 * conveyed through SSL) is "app", while encrypted records are "rec".
1414 * Note that from the SSL engine point of view, "sendapp" and "recvrec"
1415 * designate bytes that enter the engine ("inject" operation), while
1416 * "recvapp" and "sendrec" designate bytes that exit the engine
1417 * ("extract" operation).
1418 *
1419 * For the operation 'xxx', two functions are defined:
1420 *
1421 * br_ssl_engine_xxx_buf
1422 * Returns a pointer and length to the buffer to use for that
1423 * operation. '*len' is set to the number of bytes that may be read
1424 * from the buffer (extract operation) or written to the buffer
1425 * (inject operation). If no byte may be exchanged for that operation
1426 * at that point, then '*len' is set to zero, and NULL is returned.
1427 * The engine state is unmodified by this call.
1428 *
1429 * br_ssl_engine_xxx_ack
1430 * Informs the engine that 'len' bytes have been read from the buffer
1431 * (extract operation) or written to the buffer (inject operation).
1432 * The 'len' value MUST NOT be zero. The 'len' value MUST NOT exceed
1433 * that which was obtained from a preceeding br_ssl_engine_xxx_buf()
1434 * call.
1435 */
1436
1437 /**
1438 * \brief Get buffer for application data to send.
1439 *
1440 * If the engine is ready to accept application data to send to the
1441 * peer, then this call returns a pointer to the buffer where such
1442 * data shall be written, and its length is written in `*len`.
1443 * Otherwise, `*len` is set to 0 and `NULL` is returned.
1444 *
1445 * \param cc SSL engine context.
1446 * \param len receives the application data output buffer length, or 0.
1447 * \return the application data output buffer, or `NULL`.
1448 */
1449 unsigned char *br_ssl_engine_sendapp_buf(
1450 const br_ssl_engine_context *cc, size_t *len);
1451
1452 /**
1453 * \brief Inform the engine of some new application data.
1454 *
1455 * After writing `len` bytes in the buffer returned by
1456 * `br_ssl_engine_sendapp_buf()`, the application shall call this
1457 * function to trigger any relevant processing. The `len` parameter
1458 * MUST NOT be 0, and MUST NOT exceed the value obtained in the
1459 * `br_ssl_engine_sendapp_buf()` call.
1460 *
1461 * \param cc SSL engine context.
1462 * \param len number of bytes pushed (not zero).
1463 */
1464 void br_ssl_engine_sendapp_ack(br_ssl_engine_context *cc, size_t len);
1465
1466 /**
1467 * \brief Get buffer for received application data.
1468 *
1469 * If the engine has received application data from the peer, hen this
1470 * call returns a pointer to the buffer from where such data shall be
1471 * read, and its length is written in `*len`. Otherwise, `*len` is set
1472 * to 0 and `NULL` is returned.
1473 *
1474 * \param cc SSL engine context.
1475 * \param len receives the application data input buffer length, or 0.
1476 * \return the application data input buffer, or `NULL`.
1477 */
1478 unsigned char *br_ssl_engine_recvapp_buf(
1479 const br_ssl_engine_context *cc, size_t *len);
1480
1481 /**
1482 * \brief Acknowledge some received application data.
1483 *
1484 * After reading `len` bytes from the buffer returned by
1485 * `br_ssl_engine_recvapp_buf()`, the application shall call this
1486 * function to trigger any relevant processing. The `len` parameter
1487 * MUST NOT be 0, and MUST NOT exceed the value obtained in the
1488 * `br_ssl_engine_recvapp_buf()` call.
1489 *
1490 * \param cc SSL engine context.
1491 * \param len number of bytes read (not zero).
1492 */
1493 void br_ssl_engine_recvapp_ack(br_ssl_engine_context *cc, size_t len);
1494
1495 /**
1496 * \brief Get buffer for record data to send.
1497 *
1498 * If the engine has prepared some records to send to the peer, then this
1499 * call returns a pointer to the buffer from where such data shall be
1500 * read, and its length is written in `*len`. Otherwise, `*len` is set
1501 * to 0 and `NULL` is returned.
1502 *
1503 * \param cc SSL engine context.
1504 * \param len receives the record data output buffer length, or 0.
1505 * \return the record data output buffer, or `NULL`.
1506 */
1507 unsigned char *br_ssl_engine_sendrec_buf(
1508 const br_ssl_engine_context *cc, size_t *len);
1509
1510 /**
1511 * \brief Acknowledge some sent record data.
1512 *
1513 * After reading `len` bytes from the buffer returned by
1514 * `br_ssl_engine_sendrec_buf()`, the application shall call this
1515 * function to trigger any relevant processing. The `len` parameter
1516 * MUST NOT be 0, and MUST NOT exceed the value obtained in the
1517 * `br_ssl_engine_sendrec_buf()` call.
1518 *
1519 * \param cc SSL engine context.
1520 * \param len number of bytes read (not zero).
1521 */
1522 void br_ssl_engine_sendrec_ack(br_ssl_engine_context *cc, size_t len);
1523
1524 /**
1525 * \brief Get buffer for incoming records.
1526 *
1527 * If the engine is ready to accept records from the peer, then this
1528 * call returns a pointer to the buffer where such data shall be
1529 * written, and its length is written in `*len`. Otherwise, `*len` is
1530 * set to 0 and `NULL` is returned.
1531 *
1532 * \param cc SSL engine context.
1533 * \param len receives the record data input buffer length, or 0.
1534 * \return the record data input buffer, or `NULL`.
1535 */
1536 unsigned char *br_ssl_engine_recvrec_buf(
1537 const br_ssl_engine_context *cc, size_t *len);
1538
1539 /**
1540 * \brief Inform the engine of some new record data.
1541 *
1542 * After writing `len` bytes in the buffer returned by
1543 * `br_ssl_engine_recvrec_buf()`, the application shall call this
1544 * function to trigger any relevant processing. The `len` parameter
1545 * MUST NOT be 0, and MUST NOT exceed the value obtained in the
1546 * `br_ssl_engine_recvrec_buf()` call.
1547 *
1548 * \param cc SSL engine context.
1549 * \param len number of bytes pushed (not zero).
1550 */
1551 void br_ssl_engine_recvrec_ack(br_ssl_engine_context *cc, size_t len);
1552
1553 /**
1554 * \brief Flush buffered application data.
1555 *
1556 * If some application data has been buffered in the engine, then wrap
1557 * it into a record and mark it for sending. If no application data has
1558 * been buffered but the engine would be ready to accept some, AND the
1559 * `force` parameter is non-zero, then an empty record is assembled and
1560 * marked for sending. In all other cases, this function does nothing.
1561 *
1562 * Empty records are technically legal, but not all existing SSL/TLS
1563 * implementations support them. Empty records can be useful as a
1564 * transparent "keep-alive" mechanism to maintain some low-level
1565 * network activity.
1566 *
1567 * \param cc SSL engine context.
1568 * \param force non-zero to force sending an empty record.
1569 */
1570 void br_ssl_engine_flush(br_ssl_engine_context *cc, int force);
1571
1572 /**
1573 * \brief Initiate a closure.
1574 *
1575 * If, at that point, the context is open and in ready state, then a
1576 * `close_notify` alert is assembled and marked for sending; this
1577 * triggers the closure protocol. Otherwise, no such alert is assembled.
1578 *
1579 * \param cc SSL engine context.
1580 */
1581 void br_ssl_engine_close(br_ssl_engine_context *cc);
1582
1583 /**
1584 * \brief Initiate a renegotiation.
1585 *
1586 * If the engine is failed or closed, or if the peer is known not to
1587 * support secure renegotiation (RFC 5746), or if renegotiations have
1588 * been disabled with the `BR_OPT_NO_RENEGOTIATION` flag, then this
1589 * function returns 0 and nothing else happens.
1590 *
1591 * Otherwise, this function returns 1, and a renegotiation attempt is
1592 * triggered (if a handshake is already ongoing at that point, then
1593 * no new handshake is triggered).
1594 *
1595 * \param cc SSL engine context.
1596 * \return 1 on success, 0 on error.
1597 */
1598 int br_ssl_engine_renegotiate(br_ssl_engine_context *cc);
1599
1600 /**
1601 * \brief Context structure for a SSL client.
1602 *
1603 * The first field (called `eng`) is the SSL engine; all functions that
1604 * work on a `br_ssl_engine_context` structure shall take as parameter
1605 * a pointer to that field. The other structure fields are opaque and
1606 * must not be accessed directly.
1607 */
1608 typedef struct {
1609 /**
1610 * \brief The encapsulated engine context.
1611 */
1612 br_ssl_engine_context eng;
1613
1614 #ifndef BR_DOXYGEN_IGNORE
1615 /*
1616 * Minimum ClientHello length; padding with an extension (RFC
1617 * 7685) is added if necessary to match at least that length.
1618 * Such padding is nominally unnecessary, but it has been used
1619 * to work around some server implementation bugs.
1620 */
1621 uint16_t min_clienthello_len;
1622
1623 /*
1624 * Implementations.
1625 */
1626 br_rsa_public irsapub;
1627 br_rsa_pkcs1_vrfy irsavrfy;
1628 br_ecdsa_vrfy iecdsa;
1629 #endif
1630 } br_ssl_client_context;
1631
1632 /*
1633 * Each br_ssl_client_init_xxx() function sets the list of supported
1634 * cipher suites and used implementations, as specified by the profile
1635 * name 'xxx'. Defined profile names are:
1636 *
1637 * full all supported versions and suites; constant-time implementations
1638 * TODO: add other profiles
1639 */
1640
1641 /**
1642 * \brief SSL client profile: full.
1643 *
1644 * This function initialises the provided SSL client context with
1645 * all supported algorithms and cipher suites. It also initialises
1646 * a companion X.509 validation engine with all supported algorithms,
1647 * and the provided trust anchors; the X.509 engine will be used by
1648 * the client context to validate the server's certificate.
1649 *
1650 * \param cc client context to initialise.
1651 * \param xc X.509 validation context to initialise.
1652 * \param trust_anchors trust anchors to use.
1653 * \param trust_anchors_num number of trust anchors.
1654 */
1655 void br_ssl_client_init_full(br_ssl_client_context *cc,
1656 br_x509_minimal_context *xc,
1657 const br_x509_trust_anchor *trust_anchors, size_t trust_anchors_num);
1658
1659 /**
1660 * \brief Clear the complete contents of a SSL client context.
1661 *
1662 * Everything is cleared, including the reference to the configured buffer,
1663 * implementations, cipher suites and state. This is a preparatory step
1664 * to assembling a custom profile.
1665 *
1666 * \param cc client context to clear.
1667 */
1668 void br_ssl_client_zero(br_ssl_client_context *cc);
1669
1670 /**
1671 * \brief Set the RSA public-key operations implementation.
1672 *
1673 * This will be used to encrypt the pre-master secret with the server's
1674 * RSA public key (RSA-encryption cipher suites only).
1675 *
1676 * \param cc client context.
1677 * \param irsapub RSA public-key encryption implementation.
1678 */
1679 static inline void
1680 br_ssl_client_set_rsapub(br_ssl_client_context *cc, br_rsa_public irsapub)
1681 {
1682 cc->irsapub = irsapub;
1683 }
1684
1685 /**
1686 * \brief Set the RSA signature verification implementation.
1687 *
1688 * This will be used to verify the server's signature on its
1689 * ServerKeyExchange message (ECDHE_RSA cipher suites only).
1690 *
1691 * \param cc client context.
1692 * \param irsavrfy RSA signature verification implementation.
1693 */
1694 static inline void
1695 br_ssl_client_set_rsavrfy(br_ssl_client_context *cc, br_rsa_pkcs1_vrfy irsavrfy)
1696 {
1697 cc->irsavrfy = irsavrfy;
1698 }
1699
1700 /*
1701 * \brief Set the ECDSA implementation (signature verification).
1702 *
1703 * The ECDSA implementation will use the EC core implementation configured
1704 * in the engine context.
1705 *
1706 * \param cc client context.
1707 * \param iecdsa ECDSA verification implementation.
1708 */
1709 static inline void
1710 br_ssl_client_set_ecdsa(br_ssl_client_context *cc, br_ecdsa_vrfy iecdsa)
1711 {
1712 cc->iecdsa = iecdsa;
1713 }
1714
1715 /**
1716 * \brief Set the minimum ClientHello length (RFC 7685 padding).
1717 *
1718 * If this value is set and the ClientHello would be shorter, then
1719 * the Pad ClientHello extension will be added with enough padding bytes
1720 * to reach the target size. Because of the extension header, the resulting
1721 * size will sometimes be slightly more than `len` bytes if the target
1722 * size cannot be exactly met.
1723 *
1724 * The target length relates to the _contents_ of the ClientHello, not
1725 * counting its 4-byte header. For instance, if `len` is set to 512,
1726 * then the padding will bring the ClientHello size to 516 bytes with its
1727 * header, and 521 bytes when counting the 5-byte record header.
1728 *
1729 * \param cc client context.
1730 * \param len minimum ClientHello length (in bytes).
1731 */
1732 static inline void
1733 br_ssl_client_set_min_clienthello_len(br_ssl_client_context *cc, uint16_t len)
1734 {
1735 cc->min_clienthello_len = len;
1736 }
1737
1738 /**
1739 * \brief Prepare or reset a client context for a new connection.
1740 *
1741 * The `server_name` parameter is used to fill the SNI extension; the
1742 * X.509 "minimal" engine will also match that name against the server
1743 * names included in the server's certificate. If the parameter is
1744 * `NULL` then no SNI extension will be sent, and the X.509 "minimal"
1745 * engine (if used for server certificate validation) will not check
1746 * presence of any specific name in the received certificate.
1747 *
1748 * Therefore, setting the `server_name` to `NULL` shall be reserved
1749 * to cases where alternate or additional methods are used to ascertain
1750 * that the right server public key is used (e.g. a "known key" model).
1751 *
1752 * If `resume_session` is non-zero and the context was previously used
1753 * then the session parameters may be reused (depending on whether the
1754 * server previously sent a non-empty session ID, and accepts the session
1755 * resumption). The session parameters for session resumption can also
1756 * be set explicitly with `br_ssl_engine_set_session_parameters()`.
1757 *
1758 * On failure, the context is marked as failed, and this function
1759 * returns 0. A possible failure condition is when no initial entropy
1760 * was injected, and none could be obtained from the OS (either OS
1761 * randomness gathering is not supported, or it failed).
1762 *
1763 * \param cc client context.
1764 * \param server_name target server name, or `NULL`.
1765 * \param resume_session non-zero to try session resumption.
1766 * \return 0 on failure, 1 on success.
1767 */
1768 int br_ssl_client_reset(br_ssl_client_context *cc,
1769 const char *server_name, int resume_session);
1770
1771 /**
1772 * \brief Forget any session in the context.
1773 *
1774 * This means that the next handshake that uses this context will
1775 * necessarily be a full handshake (this applies both to new connections
1776 * and to renegotiations).
1777 *
1778 * \param cc client context.
1779 */
1780 static inline void
1781 br_ssl_client_forget_session(br_ssl_client_context *cc)
1782 {
1783 cc->eng.session.session_id_len = 0;
1784 }
1785
1786 /**
1787 * \brief Type for a "translated cipher suite", as an array of two
1788 * 16-bit integers.
1789 *
1790 * The first element is the cipher suite identifier (as used on the wire).
1791 * The second element is the concatenation of four 4-bit elements which
1792 * characterise the cipher suite contents. In most to least significant
1793 * order, these 4-bit elements are:
1794 *
1795 * - Bits 12 to 15: key exchange + server key type
1796 *
1797 * | val | symbolic constant | suite type | details |
1798 * | :-- | :----------------------- | :---------- | :----------------------------------------------- |
1799 * | 0 | `BR_SSLKEYX_RSA` | RSA | RSA key exchange, key is RSA (encryption) |
1800 * | 1 | `BR_SSLKEYX_ECDHE_RSA` | ECDHE_RSA | ECDHE key exchange, key is RSA (signature) |
1801 * | 2 | `BR_SSLKEYX_ECDHE_ECDSA` | ECDHE_ECDSA | ECDHE key exchange, key is EC (signature) |
1802 * | 3 | `BR_SSLKEYX_ECDH_RSA` | ECDH_RSA | Key is EC (key exchange), cert signed with RSA |
1803 * | 4 | `BR_SSLKEYX_ECDH_ECDSA` | ECDH_ECDSA | Key is EC (key exchange), cert signed with ECDSA |
1804 *
1805 * - Bits 8 to 11: symmetric encryption algorithm
1806 *
1807 * | val | symbolic constant | symmetric encryption | key strength (bits) |
1808 * | :-- | :--------------------- | :------------------- | :------------------ |
1809 * | 0 | `BR_SSLENC_3DES_CBC` | 3DES/CBC | 168 |
1810 * | 1 | `BR_SSLENC_AES128_CBC` | AES-128/CBC | 128 |
1811 * | 2 | `BR_SSLENC_AES256_CBC` | AES-256/CBC | 256 |
1812 * | 3 | `BR_SSLENC_AES128_GCM` | AES-128/GCM | 128 |
1813 * | 4 | `BR_SSLENC_AES256_GCM` | AES-256/GCM | 256 |
1814 * | 5 | `BR_SSLENC_CHACHA20` | ChaCha20/Poly1305 | 256 |
1815 *
1816 * - Bits 4 to 7: MAC algorithm
1817 *
1818 * | val | symbolic constant | MAC type | details |
1819 * | :-- | :----------------- | :----------- | :------------------------------------ |
1820 * | 0 | `BR_SSLMAC_AEAD` | AEAD | No dedicated MAC (encryption is AEAD) |
1821 * | 2 | `BR_SSLMAC_SHA1` | HMAC/SHA-1 | Value matches `br_sha1_ID` |
1822 * | 4 | `BR_SSLMAC_SHA256` | HMAC/SHA-256 | Value matches `br_sha256_ID` |
1823 * | 5 | `BR_SSLMAC_SHA384` | HMAC/SHA-384 | Value matches `br_sha384_ID` |
1824 *
1825 * - Bits 0 to 3: hash function for PRF when used with TLS-1.2
1826 *
1827 * | val | symbolic constant | hash function | details |
1828 * | :-- | :----------------- | :------------ | :----------------------------------- |
1829 * | 4 | `BR_SSLPRF_SHA256` | SHA-256 | Value matches `br_sha256_ID` |
1830 * | 5 | `BR_SSLPRF_SHA384` | SHA-384 | Value matches `br_sha384_ID` |
1831 *
1832 * For instance, cipher suite `TLS_RSA_WITH_AES_128_GCM_SHA256` has
1833 * standard identifier 0x009C, and is translated to 0x0304, for, in
1834 * that order: RSA key exchange (0), AES-128/GCM (3), AEAD integrity (0),
1835 * SHA-256 in the TLS PRF (4).
1836 */
1837 typedef uint16_t br_suite_translated[2];
1838
1839 #ifndef BR_DOXYGEN_IGNORE
1840 /*
1841 * Constants are already documented in the br_suite_translated type.
1842 */
1843
1844 #define BR_SSLKEYX_RSA 0
1845 #define BR_SSLKEYX_ECDHE_RSA 1
1846 #define BR_SSLKEYX_ECDHE_ECDSA 2
1847 #define BR_SSLKEYX_ECDH_RSA 3
1848 #define BR_SSLKEYX_ECDH_ECDSA 4
1849
1850 #define BR_SSLENC_3DES_CBC 0
1851 #define BR_SSLENC_AES128_CBC 1
1852 #define BR_SSLENC_AES256_CBC 2
1853 #define BR_SSLENC_AES128_GCM 3
1854 #define BR_SSLENC_AES256_GCM 4
1855 #define BR_SSLENC_CHACHA20 5
1856
1857 #define BR_SSLMAC_AEAD 0
1858 #define BR_SSLMAC_SHA1 br_sha1_ID
1859 #define BR_SSLMAC_SHA256 br_sha256_ID
1860 #define BR_SSLMAC_SHA384 br_sha384_ID
1861
1862 #define BR_SSLPRF_SHA256 br_sha256_ID
1863 #define BR_SSLPRF_SHA384 br_sha384_ID
1864
1865 #endif
1866
1867 /*
1868 * Pre-declaration for the SSL server context.
1869 */
1870 typedef struct br_ssl_server_context_ br_ssl_server_context;
1871
1872 /**
1873 * \brief Type for the server policy choices, taken after analysis of
1874 * the client message (ClientHello).
1875 */
1876 typedef struct {
1877 /**
1878 * \brief Cipher suite to use with that client.
1879 */
1880 uint16_t cipher_suite;
1881
1882 /**
1883 * \brief Hash function for signing the ServerKeyExchange.
1884 *
1885 * This is the symbolic identifier for the hash function that
1886 * will be used to sign the ServerKeyExchange message, for ECDHE
1887 * cipher suites. This is ignored for RSA and ECDH cipher suites.
1888 *
1889 * Take care that with TLS 1.0 and 1.1, that value MUST match
1890 * the protocol requirements: value must be 0 (MD5+SHA-1) for
1891 * a RSA signature, or 2 (SHA-1) for an ECDSA signature. Only
1892 * TLS 1.2 allows for other hash functions.
1893 */
1894 int hash_id;
1895
1896 /**
1897 * \brief Certificate chain to send to the client.
1898 *
1899 * This is an array of `br_x509_certificate` objects, each
1900 * normally containing a DER-encoded certificate. The server
1901 * code does not try to decode these elements.
1902 */
1903 const br_x509_certificate *chain;
1904
1905 /**
1906 * \brief Certificate chain length (number of certificates).
1907 */
1908 size_t chain_len;
1909 } br_ssl_server_choices;
1910
1911 /**
1912 * \brief Class type for a policy handler (server side).
1913 *
1914 * A policy handler selects the policy parameters for a connection
1915 * (cipher suite and other algorithms, and certificate chain to send to
1916 * the client); it also performs the server-side computations involving
1917 * its permanent private key.
1918 *
1919 * The SSL server engine will invoke first `choose()`, once the
1920 * ClientHello message has been received, then either `do_keyx()`
1921 * `do_sign()`, depending on the cipher suite.
1922 */
1923 typedef struct br_ssl_server_policy_class_ br_ssl_server_policy_class;
1924 struct br_ssl_server_policy_class_ {
1925 /**
1926 * \brief Context size (in bytes).
1927 */
1928 size_t context_size;
1929
1930 /**
1931 * \brief Select algorithms and certificates for this connection.
1932 *
1933 * This callback function shall fill the provided `choices`
1934 * structure with the policy choices for this connection. This
1935 * entails selecting the cipher suite, hash function for signing
1936 * the ServerKeyExchange (applicable only to ECDHE cipher suites),
1937 * and certificate chain to send.
1938 *
1939 * The callback receives a pointer to the server context that
1940 * contains the relevant data. In particular, the functions
1941 * `br_ssl_server_get_client_suites()`,
1942 * `br_ssl_server_get_client_hashes()` and
1943 * `br_ssl_server_get_client_curves()` can be used to obtain
1944 * the cipher suites, hash functions and elliptic curves
1945 * supported by both the client and server, respectively. The
1946 * `br_ssl_engine_get_version()` and `br_ssl_engine_get_server_name()`
1947 * functions yield the protocol version and requested server name
1948 * (SNI), respectively.
1949 *
1950 * This function may modify its context structure (`pctx`) in
1951 * arbitrary ways to keep track of its own choices.
1952 *
1953 * This function shall return 1 if appropriate policy choices
1954 * could be made, or 0 if this connection cannot be pursued.
1955 *
1956 * \param pctx policy context.
1957 * \param cc SSL server context.
1958 * \param choices destination structure for the policy choices.
1959 * \return 1 on success, 0 on error.
1960 */
1961 int (*choose)(const br_ssl_server_policy_class **pctx,
1962 const br_ssl_server_context *cc,
1963 br_ssl_server_choices *choices);
1964
1965 /**
1966 * \brief Perform key exchange (server part).
1967 *
1968 * This callback is invoked to perform the server-side cryptographic
1969 * operation for a key exchange that is not ECDHE. This callback
1970 * uses the private key.
1971 *
1972 * **For RSA key exchange**, the provided `data` (of length `len`
1973 * bytes) shall be decrypted with the server's private key, and
1974 * the 48-byte premaster secret copied back to the first 48 bytes
1975 * of `data`.
1976 *
1977 * - The caller makes sure that `len` is at least 59 bytes.
1978 *
1979 * - This callback MUST check that the provided length matches
1980 * that of the key modulus; it shall report an error otherwise.
1981 *
1982 * - If the length matches that of the RSA key modulus, then
1983 * processing MUST be constant-time, even if decryption fails,
1984 * or the padding is incorrect, or the plaintext message length
1985 * is not exactly 48 bytes.
1986 *
1987 * - This callback needs not check the two first bytes of the
1988 * obtained pre-master secret (the caller will do that).
1989 *
1990 * - If an error is reported (0), then what the callback put
1991 * in the first 48 bytes of `data` is unimportant (the caller
1992 * will use random bytes instead).
1993 *
1994 * **For ECDH key exchange**, the provided `data` (of length `len`
1995 * bytes) is the elliptic curve point from the client. The
1996 * callback shall multiply it with its private key, and store
1997 * the resulting X coordinate in `data`, starting at offset 1
1998 * (thus, simply encoding the point in compressed or uncompressed
1999 * format in `data` is fine).
2000 *
2001 * - If the input array does not have the proper length for
2002 * an encoded curve point, then an error (0) shall be reported.
2003 *
2004 * - If the input array has the proper length, then processing
2005 * MUST be constant-time, even if the data is not a valid
2006 * encoded point.
2007 *
2008 * - This callback MUST check that the input point is valid.
2009 *
2010 * Returned value is 1 on success, 0 on error.
2011 *
2012 * \param pctx policy context.
2013 * \param data key exchange data from the client.
2014 * \param len key exchange data length (in bytes).
2015 * \return 1 on success, 0 on error.
2016 */
2017 uint32_t (*do_keyx)(const br_ssl_server_policy_class **pctx,
2018 unsigned char *data, size_t len);
2019
2020 /**
2021 * \brief Perform a signature (for a ServerKeyExchange message).
2022 *
2023 * This callback function is invoked for ECDHE cipher suites.
2024 * On input, the hash value to sign is in `data`, of size
2025 * `hv_len`; the involved hash function is identified by
2026 * `hash_id`. The signature shall be computed and written
2027 * back into `data`; the total size of that buffer is `len`
2028 * bytes.
2029 *
2030 * This callback shall verify that the signature length does not
2031 * exceed `len` bytes, and abstain from writing the signature if
2032 * it does not fit.
2033 *
2034 * For RSA signatures, the `hash_id` may be 0, in which case
2035 * this is the special header-less signature specified in TLS 1.0
2036 * and 1.1, with a 36-byte hash value. Otherwise, normal PKCS#1
2037 * v1.5 signatures shall be computed.
2038 *
2039 * Returned value is the signature length (in bytes), or 0 on error.
2040 *
2041 * \param pctx policy context.
2042 * \param hash_id hash function identifier.
2043 * \param hv_len hash value length (in bytes).
2044 * \param data input/output buffer (hash value, then signature).
2045 * \param len total buffer length (in bytes).
2046 * \return signature length (in bytes) on success, or 0 on error.
2047 */
2048 size_t (*do_sign)(const br_ssl_server_policy_class **pctx,
2049 int hash_id, size_t hv_len, unsigned char *data, size_t len);
2050 };
2051
2052 /**
2053 * \brief A single-chain RSA policy handler.
2054 *
2055 * This policy context uses a single certificate chain, and a RSA
2056 * private key. The context can be restricted to only signatures or
2057 * only key exchange.
2058 *
2059 * Apart from the first field (vtable pointer), its contents are
2060 * opaque and shall not be accessed directly.
2061 */
2062 typedef struct {
2063 /** \brief Pointer to vtable. */
2064 const br_ssl_server_policy_class *vtable;
2065 #ifndef BR_DOXYGEN_IGNORE
2066 const br_x509_certificate *chain;
2067 size_t chain_len;
2068 const br_rsa_private_key *sk;
2069 unsigned allowed_usages;
2070 br_rsa_private irsacore;
2071 br_rsa_pkcs1_sign irsasign;
2072 #endif
2073 } br_ssl_server_policy_rsa_context;
2074
2075 /**
2076 * \brief A single-chain EC policy handler.
2077 *
2078 * This policy context uses a single certificate chain, and an EC
2079 * private key. The context can be restricted to only signatures or
2080 * only key exchange.
2081 *
2082 * Due to how TLS is defined, this context must be made aware whether
2083 * the server certificate was itself signed with RSA or ECDSA. The code
2084 * does not try to decode the certificate to obtain that information.
2085 *
2086 * Apart from the first field (vtable pointer), its contents are
2087 * opaque and shall not be accessed directly.
2088 */
2089 typedef struct {
2090 /** \brief Pointer to vtable. */
2091 const br_ssl_server_policy_class *vtable;
2092 #ifndef BR_DOXYGEN_IGNORE
2093 const br_x509_certificate *chain;
2094 size_t chain_len;
2095 const br_ec_private_key *sk;
2096 unsigned allowed_usages;
2097 unsigned cert_issuer_key_type;
2098 const br_multihash_context *mhash;
2099 const br_ec_impl *iec;
2100 br_ecdsa_sign iecdsa;
2101 #endif
2102 } br_ssl_server_policy_ec_context;
2103
2104 /**
2105 * \brief Class type for a session parameter cache.
2106 *
2107 * Session parameters are saved in the cache with `save()`, and
2108 * retrieved with `load()`. The cache implementation can apply any
2109 * storage and eviction strategy that it sees fit. The SSL server
2110 * context that performs the request is provided, so that its
2111 * functionalities may be used by the implementation (e.g. hash
2112 * functions or random number generation).
2113 */
2114 typedef struct br_ssl_session_cache_class_ br_ssl_session_cache_class;
2115 struct br_ssl_session_cache_class_ {
2116 /**
2117 * \brief Context size (in bytes).
2118 */
2119 size_t context_size;
2120
2121 /**
2122 * \brief Record a session.
2123 *
2124 * This callback should record the provided session parameters.
2125 * The `params` structure is transient, so its contents shall
2126 * be copied into the cache. The session ID has been randomly
2127 * generated and always has length exactly 32 bytes.
2128 *
2129 * \param ctx session cache context.
2130 * \param server_ctx SSL server context.
2131 * \param params session parameters to save.
2132 */
2133 void (*save)(const br_ssl_session_cache_class **ctx,
2134 br_ssl_server_context *server_ctx,
2135 const br_ssl_session_parameters *params);
2136
2137 /**
2138 * \brief Lookup a session in the cache.
2139 *
2140 * The session ID to lookup is in `params` and always has length
2141 * exactly 32 bytes. If the session parameters are found in the
2142 * cache, then the parameters shall be copied into the `params`
2143 * structure. Returned value is 1 on successful lookup, 0
2144 * otherwise.
2145 *
2146 * \param ctx session cache context.
2147 * \param server_ctx SSL server context.
2148 * \param params destination for session parameters.
2149 * \return 1 if found, 0 otherwise.
2150 */
2151 int (*load)(const br_ssl_session_cache_class **ctx,
2152 br_ssl_server_context *server_ctx,
2153 br_ssl_session_parameters *params);
2154 };
2155
2156 /**
2157 * \brief Context for a basic cache system.
2158 *
2159 * The system stores session parameters in a buffer provided at
2160 * initialisation time. Each entry uses exactly 100 bytes, and
2161 * buffer sizes up to 4294967295 bytes are supported.
2162 *
2163 * Entries are evicted with a LRU (Least Recently Used) policy. A
2164 * search tree is maintained to keep lookups fast even with large
2165 * caches.
2166 *
2167 * Apart from the first field (vtable pointer), the structure
2168 * contents are opaque and shall not be accessed directly.
2169 */
2170 typedef struct {
2171 /** \brief Pointer to vtable. */
2172 const br_ssl_session_cache_class *vtable;
2173 #ifndef BR_DOXYGEN_IGNORE
2174 unsigned char *store;
2175 size_t store_len, store_ptr;
2176 unsigned char index_key[32];
2177 const br_hash_class *hash;
2178 int init_done;
2179 uint32_t head, tail, root;
2180 #endif
2181 } br_ssl_session_cache_lru;
2182
2183 /**
2184 * \brief Initialise a LRU session cache with the provided storage space.
2185 *
2186 * The provided storage space must remain valid as long as the cache
2187 * is used. Arbitrary lengths are supported, up to 4294967295 bytes;
2188 * each entry uses up exactly 100 bytes.
2189 *
2190 * \param cc session cache context.
2191 * \param store storage space for cached entries.
2192 * \param store_len storage space length (in bytes).
2193 */
2194 void br_ssl_session_cache_lru_init(br_ssl_session_cache_lru *cc,
2195 unsigned char *store, size_t store_len);
2196
2197 /**
2198 * \brief Context structure for a SSL server.
2199 *
2200 * The first field (called `eng`) is the SSL engine; all functions that
2201 * work on a `br_ssl_engine_context` structure shall take as parameter
2202 * a pointer to that field. The other structure fields are opaque and
2203 * must not be accessed directly.
2204 */
2205 struct br_ssl_server_context_ {
2206 /**
2207 * \brief The encapsulated engine context.
2208 */
2209 br_ssl_engine_context eng;
2210
2211 #ifndef BR_DOXYGEN_IGNORE
2212 /*
2213 * Maximum version from the client.
2214 */
2215 uint16_t client_max_version;
2216
2217 /*
2218 * Session cache.
2219 */
2220 const br_ssl_session_cache_class **cache_vtable;
2221
2222 /*
2223 * Translated cipher suites supported by the client. The list
2224 * is trimmed to include only the cipher suites that the
2225 * server also supports; they are in the same order as in the
2226 * client message.
2227 */
2228 br_suite_translated client_suites[BR_MAX_CIPHER_SUITES];
2229 unsigned char client_suites_num;
2230
2231 /*
2232 * Hash functions supported by the client, with ECDSA and RSA
2233 * (bit mask). For hash function with id 'x', set bit index is
2234 * x for RSA, x+8 for ECDSA.
2235 */
2236 uint16_t hashes;
2237
2238 /*
2239 * Curves supported by the client (bit mask, for named curves).
2240 */
2241 uint32_t curves;
2242
2243 /*
2244 * Context for chain handler.
2245 */
2246 const br_ssl_server_policy_class **policy_vtable;
2247 const br_x509_certificate *chain;
2248 size_t chain_len;
2249 const unsigned char *cert_cur;
2250 size_t cert_len;
2251 unsigned char sign_hash_id;
2252
2253 /*
2254 * For the core handlers, thus avoiding (in most cases) the
2255 * need for an externally provided policy context.
2256 */
2257 union {
2258 const br_ssl_server_policy_class *vtable;
2259 br_ssl_server_policy_rsa_context single_rsa;
2260 br_ssl_server_policy_ec_context single_ec;
2261 } chain_handler;
2262
2263 /*
2264 * Buffer for the ECDHE private key.
2265 */
2266 unsigned char ecdhe_key[70];
2267 size_t ecdhe_key_len;
2268
2269 /*
2270 * Server-specific implementations.
2271 * (none for now)
2272 */
2273 #endif
2274 };
2275
2276 /*
2277 * Each br_ssl_server_init_xxx() function sets the list of supported
2278 * cipher suites and used implementations, as specified by the profile
2279 * name 'xxx'. Defined profile names are:
2280 *
2281 * full_rsa all supported algorithm, server key type is RSA
2282 * full_ec all supported algorithm, server key type is EC
2283 * TODO: add other profiles
2284 *
2285 * Naming scheme for "minimal" profiles: min123
2286 *
2287 * -- character 1: key exchange
2288 * r = RSA
2289 * e = ECDHE_RSA
2290 * f = ECDHE_ECDSA
2291 * u = ECDH_RSA
2292 * v = ECDH_ECDSA
2293 * -- character 2: version / PRF
2294 * 0 = TLS 1.0 / 1.1 with MD5+SHA-1
2295 * 2 = TLS 1.2 with SHA-256
2296 * 3 = TLS 1.2 with SHA-384
2297 * -- character 3: encryption
2298 * a = AES/CBC
2299 * g = AES/GCM
2300 * d = 3DES/CBC
2301 */
2302
2303 /**
2304 * \brief SSL server profile: full_rsa.
2305 *
2306 * This function initialises the provided SSL server context with
2307 * all supported algorithms and cipher suites that rely on a RSA
2308 * key pair.
2309 *
2310 * \param cc server context to initialise.
2311 * \param chain server certificate chain.
2312 * \param chain_len certificate chain length (number of certificate).
2313 * \param sk RSA private key.
2314 */
2315 void br_ssl_server_init_full_rsa(br_ssl_server_context *cc,
2316 const br_x509_certificate *chain, size_t chain_len,
2317 const br_rsa_private_key *sk);
2318
2319 /**
2320 * \brief SSL server profile: full_ec.
2321 *
2322 * This function initialises the provided SSL server context with
2323 * all supported algorithms and cipher suites that rely on an EC
2324 * key pair.
2325 *
2326 * The key type of the CA that issued the server's certificate must
2327 * be provided, since it matters for ECDH cipher suites (ECDH_RSA
2328 * suites require a RSA-powered CA). The key type is either
2329 * `BR_KEYTYPE_RSA` or `BR_KEYTYPE_EC`.
2330 *
2331 * \param cc server context to initialise.
2332 * \param chain server certificate chain.
2333 * \param chain_len chain length (number of certificates).
2334 * \param cert_issuer_key_type certificate issuer's key type.
2335 * \param sk EC private key.
2336 */
2337 void br_ssl_server_init_full_ec(br_ssl_server_context *cc,
2338 const br_x509_certificate *chain, size_t chain_len,
2339 unsigned cert_issuer_key_type, const br_ec_private_key *sk);
2340
2341 /**
2342 * \brief SSL server profile: minr2g.
2343 *
2344 * This profile uses only TLS_RSA_WITH_AES_128_GCM_SHA256. Server key is
2345 * RSA, and RSA key exchange is used (not forward secure, but uses little
2346 * CPU in the client).
2347 *
2348 * \param cc server context to initialise.
2349 * \param chain server certificate chain.
2350 * \param chain_len certificate chain length (number of certificate).
2351 * \param sk RSA private key.
2352 */
2353 void br_ssl_server_init_minr2g(br_ssl_server_context *cc,
2354 const br_x509_certificate *chain, size_t chain_len,
2355 const br_rsa_private_key *sk);
2356
2357 /**
2358 * \brief SSL server profile: mine2g.
2359 *
2360 * This profile uses only TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256. Server key
2361 * is RSA, and ECDHE key exchange is used. This suite provides forward
2362 * security, with a higher CPU expense on the client, and a somewhat
2363 * larger code footprint (compared to "minr2g").
2364 *
2365 * \param cc server context to initialise.
2366 * \param chain server certificate chain.
2367 * \param chain_len certificate chain length (number of certificate).
2368 * \param sk RSA private key.
2369 */
2370 void br_ssl_server_init_mine2g(br_ssl_server_context *cc,
2371 const br_x509_certificate *chain, size_t chain_len,
2372 const br_rsa_private_key *sk);
2373
2374 /**
2375 * \brief SSL server profile: minf2g.
2376 *
2377 * This profile uses only TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256.
2378 * Server key is EC, and ECDHE key exchange is used. This suite provides
2379 * forward security, with a higher CPU expense on the client and server
2380 * (by a factor of about 3 to 4), and a somewhat larger code footprint
2381 * (compared to "minu2g" and "minv2g").
2382 *
2383 * \param cc server context to initialise.
2384 * \param chain server certificate chain.
2385 * \param chain_len certificate chain length (number of certificate).
2386 * \param sk EC private key.
2387 */
2388 void br_ssl_server_init_minf2g(br_ssl_server_context *cc,
2389 const br_x509_certificate *chain, size_t chain_len,
2390 const br_ec_private_key *sk);
2391
2392 /**
2393 * \brief SSL server profile: minu2g.
2394 *
2395 * This profile uses only TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256.
2396 * Server key is EC, and ECDH key exchange is used; the issuing CA used
2397 * a RSA key.
2398 *
2399 * The "minu2g" and "minv2g" profiles do not provide forward secrecy,
2400 * but are the lightest on the server (for CPU usage), and are rather
2401 * inexpensive on the client as well.
2402 *
2403 * \param cc server context to initialise.
2404 * \param chain server certificate chain.
2405 * \param chain_len certificate chain length (number of certificate).
2406 * \param sk EC private key.
2407 */
2408 void br_ssl_server_init_minu2g(br_ssl_server_context *cc,
2409 const br_x509_certificate *chain, size_t chain_len,
2410 const br_ec_private_key *sk);
2411
2412 /**
2413 * \brief SSL server profile: minv2g.
2414 *
2415 * This profile uses only TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256.
2416 * Server key is EC, and ECDH key exchange is used; the issuing CA used
2417 * an EC key.
2418 *
2419 * The "minu2g" and "minv2g" profiles do not provide forward secrecy,
2420 * but are the lightest on the server (for CPU usage), and are rather
2421 * inexpensive on the client as well.
2422 *
2423 * \param cc server context to initialise.
2424 * \param chain server certificate chain.
2425 * \param chain_len certificate chain length (number of certificate).
2426 * \param sk EC private key.
2427 */
2428 void br_ssl_server_init_minv2g(br_ssl_server_context *cc,
2429 const br_x509_certificate *chain, size_t chain_len,
2430 const br_ec_private_key *sk);
2431
2432 /**
2433 * \brief Get the supported client suites.
2434 *
2435 * This function shall be called only after the ClientHello has been
2436 * processed, typically from the policy engine. The returned array
2437 * contains the cipher suites that are supported by both the client
2438 * and the server; these suites are in client preference order, unless
2439 * the `BR_OPT_ENFORCE_SERVER_PREFERENCES` flag was set, in which case
2440 * they are in server preference order.
2441 *
2442 * The suites are _translated_, which means that each suite is given
2443 * as two 16-bit integers: the standard suite identifier, and its
2444 * translated version, broken down into its individual components,
2445 * as explained with the `br_suite_translated` type.
2446 *
2447 * The returned array is allocated in the context and will be rewritten
2448 * by each handshake.
2449 *
2450 * \param cc server context.
2451 * \param num receives the array size (number of suites).
2452 * \return the translated common cipher suites, in preference order.
2453 */
2454 static inline const br_suite_translated *
2455 br_ssl_server_get_client_suites(const br_ssl_server_context *cc, size_t *num)
2456 {
2457 *num = cc->client_suites_num;
2458 return cc->client_suites;
2459 }
2460
2461 /**
2462 * \brief Get the hash functions supported by the client.
2463 *
2464 * This is a field of bits: for hash function of ID x, bit x is set if
2465 * the hash function is supported in RSA signatures, 8+x if it is supported
2466 * with ECDSA.
2467 *
2468 * \param cc server context.
2469 * \return the client-supported hash functions (for signatures).
2470 */
2471 static inline uint16_t
2472 br_ssl_server_get_client_hashes(const br_ssl_server_context *cc)
2473 {
2474 return cc->hashes;
2475 }
2476
2477 /**
2478 * \brief Get the elliptic curves supported by the client.
2479 *
2480 * This is a bit field (bit x is set if curve of ID x is supported).
2481 *
2482 * \param cc server context.
2483 * \return the client-supported elliptic curves.
2484 */
2485 static inline uint32_t
2486 br_ssl_server_get_client_curves(const br_ssl_server_context *cc)
2487 {
2488 return cc->curves;
2489 }
2490
2491 /**
2492 * \brief Clear the complete contents of a SSL server context.
2493 *
2494 * Everything is cleared, including the reference to the configured buffer,
2495 * implementations, cipher suites and state. This is a preparatory step
2496 * to assembling a custom profile.
2497 *
2498 * \param cc server context to clear.
2499 */
2500 void br_ssl_server_zero(br_ssl_server_context *cc);
2501
2502 /**
2503 * \brief Set an externally provided policy context.
2504 *
2505 * The policy context's methods are invoked to decide the cipher suite
2506 * and certificate chain, and to perform operations involving the server's
2507 * private key.
2508 *
2509 * \param cc server context.
2510 * \param pctx policy context (pointer to its vtable field).
2511 */
2512 static inline void
2513 br_ssl_server_set_policy(br_ssl_server_context *cc,
2514 const br_ssl_server_policy_class **pctx)
2515 {
2516 cc->policy_vtable = pctx;
2517 }
2518
2519 /**
2520 * \brief Set the server certificate chain and key (single RSA case).
2521 *
2522 * This function uses a policy context included in the server context.
2523 * It configures use of a single server certificate chain with a RSA
2524 * private key. The `allowed_usages` is a combination of usages, namely
2525 * `BR_KEYTYPE_KEYX` and/or `BR_KEYTYPE_SIGN`; this enables or disables
2526 * the corresponding cipher suites (i.e. `TLS_RSA_*` use the RSA key for
2527 * key exchange, while `TLS_ECDHE_RSA_*` use the RSA key for signatures).
2528 *
2529 * \param cc server context.
2530 * \param chain server certificate chain to send to the client.
2531 * \param chain_len chain length (number of certificates).
2532 * \param sk server private key (RSA).
2533 * \param allowed_usages allowed private key usages.
2534 * \param irsacore RSA core implementation.
2535 * \param irsasign RSA signature implementation (PKCS#1 v1.5).
2536 */
2537 void br_ssl_server_set_single_rsa(br_ssl_server_context *cc,
2538 const br_x509_certificate *chain, size_t chain_len,
2539 const br_rsa_private_key *sk, unsigned allowed_usages,
2540 br_rsa_private irsacore, br_rsa_pkcs1_sign irsasign);
2541
2542 /*
2543 * \brief Set the server certificate chain and key (single EC case).
2544 *
2545 * This function uses a policy context included in the server context.
2546 * It configures use of a single server certificate chain with an EC
2547 * private key. The `allowed_usages` is a combination of usages, namely
2548 * `BR_KEYTYPE_KEYX` and/or `BR_KEYTYPE_SIGN`; this enables or disables
2549 * the corresponding cipher suites (i.e. `TLS_ECDH_*` use the EC key for
2550 * key exchange, while `TLS_ECDHE_ECDSA_*` use the EC key for signatures).
2551 *
2552 * In order to support `TLS_ECDH_*` cipher suites (non-ephemeral ECDH),
2553 * the algorithm type of the key used by the issuing CA to sign the
2554 * server's certificate must be provided, as `cert_issuer_key_type`
2555 * parameter (this value is either `BR_KEYTYPE_RSA` or `BR_KEYTYPE_EC`).
2556 *
2557 * \param cc server context.
2558 * \param chain server certificate chain to send.
2559 * \param chain_len chain length (number of certificates).
2560 * \param sk server private key (EC).
2561 * \param allowed_usages allowed private key usages.
2562 * \param cert_issuer_key_type issuing CA's key type.
2563 * \param iec EC core implementation.
2564 * \param iecdsa ECDSA signature implementation ("asn1" format).
2565 */
2566 void br_ssl_server_set_single_ec(br_ssl_server_context *cc,
2567 const br_x509_certificate *chain, size_t chain_len,
2568 const br_ec_private_key *sk, unsigned allowed_usages,
2569 unsigned cert_issuer_key_type,
2570 const br_ec_impl *iec, br_ecdsa_sign iecdsa);
2571
2572 /**
2573 * \brief Configure the cache for session parameters.
2574 *
2575 * The cache context is provided as a pointer to its first field (vtable
2576 * pointer).
2577 *
2578 * \param cc server context.
2579 * \param vtable session cache context.
2580 */
2581 static inline void
2582 br_ssl_server_set_cache(br_ssl_server_context *cc,
2583 const br_ssl_session_cache_class **vtable)
2584 {
2585 cc->cache_vtable = vtable;
2586 }
2587
2588 /**
2589 * \brief Prepare or reset a server context for handling an incoming client.
2590 *
2591 * \param cc server context.
2592 * \return 1 on success, 0 on error.
2593 */
2594 int br_ssl_server_reset(br_ssl_server_context *cc);
2595
2596 /* ===================================================================== */
2597
2598 /*
2599 * Context for the simplified I/O context. The transport medium is accessed
2600 * through the low_read() and low_write() callback functions, each with
2601 * its own opaque context pointer.
2602 *
2603 * low_read() read some bytes, at most 'len' bytes, into data[]. The
2604 * returned value is the number of read bytes, or -1 on error.
2605 * The 'len' parameter is guaranteed never to exceed 20000,
2606 * so the length always fits in an 'int' on all platforms.
2607 *
2608 * low_write() write up to 'len' bytes, to be read from data[]. The
2609 * returned value is the number of written bytes, or -1 on
2610 * error. The 'len' parameter is guaranteed never to exceed
2611 * 20000, so the length always fits in an 'int' on all
2612 * parameters.
2613 *
2614 * A socket closure (if the transport medium is a socket) should be reported
2615 * as an error (-1). The callbacks shall endeavour to block until at least
2616 * one byte can be read or written; a callback returning 0 at times is
2617 * acceptable, but this normally leads to the callback being immediately
2618 * called again, so the callback should at least always try to block for
2619 * some time if no I/O can take place.
2620 *
2621 * The SSL engine naturally applies some buffering, so the callbacks need
2622 * not apply buffers of their own.
2623 */
2624 /**
2625 * \brief Context structure for the simplified SSL I/O wrapper.
2626 *
2627 * This structure is initialised with `br_sslio_init()`. Its contents
2628 * are opaque and shall not be accessed directly.
2629 */
2630 typedef struct {
2631 #ifndef BR_DOXYGEN_IGNORE
2632 br_ssl_engine_context *engine;
2633 int (*low_read)(void *read_context,
2634 unsigned char *data, size_t len);
2635 void *read_context;
2636 int (*low_write)(void *write_context,
2637 const unsigned char *data, size_t len);
2638 void *write_context;
2639 #endif
2640 } br_sslio_context;
2641
2642 /**
2643 * \brief Initialise a simplified I/O wrapper context.
2644 *
2645 * The simplified I/O wrapper offers a simpler read/write API for a SSL
2646 * engine (client or server), using the provided callback functions for
2647 * reading data from, or writing data to, the transport medium.
2648 *
2649 * The callback functions have the following semantics:
2650 *
2651 * - Each callback receives an opaque context value (of type `void *`)
2652 * that the callback may use arbitrarily (or possibly ignore).
2653 *
2654 * - `low_read()` reads at least one byte, at most `len` bytes, from
2655 * the transport medium. Read bytes shall be written in `data`.
2656 *
2657 * - `low_write()` writes at least one byte, at most `len` bytes, unto
2658 * the transport medium. The bytes to write are read from `data`.
2659 *
2660 * - The `len` parameter is never zero, and is always lower than 20000.
2661 *
2662 * - The number of processed bytes (read or written) is returned. Since
2663 * that number is less than 20000, it always fits on an `int`.
2664 *
2665 * - On error, the callbacks return -1. Reaching end-of-stream is an
2666 * error. Errors are permanent: the SSL connection is terminated.
2667 *
2668 * - Callbacks SHOULD NOT return 0. This is tolerated, as long as
2669 * callbacks endeavour to block for some non-negligible amount of
2670 * time until at least one byte can be sent or received (if a
2671 * callback returns 0, then the wrapper invokes it again
2672 * immediately).
2673 *
2674 * - Callbacks MAY return as soon as at least one byte is processed;
2675 * they MAY also insist on reading or writing _all_ requested bytes.
2676 * Since SSL is a self-terminated protocol (each record has a length
2677 * header), this does not change semantics.
2678 *
2679 * - Callbacks need not apply any buffering (for performance) since SSL
2680 * itself uses buffers.
2681 *
2682 * \param ctx wrapper context to initialise.
2683 * \param engine SSL engine to wrap.
2684 * \param low_read callback for reading data from the transport.
2685 * \param read_context context pointer for `low_read()`.
2686 * \param low_write callback for writing data on the transport.
2687 * \param write_context context pointer for `low_write()`.
2688 */
2689 void br_sslio_init(br_sslio_context *ctx,
2690 br_ssl_engine_context *engine,
2691 int (*low_read)(void *read_context,
2692 unsigned char *data, size_t len),
2693 void *read_context,
2694 int (*low_write)(void *write_context,
2695 const unsigned char *data, size_t len),
2696 void *write_context);
2697
2698 /**
2699 * \brief Read some application data from a SSL connection.
2700 *
2701 * If `len` is zero, then this function returns 0 immediately. In
2702 * all other cases, it never returns 0.
2703 *
2704 * This call returns only when at least one byte has been obtained.
2705 * Returned value is the number of bytes read, or -1 on error. The
2706 * number of bytes always fits on an 'int' (data from a single SSL/TLS
2707 * record is returned).
2708 *
2709 * On error or SSL closure, this function returns -1. The caller should
2710 * inspect the error status on the SSL engine to distinguish between
2711 * normal closure and error.
2712 *
2713 * \param cc SSL wrapper context.
2714 * \param dst destination buffer for application data.
2715 * \param len maximum number of bytes to obtain.
2716 * \return number of bytes obtained, or -1 on error.
2717 */
2718 int br_sslio_read(br_sslio_context *cc, void *dst, size_t len);
2719
2720 /**
2721 * \brief Read application data from a SSL connection.
2722 *
2723 * This calls returns only when _all_ requested `len` bytes are read,
2724 * or an error is reached. Returned value is 0 on success, -1 on error.
2725 * A normal (verified) SSL closure before that many bytes are obtained
2726 * is reported as an error by this function.
2727 *
2728 * \param cc SSL wrapper context.
2729 * \param dst destination buffer for application data.
2730 * \param len number of bytes to obtain.
2731 * \return 0 on success, or -1 on error.
2732 */
2733 int br_sslio_read_all(br_sslio_context *cc, void *dst, size_t len);
2734
2735 /**
2736 * \brief Write some application data unto a SSL connection.
2737 *
2738 * If `len` is zero, then this function returns 0 immediately. In
2739 * all other cases, it never returns 0.
2740 *
2741 * This call returns only when at least one byte has been written.
2742 * Returned value is the number of bytes written, or -1 on error. The
2743 * number of bytes always fits on an 'int' (less than 20000).
2744 *
2745 * On error or SSL closure, this function returns -1. The caller should
2746 * inspect the error status on the SSL engine to distinguish between
2747 * normal closure and error.
2748 *
2749 * **Important:** SSL is buffered; a "written" byte is a byte that was
2750 * injected into the wrapped SSL engine, but this does not necessarily mean
2751 * that it has been scheduled for sending. Use `br_sslio_flush()` to
2752 * ensure that all pending data has been sent to the transport medium.
2753 *
2754 * \param cc SSL wrapper context.
2755 * \param src source buffer for application data.
2756 * \param len maximum number of bytes to write.
2757 * \return number of bytes written, or -1 on error.
2758 */
2759 int br_sslio_write(br_sslio_context *cc, const void *src, size_t len);
2760
2761 /**
2762 * \brief Write application data unto a SSL connection.
2763 *
2764 * This calls returns only when _all_ requested `len` bytes have been
2765 * written, or an error is reached. Returned value is 0 on success, -1
2766 * on error. A normal (verified) SSL closure before that many bytes are
2767 * written is reported as an error by this function.
2768 *
2769 * **Important:** SSL is buffered; a "written" byte is a byte that was
2770 * injected into the wrapped SSL engine, but this does not necessarily mean
2771 * that it has been scheduled for sending. Use `br_sslio_flush()` to
2772 * ensure that all pending data has been sent to the transport medium.
2773 *
2774 * \param cc SSL wrapper context.
2775 * \param src source buffer for application data.
2776 * \param len number of bytes to write.
2777 * \return 0 on success, or -1 on error.
2778 */
2779 int br_sslio_write_all(br_sslio_context *cc, const void *src, size_t len);
2780
2781 /**
2782 * \brief Flush pending data.
2783 *
2784 * This call makes sure that any buffered application data in the
2785 * provided context (including the wrapped SSL engine) has been sent
2786 * to the transport medium (i.e. accepted by the `low_write()` callback
2787 * method). If there is no such pending data, then this function does
2788 * nothing (and returns a success, i.e. 0).
2789 *
2790 * If the underlying transport medium has its own buffers, then it is
2791 * up to the caller to ensure the corresponding flushing.
2792 *
2793 * Returned value is 0 on success, -1 on error.
2794 *
2795 * \param cc SSL wrapper context.
2796 * \return 0 on success, or -1 on error.
2797 */
2798 int br_sslio_flush(br_sslio_context *cc);
2799
2800 /**
2801 * \brief Close the SSL connection.
2802 *
2803 * This call runs the SSL closure protocol (sending a `close_notify`,
2804 * receiving the response `close_notify`). When it returns, the SSL
2805 * connection is finished. It is still up to the caller to manage the
2806 * possible transport-level termination, if applicable (alternatively,
2807 * the underlying transport stream may be reused for non-SSL messages).
2808 *
2809 * Returned value is 0 on success, -1 on error. A failure by the peer
2810 * to process the complete closure protocol (i.e. sending back the
2811 * `close_notify`) is an error.
2812 *
2813 * \param cc SSL wrapper context.
2814 * \return 0 on success, or -1 on error.
2815 */
2816 int br_sslio_close(br_sslio_context *cc);
2817
2818 /* ===================================================================== */
2819
2820 /*
2821 * Symbolic constants for cipher suites.
2822 */
2823
2824 /* From RFC 5246 */
2825 #define BR_TLS_NULL_WITH_NULL_NULL 0x0000
2826 #define BR_TLS_RSA_WITH_NULL_MD5 0x0001
2827 #define BR_TLS_RSA_WITH_NULL_SHA 0x0002
2828 #define BR_TLS_RSA_WITH_NULL_SHA256 0x003B
2829 #define BR_TLS_RSA_WITH_RC4_128_MD5 0x0004
2830 #define BR_TLS_RSA_WITH_RC4_128_SHA 0x0005
2831 #define BR_TLS_RSA_WITH_3DES_EDE_CBC_SHA 0x000A
2832 #define BR_TLS_RSA_WITH_AES_128_CBC_SHA 0x002F
2833 #define BR_TLS_RSA_WITH_AES_256_CBC_SHA 0x0035
2834 #define BR_TLS_RSA_WITH_AES_128_CBC_SHA256 0x003C
2835 #define BR_TLS_RSA_WITH_AES_256_CBC_SHA256 0x003D
2836 #define BR_TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA 0x000D
2837 #define BR_TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA 0x0010
2838 #define BR_TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA 0x0013
2839 #define BR_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA 0x0016
2840 #define BR_TLS_DH_DSS_WITH_AES_128_CBC_SHA 0x0030
2841 #define BR_TLS_DH_RSA_WITH_AES_128_CBC_SHA 0x0031
2842 #define BR_TLS_DHE_DSS_WITH_AES_128_CBC_SHA 0x0032
2843 #define BR_TLS_DHE_RSA_WITH_AES_128_CBC_SHA 0x0033
2844 #define BR_TLS_DH_DSS_WITH_AES_256_CBC_SHA 0x0036
2845 #define BR_TLS_DH_RSA_WITH_AES_256_CBC_SHA 0x0037
2846 #define BR_TLS_DHE_DSS_WITH_AES_256_CBC_SHA 0x0038
2847 #define BR_TLS_DHE_RSA_WITH_AES_256_CBC_SHA 0x0039
2848 #define BR_TLS_DH_DSS_WITH_AES_128_CBC_SHA256 0x003E
2849 #define BR_TLS_DH_RSA_WITH_AES_128_CBC_SHA256 0x003F
2850 #define BR_TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 0x0040
2851 #define BR_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 0x0067
2852 #define BR_TLS_DH_DSS_WITH_AES_256_CBC_SHA256 0x0068
2853 #define BR_TLS_DH_RSA_WITH_AES_256_CBC_SHA256 0x0069
2854 #define BR_TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 0x006A
2855 #define BR_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 0x006B
2856 #define BR_TLS_DH_anon_WITH_RC4_128_MD5 0x0018
2857 #define BR_TLS_DH_anon_WITH_3DES_EDE_CBC_SHA 0x001B
2858 #define BR_TLS_DH_anon_WITH_AES_128_CBC_SHA 0x0034
2859 #define BR_TLS_DH_anon_WITH_AES_256_CBC_SHA 0x003A
2860 #define BR_TLS_DH_anon_WITH_AES_128_CBC_SHA256 0x006C
2861 #define BR_TLS_DH_anon_WITH_AES_256_CBC_SHA256 0x006D
2862
2863 /* From RFC 4492 */
2864 #define BR_TLS_ECDH_ECDSA_WITH_NULL_SHA 0xC001
2865 #define BR_TLS_ECDH_ECDSA_WITH_RC4_128_SHA 0xC002
2866 #define BR_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA 0xC003
2867 #define BR_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA 0xC004
2868 #define BR_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA 0xC005
2869 #define BR_TLS_ECDHE_ECDSA_WITH_NULL_SHA 0xC006
2870 #define BR_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA 0xC007
2871 #define BR_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA 0xC008
2872 #define BR_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA 0xC009
2873 #define BR_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA 0xC00A
2874 #define BR_TLS_ECDH_RSA_WITH_NULL_SHA 0xC00B
2875 #define BR_TLS_ECDH_RSA_WITH_RC4_128_SHA 0xC00C
2876 #define BR_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA 0xC00D
2877 #define BR_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA 0xC00E
2878 #define BR_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA 0xC00F
2879 #define BR_TLS_ECDHE_RSA_WITH_NULL_SHA 0xC010
2880 #define BR_TLS_ECDHE_RSA_WITH_RC4_128_SHA 0xC011
2881 #define BR_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA 0xC012
2882 #define BR_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA 0xC013
2883 #define BR_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA 0xC014
2884 #define BR_TLS_ECDH_anon_WITH_NULL_SHA 0xC015
2885 #define BR_TLS_ECDH_anon_WITH_RC4_128_SHA 0xC016
2886 #define BR_TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA 0xC017
2887 #define BR_TLS_ECDH_anon_WITH_AES_128_CBC_SHA 0xC018
2888 #define BR_TLS_ECDH_anon_WITH_AES_256_CBC_SHA 0xC019
2889
2890 /* From RFC 5288 */
2891 #define BR_TLS_RSA_WITH_AES_128_GCM_SHA256 0x009C
2892 #define BR_TLS_RSA_WITH_AES_256_GCM_SHA384 0x009D
2893 #define BR_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 0x009E
2894 #define BR_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 0x009F
2895 #define BR_TLS_DH_RSA_WITH_AES_128_GCM_SHA256 0x00A0
2896 #define BR_TLS_DH_RSA_WITH_AES_256_GCM_SHA384 0x00A1
2897 #define BR_TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 0x00A2
2898 #define BR_TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 0x00A3
2899 #define BR_TLS_DH_DSS_WITH_AES_128_GCM_SHA256 0x00A4
2900 #define BR_TLS_DH_DSS_WITH_AES_256_GCM_SHA384 0x00A5
2901 #define BR_TLS_DH_anon_WITH_AES_128_GCM_SHA256 0x00A6
2902 #define BR_TLS_DH_anon_WITH_AES_256_GCM_SHA384 0x00A7
2903
2904 /* From RFC 5289 */
2905 #define BR_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 0xC023
2906 #define BR_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 0xC024
2907 #define BR_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 0xC025
2908 #define BR_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 0xC026
2909 #define BR_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 0xC027
2910 #define BR_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 0xC028
2911 #define BR_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 0xC029
2912 #define BR_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 0xC02A
2913 #define BR_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 0xC02B
2914 #define BR_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 0xC02C
2915 #define BR_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 0xC02D
2916 #define BR_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 0xC02E
2917 #define BR_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 0xC02F
2918 #define BR_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 0xC030
2919 #define BR_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 0xC031
2920 #define BR_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 0xC032
2921
2922 /* From RFC 7905 */
2923 #define BR_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 0xCCA8
2924 #define BR_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 0xCCA9
2925 #define BR_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 0xCCAA
2926 #define BR_TLS_PSK_WITH_CHACHA20_POLY1305_SHA256 0xCCAB
2927 #define BR_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256 0xCCAC
2928 #define BR_TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256 0xCCAD
2929 #define BR_TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256 0xCCAE
2930
2931 /* From RFC 7507 */
2932 #define BR_TLS_FALLBACK_SCSV 0x5600
2933
2934 /*
2935 * Symbolic constants for alerts.
2936 */
2937 #define BR_ALERT_CLOSE_NOTIFY 0
2938 #define BR_ALERT_UNEXPECTED_MESSAGE 10
2939 #define BR_ALERT_BAD_RECORD_MAC 20
2940 #define BR_ALERT_RECORD_OVERFLOW 22
2941 #define BR_ALERT_DECOMPRESSION_FAILURE 30
2942 #define BR_ALERT_HANDSHAKE_FAILURE 40
2943 #define BR_ALERT_BAD_CERTIFICATE 42
2944 #define BR_ALERT_UNSUPPORTED_CERTIFICATE 43
2945 #define BR_ALERT_CERTIFICATE_REVOKED 44
2946 #define BR_ALERT_CERTIFICATE_EXPIRED 45
2947 #define BR_ALERT_CERTIFICATE_UNKNOWN 46
2948 #define BR_ALERT_ILLEGAL_PARAMETER 47
2949 #define BR_ALERT_UNKNOWN_CA 48
2950 #define BR_ALERT_ACCESS_DENIED 49
2951 #define BR_ALERT_DECODE_ERROR 50
2952 #define BR_ALERT_DECRYPT_ERROR 51
2953 #define BR_ALERT_PROTOCOL_VERSION 70
2954 #define BR_ALERT_INSUFFICIENT_SECURITY 71
2955 #define BR_ALERT_INTERNAL_ERROR 80
2956 #define BR_ALERT_USER_CANCELED 90
2957 #define BR_ALERT_NO_RENEGOTIATION 100
2958 #define BR_ALERT_UNSUPPORTED_EXTENSION 110
2959
2960 #endif