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
28 * If BR_USE_URANDOM is not defined, then try to autodetect its presence
29 * through compiler macros.
31 #ifndef BR_USE_URANDOM
34 * Macro values documented on:
35 * https://sourceforge.net/p/predef/wiki/OperatingSystems/
37 * Only the most common systems have been included here for now. This
38 * should be enriched later on.
41 || defined __ANDROID__ \
42 || defined __FreeBSD__ \
43 || defined __NetBSD__ \
44 || defined __OpenBSD__ \
45 || defined __DragonFly__ \
46 || defined __linux__ \
47 || (defined __sun && (defined __SVR4 || defined __svr4__)) \
48 || (defined __APPLE__ && defined __MACH__)
49 #define BR_USE_URANDOM 1
55 * If BR_USE_WIN32_RAND is not defined, perform autodetection here.
57 #ifndef BR_USE_WIN32_RAND
59 #if defined _WIN32 || defined _WIN64
60 #define BR_USE_WIN32_RAND 1
66 #include <sys/types.h>
75 #pragma comment(lib, "advapi32")
78 /* ==================================================================== */
80 * This part of the file does the low-level record management.
84 * IMPLEMENTATION NOTES
85 * ====================
87 * In this file, we designate by "input" (and the "i" letter) the "recv"
88 * operations: incoming records from the peer, from which payload data
89 * is obtained, and must be extracted by the application (or the SSL
90 * handshake engine). Similarly, "output" (and the "o" letter) is for
91 * "send": payload data injected by the application (and SSL handshake
92 * engine), to be wrapped into records, that are then conveyed to the
93 * peer over the transport medium.
95 * The input and output buffers may be distinct or shared. When
96 * shared, input and output cannot occur concurrently; the caller
97 * must make sure that it never needs to output data while input
98 * data has been received. In practice, a shared buffer prevents
99 * pipelining of HTTP requests, or similar protocols; however, a
100 * shared buffer saves RAM.
102 * The input buffer is pointed to by 'ibuf' and has size 'ibuf_len';
103 * the output buffer is pointed to by 'obuf' and has size 'obuf_len'.
104 * From the size of these buffers is derived the maximum fragment
105 * length, which will be honoured upon sending records; regardless of
106 * that length, incoming records will be processed as long as they
107 * fit in the input buffer, and their length still complies with the
108 * protocol specification (maximum plaintext payload length is 16384
111 * Three registers are used to manage buffering in ibuf, called ixa,
112 * ixb and ixc. Similarly, three registers are used to manage buffering
113 * in obuf, called oxa, oxb and oxc.
116 * At any time, the engine is in one of the following modes:
117 * -- Failed mode: an error occurs, no I/O can happen.
118 * -- Input mode: the engine can either receive record bytes from the
119 * transport layer, or it has some buffered payload bytes to yield.
120 * -- Output mode: the engine can either receive payload bytes, or it
121 * has some record bytes to send to the transport layer.
122 * -- Input/Output mode: both input and output modes are active. When
123 * the buffer is shared, this can happen only when the buffer is empty
124 * (no buffered payload bytes or record bytes in either direction).
130 * I/O failed for some reason (invalid received data, not enough room
131 * for the next record...). No I/O may ever occur again for this context,
132 * until an explicit reset is performed. This mode, and the error code,
133 * are also used for protocol errors, especially handshake errors.
139 * ixa index within ibuf[] for the currently read data
140 * ixb maximum index within ibuf[] for the currently read data
141 * ixc number of bytes not yet received for the current record
143 * -- When ixa == ixb, there is no available data for readers. When
144 * ixa != ixb, there is available data and it starts at offset ixa.
146 * -- When waiting for the next record header, ixa and ixb are equal
147 * and contain a value ranging from 0 to 4; ixc is equal to 5-ixa.
149 * -- When the header has been received, record data is obtained. The
150 * ixc field records how many bytes are still needed to reach the
151 * end of the current record.
153 * ** If encryption is active, then ixa and ixb are kept equal, and
154 * point to the end of the currently received record bytes. When
155 * ixc reaches 0, decryption/MAC is applied, and ixa and ixb are
158 * ** If encryption is not active, then ixa and ixb are distinct
159 * and data can be read right away. Additional record data is
160 * obtained only when ixa == ixb.
162 * Note: in input mode and no encryption, records larger than the buffer
163 * size are allowed. When encryption is active, the complete record must
164 * fit within the buffer, since it cannot be decrypted/MACed until it
165 * has been completely received.
167 * -- When receiving the next record header, 'version_in' contains the
168 * expected input version (0 if not expecting a specific version); on
169 * mismatch, the mode switches to 'failed'.
171 * -- When the header has been received, 'version_in' contains the received
172 * version. It is up to the caller to check and adjust the 'version_in' field
173 * to implement the required semantics.
175 * -- The 'record_type_in' field is updated with the incoming record type
176 * when the next record header has been received.
182 * oxa index within obuf[] for the currently accumulated data
183 * oxb maximum index within obuf[] for record data
184 * oxc pointer for start of record data, and for record sending
186 * -- When oxa != oxb, more data can be accumulated into the current
187 * record; when oxa == oxb, a closed record is being sent.
189 * -- When accumulating data, oxc points to the start of the data.
191 * -- During record sending, oxa (and oxb) point to the next record byte
192 * to send, and oxc indicates the end of the current record.
194 * Note: sent records must fit within the buffer, since the header is
195 * adjusted only when the complete record has been assembled.
197 * -- The 'version_out' and 'record_type_out' fields are used to build the
198 * record header when the mode is switched to 'sending'.
204 * The state register iomode contains one of the following values:
206 * BR_IO_FAILED I/O failed
207 * BR_IO_IN input mode
208 * BR_IO_OUT output mode
209 * BR_IO_INOUT input/output mode
211 * Whether encryption is active on incoming records is indicated by the
212 * incrypt flag. For outgoing records, there is no such flag; "encryption"
213 * is always considered active, but initially uses functions that do not
214 * encrypt anything. The 'incrypt' flag is needed because when there is
215 * no active encryption, records larger than the I/O buffer are accepted.
217 * Note: we do not support no-encryption modes (MAC only).
219 * TODO: implement GCM support
225 * 'max_frag_len' is the maximum plaintext size for an outgoing record.
226 * By default, it is set to the maximum value that fits in the provided
227 * buffers, in the following list: 512, 1024, 2048, 4096, 16384. The
228 * caller may change it if needed, but the new value MUST still fit in
229 * the buffers, and it MUST be one of the list above for compatibility
230 * with the Maximum Fragment Length extension.
232 * For incoming records, only the total buffer length and current
233 * encryption mode impact the maximum length for incoming records. The
234 * 'max_frag_len' value is still adjusted so that records up to that
235 * length can be both received and sent.
238 * Offsets and lengths:
239 * --------------------
241 * When sending fragments with TLS-1.1+, the maximum overhead is:
242 * 5 bytes for the record header
243 * 16 bytes for the explicit IV
244 * 48 bytes for the MAC (HMAC/SHA-384)
245 * 16 bytes for the padding (AES)
246 * so a total of 85 extra bytes. Note that we support block cipher sizes
247 * up to 16 bytes (AES) and HMAC output sizes up to 48 bytes (SHA-384).
249 * With TLS-1.0 and CBC mode, we apply a 1/n-1 split, for a maximum
251 * 5 bytes for the first record header
252 * 32 bytes for the first record payload (AES-CBC + HMAC/SHA-1)
253 * 5 bytes for the second record header
254 * 20 bytes for the MAC (HMAC/SHA-1)
255 * 16 bytes for the padding (AES)
256 * -1 byte to account for the payload byte in the first record
257 * so a total of 77 extra bytes at most, less than the 85 bytes above.
258 * Note that with TLS-1.0, the MAC is HMAC with either MD5 or SHA-1, but
259 * no other hash function.
261 * The implementation does not try to send larger records when the current
262 * encryption mode has less overhead.
264 * Maximum input record overhead is:
265 * 5 bytes for the record header
266 * 16 bytes for the explicit IV (TLS-1.1+)
267 * 48 bytes for the MAC (HMAC/SHA-384)
268 * 256 bytes for the padding
269 * so a total of 325 extra bytes.
271 * When receiving the next record header, it is written into the buffer
272 * bytes 0 to 4 (inclusive). Record data is always written into buf[]
273 * starting at offset 5. When encryption is active, the plaintext data
274 * may start at a larger offset (e.g. because of an explicit IV).
277 #define MAX_OUT_OVERHEAD 85
278 #define MAX_IN_OVERHEAD 325
282 br_ssl_engine_fail(br_ssl_engine_context
*rc
, int err
)
284 if (rc
->iomode
!= BR_IO_FAILED
) {
285 rc
->iomode
= BR_IO_FAILED
;
291 * Adjust registers for a new incoming record.
294 make_ready_in(br_ssl_engine_context
*rc
)
296 rc
->ixa
= rc
->ixb
= 0;
298 if (rc
->iomode
== BR_IO_IN
) {
299 rc
->iomode
= BR_IO_INOUT
;
304 * Adjust registers for a new outgoing record.
307 make_ready_out(br_ssl_engine_context
*rc
)
312 b
= rc
->obuf_len
- a
;
313 rc
->out
.vtable
->max_plaintext(&rc
->out
.vtable
, &a
, &b
);
314 if ((b
- a
) > rc
->max_frag_len
) {
315 b
= a
+ rc
->max_frag_len
;
320 if (rc
->iomode
== BR_IO_OUT
) {
321 rc
->iomode
= BR_IO_INOUT
;
327 br_ssl_engine_new_max_frag_len(br_ssl_engine_context
*rc
, unsigned max_frag_len
)
331 rc
->max_frag_len
= max_frag_len
;
332 nxb
= rc
->oxc
+ max_frag_len
;
333 if (rc
->oxa
< rc
->oxb
&& rc
->oxb
> nxb
&& rc
->oxa
< nxb
) {
338 /* see bearssl_ssl.h */
340 br_ssl_engine_set_buffer(br_ssl_engine_context
*rc
,
341 void *buf
, size_t buf_len
, int bidi
)
344 br_ssl_engine_set_buffers_bidi(rc
, NULL
, 0, NULL
, 0);
347 * In bidirectional mode, we want to maximise input
348 * buffer size, since we support arbitrary fragmentation
349 * when sending, but the peer will not necessarily
350 * comply to any low fragment length (in particular if
351 * we are the server, because the maximum fragment
352 * length extension is under client control).
354 * We keep a minimum size of 512 bytes for the plaintext
355 * of our outgoing records.
357 * br_ssl_engine_set_buffers_bidi() will compute the maximum
358 * fragment length for outgoing records by using the minimum
359 * of allocated spaces for both input and output records,
360 * rounded down to a standard length.
365 if (buf_len
< (512 + MAX_IN_OVERHEAD
366 + 512 + MAX_OUT_OVERHEAD
))
368 rc
->iomode
= BR_IO_FAILED
;
369 rc
->err
= BR_ERR_BAD_PARAM
;
371 } else if (buf_len
< (16384 + MAX_IN_OVERHEAD
372 + 512 + MAX_OUT_OVERHEAD
))
374 w
= 512 + MAX_OUT_OVERHEAD
;
376 w
= buf_len
- (16384 + MAX_IN_OVERHEAD
);
378 br_ssl_engine_set_buffers_bidi(rc
,
380 (unsigned char *)buf
+ w
, w
);
382 br_ssl_engine_set_buffers_bidi(rc
,
383 buf
, buf_len
, NULL
, 0);
388 /* see bearssl_ssl.h */
390 br_ssl_engine_set_buffers_bidi(br_ssl_engine_context
*rc
,
391 void *ibuf
, size_t ibuf_len
, void *obuf
, size_t obuf_len
)
393 rc
->iomode
= BR_IO_INOUT
;
397 rc
->record_type_in
= 0;
399 rc
->record_type_out
= 0;
401 if (rc
->ibuf
== NULL
) {
402 br_ssl_engine_fail(rc
, BR_ERR_BAD_PARAM
);
408 rc
->ibuf_len
= ibuf_len
;
414 rc
->obuf_len
= obuf_len
;
417 * Compute the maximum fragment length, that fits for
418 * both incoming and outgoing records. This length will
419 * be used in fragment length negotiation, so we must
420 * honour it both ways. Regardless, larger incoming
421 * records will be accepted, as long as they fit in the
422 * actual buffer size.
424 for (u
= 14; u
>= 9; u
--) {
427 flen
= (size_t)1 << u
;
428 if (obuf_len
>= flen
+ MAX_OUT_OVERHEAD
429 && ibuf_len
>= flen
+ MAX_IN_OVERHEAD
)
435 br_ssl_engine_fail(rc
, BR_ERR_BAD_PARAM
);
437 } else if (u
== 13) {
440 rc
->max_frag_len
= (size_t)1 << u
;
441 rc
->log_max_frag_len
= u
;
442 rc
->peer_log_max_frag_len
= 0;
444 rc
->out
.vtable
= &br_sslrec_out_clear_vtable
;
450 * Clear buffers in both directions.
453 engine_clearbuf(br_ssl_engine_context
*rc
)
461 br_ssl_engine_init_rand(br_ssl_engine_context
*cc
)
464 * TODO: use getrandom() on Linux systems, with a fallback to
465 * opening /dev/urandom if that system call fails.
467 * Use similar OS facilities on other OS (getentropy() on OpenBSD,
468 * specialized sysctl on NetBSD and FreeBSD...).
471 if (!cc
->rng_os_rand_done
) {
474 f
= open("/dev/urandom", O_RDONLY
);
476 unsigned char tmp
[32];
479 for (u
= 0; u
< sizeof tmp
;) {
482 len
= read(f
, tmp
+ u
, (sizeof tmp
) - u
);
484 if (errno
== EINTR
) {
492 if (u
== sizeof tmp
) {
493 br_ssl_engine_inject_entropy(cc
, tmp
, u
);
494 cc
->rng_os_rand_done
= 1;
498 #elif BR_USE_WIN32_RAND
499 if (!cc
->rng_os_rand_done
) {
502 if (CryptAcquireContextW(&hp
, 0, 0, PROV_RSA_FULL
,
503 CRYPT_VERIFYCONTEXT
| CRYPT_SILENT
))
507 if (CryptGenRandom(hp
, sizeof buf
, buf
)) {
508 br_ssl_engine_inject_entropy(cc
,
510 cc
->rng_os_rand_done
= 1;
512 CryptReleaseContext(hp
, 0);
517 if (!cc
->rng_init_done
) {
518 br_ssl_engine_fail(cc
, BR_ERR_NO_RANDOM
);
524 /* see bearssl_ssl.h */
526 br_ssl_engine_inject_entropy(br_ssl_engine_context
*cc
,
527 const void *data
, size_t len
)
529 if (cc
->rng_init_done
) {
530 br_hmac_drbg_update(&cc
->rng
, data
, len
);
533 * If using TLS-1.2, then SHA-256 or SHA-384 must be
534 * present (or both); we prefer SHA-256 which is faster
535 * for 32-bit systems.
537 * If using TLS-1.0 or 1.1 then SHA-1 must be present.
539 * Though HMAC_DRBG/SHA-1 is, as far as we know, as safe
540 * as these things can be, we still prefer the SHA-2
541 * functions over SHA-1, if only for public relations
542 * (known theoretical weaknesses of SHA-1 with regards to
543 * collisions are mostly irrelevant here, but they still
544 * make people nervous).
546 const br_hash_class
*h
;
548 h
= br_multihash_getimpl(&cc
->mhash
, br_sha256_ID
);
550 h
= br_multihash_getimpl(&cc
->mhash
, br_sha384_ID
);
552 h
= br_multihash_getimpl(&cc
->mhash
,
555 br_ssl_engine_fail(cc
,
561 br_hmac_drbg_init(&cc
->rng
, h
, data
, len
);
562 cc
->rng_init_done
= 1;
567 * We define a few internal functions that implement the low-level engine
568 * API for I/O; the external API (br_ssl_engine_sendapp_buf() and similar
569 * functions) is built upon these function, with special processing for
570 * records which are not of type "application data".
572 * recvrec_buf, recvrec_ack receives bytes from transport medium
573 * sendrec_buf, sendrec_ack send bytes to transport medium
574 * recvpld_buf, recvpld_ack receives payload data from engine
575 * sendpld_buf, sendpld_ack send payload data to engine
578 static unsigned char *
579 recvrec_buf(const br_ssl_engine_context
*rc
, size_t *len
)
581 if (rc
->shutdown_recv
) {
587 * Bytes from the transport can be injected only if the mode is
588 * compatible (in or in/out), and ixa == ixb; ixc then contains
589 * the number of bytes that are still expected (but it may
590 * exceed our buffer size).
592 * We cannot get "stuck" here (buffer is full, but still more
593 * data is expected) because oversized records are detected when
594 * their header is processed.
596 switch (rc
->iomode
) {
599 if (rc
->ixa
== rc
->ixb
) {
603 if (z
> rc
->ibuf_len
- rc
->ixa
) {
604 z
= rc
->ibuf_len
- rc
->ixa
;
607 return rc
->ibuf
+ rc
->ixa
;
616 recvrec_ack(br_ssl_engine_context
*rc
, size_t len
)
622 * Adjust state if necessary (for a shared input/output buffer):
623 * we got some incoming bytes, so we cannot (temporarily) handle
626 if (rc
->iomode
== BR_IO_INOUT
&& rc
->ibuf
== rc
->obuf
) {
627 rc
->iomode
= BR_IO_IN
;
631 * Adjust data pointers.
633 rc
->ixb
= (rc
->ixa
+= len
);
637 * If we are receiving a header and did not fully obtained it
638 * yet, then just wait for the next bytes.
645 * If we just obtained a full header, process it.
652 * Get record type and version. We support only versions
653 * 3.x (if the version major number does not match, then
654 * we suppose that the record format is too alien for us
657 * Note: right now, we reject clients that try to send
658 * a ClientHello in a format compatible with SSL-2.0. It
659 * is unclear whether this will ever be supported; and
660 * if we want to support it, then this might be done in
661 * in the server-specific code, not here.
663 rc
->record_type_in
= rc
->ibuf
[0];
664 version
= br_dec16be(rc
->ibuf
+ 1);
665 if ((version
>> 8) != 3) {
666 br_ssl_engine_fail(rc
, BR_ERR_UNSUPPORTED_VERSION
);
671 * We ensure that successive records have the same
672 * version. The handshake code must check and adjust the
673 * variables when necessary to accommodate the protocol
674 * negotiation details.
676 if (rc
->version_in
!= 0 && rc
->version_in
!= version
) {
677 br_ssl_engine_fail(rc
, BR_ERR_BAD_VERSION
);
680 rc
->version_in
= version
;
683 * Decode record length. We must check that the length
684 * is valid (relatively to the current encryption mode)
685 * and also (if encryption is active) that the record
686 * will fit in our buffer.
688 * When no encryption is active, we can process records
689 * by chunks, and thus accept any record up to the
690 * maximum allowed plaintext length (16384 bytes).
692 rlen
= br_dec16be(rc
->ibuf
+ 3);
694 if (!rc
->in
.vtable
->check_length(
695 &rc
->in
.vtable
, rlen
))
697 br_ssl_engine_fail(rc
, BR_ERR_BAD_LENGTH
);
700 if (rlen
> (rc
->ibuf_len
- 5)) {
701 br_ssl_engine_fail(rc
, BR_ERR_TOO_LARGE
);
706 br_ssl_engine_fail(rc
, BR_ERR_BAD_LENGTH
);
712 * If the record is completely empty then we must switch
713 * to a new record. Note that, in that case, we
714 * completely ignore the record type, which is fitting
715 * since we received no actual data of that type.
717 * A completely empty record is technically allowed as
718 * long as encryption/MAC is not active, i.e. before
719 * completion of the first handshake. It it still weird;
720 * it might conceptually be useful as a heartbeat or
721 * keep-alive mechanism while some lengthy operation is
722 * going on, e.g. interaction with a human user.
727 rc
->ixa
= rc
->ixb
= 5;
734 * If there is no active encryption, then the data can be read
735 * right away. Note that we do not receive bytes from the
736 * transport medium when we still have payload bytes to be
745 * Since encryption is active, we must wait for a full record
746 * before processing it.
753 * We got the full record. Decrypt it.
755 pbuf_len
= rc
->ixa
- 5;
756 pbuf
= rc
->in
.vtable
->decrypt(&rc
->in
.vtable
,
757 rc
->record_type_in
, rc
->version_in
, rc
->ibuf
+ 5, &pbuf_len
);
759 br_ssl_engine_fail(rc
, BR_ERR_BAD_MAC
);
762 rc
->ixa
= (size_t)(pbuf
- rc
->ibuf
);
763 rc
->ixb
= rc
->ixa
+ pbuf_len
;
766 * Decryption may have yielded an empty record, in which case
767 * we get back to "ready" state immediately.
769 if (rc
->ixa
== rc
->ixb
) {
776 br_ssl_engine_recvrec_finished(const br_ssl_engine_context
*rc
)
778 switch (rc
->iomode
) {
781 return rc
->ixc
== 0 || rc
->ixa
< 5;
787 static unsigned char *
788 recvpld_buf(const br_ssl_engine_context
*rc
, size_t *len
)
791 * There is payload data to be read only if the mode is
792 * compatible, and ixa != ixb.
794 switch (rc
->iomode
) {
797 *len
= rc
->ixb
- rc
->ixa
;
798 return (*len
== 0) ? NULL
: (rc
->ibuf
+ rc
->ixa
);
806 recvpld_ack(br_ssl_engine_context
*rc
, size_t len
)
811 * If we read all the available data, then we either expect
812 * the remainder of the current record (if the current record
813 * was not finished; this may happen when encryption is not
814 * active), or go to "ready" state.
816 if (rc
->ixa
== rc
->ixb
) {
820 rc
->ixa
= rc
->ixb
= 5;
825 static unsigned char *
826 sendpld_buf(const br_ssl_engine_context
*rc
, size_t *len
)
829 * Payload data can be injected only if the current mode is
830 * compatible, and oxa != oxb.
832 switch (rc
->iomode
) {
835 *len
= rc
->oxb
- rc
->oxa
;
836 return (*len
== 0) ? NULL
: (rc
->obuf
+ rc
->oxa
);
844 * If some payload bytes have been accumulated, then wrap them into
845 * an outgoing record. Otherwise, this function does nothing, unless
846 * 'force' is non-zero, in which case an empty record is assembled.
848 * The caller must take care not to invoke this function if the engine
849 * is not currently ready to receive payload bytes to send.
852 sendpld_flush(br_ssl_engine_context
*rc
, int force
)
857 if (rc
->oxa
== rc
->oxb
) {
860 xlen
= rc
->oxa
- rc
->oxc
;
861 if (xlen
== 0 && !force
) {
864 buf
= rc
->out
.vtable
->encrypt(&rc
->out
.vtable
,
865 rc
->record_type_out
, rc
->version_out
,
866 rc
->obuf
+ rc
->oxc
, &xlen
);
867 rc
->oxb
= rc
->oxa
= (size_t)(buf
- rc
->obuf
);
868 rc
->oxc
= rc
->oxa
+ xlen
;
872 sendpld_ack(br_ssl_engine_context
*rc
, size_t len
)
875 * If using a shared buffer, then we may have to modify the
878 if (rc
->iomode
== BR_IO_INOUT
&& rc
->ibuf
== rc
->obuf
) {
879 rc
->iomode
= BR_IO_OUT
;
882 if (rc
->oxa
>= rc
->oxb
) {
884 * Set oxb to one more than oxa so that sendpld_flush()
885 * does not mistakingly believe that a record is
886 * already prepared and being sent.
888 rc
->oxb
= rc
->oxa
+ 1;
889 sendpld_flush(rc
, 0);
893 static unsigned char *
894 sendrec_buf(const br_ssl_engine_context
*rc
, size_t *len
)
897 * When still gathering payload bytes, oxc points to the start
898 * of the record data, so oxc <= oxa. However, when a full
899 * record has been completed, oxc points to the end of the record,
902 switch (rc
->iomode
) {
905 if (rc
->oxc
> rc
->oxa
) {
906 *len
= rc
->oxc
- rc
->oxa
;
907 return rc
->obuf
+ rc
->oxa
;
916 sendrec_ack(br_ssl_engine_context
*rc
, size_t len
)
918 rc
->oxb
= (rc
->oxa
+= len
);
919 if (rc
->oxa
== rc
->oxc
) {
925 * Test whether there is some buffered outgoing record that still must
929 has_rec_tosend(const br_ssl_engine_context
*rc
)
931 return rc
->oxa
== rc
->oxb
&& rc
->oxa
!= rc
->oxc
;
935 * The "no encryption" mode has no overhead. It limits the payload size
936 * to the maximum size allowed by the standard (16384 bytes); the caller
937 * is responsible for possibly enforcing a smaller fragment length.
940 clear_max_plaintext(const br_sslrec_out_clear_context
*cc
,
941 size_t *start
, size_t *end
)
948 *end
= *start
+ 16384;
953 * In "no encryption" mode, encryption is trivial (a no-operation) so
954 * we just have to encode the header.
956 static unsigned char *
957 clear_encrypt(br_sslrec_out_clear_context
*cc
,
958 int record_type
, unsigned version
, void *data
, size_t *data_len
)
963 buf
= (unsigned char *)data
- 5;
964 buf
[0] = record_type
;
965 br_enc16be(buf
+ 1, version
);
966 br_enc16be(buf
+ 3, *data_len
);
971 /* see bearssl_ssl.h */
972 const br_sslrec_out_class br_sslrec_out_clear_vtable
= {
973 sizeof(br_sslrec_out_clear_context
),
974 (void (*)(const br_sslrec_out_class
*const *, size_t *, size_t *))
975 &clear_max_plaintext
,
976 (unsigned char *(*)(const br_sslrec_out_class
**,
977 int, unsigned, void *, size_t *))
981 /* ==================================================================== */
983 * In this part of the file, we handle the various record types, and
984 * communications with the handshake processor.
988 * IMPLEMENTATION NOTES
989 * ====================
991 * The handshake processor is written in T0 and runs as a coroutine.
992 * It receives the contents of all records except application data, and
993 * is responsible for producing the contents of all records except
996 * A state flag is maintained, which specifies whether application data
997 * is acceptable or not. When it is set:
999 * -- Application data can be injected as payload data (provided that
1000 * the output buffer is ready for that).
1002 * -- Incoming application data records are accepted, and yield data
1003 * that the caller may retrieve.
1005 * When the flag is cleared, application data is not accepted from the
1006 * application, and incoming application data records trigger an error.
1009 * Records of type handshake, alert or change-cipher-spec are handled
1010 * by the handshake processor. The handshake processor is written in T0
1011 * and runs as a coroutine; it gets invoked whenever one of the following
1012 * situations is reached:
1014 * -- An incoming record has type handshake, alert or change-cipher-spec,
1015 * and yields data that can be read (zero-length records are thus
1018 * -- An outgoing record has just finished being sent, and the "application
1019 * data" flag is cleared.
1021 * -- The caller wishes to perform a close (call to br_ssl_engine_close()).
1023 * -- The caller wishes to perform a renegotiation (call to
1024 * br_ssl_engine_renegotiate()).
1026 * Whenever the handshake processor is entered, access to the payload
1027 * buffers is provided, along with some information about explicit
1028 * closures or renegotiations.
1031 /* see bearssl_ssl.h */
1033 br_ssl_engine_set_suites(br_ssl_engine_context
*cc
,
1034 const uint16_t *suites
, size_t suites_num
)
1036 if ((suites_num
* sizeof *suites
) > sizeof cc
->suites_buf
) {
1037 br_ssl_engine_fail(cc
, BR_ERR_BAD_PARAM
);
1040 memcpy(cc
->suites_buf
, suites
, suites_num
* sizeof *suites
);
1041 cc
->suites_num
= suites_num
;
1045 * Give control to handshake processor. 'action' is 1 for a close,
1046 * 2 for a renegotiation, or 0 for a jump due to I/O completion.
1049 jump_handshake(br_ssl_engine_context
*cc
, int action
)
1052 * We use a loop because the handshake processor actions may
1053 * allow for more actions; namely, if the processor reads all
1054 * input data, then it may allow for output data to be produced,
1055 * in case of a shared in/out buffer.
1058 size_t hlen_in
, hlen_out
;
1061 * Get input buffer. We do not want to provide
1062 * application data to the handshake processor (we could
1063 * get called with an explicit close or renegotiation
1064 * while there is application data ready to be read).
1066 cc
->hbuf_in
= recvpld_buf(cc
, &hlen_in
);
1067 if (cc
->hbuf_in
!= NULL
1068 && cc
->record_type_in
== BR_SSL_APPLICATION_DATA
)
1074 * Get output buffer. The handshake processor never
1075 * leaves an unfinished outgoing record, so if there is
1076 * buffered output, then it MUST be some application
1077 * data, so the processor cannot write to it.
1079 cc
->saved_hbuf_out
= cc
->hbuf_out
= sendpld_buf(cc
, &hlen_out
);
1080 if (cc
->hbuf_out
!= NULL
&& br_ssl_engine_has_pld_to_send(cc
)) {
1085 * Note: hlen_in and hlen_out can be both non-zero only if
1086 * the input and output buffers are disjoint. Thus, we can
1087 * offer both buffers to the handshake code.
1090 cc
->hlen_in
= hlen_in
;
1091 cc
->hlen_out
= hlen_out
;
1092 cc
->action
= action
;
1093 cc
->hsrun(&cc
->cpu
);
1094 if (cc
->hbuf_out
!= cc
->saved_hbuf_out
) {
1095 sendpld_ack(cc
, cc
->hbuf_out
- cc
->saved_hbuf_out
);
1097 if (hlen_in
!= cc
->hlen_in
) {
1098 recvpld_ack(cc
, hlen_in
- cc
->hlen_in
);
1099 if (cc
->hlen_in
== 0) {
1101 * We read all data bytes, which may have
1102 * released the output buffer in case it
1103 * is shared with the input buffer, and
1104 * the handshake code might be waiting for
1117 br_ssl_engine_flush_record(br_ssl_engine_context
*cc
)
1119 if (cc
->hbuf_out
!= cc
->saved_hbuf_out
) {
1120 sendpld_ack(cc
, cc
->hbuf_out
- cc
->saved_hbuf_out
);
1122 if (br_ssl_engine_has_pld_to_send(cc
)) {
1123 sendpld_flush(cc
, 0);
1125 cc
->saved_hbuf_out
= cc
->hbuf_out
= sendpld_buf(cc
, &cc
->hlen_out
);
1128 /* see bearssl_ssl.h */
1130 br_ssl_engine_sendapp_buf(const br_ssl_engine_context
*cc
, size_t *len
)
1132 if (!cc
->application_data
) {
1136 return sendpld_buf(cc
, len
);
1139 /* see bearssl_ssl.h */
1141 br_ssl_engine_sendapp_ack(br_ssl_engine_context
*cc
, size_t len
)
1143 sendpld_ack(cc
, len
);
1146 /* see bearssl_ssl.h */
1148 br_ssl_engine_recvapp_buf(const br_ssl_engine_context
*cc
, size_t *len
)
1150 if (!cc
->application_data
1151 || cc
->record_type_in
!= BR_SSL_APPLICATION_DATA
)
1156 return recvpld_buf(cc
, len
);
1159 /* see bearssl_ssl.h */
1161 br_ssl_engine_recvapp_ack(br_ssl_engine_context
*cc
, size_t len
)
1163 recvpld_ack(cc
, len
);
1166 /* see bearssl_ssl.h */
1168 br_ssl_engine_sendrec_buf(const br_ssl_engine_context
*cc
, size_t *len
)
1170 return sendrec_buf(cc
, len
);
1173 /* see bearssl_ssl.h */
1175 br_ssl_engine_sendrec_ack(br_ssl_engine_context
*cc
, size_t len
)
1177 sendrec_ack(cc
, len
);
1178 if (len
!= 0 && !has_rec_tosend(cc
)
1179 && (cc
->record_type_out
!= BR_SSL_APPLICATION_DATA
1180 || cc
->application_data
== 0))
1182 jump_handshake(cc
, 0);
1186 /* see bearssl_ssl.h */
1188 br_ssl_engine_recvrec_buf(const br_ssl_engine_context
*cc
, size_t *len
)
1190 return recvrec_buf(cc
, len
);
1193 /* see bearssl_ssl.h */
1195 br_ssl_engine_recvrec_ack(br_ssl_engine_context
*cc
, size_t len
)
1199 recvrec_ack(cc
, len
);
1200 if (br_ssl_engine_closed(cc
)) {
1205 * We just received some bytes from the peer. This may have
1206 * yielded some payload bytes, in which case we must process
1207 * them according to the record type.
1209 buf
= recvpld_buf(cc
, &len
);
1211 switch (cc
->record_type_in
) {
1212 case BR_SSL_CHANGE_CIPHER_SPEC
:
1214 case BR_SSL_HANDSHAKE
:
1215 jump_handshake(cc
, 0);
1217 case BR_SSL_APPLICATION_DATA
:
1218 if (cc
->application_data
) {
1223 br_ssl_engine_fail(cc
, BR_ERR_UNEXPECTED
);
1229 /* see bearssl_ssl.h */
1231 br_ssl_engine_close(br_ssl_engine_context
*cc
)
1233 if (!br_ssl_engine_closed(cc
)) {
1234 jump_handshake(cc
, 1);
1238 /* see bearssl_ssl.h */
1240 br_ssl_engine_renegotiate(br_ssl_engine_context
*cc
)
1242 if (br_ssl_engine_closed(cc
) || cc
->reneg
== 1) {
1245 jump_handshake(cc
, 2);
1251 br_ssl_engine_current_state(const br_ssl_engine_context
*cc
)
1256 if (br_ssl_engine_closed(cc
)) {
1257 return BR_SSL_CLOSED
;
1261 if (br_ssl_engine_sendrec_buf(cc
, &len
) != NULL
) {
1262 s
|= BR_SSL_SENDREC
;
1264 if (br_ssl_engine_recvrec_buf(cc
, &len
) != NULL
) {
1265 s
|= BR_SSL_RECVREC
;
1267 if (br_ssl_engine_sendapp_buf(cc
, &len
) != NULL
) {
1268 s
|= BR_SSL_SENDAPP
;
1270 if (br_ssl_engine_recvapp_buf(cc
, &len
) != NULL
) {
1271 s
|= BR_SSL_RECVAPP
;
1276 /* see bearssl_ssl.h */
1278 br_ssl_engine_flush(br_ssl_engine_context
*cc
, int force
)
1280 if (!br_ssl_engine_closed(cc
) && cc
->application_data
) {
1281 sendpld_flush(cc
, force
);
1287 br_ssl_engine_hs_reset(br_ssl_engine_context
*cc
,
1288 void (*hsinit
)(void *), void (*hsrun
)(void *))
1290 engine_clearbuf(cc
);
1291 cc
->cpu
.dp
= cc
->dp_stack
;
1292 cc
->cpu
.rp
= cc
->rp_stack
;
1295 cc
->shutdown_recv
= 0;
1296 cc
->application_data
= 0;
1297 jump_handshake(cc
, 0);
1302 br_ssl_engine_get_PRF(br_ssl_engine_context
*cc
, int prf_id
)
1304 if (cc
->session
.version
>= BR_TLS12
) {
1305 if (prf_id
== br_sha384_ID
) {
1306 return cc
->prf_sha384
;
1308 return cc
->prf_sha256
;
1317 br_ssl_engine_compute_master(br_ssl_engine_context
*cc
,
1318 int prf_id
, const void *pms
, size_t pms_len
)
1320 br_tls_prf_impl iprf
;
1321 unsigned char seed
[64];
1323 iprf
= br_ssl_engine_get_PRF(cc
, prf_id
);
1324 memcpy(seed
, cc
->client_random
, 32);
1325 memcpy(seed
+ 32, cc
->server_random
, 32);
1326 iprf(cc
->session
.master_secret
, sizeof cc
->session
.master_secret
,
1327 pms
, pms_len
, "master secret", seed
, sizeof seed
);
1331 * Compute key block.
1334 compute_key_block(br_ssl_engine_context
*cc
, int prf_id
,
1335 size_t half_len
, unsigned char *kb
)
1337 br_tls_prf_impl iprf
;
1338 unsigned char seed
[64];
1340 iprf
= br_ssl_engine_get_PRF(cc
, prf_id
);
1341 memcpy(seed
, cc
->server_random
, 32);
1342 memcpy(seed
+ 32, cc
->client_random
, 32);
1343 iprf(kb
, half_len
<< 1,
1344 cc
->session
.master_secret
, sizeof cc
->session
.master_secret
,
1345 "key expansion", seed
, sizeof seed
);
1350 br_ssl_engine_switch_cbc_in(br_ssl_engine_context
*cc
,
1351 int is_client
, int prf_id
, int mac_id
,
1352 const br_block_cbcdec_class
*bc_impl
, size_t cipher_key_len
)
1354 unsigned char kb
[192];
1355 unsigned char *cipher_key
, *mac_key
, *iv
;
1356 const br_hash_class
*imh
;
1357 size_t mac_key_len
, mac_out_len
, iv_len
;
1359 imh
= br_ssl_engine_get_hash(cc
, mac_id
);
1360 mac_out_len
= (imh
->desc
>> BR_HASHDESC_OUT_OFF
) & BR_HASHDESC_OUT_MASK
;
1361 mac_key_len
= mac_out_len
;
1364 * TLS 1.1+ uses per-record explicit IV, so no IV to generate here.
1366 if (cc
->session
.version
>= BR_TLS11
) {
1369 iv_len
= bc_impl
->block_size
;
1371 compute_key_block(cc
, prf_id
,
1372 mac_key_len
+ cipher_key_len
+ iv_len
, kb
);
1374 mac_key
= &kb
[mac_key_len
];
1375 cipher_key
= &kb
[(mac_key_len
<< 1) + cipher_key_len
];
1376 iv
= &kb
[((mac_key_len
+ cipher_key_len
) << 1) + iv_len
];
1379 cipher_key
= &kb
[mac_key_len
<< 1];
1380 iv
= &kb
[(mac_key_len
+ cipher_key_len
) << 1];
1385 cc
->icbc_in
->init(&cc
->in
.cbc
.vtable
,
1386 bc_impl
, cipher_key
, cipher_key_len
,
1387 imh
, mac_key
, mac_key_len
, mac_out_len
, iv
);
1393 br_ssl_engine_switch_cbc_out(br_ssl_engine_context
*cc
,
1394 int is_client
, int prf_id
, int mac_id
,
1395 const br_block_cbcenc_class
*bc_impl
, size_t cipher_key_len
)
1397 unsigned char kb
[192];
1398 unsigned char *cipher_key
, *mac_key
, *iv
;
1399 const br_hash_class
*imh
;
1400 size_t mac_key_len
, mac_out_len
, iv_len
;
1402 imh
= br_ssl_engine_get_hash(cc
, mac_id
);
1403 mac_out_len
= (imh
->desc
>> BR_HASHDESC_OUT_OFF
) & BR_HASHDESC_OUT_MASK
;
1404 mac_key_len
= mac_out_len
;
1407 * TLS 1.1+ uses per-record explicit IV, so no IV to generate here.
1409 if (cc
->session
.version
>= BR_TLS11
) {
1412 iv_len
= bc_impl
->block_size
;
1414 compute_key_block(cc
, prf_id
,
1415 mac_key_len
+ cipher_key_len
+ iv_len
, kb
);
1418 cipher_key
= &kb
[mac_key_len
<< 1];
1419 iv
= &kb
[(mac_key_len
+ cipher_key_len
) << 1];
1421 mac_key
= &kb
[mac_key_len
];
1422 cipher_key
= &kb
[(mac_key_len
<< 1) + cipher_key_len
];
1423 iv
= &kb
[((mac_key_len
+ cipher_key_len
) << 1) + iv_len
];
1428 cc
->icbc_out
->init(&cc
->out
.cbc
.vtable
,
1429 bc_impl
, cipher_key
, cipher_key_len
,
1430 imh
, mac_key
, mac_key_len
, mac_out_len
, iv
);
1435 br_ssl_engine_switch_gcm_in(br_ssl_engine_context
*cc
,
1436 int is_client
, int prf_id
,
1437 const br_block_ctr_class
*bc_impl
, size_t cipher_key_len
)
1439 unsigned char kb
[72];
1440 unsigned char *cipher_key
, *iv
;
1442 compute_key_block(cc
, prf_id
, cipher_key_len
+ 4, kb
);
1444 cipher_key
= &kb
[cipher_key_len
];
1445 iv
= &kb
[(cipher_key_len
<< 1) + 4];
1447 cipher_key
= &kb
[0];
1448 iv
= &kb
[cipher_key_len
<< 1];
1450 cc
->igcm_in
->init(&cc
->in
.gcm
.vtable
.in
,
1451 bc_impl
, cipher_key
, cipher_key_len
, cc
->ighash
, iv
);
1457 br_ssl_engine_switch_gcm_out(br_ssl_engine_context
*cc
,
1458 int is_client
, int prf_id
,
1459 const br_block_ctr_class
*bc_impl
, size_t cipher_key_len
)
1461 unsigned char kb
[72];
1462 unsigned char *cipher_key
, *iv
;
1464 compute_key_block(cc
, prf_id
, cipher_key_len
+ 4, kb
);
1466 cipher_key
= &kb
[0];
1467 iv
= &kb
[cipher_key_len
<< 1];
1469 cipher_key
= &kb
[cipher_key_len
];
1470 iv
= &kb
[(cipher_key_len
<< 1) + 4];
1472 cc
->igcm_out
->init(&cc
->out
.gcm
.vtable
.out
,
1473 bc_impl
, cipher_key
, cipher_key_len
, cc
->ighash
, iv
);