Path: blob/main/contrib/bearssl/src/ssl/ssl_engine.c
39488 views
/*1* Copyright (c) 2016 Thomas Pornin <[email protected]>2*3* Permission is hereby granted, free of charge, to any person obtaining4* a copy of this software and associated documentation files (the5* "Software"), to deal in the Software without restriction, including6* without limitation the rights to use, copy, modify, merge, publish,7* distribute, sublicense, and/or sell copies of the Software, and to8* permit persons to whom the Software is furnished to do so, subject to9* the following conditions:10*11* The above copyright notice and this permission notice shall be12* included in all copies or substantial portions of the Software.13*14* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,15* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF16* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND17* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS18* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN19* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN20* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE21* SOFTWARE.22*/2324#include "inner.h"2526#if 027/* obsolete */2829/*30* If BR_USE_URANDOM is not defined, then try to autodetect its presence31* through compiler macros.32*/33#ifndef BR_USE_URANDOM3435/*36* Macro values documented on:37* https://sourceforge.net/p/predef/wiki/OperatingSystems/38*39* Only the most common systems have been included here for now. This40* should be enriched later on.41*/42#if defined _AIX \43|| defined __ANDROID__ \44|| defined __FreeBSD__ \45|| defined __NetBSD__ \46|| defined __OpenBSD__ \47|| defined __DragonFly__ \48|| defined __linux__ \49|| (defined __sun && (defined __SVR4 || defined __svr4__)) \50|| (defined __APPLE__ && defined __MACH__)51#define BR_USE_URANDOM 152#endif5354#endif5556/*57* If BR_USE_WIN32_RAND is not defined, perform autodetection here.58*/59#ifndef BR_USE_WIN32_RAND6061#if defined _WIN32 || defined _WIN6462#define BR_USE_WIN32_RAND 163#endif6465#endif6667#if BR_USE_URANDOM68#include <sys/types.h>69#include <unistd.h>70#include <fcntl.h>71#include <errno.h>72#endif7374#if BR_USE_WIN32_RAND75#include <windows.h>76#include <wincrypt.h>77#pragma comment(lib, "advapi32")78#endif7980#endif8182/* ==================================================================== */83/*84* This part of the file does the low-level record management.85*/8687/*88* IMPLEMENTATION NOTES89* ====================90*91* In this file, we designate by "input" (and the "i" letter) the "recv"92* operations: incoming records from the peer, from which payload data93* is obtained, and must be extracted by the application (or the SSL94* handshake engine). Similarly, "output" (and the "o" letter) is for95* "send": payload data injected by the application (and SSL handshake96* engine), to be wrapped into records, that are then conveyed to the97* peer over the transport medium.98*99* The input and output buffers may be distinct or shared. When100* shared, input and output cannot occur concurrently; the caller101* must make sure that it never needs to output data while input102* data has been received. In practice, a shared buffer prevents103* pipelining of HTTP requests, or similar protocols; however, a104* shared buffer saves RAM.105*106* The input buffer is pointed to by 'ibuf' and has size 'ibuf_len';107* the output buffer is pointed to by 'obuf' and has size 'obuf_len'.108* From the size of these buffers is derived the maximum fragment109* length, which will be honoured upon sending records; regardless of110* that length, incoming records will be processed as long as they111* fit in the input buffer, and their length still complies with the112* protocol specification (maximum plaintext payload length is 16384113* bytes).114*115* Three registers are used to manage buffering in ibuf, called ixa,116* ixb and ixc. Similarly, three registers are used to manage buffering117* in obuf, called oxa, oxb and oxc.118*119*120* At any time, the engine is in one of the following modes:121* -- Failed mode: an error occurs, no I/O can happen.122* -- Input mode: the engine can either receive record bytes from the123* transport layer, or it has some buffered payload bytes to yield.124* -- Output mode: the engine can either receive payload bytes, or it125* has some record bytes to send to the transport layer.126* -- Input/Output mode: both input and output modes are active. When127* the buffer is shared, this can happen only when the buffer is empty128* (no buffered payload bytes or record bytes in either direction).129*130*131* Failed mode:132* ------------133*134* I/O failed for some reason (invalid received data, not enough room135* for the next record...). No I/O may ever occur again for this context,136* until an explicit reset is performed. This mode, and the error code,137* are also used for protocol errors, especially handshake errors.138*139*140* Input mode:141* -----------142*143* ixa index within ibuf[] for the currently read data144* ixb maximum index within ibuf[] for the currently read data145* ixc number of bytes not yet received for the current record146*147* -- When ixa == ixb, there is no available data for readers. When148* ixa != ixb, there is available data and it starts at offset ixa.149*150* -- When waiting for the next record header, ixa and ixb are equal151* and contain a value ranging from 0 to 4; ixc is equal to 5-ixa.152*153* -- When the header has been received, record data is obtained. The154* ixc field records how many bytes are still needed to reach the155* end of the current record.156*157* ** If encryption is active, then ixa and ixb are kept equal, and158* point to the end of the currently received record bytes. When159* ixc reaches 0, decryption/MAC is applied, and ixa and ixb are160* adjusted.161*162* ** If encryption is not active, then ixa and ixb are distinct163* and data can be read right away. Additional record data is164* obtained only when ixa == ixb.165*166* Note: in input mode and no encryption, records larger than the buffer167* size are allowed. When encryption is active, the complete record must168* fit within the buffer, since it cannot be decrypted/MACed until it169* has been completely received.170*171* -- When receiving the next record header, 'version_in' contains the172* expected input version (0 if not expecting a specific version); on173* mismatch, the mode switches to 'failed'.174*175* -- When the header has been received, 'version_in' contains the received176* version. It is up to the caller to check and adjust the 'version_in' field177* to implement the required semantics.178*179* -- The 'record_type_in' field is updated with the incoming record type180* when the next record header has been received.181*182*183* Output mode:184* ------------185*186* oxa index within obuf[] for the currently accumulated data187* oxb maximum index within obuf[] for record data188* oxc pointer for start of record data, and for record sending189*190* -- When oxa != oxb, more data can be accumulated into the current191* record; when oxa == oxb, a closed record is being sent.192*193* -- When accumulating data, oxc points to the start of the data.194*195* -- During record sending, oxa (and oxb) point to the next record byte196* to send, and oxc indicates the end of the current record.197*198* Note: sent records must fit within the buffer, since the header is199* adjusted only when the complete record has been assembled.200*201* -- The 'version_out' and 'record_type_out' fields are used to build the202* record header when the mode is switched to 'sending'.203*204*205* Modes:206* ------207*208* The state register iomode contains one of the following values:209*210* BR_IO_FAILED I/O failed211* BR_IO_IN input mode212* BR_IO_OUT output mode213* BR_IO_INOUT input/output mode214*215* Whether encryption is active on incoming records is indicated by the216* incrypt flag. For outgoing records, there is no such flag; "encryption"217* is always considered active, but initially uses functions that do not218* encrypt anything. The 'incrypt' flag is needed because when there is219* no active encryption, records larger than the I/O buffer are accepted.220*221* Note: we do not support no-encryption modes (MAC only).222*223* TODO: implement GCM support224*225*226* Misc:227* -----228*229* 'max_frag_len' is the maximum plaintext size for an outgoing record.230* By default, it is set to the maximum value that fits in the provided231* buffers, in the following list: 512, 1024, 2048, 4096, 16384. The232* caller may change it if needed, but the new value MUST still fit in233* the buffers, and it MUST be one of the list above for compatibility234* with the Maximum Fragment Length extension.235*236* For incoming records, only the total buffer length and current237* encryption mode impact the maximum length for incoming records. The238* 'max_frag_len' value is still adjusted so that records up to that239* length can be both received and sent.240*241*242* Offsets and lengths:243* --------------------244*245* When sending fragments with TLS-1.1+, the maximum overhead is:246* 5 bytes for the record header247* 16 bytes for the explicit IV248* 48 bytes for the MAC (HMAC/SHA-384)249* 16 bytes for the padding (AES)250* so a total of 85 extra bytes. Note that we support block cipher sizes251* up to 16 bytes (AES) and HMAC output sizes up to 48 bytes (SHA-384).252*253* With TLS-1.0 and CBC mode, we apply a 1/n-1 split, for a maximum254* overhead of:255* 5 bytes for the first record header256* 32 bytes for the first record payload (AES-CBC + HMAC/SHA-1)257* 5 bytes for the second record header258* 20 bytes for the MAC (HMAC/SHA-1)259* 16 bytes for the padding (AES)260* -1 byte to account for the payload byte in the first record261* so a total of 77 extra bytes at most, less than the 85 bytes above.262* Note that with TLS-1.0, the MAC is HMAC with either MD5 or SHA-1, but263* no other hash function.264*265* The implementation does not try to send larger records when the current266* encryption mode has less overhead.267*268* Maximum input record overhead is:269* 5 bytes for the record header270* 16 bytes for the explicit IV (TLS-1.1+)271* 48 bytes for the MAC (HMAC/SHA-384)272* 256 bytes for the padding273* so a total of 325 extra bytes.274*275* When receiving the next record header, it is written into the buffer276* bytes 0 to 4 (inclusive). Record data is always written into buf[]277* starting at offset 5. When encryption is active, the plaintext data278* may start at a larger offset (e.g. because of an explicit IV).279*/280281#define MAX_OUT_OVERHEAD 85282#define MAX_IN_OVERHEAD 325283284/* see inner.h */285void286br_ssl_engine_fail(br_ssl_engine_context *rc, int err)287{288if (rc->iomode != BR_IO_FAILED) {289rc->iomode = BR_IO_FAILED;290rc->err = err;291}292}293294/*295* Adjust registers for a new incoming record.296*/297static void298make_ready_in(br_ssl_engine_context *rc)299{300rc->ixa = rc->ixb = 0;301rc->ixc = 5;302if (rc->iomode == BR_IO_IN) {303rc->iomode = BR_IO_INOUT;304}305}306307/*308* Adjust registers for a new outgoing record.309*/310static void311make_ready_out(br_ssl_engine_context *rc)312{313size_t a, b;314315a = 5;316b = rc->obuf_len - a;317rc->out.vtable->max_plaintext(&rc->out.vtable, &a, &b);318if ((b - a) > rc->max_frag_len) {319b = a + rc->max_frag_len;320}321rc->oxa = a;322rc->oxb = b;323rc->oxc = a;324if (rc->iomode == BR_IO_OUT) {325rc->iomode = BR_IO_INOUT;326}327}328329/* see inner.h */330void331br_ssl_engine_new_max_frag_len(br_ssl_engine_context *rc, unsigned max_frag_len)332{333size_t nxb;334335rc->max_frag_len = max_frag_len;336nxb = rc->oxc + max_frag_len;337if (rc->oxa < rc->oxb && rc->oxb > nxb && rc->oxa < nxb) {338rc->oxb = nxb;339}340}341342/* see bearssl_ssl.h */343void344br_ssl_engine_set_buffer(br_ssl_engine_context *rc,345void *buf, size_t buf_len, int bidi)346{347if (buf == NULL) {348br_ssl_engine_set_buffers_bidi(rc, NULL, 0, NULL, 0);349} else {350/*351* In bidirectional mode, we want to maximise input352* buffer size, since we support arbitrary fragmentation353* when sending, but the peer will not necessarily354* comply to any low fragment length (in particular if355* we are the server, because the maximum fragment356* length extension is under client control).357*358* We keep a minimum size of 512 bytes for the plaintext359* of our outgoing records.360*361* br_ssl_engine_set_buffers_bidi() will compute the maximum362* fragment length for outgoing records by using the minimum363* of allocated spaces for both input and output records,364* rounded down to a standard length.365*/366if (bidi) {367size_t w;368369if (buf_len < (512 + MAX_IN_OVERHEAD370+ 512 + MAX_OUT_OVERHEAD))371{372rc->iomode = BR_IO_FAILED;373rc->err = BR_ERR_BAD_PARAM;374return;375} else if (buf_len < (16384 + MAX_IN_OVERHEAD376+ 512 + MAX_OUT_OVERHEAD))377{378w = 512 + MAX_OUT_OVERHEAD;379} else {380w = buf_len - (16384 + MAX_IN_OVERHEAD);381}382br_ssl_engine_set_buffers_bidi(rc,383buf, buf_len - w,384(unsigned char *)buf + w, w);385} else {386br_ssl_engine_set_buffers_bidi(rc,387buf, buf_len, NULL, 0);388}389}390}391392/* see bearssl_ssl.h */393void394br_ssl_engine_set_buffers_bidi(br_ssl_engine_context *rc,395void *ibuf, size_t ibuf_len, void *obuf, size_t obuf_len)396{397rc->iomode = BR_IO_INOUT;398rc->incrypt = 0;399rc->err = BR_ERR_OK;400rc->version_in = 0;401rc->record_type_in = 0;402rc->version_out = 0;403rc->record_type_out = 0;404if (ibuf == NULL) {405if (rc->ibuf == NULL) {406br_ssl_engine_fail(rc, BR_ERR_BAD_PARAM);407}408} else {409unsigned u;410411rc->ibuf = ibuf;412rc->ibuf_len = ibuf_len;413if (obuf == NULL) {414obuf = ibuf;415obuf_len = ibuf_len;416}417rc->obuf = obuf;418rc->obuf_len = obuf_len;419420/*421* Compute the maximum fragment length, that fits for422* both incoming and outgoing records. This length will423* be used in fragment length negotiation, so we must424* honour it both ways. Regardless, larger incoming425* records will be accepted, as long as they fit in the426* actual buffer size.427*/428for (u = 14; u >= 9; u --) {429size_t flen;430431flen = (size_t)1 << u;432if (obuf_len >= flen + MAX_OUT_OVERHEAD433&& ibuf_len >= flen + MAX_IN_OVERHEAD)434{435break;436}437}438if (u == 8) {439br_ssl_engine_fail(rc, BR_ERR_BAD_PARAM);440return;441} else if (u == 13) {442u = 12;443}444rc->max_frag_len = (size_t)1 << u;445rc->log_max_frag_len = u;446rc->peer_log_max_frag_len = 0;447}448rc->out.vtable = &br_sslrec_out_clear_vtable;449make_ready_in(rc);450make_ready_out(rc);451}452453/*454* Clear buffers in both directions.455*/456static void457engine_clearbuf(br_ssl_engine_context *rc)458{459make_ready_in(rc);460make_ready_out(rc);461}462463/*464* Make sure the internal PRNG is initialised (but not necessarily465* seeded properly yet).466*/467static int468rng_init(br_ssl_engine_context *cc)469{470const br_hash_class *h;471472if (cc->rng_init_done != 0) {473return 1;474}475476/*477* If using TLS-1.2, then SHA-256 or SHA-384 must be present (or478* both); we prefer SHA-256 which is faster for 32-bit systems.479*480* If using TLS-1.0 or 1.1 then SHA-1 must be present.481*482* Though HMAC_DRBG/SHA-1 is, as far as we know, as safe as483* these things can be, we still prefer the SHA-2 functions over484* SHA-1, if only for public relations (known theoretical485* weaknesses of SHA-1 with regards to collisions are mostly486* irrelevant here, but they still make people nervous).487*/488h = br_multihash_getimpl(&cc->mhash, br_sha256_ID);489if (!h) {490h = br_multihash_getimpl(&cc->mhash, br_sha384_ID);491if (!h) {492h = br_multihash_getimpl(&cc->mhash,493br_sha1_ID);494if (!h) {495br_ssl_engine_fail(cc, BR_ERR_BAD_STATE);496return 0;497}498}499}500br_hmac_drbg_init(&cc->rng, h, NULL, 0);501cc->rng_init_done = 1;502return 1;503}504505/* see inner.h */506int507br_ssl_engine_init_rand(br_ssl_engine_context *cc)508{509if (!rng_init(cc)) {510return 0;511}512513/*514* We always try OS/hardware seeding once. If it works, then515* we assume proper seeding. If not, then external entropy must516* have been injected; otherwise, we report an error.517*/518if (!cc->rng_os_rand_done) {519br_prng_seeder sd;520521sd = br_prng_seeder_system(NULL);522if (sd != 0 && sd(&cc->rng.vtable)) {523cc->rng_init_done = 2;524}525cc->rng_os_rand_done = 1;526}527if (cc->rng_init_done < 2) {528br_ssl_engine_fail(cc, BR_ERR_NO_RANDOM);529return 0;530}531return 1;532}533534/* see bearssl_ssl.h */535void536br_ssl_engine_inject_entropy(br_ssl_engine_context *cc,537const void *data, size_t len)538{539/*540* Externally provided entropy is assumed to be "good enough"541* (we cannot really test its quality) so if the RNG structure542* could be initialised at all, then we marked the RNG as543* "properly seeded".544*/545if (!rng_init(cc)) {546return;547}548br_hmac_drbg_update(&cc->rng, data, len);549cc->rng_init_done = 2;550}551552/*553* We define a few internal functions that implement the low-level engine554* API for I/O; the external API (br_ssl_engine_sendapp_buf() and similar555* functions) is built upon these function, with special processing for556* records which are not of type "application data".557*558* recvrec_buf, recvrec_ack receives bytes from transport medium559* sendrec_buf, sendrec_ack send bytes to transport medium560* recvpld_buf, recvpld_ack receives payload data from engine561* sendpld_buf, sendpld_ack send payload data to engine562*/563564static unsigned char *565recvrec_buf(const br_ssl_engine_context *rc, size_t *len)566{567if (rc->shutdown_recv) {568*len = 0;569return NULL;570}571572/*573* Bytes from the transport can be injected only if the mode is574* compatible (in or in/out), and ixa == ixb; ixc then contains575* the number of bytes that are still expected (but it may576* exceed our buffer size).577*578* We cannot get "stuck" here (buffer is full, but still more579* data is expected) because oversized records are detected when580* their header is processed.581*/582switch (rc->iomode) {583case BR_IO_IN:584case BR_IO_INOUT:585if (rc->ixa == rc->ixb) {586size_t z;587588z = rc->ixc;589if (z > rc->ibuf_len - rc->ixa) {590z = rc->ibuf_len - rc->ixa;591}592*len = z;593return rc->ibuf + rc->ixa;594}595break;596}597*len = 0;598return NULL;599}600601static void602recvrec_ack(br_ssl_engine_context *rc, size_t len)603{604unsigned char *pbuf;605size_t pbuf_len;606607/*608* Adjust state if necessary (for a shared input/output buffer):609* we got some incoming bytes, so we cannot (temporarily) handle610* outgoing data.611*/612if (rc->iomode == BR_IO_INOUT && rc->ibuf == rc->obuf) {613rc->iomode = BR_IO_IN;614}615616/*617* Adjust data pointers.618*/619rc->ixb = (rc->ixa += len);620rc->ixc -= len;621622/*623* If we are receiving a header and did not fully obtained it624* yet, then just wait for the next bytes.625*/626if (rc->ixa < 5) {627return;628}629630/*631* If we just obtained a full header, process it.632*/633if (rc->ixa == 5) {634unsigned version;635unsigned rlen;636637/*638* Get record type and version. We support only versions639* 3.x (if the version major number does not match, then640* we suppose that the record format is too alien for us641* to process it).642*643* Note: right now, we reject clients that try to send644* a ClientHello in a format compatible with SSL-2.0. It645* is unclear whether this will ever be supported; and646* if we want to support it, then this might be done in647* in the server-specific code, not here.648*/649rc->record_type_in = rc->ibuf[0];650version = br_dec16be(rc->ibuf + 1);651if ((version >> 8) != 3) {652br_ssl_engine_fail(rc, BR_ERR_UNSUPPORTED_VERSION);653return;654}655656/*657* We ensure that successive records have the same658* version. The handshake code must check and adjust the659* variables when necessary to accommodate the protocol660* negotiation details.661*/662if (rc->version_in != 0 && rc->version_in != version) {663br_ssl_engine_fail(rc, BR_ERR_BAD_VERSION);664return;665}666rc->version_in = version;667668/*669* Decode record length. We must check that the length670* is valid (relatively to the current encryption mode)671* and also (if encryption is active) that the record672* will fit in our buffer.673*674* When no encryption is active, we can process records675* by chunks, and thus accept any record up to the676* maximum allowed plaintext length (16384 bytes).677*/678rlen = br_dec16be(rc->ibuf + 3);679if (rc->incrypt) {680if (!rc->in.vtable->check_length(681&rc->in.vtable, rlen))682{683br_ssl_engine_fail(rc, BR_ERR_BAD_LENGTH);684return;685}686if (rlen > (rc->ibuf_len - 5)) {687br_ssl_engine_fail(rc, BR_ERR_TOO_LARGE);688return;689}690} else {691if (rlen > 16384) {692br_ssl_engine_fail(rc, BR_ERR_BAD_LENGTH);693return;694}695}696697/*698* If the record is completely empty then we must switch699* to a new record. Note that, in that case, we700* completely ignore the record type, which is fitting701* since we received no actual data of that type.702*703* A completely empty record is technically allowed as704* long as encryption/MAC is not active, i.e. before705* completion of the first handshake. It it still weird;706* it might conceptually be useful as a heartbeat or707* keep-alive mechanism while some lengthy operation is708* going on, e.g. interaction with a human user.709*/710if (rlen == 0) {711make_ready_in(rc);712} else {713rc->ixa = rc->ixb = 5;714rc->ixc = rlen;715}716return;717}718719/*720* If there is no active encryption, then the data can be read721* right away. Note that we do not receive bytes from the722* transport medium when we still have payload bytes to be723* acknowledged.724*/725if (!rc->incrypt) {726rc->ixa = 5;727return;728}729730/*731* Since encryption is active, we must wait for a full record732* before processing it.733*/734if (rc->ixc != 0) {735return;736}737738/*739* We got the full record. Decrypt it.740*/741pbuf_len = rc->ixa - 5;742pbuf = rc->in.vtable->decrypt(&rc->in.vtable,743rc->record_type_in, rc->version_in, rc->ibuf + 5, &pbuf_len);744if (pbuf == 0) {745br_ssl_engine_fail(rc, BR_ERR_BAD_MAC);746return;747}748rc->ixa = (size_t)(pbuf - rc->ibuf);749rc->ixb = rc->ixa + pbuf_len;750751/*752* Decryption may have yielded an empty record, in which case753* we get back to "ready" state immediately.754*/755if (rc->ixa == rc->ixb) {756make_ready_in(rc);757}758}759760/* see inner.h */761int762br_ssl_engine_recvrec_finished(const br_ssl_engine_context *rc)763{764switch (rc->iomode) {765case BR_IO_IN:766case BR_IO_INOUT:767return rc->ixc == 0 || rc->ixa < 5;768default:769return 1;770}771}772773static unsigned char *774recvpld_buf(const br_ssl_engine_context *rc, size_t *len)775{776/*777* There is payload data to be read only if the mode is778* compatible, and ixa != ixb.779*/780switch (rc->iomode) {781case BR_IO_IN:782case BR_IO_INOUT:783*len = rc->ixb - rc->ixa;784return (*len == 0) ? NULL : (rc->ibuf + rc->ixa);785default:786*len = 0;787return NULL;788}789}790791static void792recvpld_ack(br_ssl_engine_context *rc, size_t len)793{794rc->ixa += len;795796/*797* If we read all the available data, then we either expect798* the remainder of the current record (if the current record799* was not finished; this may happen when encryption is not800* active), or go to "ready" state.801*/802if (rc->ixa == rc->ixb) {803if (rc->ixc == 0) {804make_ready_in(rc);805} else {806rc->ixa = rc->ixb = 5;807}808}809}810811static unsigned char *812sendpld_buf(const br_ssl_engine_context *rc, size_t *len)813{814/*815* Payload data can be injected only if the current mode is816* compatible, and oxa != oxb.817*/818switch (rc->iomode) {819case BR_IO_OUT:820case BR_IO_INOUT:821*len = rc->oxb - rc->oxa;822return (*len == 0) ? NULL : (rc->obuf + rc->oxa);823default:824*len = 0;825return NULL;826}827}828829/*830* If some payload bytes have been accumulated, then wrap them into831* an outgoing record. Otherwise, this function does nothing, unless832* 'force' is non-zero, in which case an empty record is assembled.833*834* The caller must take care not to invoke this function if the engine835* is not currently ready to receive payload bytes to send.836*/837static void838sendpld_flush(br_ssl_engine_context *rc, int force)839{840size_t xlen;841unsigned char *buf;842843if (rc->oxa == rc->oxb) {844return;845}846xlen = rc->oxa - rc->oxc;847if (xlen == 0 && !force) {848return;849}850buf = rc->out.vtable->encrypt(&rc->out.vtable,851rc->record_type_out, rc->version_out,852rc->obuf + rc->oxc, &xlen);853rc->oxb = rc->oxa = (size_t)(buf - rc->obuf);854rc->oxc = rc->oxa + xlen;855}856857static void858sendpld_ack(br_ssl_engine_context *rc, size_t len)859{860/*861* If using a shared buffer, then we may have to modify the862* current mode.863*/864if (rc->iomode == BR_IO_INOUT && rc->ibuf == rc->obuf) {865rc->iomode = BR_IO_OUT;866}867rc->oxa += len;868if (rc->oxa >= rc->oxb) {869/*870* Set oxb to one more than oxa so that sendpld_flush()871* does not mistakingly believe that a record is872* already prepared and being sent.873*/874rc->oxb = rc->oxa + 1;875sendpld_flush(rc, 0);876}877}878879static unsigned char *880sendrec_buf(const br_ssl_engine_context *rc, size_t *len)881{882/*883* When still gathering payload bytes, oxc points to the start884* of the record data, so oxc <= oxa. However, when a full885* record has been completed, oxc points to the end of the record,886* so oxc > oxa.887*/888switch (rc->iomode) {889case BR_IO_OUT:890case BR_IO_INOUT:891if (rc->oxc > rc->oxa) {892*len = rc->oxc - rc->oxa;893return rc->obuf + rc->oxa;894}895break;896}897*len = 0;898return NULL;899}900901static void902sendrec_ack(br_ssl_engine_context *rc, size_t len)903{904rc->oxb = (rc->oxa += len);905if (rc->oxa == rc->oxc) {906make_ready_out(rc);907}908}909910/*911* Test whether there is some buffered outgoing record that still must912* sent.913*/914static inline int915has_rec_tosend(const br_ssl_engine_context *rc)916{917return rc->oxa == rc->oxb && rc->oxa != rc->oxc;918}919920/*921* The "no encryption" mode has no overhead. It limits the payload size922* to the maximum size allowed by the standard (16384 bytes); the caller923* is responsible for possibly enforcing a smaller fragment length.924*/925static void926clear_max_plaintext(const br_sslrec_out_clear_context *cc,927size_t *start, size_t *end)928{929size_t len;930931(void)cc;932len = *end - *start;933if (len > 16384) {934*end = *start + 16384;935}936}937938/*939* In "no encryption" mode, encryption is trivial (a no-operation) so940* we just have to encode the header.941*/942static unsigned char *943clear_encrypt(br_sslrec_out_clear_context *cc,944int record_type, unsigned version, void *data, size_t *data_len)945{946unsigned char *buf;947948(void)cc;949buf = (unsigned char *)data - 5;950buf[0] = record_type;951br_enc16be(buf + 1, version);952br_enc16be(buf + 3, *data_len);953*data_len += 5;954return buf;955}956957/* see bearssl_ssl.h */958const br_sslrec_out_class br_sslrec_out_clear_vtable = {959sizeof(br_sslrec_out_clear_context),960(void (*)(const br_sslrec_out_class *const *, size_t *, size_t *))961&clear_max_plaintext,962(unsigned char *(*)(const br_sslrec_out_class **,963int, unsigned, void *, size_t *))964&clear_encrypt965};966967/* ==================================================================== */968/*969* In this part of the file, we handle the various record types, and970* communications with the handshake processor.971*/972973/*974* IMPLEMENTATION NOTES975* ====================976*977* The handshake processor is written in T0 and runs as a coroutine.978* It receives the contents of all records except application data, and979* is responsible for producing the contents of all records except980* application data.981*982* A state flag is maintained, which specifies whether application data983* is acceptable or not. When it is set:984*985* -- Application data can be injected as payload data (provided that986* the output buffer is ready for that).987*988* -- Incoming application data records are accepted, and yield data989* that the caller may retrieve.990*991* When the flag is cleared, application data is not accepted from the992* application, and incoming application data records trigger an error.993*994*995* Records of type handshake, alert or change-cipher-spec are handled996* by the handshake processor. The handshake processor is written in T0997* and runs as a coroutine; it gets invoked whenever one of the following998* situations is reached:999*1000* -- An incoming record has type handshake, alert or change-cipher-spec,1001* and yields data that can be read (zero-length records are thus1002* ignored).1003*1004* -- An outgoing record has just finished being sent, and the "application1005* data" flag is cleared.1006*1007* -- The caller wishes to perform a close (call to br_ssl_engine_close()).1008*1009* -- The caller wishes to perform a renegotiation (call to1010* br_ssl_engine_renegotiate()).1011*1012* Whenever the handshake processor is entered, access to the payload1013* buffers is provided, along with some information about explicit1014* closures or renegotiations.1015*/10161017/* see bearssl_ssl.h */1018void1019br_ssl_engine_set_suites(br_ssl_engine_context *cc,1020const uint16_t *suites, size_t suites_num)1021{1022if ((suites_num * sizeof *suites) > sizeof cc->suites_buf) {1023br_ssl_engine_fail(cc, BR_ERR_BAD_PARAM);1024return;1025}1026memcpy(cc->suites_buf, suites, suites_num * sizeof *suites);1027cc->suites_num = suites_num;1028}10291030/*1031* Give control to handshake processor. 'action' is 1 for a close,1032* 2 for a renegotiation, or 0 for a jump due to I/O completion.1033*/1034static void1035jump_handshake(br_ssl_engine_context *cc, int action)1036{1037/*1038* We use a loop because the handshake processor actions may1039* allow for more actions; namely, if the processor reads all1040* input data, then it may allow for output data to be produced,1041* in case of a shared in/out buffer.1042*/1043for (;;) {1044size_t hlen_in, hlen_out;10451046/*1047* Get input buffer. We do not want to provide1048* application data to the handshake processor (we could1049* get called with an explicit close or renegotiation1050* while there is application data ready to be read).1051*/1052cc->hbuf_in = recvpld_buf(cc, &hlen_in);1053if (cc->hbuf_in != NULL1054&& cc->record_type_in == BR_SSL_APPLICATION_DATA)1055{1056hlen_in = 0;1057}10581059/*1060* Get output buffer. The handshake processor never1061* leaves an unfinished outgoing record, so if there is1062* buffered output, then it MUST be some application1063* data, so the processor cannot write to it.1064*/1065cc->saved_hbuf_out = cc->hbuf_out = sendpld_buf(cc, &hlen_out);1066if (cc->hbuf_out != NULL && br_ssl_engine_has_pld_to_send(cc)) {1067hlen_out = 0;1068}10691070/*1071* Note: hlen_in and hlen_out can be both non-zero only if1072* the input and output buffers are disjoint. Thus, we can1073* offer both buffers to the handshake code.1074*/10751076cc->hlen_in = hlen_in;1077cc->hlen_out = hlen_out;1078cc->action = action;1079cc->hsrun(&cc->cpu);1080if (br_ssl_engine_closed(cc)) {1081return;1082}1083if (cc->hbuf_out != cc->saved_hbuf_out) {1084sendpld_ack(cc, cc->hbuf_out - cc->saved_hbuf_out);1085}1086if (hlen_in != cc->hlen_in) {1087recvpld_ack(cc, hlen_in - cc->hlen_in);1088if (cc->hlen_in == 0) {1089/*1090* We read all data bytes, which may have1091* released the output buffer in case it1092* is shared with the input buffer, and1093* the handshake code might be waiting for1094* that.1095*/1096action = 0;1097continue;1098}1099}1100break;1101}1102}11031104/* see inner.h */1105void1106br_ssl_engine_flush_record(br_ssl_engine_context *cc)1107{1108if (cc->hbuf_out != cc->saved_hbuf_out) {1109sendpld_ack(cc, cc->hbuf_out - cc->saved_hbuf_out);1110}1111if (br_ssl_engine_has_pld_to_send(cc)) {1112sendpld_flush(cc, 0);1113}1114cc->saved_hbuf_out = cc->hbuf_out = sendpld_buf(cc, &cc->hlen_out);1115}11161117/* see bearssl_ssl.h */1118unsigned char *1119br_ssl_engine_sendapp_buf(const br_ssl_engine_context *cc, size_t *len)1120{1121if (!(cc->application_data & 1)) {1122*len = 0;1123return NULL;1124}1125return sendpld_buf(cc, len);1126}11271128/* see bearssl_ssl.h */1129void1130br_ssl_engine_sendapp_ack(br_ssl_engine_context *cc, size_t len)1131{1132sendpld_ack(cc, len);1133}11341135/* see bearssl_ssl.h */1136unsigned char *1137br_ssl_engine_recvapp_buf(const br_ssl_engine_context *cc, size_t *len)1138{1139if (!(cc->application_data & 1)1140|| cc->record_type_in != BR_SSL_APPLICATION_DATA)1141{1142*len = 0;1143return NULL;1144}1145return recvpld_buf(cc, len);1146}11471148/* see bearssl_ssl.h */1149void1150br_ssl_engine_recvapp_ack(br_ssl_engine_context *cc, size_t len)1151{1152recvpld_ack(cc, len);1153}11541155/* see bearssl_ssl.h */1156unsigned char *1157br_ssl_engine_sendrec_buf(const br_ssl_engine_context *cc, size_t *len)1158{1159return sendrec_buf(cc, len);1160}11611162/* see bearssl_ssl.h */1163void1164br_ssl_engine_sendrec_ack(br_ssl_engine_context *cc, size_t len)1165{1166sendrec_ack(cc, len);1167if (len != 0 && !has_rec_tosend(cc)1168&& (cc->record_type_out != BR_SSL_APPLICATION_DATA1169|| (cc->application_data & 1) == 0))1170{1171jump_handshake(cc, 0);1172}1173}11741175/* see bearssl_ssl.h */1176unsigned char *1177br_ssl_engine_recvrec_buf(const br_ssl_engine_context *cc, size_t *len)1178{1179return recvrec_buf(cc, len);1180}11811182/* see bearssl_ssl.h */1183void1184br_ssl_engine_recvrec_ack(br_ssl_engine_context *cc, size_t len)1185{1186unsigned char *buf;11871188recvrec_ack(cc, len);1189if (br_ssl_engine_closed(cc)) {1190return;1191}11921193/*1194* We just received some bytes from the peer. This may have1195* yielded some payload bytes, in which case we must process1196* them according to the record type.1197*/1198buf = recvpld_buf(cc, &len);1199if (buf != NULL) {1200switch (cc->record_type_in) {1201case BR_SSL_CHANGE_CIPHER_SPEC:1202case BR_SSL_ALERT:1203case BR_SSL_HANDSHAKE:1204jump_handshake(cc, 0);1205break;1206case BR_SSL_APPLICATION_DATA:1207if (cc->application_data == 1) {1208break;1209}12101211/*1212* If we are currently closing, and waiting for1213* a close_notify from the peer, then incoming1214* application data should be discarded.1215*/1216if (cc->application_data == 2) {1217recvpld_ack(cc, len);1218break;1219}12201221/* Fall through */1222default:1223br_ssl_engine_fail(cc, BR_ERR_UNEXPECTED);1224break;1225}1226}1227}12281229/* see bearssl_ssl.h */1230void1231br_ssl_engine_close(br_ssl_engine_context *cc)1232{1233if (!br_ssl_engine_closed(cc)) {1234/*1235* If we are not already closed, then we need to1236* initiate the closure. Once closing, any incoming1237* application data is discarded; we should also discard1238* application data which is already there but has not1239* been acknowledged by the application yet (this mimics1240* usual semantics on BSD sockets: you cannot read()1241* once you called close(), even if there was some1242* unread data already buffered).1243*/1244size_t len;12451246if (br_ssl_engine_recvapp_buf(cc, &len) != NULL && len != 0) {1247br_ssl_engine_recvapp_ack(cc, len);1248}1249jump_handshake(cc, 1);1250}1251}12521253/* see bearssl_ssl.h */1254int1255br_ssl_engine_renegotiate(br_ssl_engine_context *cc)1256{1257size_t len;12581259if (br_ssl_engine_closed(cc) || cc->reneg == 11260|| (cc->flags & BR_OPT_NO_RENEGOTIATION) != 01261|| br_ssl_engine_recvapp_buf(cc, &len) != NULL)1262{1263return 0;1264}1265jump_handshake(cc, 2);1266return 1;1267}12681269/* see bearssl.h */1270unsigned1271br_ssl_engine_current_state(const br_ssl_engine_context *cc)1272{1273unsigned s;1274size_t len;12751276if (br_ssl_engine_closed(cc)) {1277return BR_SSL_CLOSED;1278}12791280s = 0;1281if (br_ssl_engine_sendrec_buf(cc, &len) != NULL) {1282s |= BR_SSL_SENDREC;1283}1284if (br_ssl_engine_recvrec_buf(cc, &len) != NULL) {1285s |= BR_SSL_RECVREC;1286}1287if (br_ssl_engine_sendapp_buf(cc, &len) != NULL) {1288s |= BR_SSL_SENDAPP;1289}1290if (br_ssl_engine_recvapp_buf(cc, &len) != NULL) {1291s |= BR_SSL_RECVAPP;1292}1293return s;1294}12951296/* see bearssl_ssl.h */1297void1298br_ssl_engine_flush(br_ssl_engine_context *cc, int force)1299{1300if (!br_ssl_engine_closed(cc) && (cc->application_data & 1) != 0) {1301sendpld_flush(cc, force);1302}1303}13041305/* see inner.h */1306void1307br_ssl_engine_hs_reset(br_ssl_engine_context *cc,1308void (*hsinit)(void *), void (*hsrun)(void *))1309{1310engine_clearbuf(cc);1311cc->cpu.dp = cc->dp_stack;1312cc->cpu.rp = cc->rp_stack;1313hsinit(&cc->cpu);1314cc->hsrun = hsrun;1315cc->shutdown_recv = 0;1316cc->application_data = 0;1317cc->alert = 0;1318jump_handshake(cc, 0);1319}13201321/* see inner.h */1322br_tls_prf_impl1323br_ssl_engine_get_PRF(br_ssl_engine_context *cc, int prf_id)1324{1325if (cc->session.version >= BR_TLS12) {1326if (prf_id == br_sha384_ID) {1327return cc->prf_sha384;1328} else {1329return cc->prf_sha256;1330}1331} else {1332return cc->prf10;1333}1334}13351336/* see inner.h */1337void1338br_ssl_engine_compute_master(br_ssl_engine_context *cc,1339int prf_id, const void *pms, size_t pms_len)1340{1341br_tls_prf_impl iprf;1342br_tls_prf_seed_chunk seed[2] = {1343{ cc->client_random, sizeof cc->client_random },1344{ cc->server_random, sizeof cc->server_random }1345};13461347iprf = br_ssl_engine_get_PRF(cc, prf_id);1348iprf(cc->session.master_secret, sizeof cc->session.master_secret,1349pms, pms_len, "master secret", 2, seed);1350}13511352/*1353* Compute key block.1354*/1355static void1356compute_key_block(br_ssl_engine_context *cc, int prf_id,1357size_t half_len, unsigned char *kb)1358{1359br_tls_prf_impl iprf;1360br_tls_prf_seed_chunk seed[2] = {1361{ cc->server_random, sizeof cc->server_random },1362{ cc->client_random, sizeof cc->client_random }1363};13641365iprf = br_ssl_engine_get_PRF(cc, prf_id);1366iprf(kb, half_len << 1,1367cc->session.master_secret, sizeof cc->session.master_secret,1368"key expansion", 2, seed);1369}13701371/* see inner.h */1372void1373br_ssl_engine_switch_cbc_in(br_ssl_engine_context *cc,1374int is_client, int prf_id, int mac_id,1375const br_block_cbcdec_class *bc_impl, size_t cipher_key_len)1376{1377unsigned char kb[192];1378unsigned char *cipher_key, *mac_key, *iv;1379const br_hash_class *imh;1380size_t mac_key_len, mac_out_len, iv_len;13811382imh = br_ssl_engine_get_hash(cc, mac_id);1383mac_out_len = (imh->desc >> BR_HASHDESC_OUT_OFF) & BR_HASHDESC_OUT_MASK;1384mac_key_len = mac_out_len;13851386/*1387* TLS 1.1+ uses per-record explicit IV, so no IV to generate here.1388*/1389if (cc->session.version >= BR_TLS11) {1390iv_len = 0;1391} else {1392iv_len = bc_impl->block_size;1393}1394compute_key_block(cc, prf_id,1395mac_key_len + cipher_key_len + iv_len, kb);1396if (is_client) {1397mac_key = &kb[mac_key_len];1398cipher_key = &kb[(mac_key_len << 1) + cipher_key_len];1399iv = &kb[((mac_key_len + cipher_key_len) << 1) + iv_len];1400} else {1401mac_key = &kb[0];1402cipher_key = &kb[mac_key_len << 1];1403iv = &kb[(mac_key_len + cipher_key_len) << 1];1404}1405if (iv_len == 0) {1406iv = NULL;1407}1408cc->icbc_in->init(&cc->in.cbc.vtable,1409bc_impl, cipher_key, cipher_key_len,1410imh, mac_key, mac_key_len, mac_out_len, iv);1411cc->incrypt = 1;1412}14131414/* see inner.h */1415void1416br_ssl_engine_switch_cbc_out(br_ssl_engine_context *cc,1417int is_client, int prf_id, int mac_id,1418const br_block_cbcenc_class *bc_impl, size_t cipher_key_len)1419{1420unsigned char kb[192];1421unsigned char *cipher_key, *mac_key, *iv;1422const br_hash_class *imh;1423size_t mac_key_len, mac_out_len, iv_len;14241425imh = br_ssl_engine_get_hash(cc, mac_id);1426mac_out_len = (imh->desc >> BR_HASHDESC_OUT_OFF) & BR_HASHDESC_OUT_MASK;1427mac_key_len = mac_out_len;14281429/*1430* TLS 1.1+ uses per-record explicit IV, so no IV to generate here.1431*/1432if (cc->session.version >= BR_TLS11) {1433iv_len = 0;1434} else {1435iv_len = bc_impl->block_size;1436}1437compute_key_block(cc, prf_id,1438mac_key_len + cipher_key_len + iv_len, kb);1439if (is_client) {1440mac_key = &kb[0];1441cipher_key = &kb[mac_key_len << 1];1442iv = &kb[(mac_key_len + cipher_key_len) << 1];1443} else {1444mac_key = &kb[mac_key_len];1445cipher_key = &kb[(mac_key_len << 1) + cipher_key_len];1446iv = &kb[((mac_key_len + cipher_key_len) << 1) + iv_len];1447}1448if (iv_len == 0) {1449iv = NULL;1450}1451cc->icbc_out->init(&cc->out.cbc.vtable,1452bc_impl, cipher_key, cipher_key_len,1453imh, mac_key, mac_key_len, mac_out_len, iv);1454}14551456/* see inner.h */1457void1458br_ssl_engine_switch_gcm_in(br_ssl_engine_context *cc,1459int is_client, int prf_id,1460const br_block_ctr_class *bc_impl, size_t cipher_key_len)1461{1462unsigned char kb[72];1463unsigned char *cipher_key, *iv;14641465compute_key_block(cc, prf_id, cipher_key_len + 4, kb);1466if (is_client) {1467cipher_key = &kb[cipher_key_len];1468iv = &kb[(cipher_key_len << 1) + 4];1469} else {1470cipher_key = &kb[0];1471iv = &kb[cipher_key_len << 1];1472}1473cc->igcm_in->init(&cc->in.gcm.vtable.in,1474bc_impl, cipher_key, cipher_key_len, cc->ighash, iv);1475cc->incrypt = 1;1476}14771478/* see inner.h */1479void1480br_ssl_engine_switch_gcm_out(br_ssl_engine_context *cc,1481int is_client, int prf_id,1482const br_block_ctr_class *bc_impl, size_t cipher_key_len)1483{1484unsigned char kb[72];1485unsigned char *cipher_key, *iv;14861487compute_key_block(cc, prf_id, cipher_key_len + 4, kb);1488if (is_client) {1489cipher_key = &kb[0];1490iv = &kb[cipher_key_len << 1];1491} else {1492cipher_key = &kb[cipher_key_len];1493iv = &kb[(cipher_key_len << 1) + 4];1494}1495cc->igcm_out->init(&cc->out.gcm.vtable.out,1496bc_impl, cipher_key, cipher_key_len, cc->ighash, iv);1497}14981499/* see inner.h */1500void1501br_ssl_engine_switch_chapol_in(br_ssl_engine_context *cc,1502int is_client, int prf_id)1503{1504unsigned char kb[88];1505unsigned char *cipher_key, *iv;15061507compute_key_block(cc, prf_id, 44, kb);1508if (is_client) {1509cipher_key = &kb[32];1510iv = &kb[76];1511} else {1512cipher_key = &kb[0];1513iv = &kb[64];1514}1515cc->ichapol_in->init(&cc->in.chapol.vtable.in,1516cc->ichacha, cc->ipoly, cipher_key, iv);1517cc->incrypt = 1;1518}15191520/* see inner.h */1521void1522br_ssl_engine_switch_chapol_out(br_ssl_engine_context *cc,1523int is_client, int prf_id)1524{1525unsigned char kb[88];1526unsigned char *cipher_key, *iv;15271528compute_key_block(cc, prf_id, 44, kb);1529if (is_client) {1530cipher_key = &kb[0];1531iv = &kb[64];1532} else {1533cipher_key = &kb[32];1534iv = &kb[76];1535}1536cc->ichapol_out->init(&cc->out.chapol.vtable.out,1537cc->ichacha, cc->ipoly, cipher_key, iv);1538}15391540/* see inner.h */1541void1542br_ssl_engine_switch_ccm_in(br_ssl_engine_context *cc,1543int is_client, int prf_id,1544const br_block_ctrcbc_class *bc_impl,1545size_t cipher_key_len, size_t tag_len)1546{1547unsigned char kb[72];1548unsigned char *cipher_key, *iv;15491550compute_key_block(cc, prf_id, cipher_key_len + 4, kb);1551if (is_client) {1552cipher_key = &kb[cipher_key_len];1553iv = &kb[(cipher_key_len << 1) + 4];1554} else {1555cipher_key = &kb[0];1556iv = &kb[cipher_key_len << 1];1557}1558cc->iccm_in->init(&cc->in.ccm.vtable.in,1559bc_impl, cipher_key, cipher_key_len, iv, tag_len);1560cc->incrypt = 1;1561}15621563/* see inner.h */1564void1565br_ssl_engine_switch_ccm_out(br_ssl_engine_context *cc,1566int is_client, int prf_id,1567const br_block_ctrcbc_class *bc_impl,1568size_t cipher_key_len, size_t tag_len)1569{1570unsigned char kb[72];1571unsigned char *cipher_key, *iv;15721573compute_key_block(cc, prf_id, cipher_key_len + 4, kb);1574if (is_client) {1575cipher_key = &kb[0];1576iv = &kb[cipher_key_len << 1];1577} else {1578cipher_key = &kb[cipher_key_len];1579iv = &kb[(cipher_key_len << 1) + 4];1580}1581cc->iccm_out->init(&cc->out.ccm.vtable.out,1582bc_impl, cipher_key, cipher_key_len, iv, tag_len);1583}158415851586