2 * Copyright (c) 2016 Thomas Pornin <pornin@bolet.org>
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:
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
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
31 * If BR_USE_URANDOM is not defined, then try to autodetect its presence
32 * through compiler macros.
34 #ifndef BR_USE_URANDOM
37 * Macro values documented on:
38 * https://sourceforge.net/p/predef/wiki/OperatingSystems/
40 * Only the most common systems have been included here for now. This
41 * should be enriched later on.
44 || defined __ANDROID__ \
45 || defined __FreeBSD__ \
46 || defined __NetBSD__ \
47 || defined __OpenBSD__ \
48 || defined __DragonFly__ \
49 || defined __linux__ \
50 || (defined __sun && (defined __SVR4 || defined __svr4__)) \
51 || (defined __APPLE__ && defined __MACH__)
52 #define BR_USE_URANDOM 1
58 * If BR_USE_WIN32_RAND is not defined, perform autodetection here.
60 #ifndef BR_USE_WIN32_RAND
62 #if defined _WIN32 || defined _WIN64
63 #define BR_USE_WIN32_RAND 1
69 #include <sys/types.h>
78 #pragma comment(lib, "advapi32")
83 /* ==================================================================== */
85 * This part of the file does the low-level record management.
89 * IMPLEMENTATION NOTES
90 * ====================
92 * In this file, we designate by "input" (and the "i" letter) the "recv"
93 * operations: incoming records from the peer, from which payload data
94 * is obtained, and must be extracted by the application (or the SSL
95 * handshake engine). Similarly, "output" (and the "o" letter) is for
96 * "send": payload data injected by the application (and SSL handshake
97 * engine), to be wrapped into records, that are then conveyed to the
98 * peer over the transport medium.
100 * The input and output buffers may be distinct or shared. When
101 * shared, input and output cannot occur concurrently; the caller
102 * must make sure that it never needs to output data while input
103 * data has been received. In practice, a shared buffer prevents
104 * pipelining of HTTP requests, or similar protocols; however, a
105 * shared buffer saves RAM.
107 * The input buffer is pointed to by 'ibuf' and has size 'ibuf_len';
108 * the output buffer is pointed to by 'obuf' and has size 'obuf_len'.
109 * From the size of these buffers is derived the maximum fragment
110 * length, which will be honoured upon sending records; regardless of
111 * that length, incoming records will be processed as long as they
112 * fit in the input buffer, and their length still complies with the
113 * protocol specification (maximum plaintext payload length is 16384
116 * Three registers are used to manage buffering in ibuf, called ixa,
117 * ixb and ixc. Similarly, three registers are used to manage buffering
118 * in obuf, called oxa, oxb and oxc.
121 * At any time, the engine is in one of the following modes:
122 * -- Failed mode: an error occurs, no I/O can happen.
123 * -- Input mode: the engine can either receive record bytes from the
124 * transport layer, or it has some buffered payload bytes to yield.
125 * -- Output mode: the engine can either receive payload bytes, or it
126 * has some record bytes to send to the transport layer.
127 * -- Input/Output mode: both input and output modes are active. When
128 * the buffer is shared, this can happen only when the buffer is empty
129 * (no buffered payload bytes or record bytes in either direction).
135 * I/O failed for some reason (invalid received data, not enough room
136 * for the next record...). No I/O may ever occur again for this context,
137 * until an explicit reset is performed. This mode, and the error code,
138 * are also used for protocol errors, especially handshake errors.
144 * ixa index within ibuf[] for the currently read data
145 * ixb maximum index within ibuf[] for the currently read data
146 * ixc number of bytes not yet received for the current record
148 * -- When ixa == ixb, there is no available data for readers. When
149 * ixa != ixb, there is available data and it starts at offset ixa.
151 * -- When waiting for the next record header, ixa and ixb are equal
152 * and contain a value ranging from 0 to 4; ixc is equal to 5-ixa.
154 * -- When the header has been received, record data is obtained. The
155 * ixc field records how many bytes are still needed to reach the
156 * end of the current record.
158 * ** If encryption is active, then ixa and ixb are kept equal, and
159 * point to the end of the currently received record bytes. When
160 * ixc reaches 0, decryption/MAC is applied, and ixa and ixb are
163 * ** If encryption is not active, then ixa and ixb are distinct
164 * and data can be read right away. Additional record data is
165 * obtained only when ixa == ixb.
167 * Note: in input mode and no encryption, records larger than the buffer
168 * size are allowed. When encryption is active, the complete record must
169 * fit within the buffer, since it cannot be decrypted/MACed until it
170 * has been completely received.
172 * -- When receiving the next record header, 'version_in' contains the
173 * expected input version (0 if not expecting a specific version); on
174 * mismatch, the mode switches to 'failed'.
176 * -- When the header has been received, 'version_in' contains the received
177 * version. It is up to the caller to check and adjust the 'version_in' field
178 * to implement the required semantics.
180 * -- The 'record_type_in' field is updated with the incoming record type
181 * when the next record header has been received.
187 * oxa index within obuf[] for the currently accumulated data
188 * oxb maximum index within obuf[] for record data
189 * oxc pointer for start of record data, and for record sending
191 * -- When oxa != oxb, more data can be accumulated into the current
192 * record; when oxa == oxb, a closed record is being sent.
194 * -- When accumulating data, oxc points to the start of the data.
196 * -- During record sending, oxa (and oxb) point to the next record byte
197 * to send, and oxc indicates the end of the current record.
199 * Note: sent records must fit within the buffer, since the header is
200 * adjusted only when the complete record has been assembled.
202 * -- The 'version_out' and 'record_type_out' fields are used to build the
203 * record header when the mode is switched to 'sending'.
209 * The state register iomode contains one of the following values:
211 * BR_IO_FAILED I/O failed
212 * BR_IO_IN input mode
213 * BR_IO_OUT output mode
214 * BR_IO_INOUT input/output mode
216 * Whether encryption is active on incoming records is indicated by the
217 * incrypt flag. For outgoing records, there is no such flag; "encryption"
218 * is always considered active, but initially uses functions that do not
219 * encrypt anything. The 'incrypt' flag is needed because when there is
220 * no active encryption, records larger than the I/O buffer are accepted.
222 * Note: we do not support no-encryption modes (MAC only).
224 * TODO: implement GCM support
230 * 'max_frag_len' is the maximum plaintext size for an outgoing record.
231 * By default, it is set to the maximum value that fits in the provided
232 * buffers, in the following list: 512, 1024, 2048, 4096, 16384. The
233 * caller may change it if needed, but the new value MUST still fit in
234 * the buffers, and it MUST be one of the list above for compatibility
235 * with the Maximum Fragment Length extension.
237 * For incoming records, only the total buffer length and current
238 * encryption mode impact the maximum length for incoming records. The
239 * 'max_frag_len' value is still adjusted so that records up to that
240 * length can be both received and sent.
243 * Offsets and lengths:
244 * --------------------
246 * When sending fragments with TLS-1.1+, the maximum overhead is:
247 * 5 bytes for the record header
248 * 16 bytes for the explicit IV
249 * 48 bytes for the MAC (HMAC/SHA-384)
250 * 16 bytes for the padding (AES)
251 * so a total of 85 extra bytes. Note that we support block cipher sizes
252 * up to 16 bytes (AES) and HMAC output sizes up to 48 bytes (SHA-384).
254 * With TLS-1.0 and CBC mode, we apply a 1/n-1 split, for a maximum
256 * 5 bytes for the first record header
257 * 32 bytes for the first record payload (AES-CBC + HMAC/SHA-1)
258 * 5 bytes for the second record header
259 * 20 bytes for the MAC (HMAC/SHA-1)
260 * 16 bytes for the padding (AES)
261 * -1 byte to account for the payload byte in the first record
262 * so a total of 77 extra bytes at most, less than the 85 bytes above.
263 * Note that with TLS-1.0, the MAC is HMAC with either MD5 or SHA-1, but
264 * no other hash function.
266 * The implementation does not try to send larger records when the current
267 * encryption mode has less overhead.
269 * Maximum input record overhead is:
270 * 5 bytes for the record header
271 * 16 bytes for the explicit IV (TLS-1.1+)
272 * 48 bytes for the MAC (HMAC/SHA-384)
273 * 256 bytes for the padding
274 * so a total of 325 extra bytes.
276 * When receiving the next record header, it is written into the buffer
277 * bytes 0 to 4 (inclusive). Record data is always written into buf[]
278 * starting at offset 5. When encryption is active, the plaintext data
279 * may start at a larger offset (e.g. because of an explicit IV).
282 #define MAX_OUT_OVERHEAD 85
283 #define MAX_IN_OVERHEAD 325
287 br_ssl_engine_fail(br_ssl_engine_context
*rc
, int err
)
289 if (rc
->iomode
!= BR_IO_FAILED
) {
290 rc
->iomode
= BR_IO_FAILED
;
296 * Adjust registers for a new incoming record.
299 make_ready_in(br_ssl_engine_context
*rc
)
301 rc
->ixa
= rc
->ixb
= 0;
303 if (rc
->iomode
== BR_IO_IN
) {
304 rc
->iomode
= BR_IO_INOUT
;
309 * Adjust registers for a new outgoing record.
312 make_ready_out(br_ssl_engine_context
*rc
)
317 b
= rc
->obuf_len
- a
;
318 rc
->out
.vtable
->max_plaintext(&rc
->out
.vtable
, &a
, &b
);
319 if ((b
- a
) > rc
->max_frag_len
) {
320 b
= a
+ rc
->max_frag_len
;
325 if (rc
->iomode
== BR_IO_OUT
) {
326 rc
->iomode
= BR_IO_INOUT
;
332 br_ssl_engine_new_max_frag_len(br_ssl_engine_context
*rc
, unsigned max_frag_len
)
336 rc
->max_frag_len
= max_frag_len
;
337 nxb
= rc
->oxc
+ max_frag_len
;
338 if (rc
->oxa
< rc
->oxb
&& rc
->oxb
> nxb
&& rc
->oxa
< nxb
) {
343 /* see bearssl_ssl.h */
345 br_ssl_engine_set_buffer(br_ssl_engine_context
*rc
,
346 void *buf
, size_t buf_len
, int bidi
)
349 br_ssl_engine_set_buffers_bidi(rc
, NULL
, 0, NULL
, 0);
352 * In bidirectional mode, we want to maximise input
353 * buffer size, since we support arbitrary fragmentation
354 * when sending, but the peer will not necessarily
355 * comply to any low fragment length (in particular if
356 * we are the server, because the maximum fragment
357 * length extension is under client control).
359 * We keep a minimum size of 512 bytes for the plaintext
360 * of our outgoing records.
362 * br_ssl_engine_set_buffers_bidi() will compute the maximum
363 * fragment length for outgoing records by using the minimum
364 * of allocated spaces for both input and output records,
365 * rounded down to a standard length.
370 if (buf_len
< (512 + MAX_IN_OVERHEAD
371 + 512 + MAX_OUT_OVERHEAD
))
373 rc
->iomode
= BR_IO_FAILED
;
374 rc
->err
= BR_ERR_BAD_PARAM
;
376 } else if (buf_len
< (16384 + MAX_IN_OVERHEAD
377 + 512 + MAX_OUT_OVERHEAD
))
379 w
= 512 + MAX_OUT_OVERHEAD
;
381 w
= buf_len
- (16384 + MAX_IN_OVERHEAD
);
383 br_ssl_engine_set_buffers_bidi(rc
,
385 (unsigned char *)buf
+ w
, w
);
387 br_ssl_engine_set_buffers_bidi(rc
,
388 buf
, buf_len
, NULL
, 0);
393 /* see bearssl_ssl.h */
395 br_ssl_engine_set_buffers_bidi(br_ssl_engine_context
*rc
,
396 void *ibuf
, size_t ibuf_len
, void *obuf
, size_t obuf_len
)
398 rc
->iomode
= BR_IO_INOUT
;
402 rc
->record_type_in
= 0;
404 rc
->record_type_out
= 0;
406 if (rc
->ibuf
== NULL
) {
407 br_ssl_engine_fail(rc
, BR_ERR_BAD_PARAM
);
413 rc
->ibuf_len
= ibuf_len
;
419 rc
->obuf_len
= obuf_len
;
422 * Compute the maximum fragment length, that fits for
423 * both incoming and outgoing records. This length will
424 * be used in fragment length negotiation, so we must
425 * honour it both ways. Regardless, larger incoming
426 * records will be accepted, as long as they fit in the
427 * actual buffer size.
429 for (u
= 14; u
>= 9; u
--) {
432 flen
= (size_t)1 << u
;
433 if (obuf_len
>= flen
+ MAX_OUT_OVERHEAD
434 && ibuf_len
>= flen
+ MAX_IN_OVERHEAD
)
440 br_ssl_engine_fail(rc
, BR_ERR_BAD_PARAM
);
442 } else if (u
== 13) {
445 rc
->max_frag_len
= (size_t)1 << u
;
446 rc
->log_max_frag_len
= u
;
447 rc
->peer_log_max_frag_len
= 0;
449 rc
->out
.vtable
= &br_sslrec_out_clear_vtable
;
455 * Clear buffers in both directions.
458 engine_clearbuf(br_ssl_engine_context
*rc
)
465 * Make sure the internal PRNG is initialised (but not necessarily
466 * seeded properly yet).
469 rng_init(br_ssl_engine_context
*cc
)
471 const br_hash_class
*h
;
473 if (cc
->rng_init_done
!= 0) {
478 * If using TLS-1.2, then SHA-256 or SHA-384 must be present (or
479 * both); we prefer SHA-256 which is faster for 32-bit systems.
481 * If using TLS-1.0 or 1.1 then SHA-1 must be present.
483 * Though HMAC_DRBG/SHA-1 is, as far as we know, as safe as
484 * these things can be, we still prefer the SHA-2 functions over
485 * SHA-1, if only for public relations (known theoretical
486 * weaknesses of SHA-1 with regards to collisions are mostly
487 * irrelevant here, but they still make people nervous).
489 h
= br_multihash_getimpl(&cc
->mhash
, br_sha256_ID
);
491 h
= br_multihash_getimpl(&cc
->mhash
, br_sha384_ID
);
493 h
= br_multihash_getimpl(&cc
->mhash
,
496 br_ssl_engine_fail(cc
, BR_ERR_BAD_STATE
);
501 br_hmac_drbg_init(&cc
->rng
, h
, NULL
, 0);
502 cc
->rng_init_done
= 1;
508 br_ssl_engine_init_rand(br_ssl_engine_context
*cc
)
515 * We always try OS/hardware seeding once. If it works, then
516 * we assume proper seeding. If not, then external entropy must
517 * have been injected; otherwise, we report an error.
519 if (!cc
->rng_os_rand_done
) {
522 sd
= br_prng_seeder_system(NULL
);
523 if (sd
!= 0 && sd(&cc
->rng
.vtable
)) {
524 cc
->rng_init_done
= 2;
526 cc
->rng_os_rand_done
= 1;
528 if (cc
->rng_init_done
< 2) {
529 br_ssl_engine_fail(cc
, BR_ERR_NO_RANDOM
);
535 /* see bearssl_ssl.h */
537 br_ssl_engine_inject_entropy(br_ssl_engine_context
*cc
,
538 const void *data
, size_t len
)
541 * Externally provided entropy is assumed to be "good enough"
542 * (we cannot really test its quality) so if the RNG structure
543 * could be initialised at all, then we marked the RNG as
549 br_hmac_drbg_update(&cc
->rng
, data
, len
);
550 cc
->rng_init_done
= 2;
554 * We define a few internal functions that implement the low-level engine
555 * API for I/O; the external API (br_ssl_engine_sendapp_buf() and similar
556 * functions) is built upon these function, with special processing for
557 * records which are not of type "application data".
559 * recvrec_buf, recvrec_ack receives bytes from transport medium
560 * sendrec_buf, sendrec_ack send bytes to transport medium
561 * recvpld_buf, recvpld_ack receives payload data from engine
562 * sendpld_buf, sendpld_ack send payload data to engine
565 static unsigned char *
566 recvrec_buf(const br_ssl_engine_context
*rc
, size_t *len
)
568 if (rc
->shutdown_recv
) {
574 * Bytes from the transport can be injected only if the mode is
575 * compatible (in or in/out), and ixa == ixb; ixc then contains
576 * the number of bytes that are still expected (but it may
577 * exceed our buffer size).
579 * We cannot get "stuck" here (buffer is full, but still more
580 * data is expected) because oversized records are detected when
581 * their header is processed.
583 switch (rc
->iomode
) {
586 if (rc
->ixa
== rc
->ixb
) {
590 if (z
> rc
->ibuf_len
- rc
->ixa
) {
591 z
= rc
->ibuf_len
- rc
->ixa
;
594 return rc
->ibuf
+ rc
->ixa
;
603 recvrec_ack(br_ssl_engine_context
*rc
, size_t len
)
609 * Adjust state if necessary (for a shared input/output buffer):
610 * we got some incoming bytes, so we cannot (temporarily) handle
613 if (rc
->iomode
== BR_IO_INOUT
&& rc
->ibuf
== rc
->obuf
) {
614 rc
->iomode
= BR_IO_IN
;
618 * Adjust data pointers.
620 rc
->ixb
= (rc
->ixa
+= len
);
624 * If we are receiving a header and did not fully obtained it
625 * yet, then just wait for the next bytes.
632 * If we just obtained a full header, process it.
639 * Get record type and version. We support only versions
640 * 3.x (if the version major number does not match, then
641 * we suppose that the record format is too alien for us
644 * Note: right now, we reject clients that try to send
645 * a ClientHello in a format compatible with SSL-2.0. It
646 * is unclear whether this will ever be supported; and
647 * if we want to support it, then this might be done in
648 * in the server-specific code, not here.
650 rc
->record_type_in
= rc
->ibuf
[0];
651 version
= br_dec16be(rc
->ibuf
+ 1);
652 if ((version
>> 8) != 3) {
653 br_ssl_engine_fail(rc
, BR_ERR_UNSUPPORTED_VERSION
);
658 * We ensure that successive records have the same
659 * version. The handshake code must check and adjust the
660 * variables when necessary to accommodate the protocol
661 * negotiation details.
663 if (rc
->version_in
!= 0 && rc
->version_in
!= version
) {
664 br_ssl_engine_fail(rc
, BR_ERR_BAD_VERSION
);
667 rc
->version_in
= version
;
670 * Decode record length. We must check that the length
671 * is valid (relatively to the current encryption mode)
672 * and also (if encryption is active) that the record
673 * will fit in our buffer.
675 * When no encryption is active, we can process records
676 * by chunks, and thus accept any record up to the
677 * maximum allowed plaintext length (16384 bytes).
679 rlen
= br_dec16be(rc
->ibuf
+ 3);
681 if (!rc
->in
.vtable
->check_length(
682 &rc
->in
.vtable
, rlen
))
684 br_ssl_engine_fail(rc
, BR_ERR_BAD_LENGTH
);
687 if (rlen
> (rc
->ibuf_len
- 5)) {
688 br_ssl_engine_fail(rc
, BR_ERR_TOO_LARGE
);
693 br_ssl_engine_fail(rc
, BR_ERR_BAD_LENGTH
);
699 * If the record is completely empty then we must switch
700 * to a new record. Note that, in that case, we
701 * completely ignore the record type, which is fitting
702 * since we received no actual data of that type.
704 * A completely empty record is technically allowed as
705 * long as encryption/MAC is not active, i.e. before
706 * completion of the first handshake. It it still weird;
707 * it might conceptually be useful as a heartbeat or
708 * keep-alive mechanism while some lengthy operation is
709 * going on, e.g. interaction with a human user.
714 rc
->ixa
= rc
->ixb
= 5;
721 * If there is no active encryption, then the data can be read
722 * right away. Note that we do not receive bytes from the
723 * transport medium when we still have payload bytes to be
732 * Since encryption is active, we must wait for a full record
733 * before processing it.
740 * We got the full record. Decrypt it.
742 pbuf_len
= rc
->ixa
- 5;
743 pbuf
= rc
->in
.vtable
->decrypt(&rc
->in
.vtable
,
744 rc
->record_type_in
, rc
->version_in
, rc
->ibuf
+ 5, &pbuf_len
);
746 br_ssl_engine_fail(rc
, BR_ERR_BAD_MAC
);
749 rc
->ixa
= (size_t)(pbuf
- rc
->ibuf
);
750 rc
->ixb
= rc
->ixa
+ pbuf_len
;
753 * Decryption may have yielded an empty record, in which case
754 * we get back to "ready" state immediately.
756 if (rc
->ixa
== rc
->ixb
) {
763 br_ssl_engine_recvrec_finished(const br_ssl_engine_context
*rc
)
765 switch (rc
->iomode
) {
768 return rc
->ixc
== 0 || rc
->ixa
< 5;
774 static unsigned char *
775 recvpld_buf(const br_ssl_engine_context
*rc
, size_t *len
)
778 * There is payload data to be read only if the mode is
779 * compatible, and ixa != ixb.
781 switch (rc
->iomode
) {
784 *len
= rc
->ixb
- rc
->ixa
;
785 return (*len
== 0) ? NULL
: (rc
->ibuf
+ rc
->ixa
);
793 recvpld_ack(br_ssl_engine_context
*rc
, size_t len
)
798 * If we read all the available data, then we either expect
799 * the remainder of the current record (if the current record
800 * was not finished; this may happen when encryption is not
801 * active), or go to "ready" state.
803 if (rc
->ixa
== rc
->ixb
) {
807 rc
->ixa
= rc
->ixb
= 5;
812 static unsigned char *
813 sendpld_buf(const br_ssl_engine_context
*rc
, size_t *len
)
816 * Payload data can be injected only if the current mode is
817 * compatible, and oxa != oxb.
819 switch (rc
->iomode
) {
822 *len
= rc
->oxb
- rc
->oxa
;
823 return (*len
== 0) ? NULL
: (rc
->obuf
+ rc
->oxa
);
831 * If some payload bytes have been accumulated, then wrap them into
832 * an outgoing record. Otherwise, this function does nothing, unless
833 * 'force' is non-zero, in which case an empty record is assembled.
835 * The caller must take care not to invoke this function if the engine
836 * is not currently ready to receive payload bytes to send.
839 sendpld_flush(br_ssl_engine_context
*rc
, int force
)
844 if (rc
->oxa
== rc
->oxb
) {
847 xlen
= rc
->oxa
- rc
->oxc
;
848 if (xlen
== 0 && !force
) {
851 buf
= rc
->out
.vtable
->encrypt(&rc
->out
.vtable
,
852 rc
->record_type_out
, rc
->version_out
,
853 rc
->obuf
+ rc
->oxc
, &xlen
);
854 rc
->oxb
= rc
->oxa
= (size_t)(buf
- rc
->obuf
);
855 rc
->oxc
= rc
->oxa
+ xlen
;
859 sendpld_ack(br_ssl_engine_context
*rc
, size_t len
)
862 * If using a shared buffer, then we may have to modify the
865 if (rc
->iomode
== BR_IO_INOUT
&& rc
->ibuf
== rc
->obuf
) {
866 rc
->iomode
= BR_IO_OUT
;
869 if (rc
->oxa
>= rc
->oxb
) {
871 * Set oxb to one more than oxa so that sendpld_flush()
872 * does not mistakingly believe that a record is
873 * already prepared and being sent.
875 rc
->oxb
= rc
->oxa
+ 1;
876 sendpld_flush(rc
, 0);
880 static unsigned char *
881 sendrec_buf(const br_ssl_engine_context
*rc
, size_t *len
)
884 * When still gathering payload bytes, oxc points to the start
885 * of the record data, so oxc <= oxa. However, when a full
886 * record has been completed, oxc points to the end of the record,
889 switch (rc
->iomode
) {
892 if (rc
->oxc
> rc
->oxa
) {
893 *len
= rc
->oxc
- rc
->oxa
;
894 return rc
->obuf
+ rc
->oxa
;
903 sendrec_ack(br_ssl_engine_context
*rc
, size_t len
)
905 rc
->oxb
= (rc
->oxa
+= len
);
906 if (rc
->oxa
== rc
->oxc
) {
912 * Test whether there is some buffered outgoing record that still must
916 has_rec_tosend(const br_ssl_engine_context
*rc
)
918 return rc
->oxa
== rc
->oxb
&& rc
->oxa
!= rc
->oxc
;
922 * The "no encryption" mode has no overhead. It limits the payload size
923 * to the maximum size allowed by the standard (16384 bytes); the caller
924 * is responsible for possibly enforcing a smaller fragment length.
927 clear_max_plaintext(const br_sslrec_out_clear_context
*cc
,
928 size_t *start
, size_t *end
)
935 *end
= *start
+ 16384;
940 * In "no encryption" mode, encryption is trivial (a no-operation) so
941 * we just have to encode the header.
943 static unsigned char *
944 clear_encrypt(br_sslrec_out_clear_context
*cc
,
945 int record_type
, unsigned version
, void *data
, size_t *data_len
)
950 buf
= (unsigned char *)data
- 5;
951 buf
[0] = record_type
;
952 br_enc16be(buf
+ 1, version
);
953 br_enc16be(buf
+ 3, *data_len
);
958 /* see bearssl_ssl.h */
959 const br_sslrec_out_class br_sslrec_out_clear_vtable
= {
960 sizeof(br_sslrec_out_clear_context
),
961 (void (*)(const br_sslrec_out_class
*const *, size_t *, size_t *))
962 &clear_max_plaintext
,
963 (unsigned char *(*)(const br_sslrec_out_class
**,
964 int, unsigned, void *, size_t *))
968 /* ==================================================================== */
970 * In this part of the file, we handle the various record types, and
971 * communications with the handshake processor.
975 * IMPLEMENTATION NOTES
976 * ====================
978 * The handshake processor is written in T0 and runs as a coroutine.
979 * It receives the contents of all records except application data, and
980 * is responsible for producing the contents of all records except
983 * A state flag is maintained, which specifies whether application data
984 * is acceptable or not. When it is set:
986 * -- Application data can be injected as payload data (provided that
987 * the output buffer is ready for that).
989 * -- Incoming application data records are accepted, and yield data
990 * that the caller may retrieve.
992 * When the flag is cleared, application data is not accepted from the
993 * application, and incoming application data records trigger an error.
996 * Records of type handshake, alert or change-cipher-spec are handled
997 * by the handshake processor. The handshake processor is written in T0
998 * and runs as a coroutine; it gets invoked whenever one of the following
999 * situations is reached:
1001 * -- An incoming record has type handshake, alert or change-cipher-spec,
1002 * and yields data that can be read (zero-length records are thus
1005 * -- An outgoing record has just finished being sent, and the "application
1006 * data" flag is cleared.
1008 * -- The caller wishes to perform a close (call to br_ssl_engine_close()).
1010 * -- The caller wishes to perform a renegotiation (call to
1011 * br_ssl_engine_renegotiate()).
1013 * Whenever the handshake processor is entered, access to the payload
1014 * buffers is provided, along with some information about explicit
1015 * closures or renegotiations.
1018 /* see bearssl_ssl.h */
1020 br_ssl_engine_set_suites(br_ssl_engine_context
*cc
,
1021 const uint16_t *suites
, size_t suites_num
)
1023 if ((suites_num
* sizeof *suites
) > sizeof cc
->suites_buf
) {
1024 br_ssl_engine_fail(cc
, BR_ERR_BAD_PARAM
);
1027 memcpy(cc
->suites_buf
, suites
, suites_num
* sizeof *suites
);
1028 cc
->suites_num
= suites_num
;
1032 * Give control to handshake processor. 'action' is 1 for a close,
1033 * 2 for a renegotiation, or 0 for a jump due to I/O completion.
1036 jump_handshake(br_ssl_engine_context
*cc
, int action
)
1039 * We use a loop because the handshake processor actions may
1040 * allow for more actions; namely, if the processor reads all
1041 * input data, then it may allow for output data to be produced,
1042 * in case of a shared in/out buffer.
1045 size_t hlen_in
, hlen_out
;
1048 * Get input buffer. We do not want to provide
1049 * application data to the handshake processor (we could
1050 * get called with an explicit close or renegotiation
1051 * while there is application data ready to be read).
1053 cc
->hbuf_in
= recvpld_buf(cc
, &hlen_in
);
1054 if (cc
->hbuf_in
!= NULL
1055 && cc
->record_type_in
== BR_SSL_APPLICATION_DATA
)
1061 * Get output buffer. The handshake processor never
1062 * leaves an unfinished outgoing record, so if there is
1063 * buffered output, then it MUST be some application
1064 * data, so the processor cannot write to it.
1066 cc
->saved_hbuf_out
= cc
->hbuf_out
= sendpld_buf(cc
, &hlen_out
);
1067 if (cc
->hbuf_out
!= NULL
&& br_ssl_engine_has_pld_to_send(cc
)) {
1072 * Note: hlen_in and hlen_out can be both non-zero only if
1073 * the input and output buffers are disjoint. Thus, we can
1074 * offer both buffers to the handshake code.
1077 cc
->hlen_in
= hlen_in
;
1078 cc
->hlen_out
= hlen_out
;
1079 cc
->action
= action
;
1080 cc
->hsrun(&cc
->cpu
);
1081 if (br_ssl_engine_closed(cc
)) {
1084 if (cc
->hbuf_out
!= cc
->saved_hbuf_out
) {
1085 sendpld_ack(cc
, cc
->hbuf_out
- cc
->saved_hbuf_out
);
1087 if (hlen_in
!= cc
->hlen_in
) {
1088 recvpld_ack(cc
, hlen_in
- cc
->hlen_in
);
1089 if (cc
->hlen_in
== 0) {
1091 * We read all data bytes, which may have
1092 * released the output buffer in case it
1093 * is shared with the input buffer, and
1094 * the handshake code might be waiting for
1107 br_ssl_engine_flush_record(br_ssl_engine_context
*cc
)
1109 if (cc
->hbuf_out
!= cc
->saved_hbuf_out
) {
1110 sendpld_ack(cc
, cc
->hbuf_out
- cc
->saved_hbuf_out
);
1112 if (br_ssl_engine_has_pld_to_send(cc
)) {
1113 sendpld_flush(cc
, 0);
1115 cc
->saved_hbuf_out
= cc
->hbuf_out
= sendpld_buf(cc
, &cc
->hlen_out
);
1118 /* see bearssl_ssl.h */
1120 br_ssl_engine_sendapp_buf(const br_ssl_engine_context
*cc
, size_t *len
)
1122 if (!(cc
->application_data
& 1)) {
1126 return sendpld_buf(cc
, len
);
1129 /* see bearssl_ssl.h */
1131 br_ssl_engine_sendapp_ack(br_ssl_engine_context
*cc
, size_t len
)
1133 sendpld_ack(cc
, len
);
1136 /* see bearssl_ssl.h */
1138 br_ssl_engine_recvapp_buf(const br_ssl_engine_context
*cc
, size_t *len
)
1140 if (!(cc
->application_data
& 1)
1141 || cc
->record_type_in
!= BR_SSL_APPLICATION_DATA
)
1146 return recvpld_buf(cc
, len
);
1149 /* see bearssl_ssl.h */
1151 br_ssl_engine_recvapp_ack(br_ssl_engine_context
*cc
, size_t len
)
1153 recvpld_ack(cc
, len
);
1156 /* see bearssl_ssl.h */
1158 br_ssl_engine_sendrec_buf(const br_ssl_engine_context
*cc
, size_t *len
)
1160 return sendrec_buf(cc
, len
);
1163 /* see bearssl_ssl.h */
1165 br_ssl_engine_sendrec_ack(br_ssl_engine_context
*cc
, size_t len
)
1167 sendrec_ack(cc
, len
);
1168 if (len
!= 0 && !has_rec_tosend(cc
)
1169 && (cc
->record_type_out
!= BR_SSL_APPLICATION_DATA
1170 || (cc
->application_data
& 1) == 0))
1172 jump_handshake(cc
, 0);
1176 /* see bearssl_ssl.h */
1178 br_ssl_engine_recvrec_buf(const br_ssl_engine_context
*cc
, size_t *len
)
1180 return recvrec_buf(cc
, len
);
1183 /* see bearssl_ssl.h */
1185 br_ssl_engine_recvrec_ack(br_ssl_engine_context
*cc
, size_t len
)
1189 recvrec_ack(cc
, len
);
1190 if (br_ssl_engine_closed(cc
)) {
1195 * We just received some bytes from the peer. This may have
1196 * yielded some payload bytes, in which case we must process
1197 * them according to the record type.
1199 buf
= recvpld_buf(cc
, &len
);
1201 switch (cc
->record_type_in
) {
1202 case BR_SSL_CHANGE_CIPHER_SPEC
:
1204 case BR_SSL_HANDSHAKE
:
1205 jump_handshake(cc
, 0);
1207 case BR_SSL_APPLICATION_DATA
:
1208 if (cc
->application_data
== 1) {
1213 * If we are currently closing, and waiting for
1214 * a close_notify from the peer, then incoming
1215 * application data should be discarded.
1217 if (cc
->application_data
== 2) {
1218 recvpld_ack(cc
, len
);
1224 br_ssl_engine_fail(cc
, BR_ERR_UNEXPECTED
);
1230 /* see bearssl_ssl.h */
1232 br_ssl_engine_close(br_ssl_engine_context
*cc
)
1234 if (!br_ssl_engine_closed(cc
)) {
1235 jump_handshake(cc
, 1);
1239 /* see bearssl_ssl.h */
1241 br_ssl_engine_renegotiate(br_ssl_engine_context
*cc
)
1245 if (br_ssl_engine_closed(cc
) || cc
->reneg
== 1
1246 || (cc
->flags
& BR_OPT_NO_RENEGOTIATION
) != 0
1247 || br_ssl_engine_recvapp_buf(cc
, &len
) != NULL
)
1251 jump_handshake(cc
, 2);
1257 br_ssl_engine_current_state(const br_ssl_engine_context
*cc
)
1262 if (br_ssl_engine_closed(cc
)) {
1263 return BR_SSL_CLOSED
;
1267 if (br_ssl_engine_sendrec_buf(cc
, &len
) != NULL
) {
1268 s
|= BR_SSL_SENDREC
;
1270 if (br_ssl_engine_recvrec_buf(cc
, &len
) != NULL
) {
1271 s
|= BR_SSL_RECVREC
;
1273 if (br_ssl_engine_sendapp_buf(cc
, &len
) != NULL
) {
1274 s
|= BR_SSL_SENDAPP
;
1276 if (br_ssl_engine_recvapp_buf(cc
, &len
) != NULL
) {
1277 s
|= BR_SSL_RECVAPP
;
1282 /* see bearssl_ssl.h */
1284 br_ssl_engine_flush(br_ssl_engine_context
*cc
, int force
)
1286 if (!br_ssl_engine_closed(cc
) && (cc
->application_data
& 1) != 0) {
1287 sendpld_flush(cc
, force
);
1293 br_ssl_engine_hs_reset(br_ssl_engine_context
*cc
,
1294 void (*hsinit
)(void *), void (*hsrun
)(void *))
1296 engine_clearbuf(cc
);
1297 cc
->cpu
.dp
= cc
->dp_stack
;
1298 cc
->cpu
.rp
= cc
->rp_stack
;
1301 cc
->shutdown_recv
= 0;
1302 cc
->application_data
= 0;
1304 jump_handshake(cc
, 0);
1309 br_ssl_engine_get_PRF(br_ssl_engine_context
*cc
, int prf_id
)
1311 if (cc
->session
.version
>= BR_TLS12
) {
1312 if (prf_id
== br_sha384_ID
) {
1313 return cc
->prf_sha384
;
1315 return cc
->prf_sha256
;
1324 br_ssl_engine_compute_master(br_ssl_engine_context
*cc
,
1325 int prf_id
, const void *pms
, size_t pms_len
)
1327 br_tls_prf_impl iprf
;
1328 br_tls_prf_seed_chunk seed
[2] = {
1329 { cc
->client_random
, sizeof cc
->client_random
},
1330 { cc
->server_random
, sizeof cc
->server_random
}
1333 iprf
= br_ssl_engine_get_PRF(cc
, prf_id
);
1334 iprf(cc
->session
.master_secret
, sizeof cc
->session
.master_secret
,
1335 pms
, pms_len
, "master secret", 2, seed
);
1339 * Compute key block.
1342 compute_key_block(br_ssl_engine_context
*cc
, int prf_id
,
1343 size_t half_len
, unsigned char *kb
)
1345 br_tls_prf_impl iprf
;
1346 br_tls_prf_seed_chunk seed
[2] = {
1347 { cc
->server_random
, sizeof cc
->server_random
},
1348 { cc
->client_random
, sizeof cc
->client_random
}
1351 iprf
= br_ssl_engine_get_PRF(cc
, prf_id
);
1352 iprf(kb
, half_len
<< 1,
1353 cc
->session
.master_secret
, sizeof cc
->session
.master_secret
,
1354 "key expansion", 2, seed
);
1359 br_ssl_engine_switch_cbc_in(br_ssl_engine_context
*cc
,
1360 int is_client
, int prf_id
, int mac_id
,
1361 const br_block_cbcdec_class
*bc_impl
, size_t cipher_key_len
)
1363 unsigned char kb
[192];
1364 unsigned char *cipher_key
, *mac_key
, *iv
;
1365 const br_hash_class
*imh
;
1366 size_t mac_key_len
, mac_out_len
, iv_len
;
1368 imh
= br_ssl_engine_get_hash(cc
, mac_id
);
1369 mac_out_len
= (imh
->desc
>> BR_HASHDESC_OUT_OFF
) & BR_HASHDESC_OUT_MASK
;
1370 mac_key_len
= mac_out_len
;
1373 * TLS 1.1+ uses per-record explicit IV, so no IV to generate here.
1375 if (cc
->session
.version
>= BR_TLS11
) {
1378 iv_len
= bc_impl
->block_size
;
1380 compute_key_block(cc
, prf_id
,
1381 mac_key_len
+ cipher_key_len
+ iv_len
, kb
);
1383 mac_key
= &kb
[mac_key_len
];
1384 cipher_key
= &kb
[(mac_key_len
<< 1) + cipher_key_len
];
1385 iv
= &kb
[((mac_key_len
+ cipher_key_len
) << 1) + iv_len
];
1388 cipher_key
= &kb
[mac_key_len
<< 1];
1389 iv
= &kb
[(mac_key_len
+ cipher_key_len
) << 1];
1394 cc
->icbc_in
->init(&cc
->in
.cbc
.vtable
,
1395 bc_impl
, cipher_key
, cipher_key_len
,
1396 imh
, mac_key
, mac_key_len
, mac_out_len
, iv
);
1402 br_ssl_engine_switch_cbc_out(br_ssl_engine_context
*cc
,
1403 int is_client
, int prf_id
, int mac_id
,
1404 const br_block_cbcenc_class
*bc_impl
, size_t cipher_key_len
)
1406 unsigned char kb
[192];
1407 unsigned char *cipher_key
, *mac_key
, *iv
;
1408 const br_hash_class
*imh
;
1409 size_t mac_key_len
, mac_out_len
, iv_len
;
1411 imh
= br_ssl_engine_get_hash(cc
, mac_id
);
1412 mac_out_len
= (imh
->desc
>> BR_HASHDESC_OUT_OFF
) & BR_HASHDESC_OUT_MASK
;
1413 mac_key_len
= mac_out_len
;
1416 * TLS 1.1+ uses per-record explicit IV, so no IV to generate here.
1418 if (cc
->session
.version
>= BR_TLS11
) {
1421 iv_len
= bc_impl
->block_size
;
1423 compute_key_block(cc
, prf_id
,
1424 mac_key_len
+ cipher_key_len
+ iv_len
, kb
);
1427 cipher_key
= &kb
[mac_key_len
<< 1];
1428 iv
= &kb
[(mac_key_len
+ cipher_key_len
) << 1];
1430 mac_key
= &kb
[mac_key_len
];
1431 cipher_key
= &kb
[(mac_key_len
<< 1) + cipher_key_len
];
1432 iv
= &kb
[((mac_key_len
+ cipher_key_len
) << 1) + iv_len
];
1437 cc
->icbc_out
->init(&cc
->out
.cbc
.vtable
,
1438 bc_impl
, cipher_key
, cipher_key_len
,
1439 imh
, mac_key
, mac_key_len
, mac_out_len
, iv
);
1444 br_ssl_engine_switch_gcm_in(br_ssl_engine_context
*cc
,
1445 int is_client
, int prf_id
,
1446 const br_block_ctr_class
*bc_impl
, size_t cipher_key_len
)
1448 unsigned char kb
[72];
1449 unsigned char *cipher_key
, *iv
;
1451 compute_key_block(cc
, prf_id
, cipher_key_len
+ 4, kb
);
1453 cipher_key
= &kb
[cipher_key_len
];
1454 iv
= &kb
[(cipher_key_len
<< 1) + 4];
1456 cipher_key
= &kb
[0];
1457 iv
= &kb
[cipher_key_len
<< 1];
1459 cc
->igcm_in
->init(&cc
->in
.gcm
.vtable
.in
,
1460 bc_impl
, cipher_key
, cipher_key_len
, cc
->ighash
, iv
);
1466 br_ssl_engine_switch_gcm_out(br_ssl_engine_context
*cc
,
1467 int is_client
, int prf_id
,
1468 const br_block_ctr_class
*bc_impl
, size_t cipher_key_len
)
1470 unsigned char kb
[72];
1471 unsigned char *cipher_key
, *iv
;
1473 compute_key_block(cc
, prf_id
, cipher_key_len
+ 4, kb
);
1475 cipher_key
= &kb
[0];
1476 iv
= &kb
[cipher_key_len
<< 1];
1478 cipher_key
= &kb
[cipher_key_len
];
1479 iv
= &kb
[(cipher_key_len
<< 1) + 4];
1481 cc
->igcm_out
->init(&cc
->out
.gcm
.vtable
.out
,
1482 bc_impl
, cipher_key
, cipher_key_len
, cc
->ighash
, iv
);
1487 br_ssl_engine_switch_chapol_in(br_ssl_engine_context
*cc
,
1488 int is_client
, int prf_id
)
1490 unsigned char kb
[88];
1491 unsigned char *cipher_key
, *iv
;
1493 compute_key_block(cc
, prf_id
, 44, kb
);
1495 cipher_key
= &kb
[32];
1498 cipher_key
= &kb
[0];
1501 cc
->ichapol_in
->init(&cc
->in
.chapol
.vtable
.in
,
1502 cc
->ichacha
, cc
->ipoly
, cipher_key
, iv
);
1508 br_ssl_engine_switch_chapol_out(br_ssl_engine_context
*cc
,
1509 int is_client
, int prf_id
)
1511 unsigned char kb
[88];
1512 unsigned char *cipher_key
, *iv
;
1514 compute_key_block(cc
, prf_id
, 44, kb
);
1516 cipher_key
= &kb
[0];
1519 cipher_key
= &kb
[32];
1522 cc
->ichapol_out
->init(&cc
->out
.chapol
.vtable
.out
,
1523 cc
->ichacha
, cc
->ipoly
, cipher_key
, iv
);