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