diff --git a/.github/configs/os-check-linux.json b/.github/configs/os-check-linux.json index d26e8301ea1..ad91c47264f 100644 --- a/.github/configs/os-check-linux.json +++ b/.github/configs/os-check-linux.json @@ -2,6 +2,15 @@ {"name": "all-static", "minutes": 8, "comment": "Static-only build, so configure defines WOLFSSL_TEST_STATIC_BUILD and the tests that call WOLFSSL_LOCAL functions directly are compiled and run.", "configure": ["--enable-all", "--enable-static", "--disable-shared"]}, +{"name": "record-size-limit", + "comment": "RFC 8449 on its own. --enable-all covers it alongside everything else; this is the minimal build, which is where the extension's own guards get exercised.", + "configure": ["--enable-recordsizelimit"]}, +{"name": "record-size-limit-tls12", + "comment": "RFC 8449 defines the extension for TLS 1.2 too, where the server answers in the ServerHello. Guards the parse dispatch staying outside the WOLFSSL_TLS13 block.", + "configure": ["--enable-recordsizelimit", "--disable-tls13"]}, +{"name": "record-size-limit-libz", + "comment": "RFC 8449 alongside TLS record layer compression. Both are built, and each connection uses at most one: wolfSSL_set_compression() and wolfSSL_UseRecordSizeLimit() refuse each other, so this is where that pairing gets exercised.", + "configure": ["--enable-recordsizelimit", "--with-libz"]}, {"name": "user-settings-all-compat", "minutes": 9.5, "comment": "user_settings_all.h with the compatibility layer enabled by flipping its \"#if 0\" block, as a build-dir copy.", "user_settings": "examples/configs/user_settings_all.h", diff --git a/CMakeLists.txt b/CMakeLists.txt index 51a7439b122..5e9a8cd85df 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -374,7 +374,7 @@ if(WOLFSSL_ALL) WOLFSSL_OCSPSTAPLING WOLFSSL_OCSPSTAPLING_V2 WOLFSSL_OPENSSLALL WOLFSSL_OPENSSLEXTRA WOLFSSL_POSTAUTH WOLFSSL_QUIC WOLFSSL_SAVECERT WOLFSSL_SAVESESSION WOLFSSL_SCEP WOLFSSL_SESSION_TICKET WOLFSSL_SNI - WOLFSSL_SRTP WOLFSSL_TLS13) + WOLFSSL_SRTP WOLFSSL_TLS13 WOLFSSL_RECORDSIZELIMIT) default_option(${_o} "yes") endforeach() @@ -857,7 +857,7 @@ if(WOLFSSL_CRYPT_ONLY) WOLFSSL_PKCALLBACKS WOLFSSL_QUIC WOLFSSL_RENEGOTIATION_INDICATION WOLFSSL_SECURE_RENEGOTIATION WOLFSSL_SECURE_RENEGOTIATION_INFO - WOLFSSL_SNI WOLFSSL_SRTP WOLFSSL_TLSX) + WOLFSSL_SNI WOLFSSL_SRTP WOLFSSL_TLSX WOLFSSL_RECORDSIZELIMIT) force_option(${_o} "no") endforeach() message(STATUS "WOLFSSL_CRYPT_ONLY: TLS layer off, including its options") @@ -2234,6 +2234,9 @@ add_option("WOLFSSL_TLS" "Enable TLS (default: enabled)" "yes" "yes;no") if(NOT WOLFSSL_TLS) list(APPEND WOLFSSL_DEFINITIONS "-DNO_TLS") default_option(WOLFSSL_SECURE_RENEGOTIATION_INFO "no") + # record_size_limit needs the TLS layer, and its API is compiled only with it, so + # an explicit -DWOLFSSL_RECORDSIZELIMIT=yes is overridden here, as --disable-tls does. + force_option(WOLFSSL_RECORDSIZELIMIT "no") endif() # TLSv1.2 @@ -3066,6 +3069,8 @@ endif() if(WOLFSSL_TLSX) override_cache(WOLFSSL_ENC_THEN_MAC "yes") + # A pure extension, which is what --enable-tlsx means in configure.ac. + default_option(WOLFSSL_RECORDSIZELIMIT "yes") endif() if(WOLFSSL_SNIFFER) @@ -4750,6 +4755,17 @@ if(WOLFSSL_LIBZ) list(APPEND WOLFSSL_INCLUDE_DIRS ${ZLIB_INCLUDE_DIRS}) endif() +# Record size limit (RFC 8449). Applies to TLS 1.2 as well as TLS 1.3, where +# the server answers in the ServerHello rather than EncryptedExtensions, so +# it imposes no TLS 1.3 requirement. +add_option("WOLFSSL_RECORDSIZELIMIT" + "Enable RFC 8449 record_size_limit, for TLS 1.2 and TLS 1.3 (default: disabled)" + "no" "yes;no") +if(WOLFSSL_RECORDSIZELIMIT) + list(APPEND WOLFSSL_DEFINITIONS "-DHAVE_TLS_EXTENSIONS") + list(APPEND WOLFSSL_DEFINITIONS "-DHAVE_RECORD_SIZE_LIMIT") +endif() + #################################################### # Maximum key size options (parity with configure.ac) diff --git a/ChangeLog.md b/ChangeLog.md index a8273b994ff..44751dd08dd 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -27,6 +27,15 @@ Both macros are documented in `wolfcrypt/src/port/nxp/README_SE050.md` and `IDE/CRYPTOCELL/README.md`. by @SparkiDev +* Added the RFC 8449 record_size_limit TLS extension for TLS 1.2 and TLS 1.3 + (`--enable-recordsizelimit`, CMake `WOLFSSL_RECORDSIZELIMIT`, macro + `HAVE_RECORD_SIZE_LIMIT`), the byte-exact replacement for + max_fragment_length. `wolfSSL_CTX_UseRecordSizeLimit()` and + `wolfSSL_UseRecordSizeLimit()` set the largest record this end accepts, and + the records sent are sized to the limit the peer advertised. Record layer + compression and a record size limit cannot share a connection, so each is + refused while the other is in use. by @SparkiDev (PR 12258) + ## Behavioral Changes * **Behavioral change (DSA now uses the leftmost |q| bytes of the digest)**: `wc_DsaSign_ex()`/`wc_DsaVerify_ex()` read the whole digest, and the EVP DSA @@ -125,6 +134,17 @@ because callers fold the result into constant-time masks that read a negative value as a match. +* **Behavioral change (`--enable-all` and `--enable-tlsx` advertise a record + size limit)**: both options now enable record_size_limit, and a build with + it advertises the protocol maximum by default, adding 6 bytes to every + ClientHello. When both peers send it, RFC 8449 has record_size_limit + override max_fragment_length. Session export is refused for a connection + that negotiated a limit below the maximum, as the export format does not + carry it. Pass `WOLFSSL_RECORD_SIZE_LIMIT_OFF` to + `wolfSSL_UseRecordSizeLimit()` to stop advertising one, or build with + `--disable-recordsizelimit` (CMake `-DWOLFSSL_RECORDSIZELIMIT=no`). + by @SparkiDev (PR 12258) + ## Post-Quantum Cryptography (PQC) * Added opt-in per-key Falcon signing caches (`--enable-falcon=cache-key`, `cache-basis`), roughly doubling signing speed with the default integer fpr backend. by @Frauschi diff --git a/cmake/options.h.in b/cmake/options.h.in index c19d8fc163d..9e03221d130 100644 --- a/cmake/options.h.in +++ b/cmake/options.h.in @@ -159,6 +159,8 @@ extern "C" { #cmakedefine HAVE_PTHREAD 1 #undef HAVE_REPRODUCIBLE_BUILD #cmakedefine HAVE_REPRODUCIBLE_BUILD +#undef HAVE_RECORD_SIZE_LIMIT +#cmakedefine HAVE_RECORD_SIZE_LIMIT #undef HAVE_SESSION_TICKET #cmakedefine HAVE_SESSION_TICKET #undef HAVE_SNI diff --git a/configure.ac b/configure.ac index 5ce318b9b2a..fc2768742c1 100644 --- a/configure.ac +++ b/configure.ac @@ -1406,6 +1406,7 @@ then test "$enable_srtp" = "" && enable_srtp=no test "$enable_ocsp" = "" && enable_ocsp=no test "$enable_tlsx" = "" && enable_tlsx=no + test "$enable_recordsizelimit" = "" && enable_recordsizelimit=no test "$enable_sni" = "" && enable_sni=no test "$enable_crl_monitor" = "" && enable_crl_monitor=no test "$enable_alpn" = "" && enable_alpn=no @@ -1583,6 +1584,7 @@ then test "$enable_earlydata" = "" && enable_earlydata=yes test "$enable_rpk" = "" && enable_rpk=yes + test "$enable_recordsizelimit" = "" && enable_recordsizelimit=yes if test "$KERNEL_MODE_DEFAULTS" != "yes" then # Disable QUIC with JNI since incompatible with client-side @@ -10228,6 +10230,10 @@ then ENABLED_ALPN=yes ENABLED_TRUSTED_CA=yes ENABLED_ENCRYPT_THEN_MAC=yes + dnl A seed rather than an ENABLED_ var: this block runs before that option + dnl is declared, and AC_ARG_ENABLE keys off ${enable_X+set}. It is a pure + dnl extension, which is what --enable-tlsx means. + test "$enable_recordsizelimit" = "" && enable_recordsizelimit=yes AM_CFLAGS="$AM_CFLAGS -DHAVE_TLS_EXTENSIONS -DHAVE_SNI -DHAVE_MAX_FRAGMENT -DHAVE_TRUNCATED_HMAC -DHAVE_ALPN -DHAVE_TRUSTED_CA" # Check the ECC supported curves prereq AS_IF([test "x$ENABLED_ECC" != "xno" || test "$ENABLED_CURVE25519" != "no" || test "x$ENABLED_CURVE448" = "xyes" || test "x$ENABLED_TLS13" = "xyes"], @@ -11663,6 +11669,27 @@ AC_ARG_WITH([libz], ] ) +# Record Size Limit (RFC 8449) +AC_ARG_ENABLE([recordsizelimit], + [AS_HELP_STRING([--enable-recordsizelimit],[Enable RFC 8449 record_size_limit, the byte-exact replacement for max_fragment_length. Applies to TLS 1.2 and TLS 1.3. A connection cannot both use it and compress its records, so wolfSSL_set_compression() and wolfSSL_UseRecordSizeLimit() refuse each other (default: disabled)])], + [ ENABLED_RECORD_SIZE_LIMIT=$enableval ], + [ ENABLED_RECORD_SIZE_LIMIT=no ] + ) +dnl RFC 8449 defines the extension for TLS 1.2 as well as TLS 1.3, where the +dnl server answers in the ServerHello rather than EncryptedExtensions, so no +dnl TLS 1.3 dependency is imposed here. It does need TLS: the no-TLS defaults +dnl above only cover an unset option, so an explicit --enable-recordsizelimit +dnl is overridden here in a crypto-only or no-TLS build, as CMake does. +if test "$ENABLED_RECORD_SIZE_LIMIT" = "yes" && test "$ENABLED_TLS" = "no" +then + AC_MSG_WARN([--enable-recordsizelimit needs TLS; disabled in this no-TLS build]) + ENABLED_RECORD_SIZE_LIMIT=no +fi +if test "$ENABLED_RECORD_SIZE_LIMIT" = "yes" +then + AM_CFLAGS="$AM_CFLAGS -DHAVE_TLS_EXTENSIONS -DHAVE_RECORD_SIZE_LIMIT" +fi + # PKCS#11 AC_ARG_ENABLE([pkcs11], @@ -15505,6 +15532,7 @@ echo " * Falcon: $ENABLED_FALCON" echo " * Server Name Indication: $ENABLED_SNI" echo " * ALPN: $ENABLED_ALPN" echo " * Maximum Fragment Length: $ENABLED_MAX_FRAGMENT" +echo " * Record Size Limit: $ENABLED_RECORD_SIZE_LIMIT" echo " * Trusted CA Indication: $ENABLED_TRUSTED_CA" echo " * Truncated HMAC: $ENABLED_TRUNCATED_HMAC" echo " * Supported Elliptic Curves: $ENABLED_SUPPORTED_CURVES" diff --git a/doc/dox_comments/header_files/ssl.h b/doc/dox_comments/header_files/ssl.h index 308eeddb0d7..85a632f89ce 100644 --- a/doc/dox_comments/header_files/ssl.h +++ b/doc/dox_comments/header_files/ssl.h @@ -8770,10 +8770,22 @@ int wolfSSL_negotiate(WOLFSSL* ssl); transport is known when the WOLFSSL object is created, this is reported rather than dropped. + A connection cannot both compress its records and use the RFC 8449 + record_size_limit extension: the limit bounds the plaintext, which deflate + may expand past it. A limit the application set with + wolfSSL_UseRecordSizeLimit() or wolfSSL_CTX_UseRecordSizeLimit() is its + request, so this call is refused; the advertisement that is on by default + gives way instead, and such a connection offers no limit. It can give way + only before it is sent or answered, so call this before the handshake + starts: from a server's SNI callback, for one, it is refused whenever the + client offered record_size_limit. + \return SSL_SUCCESS upon success. \return NOT_COMPILED_IN will be returned if compression support wasn’t built into the library. - \return BAD_FUNC_ARG will be returned if ssl is NULL or is a DTLS session. + \return BAD_FUNC_ARG will be returned if ssl is NULL, is a DTLS session, + was given a record size limit, or has already advertised, sent or + received one. \param ssl pointer to the SSL session, created with wolfSSL_new(). @@ -11171,12 +11183,13 @@ int wolfSSL_GetOutputSize(WOLFSSL* ssl, int inSz); /*! \brief Returns the maximum record layer size for plaintext data. This - will correspond to either the maximum SSL/TLS record size as specified - by the protocol standard, the maximum TLS fragment size as set by the - TLS Max Fragment Length extension. This function is helpful when the - application has called wolfSSL_GetOutputSize() and received a INPUT_SIZE_E - error. This function must be called after the SSL/TLS handshake has been - completed. + will correspond to the smallest of the maximum SSL/TLS record size as + specified by the protocol standard, the maximum TLS fragment size as set + by the TLS Max Fragment Length extension, and the limit the peer + advertised with the RFC 8449 record_size_limit extension. This function is + helpful when the application has called wolfSSL_GetOutputSize() and + received a INPUT_SIZE_E error. This function must be called after the + SSL/TLS handshake has been completed. \return size Upon success, the maximum output size will be returned \return BAD_FUNC_ARG will be returned upon invalid function argument, @@ -11190,6 +11203,8 @@ int wolfSSL_GetOutputSize(WOLFSSL* ssl, int inSz); \endcode \sa wolfSSL_GetOutputSize + \sa wolfSSL_UseRecordSizeLimit + \sa wolfSSL_UseMaxFragment */ int wolfSSL_GetMaxOutputSize(WOLFSSL* ssl); @@ -14100,9 +14115,105 @@ int wolfSSL_ALPN_GetPeerProtocol(WOLFSSL* ssl, char **list, \sa wolfSSL_new \sa wolfSSL_CTX_UseMaxFragment + \sa wolfSSL_UseRecordSizeLimit */ int wolfSSL_UseMaxFragment(WOLFSSL* ssl, unsigned char mfl); +/*! + \brief Sets the largest record payload this end will accept, advertised as + the RFC 8449 record_size_limit extension. A client sends it in the + ClientHello; a server that received one answers in EncryptedExtensions + under TLS 1.3 or in the ServerHello under TLS 1.2. The extension only + takes effect when both ends send it, so the peer's records are capped only + once it has answered. It supersedes max_fragment_length, which offers four + fixed sizes rather than an exact byte count; where a peer sends both, RFC + 8449 Sect. 5 says record_size_limit governs. + + The count is payload. RFC 8449's field on the wire covers the whole TLS + 1.3 TLSInnerPlaintext, so a request for n goes out as n+1 under TLS 1.3 + and as n under TLS 1.2; the conversion is internal. + + A limit is advertised by default. Pass WOLFSSL_RECORD_SIZE_LIMIT_OFF to + stop advertising one. Must be called before the handshake starts, since + the value is both advertised to the peer and enforced on arrival: on the + context, or on the object before wolfSSL_connect() or wolfSSL_accept(). + A server callback is too late. A certificate setup callback and an SNI + callback both run after the ClientHello's extensions have been parsed, so + either is refused whenever the client sent record_size_limit - and a + client that sent the extension is the only case in which a server's limit + would be answered at all. + + Record layer compression is refused on a connection that was given a + limit, and a limit is refused on one that compresses: RFC 8449 Sect. 4 + measures the limit against the plaintext, which deflate may expand past + it. A limit set here is the application's request and wins, so + wolfSSL_set_compression() then fails; the advertisement that is on by + default gives way instead, and such a connection offers no limit. + + The default limit stands aside for an application that asked for + max_fragment_length with wolfSSL_UseMaxFragment(), so a client that set + one keeps offering it alone. Calling this function explicitly overrides + that: the application has then asked for both, and RFC 8449 Sect. 5 says + record_size_limit governs. + + \return WOLFSSL_SUCCESS upon success. + \return BAD_FUNC_ARG for any of four distinct causes: ssl is NULL, limit + is outside WOLFSSL_RECORD_SIZE_LIMIT_MIN..WOLFSSL_RECORD_SIZE_LIMIT_MAX + (and not WOLFSSL_RECORD_SIZE_LIMIT_OFF), the handshake has already begun, + or wolfSSL_set_compression() was called on this object. The last two are + state errors rather than bad arguments; they share the code so that + existing callers testing for failure are unaffected. + + \param ssl pointer to a SSL object, created with wolfSSL_new(). + \param limit largest record payload accepted, from + WOLFSSL_RECORD_SIZE_LIMIT_MIN (64) to WOLFSSL_RECORD_SIZE_LIMIT_MAX + (16384), or WOLFSSL_RECORD_SIZE_LIMIT_OFF (0) to advertise nothing. + Defaults to WOLFSSL_RECORD_SIZE_LIMIT_DEFAULT. + + _Example_ + \code + int ret = 0; + WOLFSSL* ssl = wolfSSL_new(ctx); + if (ssl == NULL) { + // ssl creation failed + } + ret = wolfSSL_UseRecordSizeLimit(ssl, 1024); + if (ret != WOLFSSL_SUCCESS) { + // limit rejected + } + \endcode + + \sa wolfSSL_CTX_UseRecordSizeLimit + \sa wolfSSL_UseMaxFragment + \sa wolfSSL_GetMaxOutputSize +*/ +int wolfSSL_UseRecordSizeLimit(WOLFSSL* ssl, unsigned short limit); + +/*! + \brief Sets the record_size_limit inherited by every WOLFSSL object + created from this context afterwards. See wolfSSL_UseRecordSizeLimit() for + what the value means and how the extension is negotiated. + + \return WOLFSSL_SUCCESS upon success. + \return BAD_FUNC_ARG when ctx is NULL or limit is out of range. + + \param ctx pointer to a SSL context, created with wolfSSL_CTX_new(). + \param limit largest record payload accepted, from + WOLFSSL_RECORD_SIZE_LIMIT_MIN (64) to WOLFSSL_RECORD_SIZE_LIMIT_MAX + (16384), or WOLFSSL_RECORD_SIZE_LIMIT_OFF (0) to advertise nothing. + + _Example_ + \code + int ret = wolfSSL_CTX_UseRecordSizeLimit(ctx, 512); + if (ret != WOLFSSL_SUCCESS) { + // limit rejected + } + \endcode + + \sa wolfSSL_UseRecordSizeLimit +*/ +int wolfSSL_CTX_UseRecordSizeLimit(WOLFSSL_CTX* ctx, unsigned short limit); + /*! \brief This function is called on the client side to enable the use of Maximum Fragment Length for SSL objects created from the SSL context diff --git a/src/internal.c b/src/internal.c index b79f2bfb029..6788d84cbdb 100644 --- a/src/internal.c +++ b/src/internal.c @@ -2607,6 +2607,24 @@ int wolfSSL_session_export_internal(WOLFSSL* ssl, byte* buf, word32* sz, } #endif +#ifdef HAVE_RECORD_SIZE_LIMIT + /* The export format has no room for the RFC 8449 limits, so an imported + * copy would neither enforce this end's limit nor honour the peer's, and + * would send records the peer rejects with record_overflow. Refuse rather + * than hand back a session that misbehaves - but only for a limit that + * restricts anything. Both ends advertise the protocol maximum by + * default, which an imported copy enforces anyway, and refusing those + * would block exporting every connection in a build with the extension. */ + if (ret == 0 && ssl->peerRecordSizeLimit != 0 && + ((ssl->peerRecordSizeLimit < MAX_RECORD_SIZE) || + ((ssl->recordSizeLimit != 0) && + (ssl->recordSizeLimit < MAX_RECORD_SIZE)))) { + WOLFSSL_MSG("Can not export a session that negotiated " + "record_size_limit"); + ret = BAD_STATE_E; + } +#endif + if (ret == 0) { totalLen += WOLFSSL_EXPORT_LEN * 2; /* 2 protocol bytes and 2 length bytes */ /* each of the following have a 2 byte length before data */ @@ -3167,6 +3185,13 @@ int InitSSL_Ctx(WOLFSSL_CTX* ctx, WOLFSSL_METHOD* method, void* heap) ctx->readAheadSz = WOLFSSL_READ_AHEAD_SZ; #endif +#ifdef HAVE_RECORD_SIZE_LIMIT + /* Advertise by default so the extension actually negotiates; an + * application that does not want to offer one sets 0. Inherited by every + * WOLFSSL made from this context. */ + ctx->recordSizeLimit = WOLFSSL_RECORD_SIZE_LIMIT_DEFAULT; +#endif + #ifdef WOLFSSL_DTLS if (method->version.major == DTLS_MAJOR) { ctx->minDowngrade = WOLFSSL_MIN_DTLS_DOWNGRADE; @@ -9460,6 +9485,15 @@ int InitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup) ssl->options.useClientOrder = ctx->useClientOrder; ssl->options.mutualAuth = ctx->mutualAuth; +#ifdef HAVE_RECORD_SIZE_LIMIT + /* Version independent on purpose: RFC 8449 covers TLS 1.2, where the + * server answers in the ServerHello, so this must not live in + * InitSSL_Tls13Options() - a TLS 1.2 only build would never inherit the + * context's limit and would silently never offer the extension. */ + ssl->recordSizeLimit = ctx->recordSizeLimit; + ssl->recordSizeLimitSet = ctx->recordSizeLimitSet; +#endif + #ifdef WOLFSSL_TLS13 InitSSL_Tls13Options(ssl, ctx); #endif /* WOLFSSL_TLS13 */ @@ -14326,6 +14360,76 @@ static int GetDtlsRecordHeader(WOLFSSL* ssl, word32* inOutIdx, } #endif /* WOLFSSL_DTLS */ +#ifdef HAVE_RECORD_SIZE_LIMIT +/* Whether RFC 8449's limit binds the record being processed. + * + * "The limits ... apply only once the extension is negotiated", which is when + * both ends have sent one, and "unprotected messages are not subject to this + * limit" -- which matters at TLS 1.2, where the certificate flight travels in + * the clear. + * + * Early data received by a server is excluded: a client composes it before it + * can have seen the server's limit, which RFC 8449 does not carry in the + * ticket. A client needs no such exemption: the server has its ClientHello, + * and so its limit, before it encrypts anything. Every state from + * early_data_ext on is exempt, since a server that never calls + * wolfSSL_read_early_data() stays there and its rejected 0-RTT records have + * to reach the skip path in ProcessReply() rather than be refused here. The + * exemption ends with the handshake, as no early data follows it. + */ +static int RecordSizeLimitBinds(const WOLFSSL* ssl) +{ + if ((ssl->recordSizeLimit == 0) || (ssl->peerRecordSizeLimit == 0)) + return 0; + if (!IsEncryptionOn(ssl, 0)) + return 0; +#ifdef WOLFSSL_EARLY_DATA + if ((ssl->options.side == WOLFSSL_SERVER_END) && + (ssl->earlyData >= early_data_ext) && + (ssl->earlyData < done_early_data) && + (ssl->options.handShakeState != HANDSHAKE_DONE)) { + return 0; + } +#endif + + return 1; +} + +/* The largest plaintext the peer may send, measured the way RFC 8449 Sect. 4 + * measures it: the content alone, with no content type byte, no padding and + * no cipher expansion. + * + * Taken from what this end advertised rather than from ssl->recordSizeLimit, + * because the two part company after a downgrade: + * TLSX_RecordSizeLimit_Write() folds the TLS 1.3 TLSInnerPlaintext content + * type byte into the value it sends, and a client offers before the version + * is settled, so with TLS 1.2 negotiated the whole advertised value is + * content the peer may use. + */ +static word32 RecordSizeLimitMaxPlain(const WOLFSSL* ssl) +{ + word32 maxSz; + + if (ssl->recordSizeLimitSent != 0) { + maxSz = (word32)ssl->recordSizeLimitSent; +#ifdef WOLFSSL_TLS13 + /* Written with the content type byte included exactly when the + * version in force at the time was TLS 1.3, which is also the + * version in force now unless this connection was downgraded. */ + if (IsAtLeastTLSv1_3(ssl->version)) + maxSz--; +#endif + } + else { + /* Nothing recorded as sent: ssl->recordSizeLimit counts payload + * already, at either version. */ + maxSz = (word32)ssl->recordSizeLimit; + } + + return maxSz; +} +#endif /* HAVE_RECORD_SIZE_LIMIT */ + /* do all verify and sanity checks on record header */ static int GetRecordHeader(WOLFSSL* ssl, word32* inOutIdx, RecordLayerHeader* rh, word16 *size) @@ -14445,6 +14549,88 @@ static int GetRecordHeader(WOLFSSL* ssl, word32* inOutIdx, } #endif +#ifdef HAVE_RECORD_SIZE_LIMIT + /* RFC 8449 Sect. 4: "A TLS endpoint that receives a record larger than + * its advertised limit MUST generate a fatal record_overflow alert." + * LENGTH_ERROR is what the caller turns into that alert. The limit is on + * the plaintext, so the ciphertext is allowed its expansion on top. + * RecordSizeLimitBinds() holds the rest of the conditions. */ + if (RecordSizeLimitBinds(ssl)) { + /* Start from the plaintext this end advertised room for and add back + * only what the record around it may legally carry. MAX_MSG_EXTRA is + * the worst case over every suite wolfSSL supports, wide enough at a + * small limit to wave through a record several times the size + * advertised. TLS 1.3 is AEAD throughout, so the expansion is the tag + * and the content type byte; at TLS 1.2 an explicit IV, the MAC and + * block padding vary by suite, so the negotiated suite's exact + * expansion is used. The decrypted-plaintext check reads the same + * RecordSizeLimitMaxPlain(), so the two cannot drift. */ + word32 maxSz = RecordSizeLimitMaxPlain(ssl); + + #ifdef WOLFSSL_TLS13 + if (IsAtLeastTLSv1_3(ssl->version)) { + /* The content type byte and any padding are inside the limit, + * leaving the tag as the only expansion. */ + maxSz += 1 + (word32)ssl->specs.aead_mac_size; + } + else + #endif + { + /* cipherExtraData() gives the exact expansion for the negotiated + * suite - including the explicit nonce TLS 1.2 GCM and CCM carry + * and ChaCha20-Poly1305 does not - rather than MAX_MSG_EXTRA, + * which is dozens of bytes too generous for an AEAD suite and + * would leave this end accepting records above the limit it + * advertised. Compression cannot add to it: the limit only binds + * when both ends advertised it, and wolfSSL_set_compression() and + * wolfSSL_UseRecordSizeLimit() refuse to let one connection do + * both. */ + int cipherExtra = cipherExtraData(ssl); + word32 suiteExtra; + + if (cipherExtra < 0) + cipherExtra = 0; + suiteExtra = (word32)cipherExtra; + #ifndef WOLFSSL_AEAD_ONLY + if (ssl->specs.cipher_type == block) { + /* cipherExtraData() allows one block of padding, which is what + * wolfSSL itself emits. A peer may pad up to MAX_PAD_SIZE to + * hide the plaintext length, so swap that one block for the + * whole allowance. */ + if ((word32)ssl->specs.block_size < MAX_PAD_SIZE) { + suiteExtra += MAX_PAD_SIZE - + (word32)ssl->specs.block_size; + } + } + #endif + #if defined(WOLFSSL_DTLS) && defined(WOLFSSL_DTLS_CID) + /* RFC 9146 Sect. 4: a DTLS 1.2 record carrying a Connection ID is + * a DTLSInnerPlaintext - the real content, then its content type, + * then optional zero padding. cipherExtraData() counts that byte + * only when this end has a CID of its own to send, yet using one + * in this direction is the peer's choice alone: a peer that gave + * this end no CID would have its full size records refused with + * record_overflow. The padding gets the same allowance as a CBC + * suite's above, for the same reason, and the limit itself is + * enforced on the plaintext once the record has been opened. */ + if (rh->type == dtls12_cid) { + if (DtlsGetCidTxSize(ssl) == 0) + suiteExtra += 1; + suiteExtra += MAX_PAD_SIZE; + } + #endif + maxSz += suiteExtra; + } + + if ((word32)*size > maxSz) { + WOLFSSL_MSG_EX("Record length %d exceeds record size limit", + *size); + WOLFSSL_ERROR_VERBOSE(LENGTH_ERROR); + return LENGTH_ERROR; + } + } +#endif + if (*size == 0 && rh->type != application_data) { WOLFSSL_MSG("0 length, non-app data record."); WOLFSSL_ERROR_VERBOSE(LENGTH_ERROR); @@ -28386,6 +28572,25 @@ static int DoProcessReplyEx(WOLFSSL* ssl, int allowSocketErr) ssl->curSize -= (word16)ssl->keys.padSz; } +#ifdef HAVE_RECORD_SIZE_LIMIT + /* RFC 8449 Sect. 4 measures the limit against the plaintext, and + * this is the first point at which the plaintext length is known: + * the IV, MAC and padding are off, and with them the TLS 1.3 + * content type byte that the advertised value covered. The check + * on the ciphertext in GetRecordHeader() cannot do this job -- it + * has to allow every expansion a sender may legally add, up to + * MAX_PAD_SIZE of CBC padding, so a record that pads minimally + * passes it with a plaintext well over the limit. */ + if (((word32)ssl->curSize > RecordSizeLimitMaxPlain(ssl)) && + RecordSizeLimitBinds(ssl)) { + WOLFSSL_MSG_EX("Plaintext length %d exceeds record size limit", + ssl->curSize); + SendAlert(ssl, alert_fatal, record_overflow); + WOLFSSL_ERROR_VERBOSE(LENGTH_ERROR); + return LENGTH_ERROR; + } +#endif + /* in case > 1 msg per record */ ssl->curStartIdx = ssl->buffers.inputBuffer.idx; @@ -49582,6 +49787,24 @@ int wolfSSL_GetMaxFragSize(WOLFSSL* ssl) } #endif /* HAVE_MAX_FRAGMENT */ +#ifdef HAVE_RECORD_SIZE_LIMIT + /* RFC 8449 Sect. 4: never generate a protected record whose plaintext is + * larger than the peer's limit. "Unprotected messages are not subject to + * this limit": the receive check in GetRecordHeader() tests the same + * thing, so without the encryption test the two directions disagree - at + * TLS 1.2 peerRecordSizeLimit is set while parsing the ClientHello, which + * would fragment the whole cleartext certificate flight to the peer's + * limit. */ + if ((ssl->peerRecordSizeLimit != 0) && (IsEncryptionOn(ssl, 1) == 1)) { + /* Already payload: TLSX_RecordSizeLimit_Parse() took the TLS 1.3 + * content type byte off when it read the value. */ + int limit = (int)ssl->peerRecordSizeLimit; + + if (maxFragment > limit) + maxFragment = limit; + } +#endif /* HAVE_RECORD_SIZE_LIMIT */ + return maxFragment; } diff --git a/src/ssl.c b/src/ssl.c index 99adfbc6302..bfc99c1d7e3 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -950,6 +950,19 @@ static int DupSSL(WOLFSSL* dup, WOLFSSL* ssl) /* The negotiated limit applies to the records the writer sends. */ dup->max_fragment = ssl->max_fragment; #endif +#ifdef HAVE_RECORD_SIZE_LIMIT + /* RFC 8449 Sect. 4: an endpoint "MUST NOT generate a protected record + * with plaintext that is larger than the RecordSizeLimit value it + * receives from its peer", and the writer is the end that generates them. + * Left at 0 the duplicate would send 16384-byte records to a peer that + * asked for less and be killed with record_overflow. recordSizeLimit + * comes too: it is what this end advertised, which the duplicate reports + * through the getters. */ + dup->recordSizeLimit = ssl->recordSizeLimit; + dup->peerRecordSizeLimit = ssl->peerRecordSizeLimit; + dup->recordSizeLimitSent = ssl->recordSizeLimitSent; + dup->recordSizeLimitSet = ssl->recordSizeLimitSet; +#endif /* dup side now owns encrypt/write ciphers */ XMEMSET(&ssl->encrypt, 0, sizeof(Ciphers)); @@ -4047,6 +4060,9 @@ int wolfSSL_set_compression(WOLFSSL* ssl) WOLFSSL_ENTER("wolfSSL_set_compression"); (void)ssl; #ifdef HAVE_LIBZ + /* Argument and transport checks come before the record size limit check, + * so a NULL object or a DTLS connection is reported as that rather than + * as a conflict with the limit. */ if (ssl == NULL) return BAD_FUNC_ARG; #ifdef WOLFSSL_DTLS @@ -4057,12 +4073,35 @@ int wolfSSL_set_compression(WOLFSSL* ssl) WOLFSSL_MSG("Compression not supported over DTLS"); return BAD_FUNC_ARG; } +#endif +#ifdef HAVE_RECORD_SIZE_LIMIT + /* One connection cannot do both. RFC 8449 Sect. 4 measures the limit + * against the plaintext, which deflate may expand past it, while the + * receive checks measure the record as it arrives. A limit the + * application asked for is a request this call cannot honour, so it is + * refused; the advertisement that is on by default simply stands aside, + * which leaves the extension unoffered and so nothing to enforce - the + * limit binds only when both ends send it. */ + if (ssl->recordSizeLimitSet && (ssl->recordSizeLimit != 0)) { + WOLFSSL_MSG("Record size limit set, records cannot be compressed"); + return BAD_FUNC_ARG; + } + /* Too late to stand aside once the default has been queued, sent or + * answered, as wolfSSL_UseRecordSizeLimit() also finds: zeroing it then + * would put a limit of 0 on the wire, which a peer must abort on. */ + if ((TLSX_Find(ssl->extensions, TLSX_RECORD_SIZE_LIMIT) != NULL) || + (ssl->peerRecordSizeLimit != 0) || + (ssl->recordSizeLimitSent != 0)) { + WOLFSSL_MSG("Record size limit already advertised or negotiated"); + return BAD_FUNC_ARG; + } + ssl->recordSizeLimit = 0; #endif ssl->options.usingCompression = 1; return WOLFSSL_SUCCESS; #else return NOT_COMPILED_IN; -#endif +#endif /* HAVE_LIBZ */ } @@ -6001,6 +6040,19 @@ size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out, TLSX_CertificateAuthorities_FreeAll(ssl->ws_peer_ca_names, ssl->heap); ssl->ws_peer_ca_names = NULL; #endif + /* Everything below records what the peer did, so it must not survive + * into the next connection on a recycled object. The matching local + * configuration -- ssl->recordSizeLimit -- is deliberately + * kept, since that is what the caller set. */ + #ifdef HAVE_RECORD_SIZE_LIMIT + ssl->peerRecordSizeLimit = 0; + /* What this end put on the wire last time, not what it was + * configured with: ssl->recordSizeLimit is the caller's and stays. + * Left behind, it also makes wolfSSL_UseRecordSizeLimit() refuse to + * change or disable the limit on the recycled object, since that + * guard reads it as an advertisement already sent. */ + ssl->recordSizeLimitSent = 0; + #endif #if defined(HAVE_TLS_EXTENSIONS) && !defined(NO_TLS) TLSX_FreeAll(ssl->extensions, ssl->heap); diff --git a/src/ssl_api_ext.c b/src/ssl_api_ext.c index 89f442536f2..02c8a02e7dd 100644 --- a/src/ssl_api_ext.c +++ b/src/ssl_api_ext.c @@ -769,6 +769,114 @@ int wolfSSL_set1_groups(WOLFSSL* ssl, int* groups, int count) #endif /* OPENSSL_EXTRA */ #endif /* HAVE_SUPPORTED_CURVES */ +/* This extension has its own build option and depends on neither the + * OpenSSL compatibility layer nor supported-curves, so it sits at file + * scope: --enable-recordsizelimit would otherwise compile the protocol code + * while leaving no way to configure it. */ + +#ifdef HAVE_RECORD_SIZE_LIMIT +/* Set the largest protected record this end will accept. + * + * Advertised as the RFC 8449 record_size_limit extension: by a client in the + * ClientHello and echoed by a server in the TLS 1.2 ServerHello or the TLS 1.3 + * EncryptedExtensions. It replaces + * max_fragment_length's four fixed sizes with an exact byte count, and is + * advertised by default; pass 0 to stop advertising it. + * + * The count is payload. RFC 8449's wire field covers the whole TLS 1.3 + * TLSInnerPlaintext, so a request for n is advertised as n+1 under TLS 1.3 + * and as n under TLS 1.2; that conversion is internal. + * + * Must be called before the handshake starts: on the context, or on the + * object before wolfSSL_connect() or wolfSSL_accept(). A server callback is + * too late, see below. + * + * Refused on a connection that compresses its records, and + * wolfSSL_set_compression() is refused on one given a limit: RFC 8449 Sect. 4 + * measures the limit against the plaintext, which deflate may expand past. + * + * @param [in] ssl SSL/TLS object. + * @param [in] limit Largest record payload accepted, 64 to 2^14, or 0 to + * not advertise a limit at all. + * @return WOLFSSL_SUCCESS on success. + * @return BAD_FUNC_ARG when ssl is NULL, limit is out of range, this + * connection compresses its records, or the limit has already been + * advertised or the peer's read. + */ +int wolfSSL_UseRecordSizeLimit(WOLFSSL* ssl, word16 limit) +{ + WOLFSSL_ENTER("wolfSSL_UseRecordSizeLimit"); + + /* 0 turns the extension off for this ssl, the only way back to silence + * now that WOLFSSL_RECORD_SIZE_LIMIT_DEFAULT is advertised by default. + * Any other value below the RFC 8449 minimum stays an error. */ + if ((ssl == NULL) || + ((limit != 0) && (limit < WOLFSSL_RECORD_SIZE_LIMIT_MIN)) || + (limit > WOLFSSL_RECORD_SIZE_LIMIT_MAX)) { + return BAD_FUNC_ARG; + } + /* Changing the value once the handshake is under way would tighten what + * this end accepts without telling the peer, which would keep sending + * records sized to the original offer. + * + * handShakeState is no guide to that: a server stays at NULL_STATE until + * its own Finished is sent, and a client stays there with its ClientHello + * already on the wire. What matters is whether the value has been + * advertised or the peer's has been read. No server callback gets in + * ahead of it: a certificate setup callback and an SNI callback both run + * once the ClientHello's extensions have all been parsed, so either is + * refused whenever the client sent record_size_limit - and a client that + * asked for the extension is the only case where a server's limit + * matters. */ + if ((TLSX_Find(ssl->extensions, TLSX_RECORD_SIZE_LIMIT) != NULL) || + (ssl->peerRecordSizeLimit != 0) || + (ssl->recordSizeLimitSent != 0)) { + WOLFSSL_MSG("Record size limit already advertised or negotiated"); + return BAD_FUNC_ARG; + } +#ifdef HAVE_LIBZ + /* Deflate may expand what the limit bounds; wolfSSL_set_compression() + * refuses the mirror of this. */ + if (ssl->options.usingCompression) { + WOLFSSL_MSG("Records are compressed, cannot take a record size limit"); + return BAD_FUNC_ARG; + } +#endif + ssl->recordSizeLimit = limit; + ssl->recordSizeLimitSet = 1; + + return WOLFSSL_SUCCESS; +} + +/* Set the largest protected record accepted, on the context. + * + * See wolfSSL_UseRecordSizeLimit(). Objects created afterwards inherit it. + * + * @param [in] ctx SSL/TLS context object. + * @param [in] limit Largest record payload accepted, 64 to 2^14, or 0 to + * not advertise a limit at all. + * @return WOLFSSL_SUCCESS on success. + * @return BAD_FUNC_ARG when ctx is NULL or limit is out of range. + */ +int wolfSSL_CTX_UseRecordSizeLimit(WOLFSSL_CTX* ctx, word16 limit) +{ + WOLFSSL_ENTER("wolfSSL_CTX_UseRecordSizeLimit"); + + /* 0 turns the extension off for this ctx, the only way back to silence + * now that WOLFSSL_RECORD_SIZE_LIMIT_DEFAULT is advertised by default. + * Any other value below the RFC 8449 minimum stays an error. */ + if ((ctx == NULL) || + ((limit != 0) && (limit < WOLFSSL_RECORD_SIZE_LIMIT_MIN)) || + (limit > WOLFSSL_RECORD_SIZE_LIMIT_MAX)) { + return BAD_FUNC_ARG; + } + ctx->recordSizeLimit = limit; + ctx->recordSizeLimitSet = 1; + + return WOLFSSL_SUCCESS; +} +#endif /* HAVE_RECORD_SIZE_LIMIT */ + /* Application-Layer Protocol Negotiation */ #ifdef HAVE_ALPN diff --git a/src/tls.c b/src/tls.c index 94a584ee024..03dc54edde7 100644 --- a/src/tls.c +++ b/src/tls.c @@ -8582,6 +8582,159 @@ static int TLSX_CA_Names_Parse(WOLFSSL *ssl, const byte* input, #endif +/******************************************************************************/ +/* Record Size Limit - RFC 8449 */ +/******************************************************************************/ + +#ifdef HAVE_RECORD_SIZE_LIMIT + +/* Returns the size of the record_size_limit extension's data: one uint16. */ +static word16 TLSX_RecordSizeLimit_GetSize(void) +{ + return OPAQUE16_LEN; +} + +/* Writes the record_size_limit extension into the buffer. + * + * data The WOLFSSL object, passed as the extension's opaque data. + * output The buffer to write the extension into. + * returns the length of data that was written. + */ +static word16 TLSX_RecordSizeLimit_Write(void* data, byte* output) +{ + WOLFSSL* ssl = (WOLFSSL*)data; + word16 limit = ssl->recordSizeLimit; + + /* ssl->recordSizeLimit counts payload only. RFC 8449 Sect. 4's field + * counts the whole TLS 1.3 TLSInnerPlaintext, so the content type byte is + * added here and nowhere else; TLS 1.2 has no such byte. Held to payload + * internally, the value can never exceed the protocol maximum either way: + * 2^14 below TLS 1.3 and 2^14+1 at it. */ + if (IsAtLeastTLSv1_3(ssl->version)) + limit++; + + c16toa(limit, output); + /* Kept so the receive path enforces what was advertised rather than + * reconstructing it: a client offers before the version is settled, and + * after a downgrade ssl->version no longer says whether the content type + * byte was included. */ + ssl->recordSizeLimitSent = limit; + + return OPAQUE16_LEN; +} + +/* Parses the record_size_limit extension. + * + * The value is the largest protected record plaintext the peer will accept, + * counting the content type byte of the TLS 1.3 TLSInnerPlaintext, so it caps + * what this end may send rather than anything it receives. + * + * ssl The SSL/TLS object. + * input The extension data. + * length Length of the extension data in bytes. + * msgType Message the extension arrived in. + * returns 0 on success, otherwise failure. + */ +static int TLSX_RecordSizeLimit_Parse(WOLFSSL* ssl, const byte* input, + word16 length, byte msgType) +{ + word16 limit; + /* The peer's answer arrives in EncryptedExtensions under TLS 1.3 and in + * the ServerHello under TLS 1.2 (RFC 8449 Sect. 4). */ + int isResponse = (msgType == encrypted_extensions) || + (msgType == server_hello); + + if (length != OPAQUE16_LEN) + return BUFFER_ERROR; + + /* RFC 9846 Sect. 4.2: a response to an extension this end never offered + * is an unsupported_extension abort. The client only pushes the extension + * when a limit was set, so its absence means it was never asked for. */ +#ifdef WOLFSSL_OLD_UNSUPPORTED_EXTENSION + /* Legacy lenient handling applies to TLS 1.2 and earlier only, as in + * TLSX_MFL_Parse(). */ + if (isResponse && IsAtLeastTLSv1_3(ssl->version) && +#else + if (isResponse && +#endif + TLSX_Find(ssl->extensions, TLSX_RECORD_SIZE_LIMIT) == NULL) { + return TLSX_HandleUnsupportedExtension(ssl); + } + + ato16(input, &limit); + + /* RFC 8449 Sect. 4: "An endpoint MUST treat receipt of a smaller value as + * a fatal error and generate an illegal_parameter alert." */ + if (limit < WOLFSSL_RECORD_SIZE_LIMIT_MIN) { + WOLFSSL_MSG("Record size limit below the minimum of 64"); + SendAlert(ssl, alert_fatal, illegal_parameter); + WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER); + return INVALID_PARAMETER; + } + + /* A server "MUST NOT enforce" the upper bound, since a client may be + * advertising a limit enabled by an extension the server does not know. + * A client MAY reject one, and does here. The bound is 2^14+1 for TLS 1.3 + * and 2^14 for TLS 1.2, which counts no content type byte. */ + if (isResponse && limit > (IsAtLeastTLSv1_3(ssl->version) ? + WOLFSSL_RECORD_SIZE_LIMIT_MAX_13 : MAX_RECORD_SIZE)) { + WOLFSSL_MSG("Record size limit above the maximum for this version"); + SendAlert(ssl, alert_fatal, illegal_parameter); + WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER); + return INVALID_PARAMETER; + } + + /* Never send more than the protocol allows, whatever the peer says. */ + if (limit > WOLFSSL_RECORD_SIZE_LIMIT_MAX_13) + limit = WOLFSSL_RECORD_SIZE_LIMIT_MAX_13; + + /* Back to payload, the unit everything above the wire uses. The peer's + * value covers its TLSInnerPlaintext under TLS 1.3, one byte of which is + * the content type. */ + if (IsAtLeastTLSv1_3(ssl->version)) + limit--; + + /* A server that supports this extension answers in EncryptedExtensions, + * and from then on ignores any max_fragment_length in the ClientHello + * (RFC 8449 Sect. 5). */ +#ifndef NO_WOLFSSL_SERVER + /* Only a server answers, and TLSX_SetResponse() is not compiled for a + * client-only build without TLS 1.3. Every pre-existing extension wraps + * its response push the same way - see TLSX_SCTS_Parse(). */ + if (msgType == client_hello) { + int ret; + + /* RFC 8449 Sect. 4: the extension is negotiated only when both ends + * send it. A server holding no limit of its own stays silent, and so + * must not shrink its own records either - otherwise any client could + * push a server that never opted in down to 64-byte records and pay + * it in per-record overhead. */ + if (ssl->recordSizeLimit == 0) + return 0; + + ret = TLSX_Push(&ssl->extensions, TLSX_RECORD_SIZE_LIMIT, + (void*)ssl, ssl->heap); + if (ret != 0) + return ret; + TLSX_SetResponse(ssl, TLSX_RECORD_SIZE_LIMIT); + } +#endif + + ssl->peerRecordSizeLimit = limit; + + return 0; +} + +#define RSL_GET_SIZE TLSX_RecordSizeLimit_GetSize +#define RSL_WRITE TLSX_RecordSizeLimit_Write +#define RSL_PARSE TLSX_RecordSizeLimit_Parse + +#endif /* HAVE_RECORD_SIZE_LIMIT */ + +/* The section above has no dependency on certificates or signature + * algorithms. Its dispatch cases are guarded by the feature macro alone, so + * guarding the implementation more tightly than the call sites broke + * '--enable-recordsizelimit --disable-certs'. */ #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG) /******************************************************************************/ /* Signature Algorithms */ @@ -15961,6 +16114,11 @@ void TLSX_FreeAll(TLSX* list, void* heap) WOLFSSL_MSG("Signature Algorithms extension free"); break; #endif +#ifdef HAVE_RECORD_SIZE_LIMIT + case TLSX_RECORD_SIZE_LIMIT: + /* The limit lives on the SSL object. */ + break; +#endif #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) case TLSX_ENCRYPT_THEN_MAC: WOLFSSL_MSG("Encrypt-Then-Mac extension free"); @@ -16210,6 +16368,11 @@ static int TLSX_GetSize(TLSX* list, byte* semaphore, byte msgType, length += SA_GET_SIZE(extension->data); break; #endif +#ifdef HAVE_RECORD_SIZE_LIMIT + case TLSX_RECORD_SIZE_LIMIT: + length += RSL_GET_SIZE(); + break; +#endif #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) case TLSX_ENCRYPT_THEN_MAC: cbShim = 0; @@ -16494,6 +16657,12 @@ static int TLSX_Write(TLSX* list, byte* output, byte* semaphore, offset += SA_WRITE(extension->data, output + offset); break; #endif +#ifdef HAVE_RECORD_SIZE_LIMIT + case TLSX_RECORD_SIZE_LIMIT: + WOLFSSL_MSG("Record Size Limit extension to write"); + offset += RSL_WRITE(extension->data, output + offset); + break; +#endif #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY) case TLSX_ENCRYPT_THEN_MAC: WOLFSSL_MSG("Encrypt-Then-Mac extension to write"); @@ -16828,6 +16997,45 @@ int TLSX_PopulateExtensions(WOLFSSL* ssl, byte isServer) #else ret = 0; #endif + /* Outside the TLS 1.3 block below: RFC 8449 covers TLS 1.2 too, + * where the server answers in the ServerHello, so a client built + * without TLS 1.3 must still offer this. */ + #ifdef HAVE_RECORD_SIZE_LIMIT + /* RFC 8449 Sect. 4: the client states in its ClientHello the largest + * record it will accept; the server answers in EncryptedExtensions + * under TLS 1.3 or in the ServerHello under TLS 1.2, which + * TLSX_RecordSizeLimit_Parse() arranges when it sees the request. */ + /* RFC 8449 Sect. 5 has a server ignore max_fragment_length when both + * extensions appear, and Sect. 5 also says a client that depends on a + * small record size may keep advertising max_fragment_length. So the + * built-in default stands aside for an application that explicitly + * asked for max_fragment_length; an explicit + * wolfSSL_UseRecordSizeLimit() still wins, because then the + * application asked for both and RFC 8449 says which governs. */ + if (!isServer && ssl->recordSizeLimit != 0 + #ifdef HAVE_MAX_FRAGMENT + /* Both lists, because wolfSSL_UseMaxFragment() stores on the + * object and wolfSSL_CTX_UseMaxFragment() on the context, + * nothing copies the context's list onto the object, and the + * write path emits both. Missing the context's copy would + * advertise record_size_limit alongside it, and RFC 8449 + * Sect. 5 then has the server ignore max_fragment_length - + * silently dropping what the application asked for. */ + && (ssl->recordSizeLimitSet || + (TLSX_Find(ssl->extensions, + TLSX_MAX_FRAGMENT_LENGTH) == NULL && + (ssl->ctx == NULL || + TLSX_Find(ssl->ctx->extensions, + TLSX_MAX_FRAGMENT_LENGTH) == NULL))) + #endif + ) { + WOLFSSL_MSG("Adding record size limit extension"); + if ((ret = TLSX_Push(&ssl->extensions, TLSX_RECORD_SIZE_LIMIT, + (void*)ssl, ssl->heap)) != 0) { + return ret; + } + } + #endif #ifdef WOLFSSL_TLS13 #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES) if (IsAtLeastTLSv1_3(ssl->version) && HasAnyCANames(ssl)) { @@ -17523,6 +17731,11 @@ static int TLSX_CustomExt_IsKnown(word16 ext_type) case TLSXT_SERVER_CERTIFICATE: case TLSXT_ENCRYPT_THEN_MAC: case TLSXT_EXTENDED_MASTER_SECRET: + #ifdef HAVE_RECORD_SIZE_LIMIT + /* Only when built in: without it an application may still handle + * the extension itself. */ + case TLSXT_RECORD_SIZE_LIMIT: + #endif case TLSXT_CERT_WITH_EXTERN_PSK: case TLSXT_SESSION_TICKET: case TLSXT_PRE_SHARED_KEY: @@ -19267,6 +19480,31 @@ WOLFSSL_TEST_VIS int TLSX_Parse(WOLFSSL* ssl, const byte* input, word16 length, break; #endif /* HAVE_ENCRYPT_THEN_MAC */ +#ifdef HAVE_RECORD_SIZE_LIMIT + case TLSX_RECORD_SIZE_LIMIT: + WOLFSSL_MSG("Record Size Limit extension received"); + #ifdef WOLFSSL_DEBUG_TLS + WOLFSSL_BUFFER(input + offset, size); + #endif + /* RFC 9846 Table 1 lists CH and EE for TLS 1.3. RFC 8449 + * also covers TLS 1.2, where the server answers in the + * ServerHello instead. */ + if (IsAtLeastTLSv1_3(ssl->version)) { + if (msgType != client_hello && + msgType != encrypted_extensions) { + WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED); + return EXT_NOT_ALLOWED; + } + } + else if (msgType != client_hello && + msgType != server_hello) { + WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED); + return EXT_NOT_ALLOWED; + } + ret = RSL_PARSE(ssl, input + offset, size, msgType); + break; +#endif + #ifdef WOLFSSL_TLS13 case TLSX_SUPPORTED_VERSIONS: #ifdef WOLFSSL_DEBUG_TLS @@ -19785,6 +20023,46 @@ WOLFSSL_TEST_VIS int TLSX_Parse(WOLFSSL* ssl, const byte* input, word16 length, } #endif +#ifdef HAVE_RECORD_SIZE_LIMIT +#ifdef HAVE_MAX_FRAGMENT + /* RFC 8449 Sect. 5: a server that answers with record_size_limit "MUST + * ignore a max_fragment_length that appears in a ClientHello if both + * extensions appear". Done here rather than while parsing because the two + * extensions may arrive in either order, and sending both would leave the + * client obliged to abort. */ + if (ret == 0 && msgType == client_hello && + TLSX_Find(ssl->extensions, TLSX_RECORD_SIZE_LIMIT) != NULL) { + ssl->max_fragment = MAX_RECORD_SIZE; + /* The session keeps its own copy, which + * wolfSSL_SESSION_get_max_fragment_length() reports, so it is cleared + * with the live value rather than reporting a length that was never + * applied. */ + if (ssl->session != NULL) + ssl->session->mfl = 0; + TLSX_Remove(&ssl->extensions, TLSX_MAX_FRAGMENT_LENGTH, ssl->heap); + } +#endif /* HAVE_MAX_FRAGMENT */ + + /* Outside HAVE_MAX_FRAGMENT above: this is a MUST that holds whether or + * not this build can offer max_fragment_length itself, and it needs only + * the extension type and what was seen on the wire. Inside that guard the + * illegal pairing went undetected in a build without the option. */ + /* RFC 8449 Sect. 5: a client "MUST treat receipt of both + * max_fragment_length and record_size_limit as a fatal error". Only a + * client receives these two message types. Checked here for the same + * reason as above: either extension may come first, and a check made + * while parsing one of them cannot see the other. */ + if (ret == 0 && (msgType == encrypted_extensions || + msgType == server_hello) && + !IS_OFF(seenType, TLSX_ToSemaphore(TLSX_RECORD_SIZE_LIMIT)) && + !IS_OFF(seenType, TLSX_ToSemaphore(TLSX_MAX_FRAGMENT_LENGTH))) { + WOLFSSL_MSG("Server sent both max_fragment_length and size limit"); + SendAlert(ssl, alert_fatal, illegal_parameter); + WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER); + ret = INVALID_PARAMETER; + } +#endif + if (ret == 0) ret = SNI_VERIFY_PARSE(ssl, isRequest); if (ret == 0) diff --git a/src/tls13.c b/src/tls13.c index 331feb6ddf8..3a50eba466b 100644 --- a/src/tls13.c +++ b/src/tls13.c @@ -2809,8 +2809,16 @@ static void AddTls13Headers(byte* output, word32 length, byte type, AddTls13HandShakeHeader(output + outputAdj, length, 0, length, type, ssl); } -#if (!defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER)) \ - && !defined(NO_CERTS) +/* HAVE_RECORD_SIZE_LIMIT is in the condition because SendTls13FragmentedMsg() + * needs this for EncryptedExtensions and NewSessionTicket, which a PSK-only + * TLS 1.3 server sends with NO_CERTS defined and no Certificate in sight. */ +/* The record_size_limit arm needs a server as well as the option: its only + * caller is SendTls13FragmentedMsg(), which is inside the server-only region, + * so without that the function compiles with no caller at all and + * -Werror=unused-function fails the build. */ +#if ((!defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER)) \ + && !defined(NO_CERTS)) || \ + (defined(HAVE_RECORD_SIZE_LIMIT) && !defined(NO_WOLFSSL_SERVER)) /* Add both record layer and fragment handshake header to message. * * output The buffer to write the headers into. @@ -2840,7 +2848,8 @@ static void AddTls13FragHeaders(byte* output, word32 fragSz, word32 fragOffset, AddTls13HandShakeHeader(output + outputAdj, length, fragOffset, fragSz, type, ssl); } -#endif /* (!NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER) && !NO_CERTS */ +#endif /* ((!NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER) && !NO_CERTS) || + * HAVE_RECORD_SIZE_LIMIT */ /* Write the sequence number into the buffer. * No DTLS v1.3 support. @@ -9252,7 +9261,148 @@ int SendTls13ServerHello(WOLFSSL* ssl, byte extMsgType) return ret; } -/* handle generation of TLS 1.3 encrypted_extensions (8) */ +#ifdef HAVE_RECORD_SIZE_LIMIT +/* Re-emit an already-built handshake message as a series of records. + * + * EncryptedExtensions and CertificateRequest are each laid down as one record, + * which a record_size_limit smaller than the message - RFC 8449 Sect. 4 + * permits one as low as 64 - would make a record_overflow for the peer. Both + * are small and fully assembled by the time this is called, so the body is + * copied aside and laid back down across as many records as the limit needs. + * NewSessionTicket does not come here: SendTls13NewSessionTicket() fragments + * to wolfssl_local_GetMaxPlaintextSize(), which already applies the limit. + * + * None is flushed here: a WANT_WRITE part way through would strand the + * scratch copy and force the caller to rebuild, and re-hash, a message + * already in the transcript. The caller's SendBuffered() flushes them + * together. + * + * ssl The SSL/TLS object. + * output Start of the built record: record header, handshake header, + * then the body. + * msgSz Bytes written to output, headers included. + * type Handshake message type. + * hashOutput Whether the message belongs in the handshake transcript. + * returns 0 on success, otherwise failure. + */ +static int SendTls13FragmentedMsg(WOLFSSL* ssl, byte* output, word32 msgSz, + byte type, int hashOutput) +{ + byte* body; + word32 bodySz; + word32 offset = 0; + word32 maxFragment; + int maxPlain; + int ret = 0; + + if (msgSz < RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ) + return BUFFER_E; + bodySz = msgSz - RECORD_HEADER_SZ - HANDSHAKE_HEADER_SZ; + + /* Tested as a signed int before the cast: the helper returns a negative + * error code, which as a word32 would sail past the check below. A + * fragment also has to carry at least one body byte or this never ends, + * and the first one carries the handshake header too. */ + maxPlain = wolfssl_local_GetMaxPlaintextSize(ssl); + if (maxPlain <= (int)HANDSHAKE_HEADER_SZ) + return BUFFER_E; + maxFragment = (word32)maxPlain; + + body = (byte*)XMALLOC(bodySz, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); + if (body == NULL) + return MEMORY_E; + XMEMCPY(body, output + RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ, bodySz); + + /* Reserve room for every record up front. GrowOutputBuffer() allocates + * only what is asked for, so growing record by record would reallocate + * and copy the records already queued each time - quadratic in the + * message for a small limit, which the peer chooses. */ + { + word32 first = min(bodySz, maxFragment - HANDSHAKE_HEADER_SZ); + word32 frags = 1 + (bodySz - first + maxFragment - 1) / maxFragment; + word32 total = HANDSHAKE_HEADER_SZ + bodySz + frags * MAX_MSG_EXTRA; + + ret = CheckAvailableSize(ssl, (int)total); + } + + while ((ret == 0) && (offset < bodySz)) { + word32 fragSz; + word32 i; + int sendSz; + + if (offset == 0) + fragSz = min(bodySz, maxFragment - HANDSHAKE_HEADER_SZ); + else + fragSz = min(bodySz - offset, maxFragment); + + sendSz = (int)(fragSz + MAX_MSG_EXTRA); + if (offset == 0) + sendSz += HANDSHAKE_HEADER_SZ; + + ret = CheckAvailableSize(ssl, sendSz); + if (ret != 0) + break; + /* CheckAvailableSize() may have moved the buffer. */ + output = GetOutputBuffer(ssl); + + if (offset == 0) { + /* Only the first record carries the handshake header, and it + * states the length of the whole message, not of the fragment. */ + AddTls13FragHeaders(output, fragSz, 0, bodySz, type, ssl); + i = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ; + } + else { + AddTls13RecordHeader(output, fragSz, handshake, ssl); + i = RECORD_HEADER_SZ; + } + XMEMCPY(output + i, body + offset, fragSz); + i += fragSz; + + /* These messages are always encrypted. */ + sendSz = BuildTls13Message(ssl, output, sendSz, + output + RECORD_HEADER_SZ, + (int)(i - RECORD_HEADER_SZ), handshake, + hashOutput, 0, 0); + if (sendSz < 0) { + ret = sendSz; + break; + } + + ssl->buffers.outputBuffer.length += (word32)sendSz; + offset += fragSz; + } + + XFREE(body, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); + + return ret; +} + +/* Would this message overflow the record_size_limit the peer negotiated? + * Deliberately keyed on the peer's limit rather than on the maximum plaintext + * size in general: max_fragment_length has never fragmented these three + * messages either, and changing that is not this change's business. + * + * ssl The SSL/TLS object. + * msgSz Bytes written to the output buffer, headers included. + * returns 1 when the message has to be split, otherwise 0. + */ +static int Tls13MsgNeedsFragmenting(WOLFSSL* ssl, word32 msgSz) +{ + int maxPlain; + + if (ssl->peerRecordSizeLimit == 0) + return 0; + maxPlain = wolfssl_local_GetMaxPlaintextSize(ssl); + /* Returned negative on a bad argument or a DTLS MTU too small to carry a + * record. Compared directly, such a value reads as "needs splitting" and + * the real code is lost - the caller then failed in the fragmenting path + * with BUFFER_E instead. */ + if (maxPlain < 0) + return maxPlain; + return (int)(msgSz - RECORD_HEADER_SZ) > maxPlain; +} +#endif /* HAVE_RECORD_SIZE_LIMIT */ + /* Send the rest of the extensions encrypted under the handshake key. * This message is always encrypted in TLS v1.3. * Only a server will send this message. @@ -9440,6 +9590,28 @@ static int SendTls13EncryptedExtensions(WOLFSSL* ssl) } #endif /* WOLFSSL_DTLS13 */ +#ifdef HAVE_RECORD_SIZE_LIMIT + ret = Tls13MsgNeedsFragmenting(ssl, idx); + if (ret < 0) + return ret; + if (ret != 0) { + ret = SendTls13FragmentedMsg(ssl, output, idx, encrypted_extensions, + 1); + if (ret != 0) + return ret; + + ssl->options.buildingMsg = 0; + ssl->options.serverState = SERVER_ENCRYPTED_EXTENSIONS_COMPLETE; + if (!ssl->options.groupMessages) + ret = SendBuffered(ssl); + + WOLFSSL_LEAVE("SendTls13EncryptedExtensions", ret); + WOLFSSL_END(WC_FUNC_ENCRYPTED_EXTENSIONS_SEND); + + return ret; + } +#endif + /* This handshake message is always encrypted. */ sendSz = BuildTls13Message(ssl, output, sendSz, output + RECORD_HEADER_SZ, (int)(idx - RECORD_HEADER_SZ), @@ -9549,6 +9721,39 @@ static int SendTls13CertificateRequest(WOLFSSL* ssl, byte* reqCtx, } #endif /* WOLFSSL_DTLS13 */ +#ifdef HAVE_RECORD_SIZE_LIMIT + ret = Tls13MsgNeedsFragmenting(ssl, i); + if (ret < 0) + return ret; + if (ret != 0) { + #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA) + /* Traced before the split, while output still holds the whole + * message: the fragments are the same bytes in several records, and + * SendTls13FragmentedMsg() may move the buffer. */ + if (ssl->hsInfoOn) + AddPacketName(ssl, "CertificateRequest"); + if (ssl->toInfoOn) { + ret = AddPacketInfo(ssl, "CertificateRequest", handshake, output, + (int)i, WRITE_PROTO, 0, ssl->heap); + if (ret != 0) + return ret; + } + #endif + ret = SendTls13FragmentedMsg(ssl, output, i, certificate_request, 1); + if (ret != 0) + return ret; + + ssl->options.buildingMsg = 0; + if (!ssl->options.groupMessages) + ret = SendBuffered(ssl); + + WOLFSSL_LEAVE("SendTls13CertificateRequest", ret); + WOLFSSL_END(WC_FUNC_CERTIFICATE_REQUEST_SEND); + + return ret; + } +#endif + /* Always encrypted. */ sendSz = BuildTls13Message(ssl, output, sendSz, output + RECORD_HEADER_SZ, (int)(i - RECORD_HEADER_SZ), handshake, 1, 0, 0); @@ -10847,6 +11052,7 @@ static int SendTls13Certificate(WOLFSSL* ssl) word16 extSz[MAX_CERT_EXTENSIONS]; word16 extIdx = 0; word32 maxFragment; + int maxPlain; word32 totalextSz = 0; word32 len = 0; word32 idx = 0; @@ -11024,7 +11230,40 @@ static int SendTls13Certificate(WOLFSSL* ssl) if (ssl->fragOffset != 0) length -= (ssl->fragOffset + headerSz); - maxFragment = (word32)wolfssl_local_GetMaxPlaintextSize(ssl); + /* Checked before the cast: a DTLS MTU too small for any plaintext is + * reported as a negative value, which as a word32 would be larger than + * any record and would slip past every bound below. */ + maxPlain = wolfssl_local_GetMaxPlaintextSize(ssl); + if (maxPlain < 0) + return maxPlain; + maxFragment = (word32)maxPlain; + + /* The fixed part of the message -- the request context and the length + * fields counted in headerSz -- is written into the first fragment whole, + * and each piece is then subtracted from that fragment's remaining room. + * A fragment too small to hold it would take those word32 subtractions + * below zero, and the certificate would be copied far past the output + * buffer sized from fragSz. The two ends of that collision are both the + * peer's to choose: RFC 8449 Sect. 4 allows a record_size_limit as low as + * 64, and RFC 8446 Sect. 4.3.2 allows a post-handshake + * certificate_request_context of up to 255 bytes, which this end echoes. + * There is no way to answer within the limit, so refuse rather than + * fragment the fixed part, which the loop below cannot do. + * A first fragment that holds the fixed part exactly is refused too unless + * that is the whole message (an empty certificate_list): it leaves no room + * for certificate data, so ssl->fragOffset never advances and every pass + * of the loop would write the fixed part again. + * DTLS 1.3 is not affected: it leaves fragSz whole here and fragments in + * dtls13HandshakeSend(). */ + if ((ssl->fragOffset == 0) && !ssl->options.dtls && + ((maxFragment < headerSz + HANDSHAKE_HEADER_SZ) || + ((maxFragment == headerSz + HANDSHAKE_HEADER_SZ) && + (payloadSz > headerSz)))) { + WOLFSSL_MSG_EX("Certificate header of %u does not fit the peer's " + "record size limit", (unsigned int)headerSz); + WOLFSSL_ERROR_VERBOSE(BUFFER_E); + return BUFFER_E; + } extIdx = 0; diff --git a/tests/api/test_compress.c b/tests/api/test_compress.c index 5bda23c65c3..d0d4b9a2021 100644 --- a/tests/api/test_compress.c +++ b/tests/api/test_compress.c @@ -34,6 +34,7 @@ #include #include #include +#include #include /* TLS level zlib compression (wolfSSL_set_compression()) needs the record @@ -815,3 +816,112 @@ int test_wolfSSL_dtls_compression_off(void) * !NO_WOLFSSL_CLIENT */ return EXPECT_RESULT(); } + +/* Record layer compression and RFC 8449 record_size_limit cannot share a + * connection: the limit bounds the plaintext and deflate may expand past it. + * Each is available in a build that has both, so the choice is made per + * connection, and the application's explicit request wins. */ +int test_wolfSSL_tls_compression_record_size_limit(void) +{ + EXPECT_DECLS; +#if defined(HAVE_LIBZ) && defined(HAVE_RECORD_SIZE_LIMIT) && \ + !defined(WOLFSSL_NO_TLS12) && !defined(NO_WOLFSSL_CLIENT) + WOLFSSL_CTX* ctx = NULL; + WOLFSSL* ssl = NULL; + + /* A limit is advertised by default. That default gives way, since the + * application asked for compression and not for it. */ + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method())); + ExpectNotNull(ssl = wolfSSL_new(ctx)); + if (ssl != NULL) { + ExpectIntGT(ssl->recordSizeLimit, 0); + ExpectIntEQ(ssl->recordSizeLimitSet, 0); + } + ExpectIntEQ(wolfSSL_set_compression(ssl), WOLFSSL_SUCCESS); + if (ssl != NULL) { + ExpectIntEQ(ssl->options.usingCompression, 1); + ExpectIntEQ(ssl->recordSizeLimit, 0); + } + /* And a limit asked for afterwards is refused rather than silently + * dropping the compression that is already set up. */ + ExpectIntEQ(wolfSSL_UseRecordSizeLimit(ssl, 512), + WC_NO_ERR_TRACE(BAD_FUNC_ARG)); + if (ssl != NULL) + ExpectIntEQ(ssl->options.usingCompression, 1); + wolfSSL_free(ssl); ssl = NULL; + wolfSSL_CTX_free(ctx); ctx = NULL; + + /* The other order: a limit the application set is its request, so + * compression is the one refused. */ + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method())); + ExpectNotNull(ssl = wolfSSL_new(ctx)); + ExpectIntEQ(wolfSSL_UseRecordSizeLimit(ssl, 512), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_set_compression(ssl), WC_NO_ERR_TRACE(BAD_FUNC_ARG)); + if (ssl != NULL) { + ExpectIntEQ(ssl->options.usingCompression, 0); + ExpectIntEQ(ssl->recordSizeLimit, 512); + } + wolfSSL_free(ssl); ssl = NULL; + wolfSSL_CTX_free(ctx); ctx = NULL; + + /* Turning the limit off explicitly is not a limit, so compression is + * free to go ahead. */ + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method())); + ExpectNotNull(ssl = wolfSSL_new(ctx)); + ExpectIntEQ(wolfSSL_UseRecordSizeLimit(ssl, WOLFSSL_RECORD_SIZE_LIMIT_OFF), + WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_set_compression(ssl), WOLFSSL_SUCCESS); + if (ssl != NULL) + ExpectIntEQ(ssl->options.usingCompression, 1); + + wolfSSL_free(ssl); ssl = NULL; + wolfSSL_CTX_free(ctx); ctx = NULL; + +#if defined(HAVE_MANUAL_MEMIO_TESTS_DEPENDENCIES) && \ + !defined(NO_WOLFSSL_SERVER) + /* Too late for the default to give way once it is on the wire: zeroing + * it then would send or answer with a limit of 0. The client has queued + * and sent it with its ClientHello; the server has read the client's and + * queued its answer, as it would have by the time an SNI callback runs. */ + { + struct test_memio_ctx test_ctx; + WOLFSSL_CTX* ctx_c = NULL; + WOLFSSL_CTX* ctx_s = NULL; + WOLFSSL* ssl_c = NULL; + WOLFSSL* ssl_s = NULL; + word16 limit_c = 0; + word16 limit_s = 0; + + XMEMSET(&test_ctx, 0, sizeof(test_ctx)); + ExpectIntEQ(test_memio_setup(&test_ctx, &ctx_c, &ctx_s, &ssl_c, + &ssl_s, wolfTLSv1_2_client_method, wolfTLSv1_2_server_method), 0); + if ((ssl_c != NULL) && (ssl_s != NULL)) { + limit_c = ssl_c->recordSizeLimit; + limit_s = ssl_s->recordSizeLimit; + } + ExpectIntGT(limit_c, 0); + ExpectIntNE(wolfSSL_connect(ssl_c), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_get_error(ssl_c, + WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR)), WOLFSSL_ERROR_WANT_READ); + ExpectIntEQ(wolfSSL_set_compression(ssl_c), + WC_NO_ERR_TRACE(BAD_FUNC_ARG)); + ExpectIntNE(wolfSSL_accept(ssl_s), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_set_compression(ssl_s), + WC_NO_ERR_TRACE(BAD_FUNC_ARG)); + if ((ssl_c != NULL) && (ssl_s != NULL)) { + ExpectIntEQ(ssl_c->recordSizeLimit, limit_c); + ExpectIntEQ(ssl_s->recordSizeLimit, limit_s); + ExpectIntEQ(ssl_c->options.usingCompression, 0); + ExpectIntEQ(ssl_s->options.usingCompression, 0); + } + + wolfSSL_free(ssl_c); + wolfSSL_free(ssl_s); + wolfSSL_CTX_free(ctx_c); + wolfSSL_CTX_free(ctx_s); + } +#endif /* HAVE_MANUAL_MEMIO_TESTS_DEPENDENCIES && !NO_WOLFSSL_SERVER */ +#endif /* HAVE_LIBZ && HAVE_RECORD_SIZE_LIMIT && !WOLFSSL_NO_TLS12 && + * !NO_WOLFSSL_CLIENT */ + return EXPECT_RESULT(); +} diff --git a/tests/api/test_compress.h b/tests/api/test_compress.h index 4ad64137f15..d28f3198faf 100644 --- a/tests/api/test_compress.h +++ b/tests/api/test_compress.h @@ -36,6 +36,7 @@ int test_wolfSSL_tls_decompression_lowered_limit(void); int test_wolfSSL_tls_decompression_send_cap(void); int test_wolfSSL_tls_compression_output_size(void); int test_wolfSSL_dtls_compression_off(void); +int test_wolfSSL_tls_compression_record_size_limit(void); #define TEST_COMPRESS_DECLS \ TEST_DECL_GROUP("compress", test_wc_DeCompressDynamic_maxSz), \ @@ -50,6 +51,8 @@ int test_wolfSSL_dtls_compression_off(void); test_wolfSSL_tls_decompression_lowered_limit), \ TEST_DECL_GROUP("compress", test_wolfSSL_tls_decompression_send_cap), \ TEST_DECL_GROUP("compress", test_wolfSSL_tls_compression_output_size), \ - TEST_DECL_GROUP("compress", test_wolfSSL_dtls_compression_off) + TEST_DECL_GROUP("compress", test_wolfSSL_dtls_compression_off), \ + TEST_DECL_GROUP("compress", \ + test_wolfSSL_tls_compression_record_size_limit) #endif /* WOLFCRYPT_TEST_COMPRESS_H */ diff --git a/tests/api/test_dtls13.c b/tests/api/test_dtls13.c index d223d3de3b2..2b5f5c2443a 100644 --- a/tests/api/test_dtls13.c +++ b/tests/api/test_dtls13.c @@ -423,7 +423,13 @@ int test_dtls_frag_ch(void) WOLFSSL *ssl_c = NULL; WOLFSSL *ssl_s = NULL; struct test_memio_ctx test_ctx; - static unsigned int DUMMY_MTU = 256; + /* Sized so the first ClientHello still fits one datagram. It must not be + * tuned to the byte: the ClientHello grows whenever another extension is + * compiled in - record_size_limit alone adds 6 - and CH1 cannot fragment, + * so too tight a value turns into a BUFFER_ERROR rather than a fragmented + * hello. The headroom here is deliberate; CH2 still fragments, which is + * what this test is checking. */ + static unsigned int DUMMY_MTU = 288; XMEMSET(&test_ctx, 0, sizeof(test_ctx)); ExpectIntEQ(test_memio_setup(&test_ctx, &ctx_c, &ctx_s, &ssl_c, &ssl_s, diff --git a/tests/api/test_tls.c b/tests/api/test_tls.c index f0996fc9b83..2e15cb331eb 100644 --- a/tests/api/test_tls.c +++ b/tests/api/test_tls.c @@ -9362,3 +9362,145 @@ int test_tls_unset_fd_no_stdin_io(void) #endif return EXPECT_RESULT(); } + +int test_tls12_record_size_limit(void) +{ + EXPECT_DECLS; +/* Deliberately not gated on WOLFSSL_TLS13: RFC 8449 covers TLS 1.2, where the + * server answers in the ServerHello, so the extension has to work in a build + * with TLS 1.3 compiled out. The TLS 1.3 specific cases live in + * test_tls13_record_size_limit(). */ +#if defined(HAVE_RECORD_SIZE_LIMIT) && !defined(WOLFSSL_NO_TLS12) && \ + defined(HAVE_MANUAL_MEMIO_TESTS_DEPENDENCIES) && !defined(NO_CERTS) && \ + !defined(NO_RSA) && !defined(NO_WOLFSSL_CLIENT) && \ + !defined(NO_WOLFSSL_SERVER) && !defined(NO_FILESYSTEM) + WOLFSSL_CTX *ctx_c = NULL, *ctx_s = NULL; + WOLFSSL *ssl_c = NULL, *ssl_s = NULL; + struct test_memio_ctx test_ctx; + + /* TLS 1.2 has no content type byte and caps at 2^14, so the default is + * trimmed on the way out and the peer learns the smaller value. */ + XMEMSET(&test_ctx, 0, sizeof(test_ctx)); + ExpectIntEQ(test_memio_setup(&test_ctx, &ctx_c, &ctx_s, &ssl_c, &ssl_s, + wolfTLSv1_2_client_method, wolfTLSv1_2_server_method), 0); + ExpectIntEQ(test_memio_do_handshake(ssl_c, ssl_s, 10, NULL), 0); + if (ssl_s != NULL) + ExpectIntEQ(ssl_s->peerRecordSizeLimit, MAX_RECORD_SIZE); + ExpectIntEQ(wolfSSL_GetMaxOutputSize(ssl_c), MAX_RECORD_SIZE); + + wolfSSL_free(ssl_c); ssl_c = NULL; + wolfSSL_free(ssl_s); ssl_s = NULL; + wolfSSL_CTX_free(ctx_c); ctx_c = NULL; + wolfSSL_CTX_free(ctx_s); ctx_s = NULL; + + /* RFC 8449 covers TLS 1.2 too, where the server answers in the + * ServerHello and the limit counts no content type byte, so the whole + * limit is available to the payload. */ + XMEMSET(&test_ctx, 0, sizeof(test_ctx)); + ExpectIntEQ(test_memio_setup(&test_ctx, &ctx_c, &ctx_s, &ssl_c, &ssl_s, + wolfTLSv1_2_client_method, wolfTLSv1_2_server_method), 0); + ExpectIntEQ(wolfSSL_UseRecordSizeLimit(ssl_c, 512), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_UseRecordSizeLimit(ssl_s, 1024), WOLFSSL_SUCCESS); + ExpectIntEQ(test_memio_do_handshake(ssl_c, ssl_s, 10, NULL), 0); + if (ssl_c != NULL) + ExpectIntEQ(ssl_c->peerRecordSizeLimit, 1024); + if (ssl_s != NULL) + ExpectIntEQ(ssl_s->peerRecordSizeLimit, 512); + /* No content type byte to allow for at this version. */ + ExpectIntEQ(wolfSSL_GetMaxOutputSize(ssl_s), 512); + ExpectIntEQ(wolfSSL_GetMaxOutputSize(ssl_c), 1024); + + wolfSSL_free(ssl_c); ssl_c = NULL; + wolfSSL_free(ssl_s); ssl_s = NULL; + wolfSSL_CTX_free(ctx_c); ctx_c = NULL; + wolfSSL_CTX_free(ctx_s); ctx_s = NULL; + +#ifdef HAVE_MAX_FRAGMENT + /* RFC 8449 Sect. 5: a server answering with record_size_limit ignores a + * max_fragment_length sent alongside it, so the smaller record_size_limit + * governs rather than the 2048 byte fragment class. */ + XMEMSET(&test_ctx, 0, sizeof(test_ctx)); + ExpectIntEQ(test_memio_setup(&test_ctx, &ctx_c, &ctx_s, &ssl_c, &ssl_s, + wolfTLSv1_2_client_method, wolfTLSv1_2_server_method), 0); + ExpectIntEQ(wolfSSL_UseMaxFragment(ssl_c, WOLFSSL_MFL_2_11), + WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_UseRecordSizeLimit(ssl_c, 512), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_UseRecordSizeLimit(ssl_s, 900), WOLFSSL_SUCCESS); + ExpectIntEQ(test_memio_do_handshake(ssl_c, ssl_s, 10, NULL), 0); + if (ssl_s != NULL) { + ExpectIntEQ(ssl_s->peerRecordSizeLimit, 512); + ExpectIntEQ(ssl_s->max_fragment, MAX_RECORD_SIZE); + } + ExpectIntEQ(wolfSSL_GetMaxOutputSize(ssl_s), 512); + + wolfSSL_free(ssl_c); ssl_c = NULL; + wolfSSL_free(ssl_s); ssl_s = NULL; + wolfSSL_CTX_free(ctx_c); ctx_c = NULL; + wolfSSL_CTX_free(ctx_s); ctx_s = NULL; + + /* The same yielding, but with max_fragment_length asked for on the + * context. wolfSSL_CTX_UseMaxFragment() stores on ctx->extensions and + * nothing copies that list onto the object - the write path emits both - + * so a check of ssl->extensions alone does not see it. Getting this wrong + * makes the client advertise both, which by RFC 8449 Sect. 5 has the + * server ignore max_fragment_length and leaves the application's + * requested fragment size silently unapplied. */ + XMEMSET(&test_ctx, 0, sizeof(test_ctx)); + ExpectIntEQ(test_memio_setup(&test_ctx, &ctx_c, &ctx_s, &ssl_c, &ssl_s, + wolfTLSv1_2_client_method, wolfTLSv1_2_server_method), 0); + wolfSSL_free(ssl_c); ssl_c = NULL; + ExpectIntEQ(wolfSSL_CTX_UseMaxFragment(ctx_c, WOLFSSL_MFL_2_11), + WOLFSSL_SUCCESS); + ExpectNotNull(ssl_c = wolfSSL_new(ctx_c)); + wolfSSL_SetIOWriteCtx(ssl_c, &test_ctx); + wolfSSL_SetIOReadCtx(ssl_c, &test_ctx); + ExpectIntEQ(test_memio_do_handshake(ssl_c, ssl_s, 10, NULL), 0); + /* No record_size_limit was offered, so the peer learned none and the + * fragment length the application asked for is the one in force. */ + if (ssl_s != NULL) + ExpectIntEQ(ssl_s->peerRecordSizeLimit, 0); + if (ssl_c != NULL) + ExpectIntEQ(ssl_c->max_fragment, 2048); + ExpectIntEQ(wolfSSL_GetMaxOutputSize(ssl_c), 2048); + + wolfSSL_free(ssl_c); ssl_c = NULL; + wolfSSL_free(ssl_s); ssl_s = NULL; + wolfSSL_CTX_free(ctx_c); ctx_c = NULL; + wolfSSL_CTX_free(ctx_s); ctx_s = NULL; +#endif /* HAVE_MAX_FRAGMENT */ + /* Set on the context, inherited by every object made from it. The + * inheritance is version independent code on purpose - keeping it in the + * TLS 1.3 only path left a TLS 1.2 build advertising the default here + * instead of what the application asked for. */ + XMEMSET(&test_ctx, 0, sizeof(test_ctx)); + ExpectIntEQ(test_memio_setup(&test_ctx, &ctx_c, &ctx_s, &ssl_c, &ssl_s, + wolfTLSv1_2_client_method, wolfTLSv1_2_server_method), 0); + wolfSSL_free(ssl_c); ssl_c = NULL; + wolfSSL_free(ssl_s); ssl_s = NULL; + ExpectIntEQ(wolfSSL_CTX_UseRecordSizeLimit(ctx_c, 512), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_UseRecordSizeLimit(ctx_s, 1024), WOLFSSL_SUCCESS); + ExpectNotNull(ssl_c = wolfSSL_new(ctx_c)); + ExpectNotNull(ssl_s = wolfSSL_new(ctx_s)); + /* Rebuilt by hand rather than by test_memio_setup(), so the memio + * contexts the harness would have attached have to be attached here. */ + wolfSSL_SetIOWriteCtx(ssl_c, &test_ctx); + wolfSSL_SetIOReadCtx(ssl_c, &test_ctx); + wolfSSL_SetIOWriteCtx(ssl_s, &test_ctx); + wolfSSL_SetIOReadCtx(ssl_s, &test_ctx); + if (ssl_c != NULL) + ExpectIntEQ(ssl_c->recordSizeLimit, 512); + if (ssl_s != NULL) + ExpectIntEQ(ssl_s->recordSizeLimit, 1024); + ExpectIntEQ(test_memio_do_handshake(ssl_c, ssl_s, 10, NULL), 0); + if (ssl_c != NULL) + ExpectIntEQ(ssl_c->peerRecordSizeLimit, 1024); + if (ssl_s != NULL) + ExpectIntEQ(ssl_s->peerRecordSizeLimit, 512); + + wolfSSL_free(ssl_c); ssl_c = NULL; + wolfSSL_free(ssl_s); ssl_s = NULL; + wolfSSL_CTX_free(ctx_c); ctx_c = NULL; + wolfSSL_CTX_free(ctx_s); ctx_s = NULL; +#endif + return EXPECT_RESULT(); +} diff --git a/tests/api/test_tls.h b/tests/api/test_tls.h index 2357090d317..bb9561dc570 100644 --- a/tests/api/test_tls.h +++ b/tests/api/test_tls.h @@ -135,6 +135,7 @@ int test_tls12_aesgcm_record_nonce_unique(void); int test_tls_param_flags_crl_check(void); int test_tls_hmac_inner_cid_decision_coverage(void); int test_tls_unset_fd_no_stdin_io(void); +int test_tls12_record_size_limit(void); #define TEST_TLS_DECLS \ TEST_DECL_GROUP("tls", test_utils_memio_move_message), \ @@ -256,6 +257,7 @@ int test_tls_unset_fd_no_stdin_io(void); TEST_DECL_GROUP("tls", test_internal_SetSSL_CTX_DecisionCoverage), \ TEST_DECL_GROUP("tls", test_internal_CheckVersion_DecisionCoverage), \ TEST_DECL_GROUP("tls", test_tls_hmac_inner_cid_decision_coverage), \ - TEST_DECL_GROUP("tls", test_tls_unset_fd_no_stdin_io) + TEST_DECL_GROUP("tls", test_tls_unset_fd_no_stdin_io), \ + TEST_DECL_GROUP("tls", test_tls12_record_size_limit) #endif /* TESTS_API_TEST_TLS_H */ diff --git a/tests/api/test_tls13.c b/tests/api/test_tls13.c index 507b48cc34a..647951b9a43 100644 --- a/tests/api/test_tls13.c +++ b/tests/api/test_tls13.c @@ -6802,6 +6802,257 @@ int test_tls13_early_data_0rtt_replay(void) } #endif +/* The context level setter, the inheritance it relies on, and what survives a + * wolfSSL_clear(). Configuration set on the context has to reach objects made + * from it, and a recycled object has to forget the peer's limit while keeping + * its own. */ +int test_tls13_record_size_limit_ctx(void) +{ + EXPECT_DECLS; +#if defined(WOLFSSL_TLS13) && defined(HAVE_RECORD_SIZE_LIMIT) && \ + defined(HAVE_MANUAL_MEMIO_TESTS_DEPENDENCIES) && !defined(NO_CERTS) && \ + !defined(NO_RSA) && !defined(NO_WOLFSSL_CLIENT) && \ + !defined(NO_WOLFSSL_SERVER) && !defined(NO_FILESYSTEM) + WOLFSSL_CTX *ctx_c = NULL, *ctx_s = NULL; + WOLFSSL *ssl_c = NULL, *ssl_s = NULL; + struct test_memio_ctx test_ctx; + + /* Argument checking on the context setter, including the 0 opt-out. */ + ExpectIntEQ(wolfSSL_CTX_UseRecordSizeLimit(NULL, 512), + WC_NO_ERR_TRACE(BAD_FUNC_ARG)); + + ExpectNotNull(ctx_c = wolfSSL_CTX_new(wolfTLSv1_3_client_method())); + ExpectIntEQ(wolfSSL_CTX_UseRecordSizeLimit(ctx_c, 63), + WC_NO_ERR_TRACE(BAD_FUNC_ARG)); + ExpectIntEQ(wolfSSL_CTX_UseRecordSizeLimit(ctx_c, + WOLFSSL_RECORD_SIZE_LIMIT_MAX + 1), WC_NO_ERR_TRACE(BAD_FUNC_ARG)); + ExpectIntEQ(wolfSSL_CTX_UseRecordSizeLimit(ctx_c, + WOLFSSL_RECORD_SIZE_LIMIT_OFF), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_UseRecordSizeLimit(ctx_c, 700), WOLFSSL_SUCCESS); + /* test_memio_setup() only configures a context it creates itself, so this + * pre-made one needs the CA and the memio transport wired up by hand. */ + ExpectTrue(wolfSSL_CTX_load_verify_locations(ctx_c, caCertFile, 0) + == WOLFSSL_SUCCESS); + wolfSSL_SetIORecv(ctx_c, test_memio_read_cb); + wolfSSL_SetIOSend(ctx_c, test_memio_write_cb); + + XMEMSET(&test_ctx, 0, sizeof(test_ctx)); + ExpectIntEQ(test_memio_setup(&test_ctx, &ctx_c, &ctx_s, &ssl_c, &ssl_s, + wolfTLSv1_3_client_method, wolfTLSv1_3_server_method), 0); + + /* Inherited by an object made after the context was configured. */ + if (ssl_c != NULL) + ExpectIntEQ(ssl_c->recordSizeLimit, 700); + + ExpectIntEQ(test_memio_do_handshake(ssl_c, ssl_s, 10, NULL), 0); + if (ssl_s != NULL) + ExpectIntEQ(ssl_s->peerRecordSizeLimit, 700); + ExpectIntEQ(wolfSSL_GetMaxOutputSize(ssl_s), 700); + + /* Recycling the object drops what the peer said but keeps this end's own + * configuration, which is not part of the connection. */ + ExpectIntEQ(wolfSSL_clear(ssl_c), WOLFSSL_SUCCESS); + if (ssl_c != NULL) { + ExpectIntEQ(ssl_c->peerRecordSizeLimit, 0); + ExpectIntEQ(ssl_c->recordSizeLimit, 700); + /* What was advertised belongs to the connection as well: the receive + * path holds the peer to it, and wolfSSL_UseRecordSizeLimit() reads + * it as an offer already made. */ + ExpectIntEQ(ssl_c->recordSizeLimitSent, 0); + } + /* So the recycled object can be reconfigured, which is the point of + * recycling it. */ + ExpectIntEQ(wolfSSL_UseRecordSizeLimit(ssl_c, 900), WOLFSSL_SUCCESS); + if (ssl_c != NULL) + ExpectIntEQ(ssl_c->recordSizeLimit, 900); + ExpectIntEQ(wolfSSL_UseRecordSizeLimit(ssl_c, + WOLFSSL_RECORD_SIZE_LIMIT_OFF), WOLFSSL_SUCCESS); + + wolfSSL_free(ssl_c); + wolfSSL_free(ssl_s); + wolfSSL_CTX_free(ctx_c); + wolfSSL_CTX_free(ctx_s); +#endif + return EXPECT_RESULT(); +} + +/* A 0-RTT write larger than the server's record_size_limit must still get + * through. The client sends early data before it has seen + * EncryptedExtensions, so it cannot have sized those records to a limit it + * has not been told - RFC 8449 does not carry the value in the ticket - and a + * server that enforced its limit there would fail the handshake with + * record_overflow for something the peer had no way to bound. */ +int test_tls13_record_size_limit_early_data(void) +{ + EXPECT_DECLS; +#if defined(HAVE_MANUAL_MEMIO_TESTS_DEPENDENCIES) && \ + defined(WOLFSSL_TLS13) && defined(HAVE_RECORD_SIZE_LIMIT) && \ + defined(WOLFSSL_EARLY_DATA) && defined(HAVE_SESSION_TICKET) && \ + !defined(WOLFSSL_NO_DEF_TICKET_ENC_CB) && !defined(NO_CERTS) && \ + !defined(NO_RSA) && !defined(NO_WOLFSSL_CLIENT) && \ + !defined(NO_WOLFSSL_SERVER) && !defined(NO_FILESYSTEM) + struct test_memio_ctx test_ctx; + WOLFSSL_CTX *ctx_c = NULL, *ctx_s = NULL; + WOLFSSL *ssl_c = NULL, *ssl_s = NULL; + WOLFSSL_SESSION *sess = NULL; + char buf[64]; + char early[1024]; + char readBuf[sizeof(early)]; + int written = 0; + int nread = 0; + int ret; + int i; + + XMEMSET(early, 'E', sizeof(early)); + + /* First connection: get a ticket that allows 0-RTT. */ + XMEMSET(&test_ctx, 0, sizeof(test_ctx)); + ExpectIntEQ(test_memio_setup(&test_ctx, &ctx_c, &ctx_s, &ssl_c, &ssl_s, + wolfTLSv1_3_client_method, wolfTLSv1_3_server_method), 0); + ExpectIntEQ(wolfSSL_UseRecordSizeLimit(ssl_s, 512), WOLFSSL_SUCCESS); + /* The return convention is build dependent - this returns 0 on success + * unless OPENSSL_EXTRA or WOLFSSL_ERROR_CODE_OPENSSL is defined, when it + * returns WOLFSSL_SUCCESS - so assert the effect instead. */ + (void)wolfSSL_set_max_early_data(ssl_s, (unsigned int)sizeof(early) * 4); + ExpectIntEQ(wolfSSL_get_max_early_data(ssl_s), (int)sizeof(early) * 4); + ExpectIntEQ(test_memio_do_handshake(ssl_c, ssl_s, 10, NULL), 0); + ExpectIntEQ(wolfSSL_read(ssl_c, buf, sizeof(buf)), -1); + ExpectIntEQ(wolfSSL_get_error(ssl_c, -1), WOLFSSL_ERROR_WANT_READ); + ExpectNotNull(sess = wolfSSL_get1_session(ssl_c)); + wolfSSL_free(ssl_c); ssl_c = NULL; + wolfSSL_free(ssl_s); ssl_s = NULL; + + /* Resume and write early data twice the server's 512-byte limit. The + * contexts are kept: a new server context has new ticket keys, so the + * ticket would not resume and the early data would be rejected and + * skipped - which is test_tls13_record_size_limit_early_data_rejected's + * case, not this one. */ + XMEMSET(&test_ctx, 0, sizeof(test_ctx)); + ExpectIntEQ(test_memio_setup(&test_ctx, &ctx_c, &ctx_s, &ssl_c, &ssl_s, + wolfTLSv1_3_client_method, wolfTLSv1_3_server_method), 0); + ExpectIntEQ(wolfSSL_UseRecordSizeLimit(ssl_s, 512), WOLFSSL_SUCCESS); + /* The return convention is build dependent - this returns 0 on success + * unless OPENSSL_EXTRA or WOLFSSL_ERROR_CODE_OPENSSL is defined, when it + * returns WOLFSSL_SUCCESS - so assert the effect instead. */ + (void)wolfSSL_set_max_early_data(ssl_s, (unsigned int)sizeof(early) * 4); + ExpectIntEQ(wolfSSL_get_max_early_data(ssl_s), (int)sizeof(early) * 4); + ExpectIntEQ(wolfSSL_set_session(ssl_c, sess), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_write_early_data(ssl_c, early, (int)sizeof(early), + &written), (int)sizeof(early)); + + /* The point of the test. Before the 0-RTT carve-out the record-size + * check rejected the 1024-byte early-data record with LENGTH_ERROR, + * against the server's 512-byte limit - a limit the client could not + * have known. The first call only processes the ClientHello and answers + * it, so read until the early data itself is delivered, and check it + * arrives whole: accepted, not merely skipped as rejected 0-RTT. */ + for (i = 0; (i < 4) && (nread == 0) && EXPECT_SUCCESS(); i++) { + ret = wolfSSL_read_early_data(ssl_s, readBuf, (int)sizeof(readBuf), + &nread); + if (ret < 0) { + ExpectIntEQ(wolfSSL_get_error(ssl_s, ret), + WOLFSSL_ERROR_WANT_READ); + } + } + ExpectIntEQ(nread, (int)sizeof(early)); + ExpectIntEQ(XMEMCMP(readBuf, early, sizeof(early)), 0); + ExpectIntEQ(wolfSSL_get_early_data_status(ssl_s), + WOLFSSL_EARLY_DATA_ACCEPTED); + + wolfSSL_SESSION_free(sess); + wolfSSL_free(ssl_c); + wolfSSL_free(ssl_s); + wolfSSL_CTX_free(ctx_c); + wolfSSL_CTX_free(ctx_s); +#endif + return EXPECT_RESULT(); +} + +/* A server that never calls wolfSSL_read_early_data() rejects 0-RTT, and the + * records the client already sent have to be discarded rather than measured + * against a limit the client could not have known. Such a server stays at + * early_data_ext, which RecordSizeLimitBinds() did not exempt, so the first + * oversize early-data record was refused with record_overflow before + * ProcessReply() could drop it: the handshake failed with LENGTH_ERROR. */ +int test_tls13_record_size_limit_early_data_rejected(void) +{ + EXPECT_DECLS; +#if defined(HAVE_MANUAL_MEMIO_TESTS_DEPENDENCIES) && \ + defined(WOLFSSL_TLS13) && defined(HAVE_RECORD_SIZE_LIMIT) && \ + defined(WOLFSSL_EARLY_DATA) && defined(HAVE_SESSION_TICKET) && \ + !defined(WOLFSSL_NO_DEF_TICKET_ENC_CB) && !defined(NO_CERTS) && \ + !defined(NO_RSA) && !defined(NO_WOLFSSL_CLIENT) && \ + !defined(NO_WOLFSSL_SERVER) && !defined(NO_FILESYSTEM) + struct test_memio_ctx test_ctx; + WOLFSSL_CTX *ctx_c = NULL, *ctx_s = NULL; + WOLFSSL *ssl_c = NULL, *ssl_s = NULL; + WOLFSSL_SESSION *sess = NULL; + char buf[64]; + char early[1024]; + char msg[] = "hello wolfssl!"; + int written = 0; + + XMEMSET(early, 'E', sizeof(early)); + + /* First connection: a ticket whose max_early_data_size lets the client + * try 0-RTT on the next one. */ + XMEMSET(&test_ctx, 0, sizeof(test_ctx)); + ExpectIntEQ(test_memio_setup(&test_ctx, &ctx_c, &ctx_s, &ssl_c, &ssl_s, + wolfTLSv1_3_client_method, wolfTLSv1_3_server_method), 0); + /* The return convention is build dependent, so assert the effect. */ + (void)wolfSSL_set_max_early_data(ssl_s, (unsigned int)sizeof(early) * 4); + ExpectIntEQ(wolfSSL_get_max_early_data(ssl_s), (int)sizeof(early) * 4); + ExpectIntEQ(test_memio_do_handshake(ssl_c, ssl_s, 10, NULL), 0); + ExpectIntEQ(wolfSSL_read(ssl_c, buf, sizeof(buf)), -1); + ExpectIntEQ(wolfSSL_get_error(ssl_c, -1), WOLFSSL_ERROR_WANT_READ); + ExpectNotNull(sess = wolfSSL_get1_session(ssl_c)); + wolfSSL_free(ssl_c); ssl_c = NULL; + wolfSSL_free(ssl_s); ssl_s = NULL; + wolfSSL_CTX_free(ctx_c); ctx_c = NULL; + wolfSSL_CTX_free(ctx_s); ctx_s = NULL; + + /* Resume, writing early data at twice the server's limit. The server + * allows 0-RTT in its tickets but this handshake never asks for the + * data, so it answers no early_data extension and the records it has + * already been handed are rejected 0-RTT to be skipped. */ + XMEMSET(&test_ctx, 0, sizeof(test_ctx)); + ExpectIntEQ(test_memio_setup(&test_ctx, &ctx_c, &ctx_s, &ssl_c, &ssl_s, + wolfTLSv1_3_client_method, wolfTLSv1_3_server_method), 0); + ExpectIntEQ(wolfSSL_UseRecordSizeLimit(ssl_s, 512), WOLFSSL_SUCCESS); + (void)wolfSSL_set_max_early_data(ssl_s, (unsigned int)sizeof(early) * 4); + ExpectIntEQ(wolfSSL_get_max_early_data(ssl_s), (int)sizeof(early) * 4); + ExpectIntEQ(wolfSSL_set_session(ssl_c, sess), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_write_early_data(ssl_c, early, (int)sizeof(early), + &written), (int)sizeof(early)); + /* No wolfSSL_read_early_data() on the server: that is the point. */ + ExpectIntEQ(test_memio_do_handshake(ssl_c, ssl_s, 10, NULL), 0); + ExpectIntEQ(wolfSSL_get_early_data_status(ssl_c), + WOLFSSL_EARLY_DATA_REJECTED); + /* A TLS 1.3 server returns from wolfSSL_accept() with its own Finished + * sent, so the early-data records are still unread at this point. This + * read is what walks the server over them: each one fails to decrypt, + * because the server installed no early-data keys, and is discarded + * (RFC 8446 Sect. 4.2.10) until the client's Finished and the + * application data behind it. */ + ExpectIntEQ(wolfSSL_write(ssl_c, msg, (int)sizeof(msg) - 1), + (int)sizeof(msg) - 1); + ExpectIntEQ(wolfSSL_read(ssl_s, buf, (int)sizeof(buf) - 1), + (int)sizeof(msg) - 1); + /* The state this is about: the server was handed the early_data + * extension but never armed itself to read the data, so it stayed at + * early_data_ext for the whole handshake. */ + if (ssl_s != NULL) + ExpectIntEQ(ssl_s->earlyData, early_data_ext); + + wolfSSL_SESSION_free(sess); + wolfSSL_free(ssl_c); + wolfSSL_free(ssl_s); + wolfSSL_CTX_free(ctx_c); + wolfSSL_CTX_free(ctx_s); +#endif + return EXPECT_RESULT(); +} + /* Verify that maxEarlyDataSz defaults to 0 (RFC 8446 E.5): a server that * has not called wolfSSL_set_max_early_data must not advertise 0-RTT in its * NewSessionTicket. Fails without the ctx->maxEarlyDataSz=0 default fix @@ -12050,188 +12301,1186 @@ int test_tls13_hrr_bad_cookie(void) ExpectIntEQ(wolfSSL_get_error(ssl_s, WOLFSSL_FATAL_ERROR), WOLFSSL_ERROR_WANT_READ); - /* Step 3: Client processes HRR, sends CH2 with cookie */ - ExpectIntNE(wolfSSL_connect(ssl_c), WOLFSSL_SUCCESS); - ExpectIntEQ(wolfSSL_get_error(ssl_c, WOLFSSL_FATAL_ERROR), - WOLFSSL_ERROR_WANT_READ); + /* Step 3: Client processes HRR, sends CH2 with cookie */ + ExpectIntNE(wolfSSL_connect(ssl_c), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_get_error(ssl_c, WOLFSSL_FATAL_ERROR), + WOLFSSL_ERROR_WANT_READ); + + /* Corrupt the server-side cookie secret after HRR so CH2's cookie no longer + * verifies in TlsCheckCookie(). */ + if (EXPECT_SUCCESS()) { + ExpectNotNull(ssl_s->buffers.tls13CookieSecret.buffer); + ExpectIntGT(ssl_s->buffers.tls13CookieSecret.length, 0); + ssl_s->buffers.tls13CookieSecret.buffer[ + ssl_s->buffers.tls13CookieSecret.length - 1] ^= 0xFF; + } + + /* Step 4: Server processes corrupted CH2 - should fail */ + ExpectIntNE(wolfSSL_accept(ssl_s), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_get_error(ssl_s, WOLFSSL_FATAL_ERROR), + WC_NO_ERR_TRACE(HRR_COOKIE_ERROR)); + + wolfSSL_free(ssl_c); + wolfSSL_CTX_free(ctx_c); + wolfSSL_free(ssl_s); + wolfSSL_CTX_free(ctx_s); +#endif + return EXPECT_RESULT(); +} + +/* Run a handshake where the server sends a cookie in its HelloRetryRequest: + * the client must echo it back for the server to accept the second + * ClientHello. With noKeyShares the retry also asks for a different group, + * without it the cookie is the only thing the retry changes. */ +static int test_tls13_hrr_cookie_handshake_once(int noKeyShares) +{ + EXPECT_DECLS; +#if defined(WOLFSSL_TLS13) && \ + defined(HAVE_MANUAL_MEMIO_TESTS_DEPENDENCIES) && \ + defined(WOLFSSL_SEND_HRR_COOKIE) && \ + !defined(NO_WOLFSSL_CLIENT) && !defined(NO_WOLFSSL_SERVER) + WOLFSSL_CTX *ctx_c = NULL; + WOLFSSL_CTX *ctx_s = NULL; + WOLFSSL *ssl_c = NULL; + WOLFSSL *ssl_s = NULL; + struct test_memio_ctx test_ctx; + + XMEMSET(&test_ctx, 0, sizeof(test_ctx)); + ExpectIntEQ(test_memio_setup(&test_ctx, &ctx_c, &ctx_s, &ssl_c, &ssl_s, + wolfTLSv1_3_client_method, wolfTLSv1_3_server_method), 0); + + ExpectIntEQ(wolfSSL_send_hrr_cookie(ssl_s, NULL, 0), WOLFSSL_SUCCESS); + if (noKeyShares) { + ExpectIntEQ(wolfSSL_NoKeyShares(ssl_c), WOLFSSL_SUCCESS); + } + + ExpectIntEQ(test_memio_do_handshake(ssl_c, ssl_s, 10, NULL), 0); + + /* Client saw a cookie and the server accepted the one echoed back. */ + ExpectIntEQ(ssl_c->options.hrrSentCookie, 1); + ExpectIntEQ(ssl_s->options.cookieGood, 1); + ExpectIntEQ(ssl_c->options.hrrSentKeyShare, noKeyShares ? 1 : 0); + + wolfSSL_free(ssl_c); + wolfSSL_CTX_free(ctx_c); + wolfSSL_free(ssl_s); + wolfSSL_CTX_free(ctx_s); +#else + (void)noKeyShares; +#endif + return EXPECT_RESULT(); +} + +/* HelloRetryRequest carrying both a key share and a cookie. */ +int test_tls13_hrr_cookie_handshake(void) +{ + return test_tls13_hrr_cookie_handshake_once(1); +} + +/* HelloRetryRequest whose only change is the cookie. This is what a server + * sends when it wants the client's address confirmed and the offered key + * share was already usable. */ +int test_tls13_hrr_cookie_only_handshake(void) +{ + return test_tls13_hrr_cookie_handshake_once(0); +} + +/* Test that a client stores a cookie received in a HelloRetryRequest and + * writes it back out in the second ClientHello. Required of every TLS 1.3 + * client by RFC 8446 4.2.2, so it must hold without WOLFSSL_SEND_HRR_COOKIE, + * which only controls a server creating cookies. */ +int test_tls13_client_cookie_echo(void) +{ + EXPECT_DECLS; +#if defined(WOLFSSL_TLS13) && !defined(NO_WOLFSSL_CLIENT) + WOLFSSL_CTX* ctx = NULL; + WOLFSSL* ssl = NULL; + TLSX* ext = NULL; + Cookie* cookie = NULL; + word32 length = 0; + word32 offset = 0; + byte out[128]; + /* Cookie extension of a HelloRetryRequest: type, extension length, + * cookie length, cookie. */ + static const byte hrrExt[] = { + 0x00, 0x2c, 0x00, 0x08, 0x00, 0x06, 'w', 'o', 'l', 'f', 'S', 'L' + }; + + XMEMSET(out, 0, sizeof(out)); + + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfTLSv1_3_client_method())); + ExpectNotNull(ssl = wolfSSL_new(ctx)); + + ExpectIntEQ(TLSX_Parse(ssl, hrrExt, (word16)sizeof(hrrExt), + hello_retry_request, NULL), 0); + + ExpectNotNull(ext = TLSX_Find(ssl->extensions, TLSX_COOKIE)); + if (EXPECT_SUCCESS()) { + ExpectNotNull(cookie = (Cookie*)ext->data); + } + if (EXPECT_SUCCESS()) { + ExpectIntEQ(cookie->len, sizeof(hrrExt) - 6); + ExpectBufEQ(cookie->data, hrrExt + 6, sizeof(hrrExt) - 6); + } + + ExpectIntEQ(TLSX_GetRequestSize(ssl, client_hello, &length), 0); + ExpectIntGT(length, 0); + ExpectIntLE(length, (word32)sizeof(out)); + if (EXPECT_SUCCESS()) { + ExpectIntEQ(TLSX_WriteRequest(ssl, out, client_hello, &offset), 0); + ExpectIntEQ(offset, length); + } + if (EXPECT_SUCCESS()) { + int found = 0; + word32 i; + + for (i = 0; i + sizeof(hrrExt) <= offset; i++) { + if (XMEMCMP(out + i, hrrExt, sizeof(hrrExt)) == 0) { + found = 1; + break; + } + } + ExpectIntEQ(found, 1); + } + + wolfSSL_free(ssl); + wolfSSL_CTX_free(ctx); +#endif + return EXPECT_RESULT(); +} + +/* Test that a client rejects a HelloRetryRequest cookie larger than it is + * willing to store and echo back. RFC 8446 4.2.2 allows up to 2^16-1 bytes; + * WOLFSSL_MAX_TLS13_COOKIE_SZ is the smaller local cap tested here. + * One byte over the cap plus the six bytes of extension headers must still + * fit the word16 length TLSX_Parse() takes: 65535 - 1 - 6 = 65528. */ +int test_tls13_client_cookie_too_big(void) +{ + EXPECT_DECLS; +#if defined(WOLFSSL_TLS13) && !defined(NO_WOLFSSL_CLIENT) && \ + WOLFSSL_MAX_TLS13_COOKIE_SZ <= 65528 + WOLFSSL_CTX* ctx = NULL; + WOLFSSL* ssl = NULL; + byte* hrrExt = NULL; + const word16 cookieLen = WOLFSSL_MAX_TLS13_COOKIE_SZ + 1; + const word16 extLen = cookieLen + OPAQUE16_LEN; + const word32 totalLen = (word32)extLen + OPAQUE16_LEN * 2; + + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfTLSv1_3_client_method())); + ExpectNotNull(ssl = wolfSSL_new(ctx)); + + ExpectNotNull(hrrExt = (byte*)XMALLOC(totalLen, NULL, + DYNAMIC_TYPE_TMP_BUFFER)); + if (EXPECT_SUCCESS()) { + XMEMSET(hrrExt, 0, totalLen); + c16toa(TLSX_COOKIE, hrrExt); + c16toa(extLen, hrrExt + OPAQUE16_LEN); + c16toa(cookieLen, hrrExt + OPAQUE16_LEN * 2); + } + + ExpectIntEQ(TLSX_Parse(ssl, hrrExt, (word16)totalLen, hello_retry_request, + NULL), WC_NO_ERR_TRACE(HRR_COOKIE_ERROR)); + ExpectNull(TLSX_Find(ssl->extensions, TLSX_COOKIE)); + + XFREE(hrrExt, NULL, DYNAMIC_TYPE_TMP_BUFFER); + wolfSSL_free(ssl); + wolfSSL_CTX_free(ctx); +#endif + return EXPECT_RESULT(); +} + +/* Drive one connection, inject a record of a chosen wire length into the + * buffer the client reads from, and report the error the client ends with. + * + * No co-operating peer will ever send an oversized record, so it is written + * straight into the memio buffer. RFC 8449's check lives in + * GetRecordHeader(), before decryption, so a header claiming the length is + * enough and the body can be filler. + * + * Returns the client's raw error, or a negative setup failure. + */ +#if defined(WOLFSSL_TLS13) && defined(HAVE_RECORD_SIZE_LIMIT) && \ + defined(HAVE_MANUAL_MEMIO_TESTS_DEPENDENCIES) && !defined(NO_CERTS) && \ + !defined(NO_RSA) && !defined(NO_WOLFSSL_CLIENT) && \ + !defined(NO_WOLFSSL_SERVER) && !defined(NO_FILESYSTEM) +/* Inject one record of ourLimit + content type + the negotiated AEAD tag + + * overBy bytes, and report the error the client raised. Those are the whole + * of a TLS 1.3 record's expansion over the payload limit, so overBy == 0 is + * exactly the largest record the limit permits and overBy == 1 is the first + * one it does not. */ +static int RecordOfSize(word16 ourLimit, int overBy, int* alertSent) +{ + WOLFSSL_CTX *ctx_c = NULL, *ctx_s = NULL; + WOLFSSL *ssl_c = NULL, *ssl_s = NULL; + struct test_memio_ctx test_ctx; + char out[128]; + int err = 0; + int before; + word32 bodySz; + word32 recSz; + + XMEMSET(&test_ctx, 0, sizeof(test_ctx)); + if (test_memio_setup(&test_ctx, &ctx_c, &ctx_s, &ssl_c, &ssl_s, + wolfTLSv1_3_client_method, wolfTLSv1_3_server_method) != 0) { + err = -1; + goto done; + } + if (wolfSSL_UseRecordSizeLimit(ssl_c, ourLimit) != WOLFSSL_SUCCESS || + wolfSSL_UseRecordSizeLimit(ssl_s, 4096) != WOLFSSL_SUCCESS) { + err = -2; + goto done; + } + if (test_memio_do_handshake(ssl_c, ssl_s, 10, NULL) != 0) { + err = -3; + goto done; + } + + /* Only known once a cipher suite is negotiated. */ + /* ourLimit is payload, so the largest permitted record is that plus the + * TLS 1.3 content type byte plus the AEAD tag. */ + bodySz = (word32)((int)ourLimit + 1 + ssl_c->specs.aead_mac_size + overBy); + recSz = RECORD_HEADER_SZ + bodySz; + + if ((test_ctx.c_len + (int)recSz) >= TEST_MEMIO_BUF_SZ || + test_ctx.c_msg_count >= TEST_MEMIO_MAX_MSGS) { + err = -4; + goto done; + } + + { + byte* p = test_ctx.c_buff + test_ctx.c_len; + + p[0] = application_data; + p[1] = SSLv3_MAJOR; + p[2] = TLSv1_2_MINOR; /* the wire version TLS 1.3 records carry */ + c16toa((word16)bodySz, p + 3); + XMEMSET(p + RECORD_HEADER_SZ, 0, bodySz); + + /* Register it the way test_memio_write_cb() would. */ + test_ctx.c_msg_sizes[test_ctx.c_msg_count++] = (int)recSz; + test_ctx.c_len += (int)recSz; + } + + before = test_ctx.s_len; + (void)wolfSSL_read(ssl_c, out, (int)sizeof(out)); + /* The raw error: wolfSSL_get_error() remaps this one under OPENSSL_EXTRA, + * as the SHA-1 chain test notes. */ + err = ssl_c->error; + if (alertSent != NULL) + *alertSent = (test_ctx.s_len > before); + +done: + wolfSSL_free(ssl_c); + wolfSSL_free(ssl_s); + wolfSSL_CTX_free(ctx_c); + wolfSSL_CTX_free(ctx_s); + return err; +} +#endif + +/* The TLS 1.2 counterpart of RecordOfSize(). The expansion a TLS 1.2 record + * adds over its plaintext depends on the negotiated suite rather than being + * one content type byte plus an AEAD tag, so the allowance is derived the same + * way GetRecordHeader() derives it: the suite's own expansion. + * overBy is measured from that boundary. + */ +#if defined(HAVE_RECORD_SIZE_LIMIT) && !defined(WOLFSSL_NO_TLS12) && \ + defined(HAVE_MANUAL_MEMIO_TESTS_DEPENDENCIES) && !defined(NO_CERTS) && \ + !defined(NO_RSA) && !defined(NO_WOLFSSL_CLIENT) && \ + !defined(NO_WOLFSSL_SERVER) && !defined(NO_FILESYSTEM) +static int Tls12RecordOfSize(word16 ourLimit, int overBy, + method_provider client_meth, int typeByteOffered) +{ + WOLFSSL_CTX *ctx_c = NULL, *ctx_s = NULL; + WOLFSSL *ssl_c = NULL, *ssl_s = NULL; + struct test_memio_ctx test_ctx; + char out[128]; + int err = 0; + word32 bodySz; + word32 recSz; + word32 extra; + + XMEMSET(&test_ctx, 0, sizeof(test_ctx)); + if (test_memio_setup(&test_ctx, &ctx_c, &ctx_s, &ssl_c, &ssl_s, + client_meth, wolfTLSv1_2_server_method) != 0) { + err = -1; + goto done; + } + if (wolfSSL_UseRecordSizeLimit(ssl_c, ourLimit) != WOLFSSL_SUCCESS || + wolfSSL_UseRecordSizeLimit(ssl_s, 4096) != WOLFSSL_SUCCESS) { + err = -2; + goto done; + } + if (test_memio_do_handshake(ssl_c, ssl_s, 10, NULL) != 0) { + err = -3; + goto done; + } + + /* Measured, not recomputed: wolfssl_local_GetRecordSize() reports what the + * implementation itself would emit for a payload, so the per-record + * expansion comes straight from the code under test rather than from a + * copy of its arithmetic here. cipherExtraData(), which GetRecordHeader() + * calls, is WOLFSSL_LOCAL and so not linkable from the tests. */ + { + int probe = wolfssl_local_GetRecordSize(ssl_c, 64, 1); + + if (probe < 0) { + err = -5; + goto done; + } + extra = (word32)probe - RECORD_HEADER_SZ - 64; + } +#ifndef WOLFSSL_AEAD_ONLY + if (ssl_c->specs.cipher_type == block) { + /* GetRecordHeader() trades the padding the probe includes for the + * full MAX_PAD_SIZE a peer may use. That padding is not always a whole + * block - 64 bytes plus a 20-byte SHA-1 MAC pads with 12, where a + * SHA-256 MAC pads with 16 - so it is taken from the measurement: + * what the probe added beyond the explicit IV and the MAC. */ + word32 fixed = (word32)ssl_c->specs.block_size + + (word32)ssl_c->specs.hash_size; + + if ((extra >= fixed) && (extra - fixed < MAX_PAD_SIZE)) + extra += MAX_PAD_SIZE - (extra - fixed); + } +#endif + /* Only when this client really did advertise with the TLS 1.3 content + * type byte folded in, which depends on the method it was built with and + * not on the build having TLS 1.3 compiled in: a client that offers TLS + * 1.3 sends the value before the version is settled, and after a + * downgrade that byte is payload the peer may use, so its boundary sits + * one byte higher. A client that only ever offered TLS 1.2 sent the value + * as it stood and must be held to exactly that. */ + if (typeByteOffered) + extra += 1; + + bodySz = (word32)((int)ourLimit + (int)extra + overBy); + recSz = RECORD_HEADER_SZ + bodySz; + if ((test_ctx.c_len + (int)recSz) >= TEST_MEMIO_BUF_SZ || + test_ctx.c_msg_count >= TEST_MEMIO_MAX_MSGS) { + err = -4; + goto done; + } + + { + byte* p = test_ctx.c_buff + test_ctx.c_len; + + p[0] = application_data; + p[1] = SSLv3_MAJOR; + p[2] = TLSv1_2_MINOR; + c16toa((word16)bodySz, p + 3); + XMEMSET(p + RECORD_HEADER_SZ, 0, bodySz); + test_ctx.c_msg_sizes[test_ctx.c_msg_count++] = (int)recSz; + test_ctx.c_len += (int)recSz; + } + + (void)wolfSSL_read(ssl_c, out, (int)sizeof(out)); + err = ssl_c->error; + +done: + wolfSSL_free(ssl_c); + wolfSSL_free(ssl_s); + wolfSSL_CTX_free(ctx_c); + wolfSSL_CTX_free(ctx_s); + return err; +} +#endif + +int test_tls12_record_size_limit_overflow(void) +{ + EXPECT_DECLS; +#if defined(HAVE_RECORD_SIZE_LIMIT) && !defined(WOLFSSL_NO_TLS12) && \ + defined(HAVE_MANUAL_MEMIO_TESTS_DEPENDENCIES) && !defined(NO_CERTS) && \ + !defined(NO_RSA) && !defined(NO_WOLFSSL_CLIENT) && \ + !defined(NO_WOLFSSL_SERVER) && !defined(NO_FILESYSTEM) + const word16 ourLimit = 512; + + /* Receive enforcement was only ever driven at TLS 1.3, where the expansion + * is a content type byte and an AEAD tag. The TLS 1.2 arm computes its + * allowance from the negotiated suite - a CBC peer may add up to + * MAX_PAD_SIZE of padding that RFC 8449 does not count against the limit - + * so it needs its own boundary case. */ + /* A TLS 1.2-only client advertised the value as it stood. One byte over + * is refused by the length check. */ + ExpectIntEQ(Tls12RecordOfSize(ourLimit, 1, wolfTLSv1_2_client_method, 0), + WC_NO_ERR_TRACE(LENGTH_ERROR)); + /* Exactly at the boundary is not. The body is filler so it fails to + * authenticate; what matters is that it fails for some other reason, the + * same way the TLS 1.3 case is asserted. */ + ExpectIntNE(Tls12RecordOfSize(ourLimit, 0, wolfTLSv1_2_client_method, 0), + WC_NO_ERR_TRACE(LENGTH_ERROR)); +#ifdef WOLFSSL_TLS13 + /* A client that offered TLS 1.3 and was downgraded did fold the content + * type byte into the value it sent, so its boundary is one byte higher. + * The pair matters: holding a downgraded client to the payload limit + * alone rejects a record its own advertisement allowed, and giving the + * byte to the client above accepts one it never offered. */ + ExpectIntEQ(Tls12RecordOfSize(ourLimit, 1, wolfSSLv23_client_method, 1), + WC_NO_ERR_TRACE(LENGTH_ERROR)); + ExpectIntNE(Tls12RecordOfSize(ourLimit, 0, wolfSSLv23_client_method, 1), + WC_NO_ERR_TRACE(LENGTH_ERROR)); +#endif +#endif + return EXPECT_RESULT(); +} + +/* RFC 8449 Sect. 4 measures the limit against the plaintext, but a record is + * first met as ciphertext, and what a CBC suite adds to it is not fixed: a + * peer may pad up to MAX_PAD_SIZE to hide the plaintext length, and padding + * does not count against the limit. The ciphertext check therefore has to + * allow that slack, and a record that pads minimally walks through it with a + * plaintext well over the limit. Only a check on the opened record catches + * that one. */ +#if defined(HAVE_RECORD_SIZE_LIMIT) && !defined(WOLFSSL_NO_TLS12) && \ + defined(HAVE_MANUAL_MEMIO_TESTS_DEPENDENCIES) && !defined(NO_CERTS) && \ + !defined(NO_RSA) && !defined(NO_WOLFSSL_CLIENT) && \ + !defined(NO_WOLFSSL_SERVER) && !defined(NO_FILESYSTEM) && \ + !defined(WOLFSSL_AEAD_ONLY) && !defined(NO_SHA256) && \ + defined(HAVE_AES_CBC) && defined(HAVE_ECC) && !defined(NO_AES_128) +/* One TLS 1.2 plaintext-limit case over a CBC suite, whose padding is what + * leaves the ciphertext check in GetRecordHeader() unable to decide this on + * its own. + * + * The client advertises ourLimit, the server is made to emit a single record + * of payloadSz bytes of content, and the client either hands that content to + * the caller or kills the connection with record_overflow. typeByteOffered + * says whether this client's advertisement was expected to include the + * TLS 1.3 content type byte, which decides how much content the limit + * actually covers once TLS 1.2 is negotiated. + */ +static int Tls12PlaintextOfSize(method_provider client_meth, word16 ourLimit, + int payloadSz, int typeByteOffered, int expectAccept) +{ + EXPECT_DECLS; + WOLFSSL_CTX *ctx_c = NULL, *ctx_s = NULL; + WOLFSSL *ssl_c = NULL, *ssl_s = NULL; + struct test_memio_ctx test_ctx; + byte payload[1024]; + char out[2048]; + + XMEMSET(payload, 'A', sizeof(payload)); + XMEMSET(&test_ctx, 0, sizeof(test_ctx)); + ExpectIntEQ(test_memio_setup(&test_ctx, &ctx_c, &ctx_s, &ssl_c, &ssl_s, + client_meth, wolfTLSv1_2_server_method), 0); + ExpectIntEQ(wolfSSL_CTX_set_cipher_list(ctx_c, + "ECDHE-RSA-AES128-SHA256"), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_set_cipher_list(ctx_s, + "ECDHE-RSA-AES128-SHA256"), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_UseRecordSizeLimit(ssl_c, ourLimit), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_UseRecordSizeLimit(ssl_s, 4096), WOLFSSL_SUCCESS); + ExpectIntEQ(test_memio_do_handshake(ssl_c, ssl_s, 10, NULL), 0); + if (ssl_c != NULL) { + ExpectIntEQ(ssl_c->specs.cipher_type, block); + /* TLS 1.2 in force however the client got here. */ + ExpectIntEQ(ssl_c->version.minor, TLSv1_2_MINOR); + /* What the client actually put on the wire, which is what it may + * hold the server to. */ + ExpectIntEQ(ssl_c->recordSizeLimitSent, + (word16)(ourLimit + (typeByteOffered ? 1 : 0))); + } + + /* The server honours the client's limit, so lift that cap to make it emit + * the record a non-conforming or hostile peer would send. */ + if (ssl_s != NULL) + ssl_s->peerRecordSizeLimit = 4096; + ExpectIntEQ(wolfSSL_write(ssl_s, payload, payloadSz), payloadSz); + + if (expectAccept) { + ExpectIntEQ(wolfSSL_read(ssl_c, out, (int)sizeof(out)), payloadSz); + } + else { + /* Refused, with the alert RFC 8449 requires. */ + ExpectIntLT(wolfSSL_read(ssl_c, out, (int)sizeof(out)), 0); + if (ssl_c != NULL) + ExpectIntEQ(ssl_c->error, WC_NO_ERR_TRACE(LENGTH_ERROR)); + } + + wolfSSL_free(ssl_c); + wolfSSL_free(ssl_s); + wolfSSL_CTX_free(ctx_c); + wolfSSL_CTX_free(ctx_s); + + return EXPECT_RESULT(); +} +#endif + +int test_tls12_record_size_limit_plaintext(void) +{ + EXPECT_DECLS; +#if defined(HAVE_RECORD_SIZE_LIMIT) && !defined(WOLFSSL_NO_TLS12) && \ + defined(HAVE_MANUAL_MEMIO_TESTS_DEPENDENCIES) && !defined(NO_CERTS) && \ + !defined(NO_RSA) && !defined(NO_WOLFSSL_CLIENT) && \ + !defined(NO_WOLFSSL_SERVER) && !defined(NO_FILESYSTEM) && \ + !defined(WOLFSSL_AEAD_ONLY) && !defined(NO_SHA256) && \ + defined(HAVE_AES_CBC) && defined(HAVE_ECC) && !defined(NO_AES_128) + const word16 ourLimit = 512; + + /* A TLS 1.2 only client advertises 512 and means 512 bytes of content. + * 576 is over it, yet inside the padding allowance the ciphertext check + * has to make: 576 + 16 explicit IV + 32 MAC + one block of padding is + * comfortably under the limit plus the MAX_PAD_SIZE that check permits, + * so only the check on the decrypted plaintext can catch it. */ + ExpectIntEQ(Tls12PlaintextOfSize(wolfTLSv1_2_client_method, ourLimit, + 576, 0, 0), TEST_SUCCESS); + /* The limit itself is content this client may be sent. */ + ExpectIntEQ(Tls12PlaintextOfSize(wolfTLSv1_2_client_method, ourLimit, + 512, 0, 1), TEST_SUCCESS); + /* One past it is not, and no content type byte was offered that could + * make room for it. */ + ExpectIntEQ(Tls12PlaintextOfSize(wolfTLSv1_2_client_method, ourLimit, + 513, 0, 0), TEST_SUCCESS); + +#ifdef WOLFSSL_TLS13 + /* A TLS 1.3 capable client offering the same 512 advertises 513, since + * the value it sends counts the TLSInnerPlaintext content type byte. The + * server here speaks only TLS 1.2, where there is no such byte, so all + * 513 are content the server is entitled to send and this end must take + * them: holding it to 512 would be enforcing a limit it never offered. */ + ExpectIntEQ(Tls12PlaintextOfSize(wolfSSLv23_client_method, ourLimit, + 513, 1, 1), TEST_SUCCESS); + /* 514 is over what was advertised either way. */ + ExpectIntEQ(Tls12PlaintextOfSize(wolfSSLv23_client_method, ourLimit, + 514, 1, 0), TEST_SUCCESS); +#endif +#endif + return EXPECT_RESULT(); +} + +/* A peer gets to choose both its record_size_limit (RFC 8449 Sect. 4 allows + * 64) and the certificate_request_context of a post-handshake + * CertificateRequest (RFC 8446 Sect. 4.3.2 allows 255 bytes, which this end + * echoes in its answer). Together they can leave the first fragment of the + * Certificate message too small for that message's fixed header, which the + * send loop cannot fragment. It has to refuse: running the arithmetic anyway + * takes the remaining-room counter below zero and copies the certificate far + * past the output buffer. + * + * Everything here comes from the real path except the two values a peer + * would have chosen: wolfSSL's own server always sends a one byte context + * and would not ask for 64 byte records. */ +#if defined(WOLFSSL_TLS13) && defined(HAVE_RECORD_SIZE_LIMIT) && \ + defined(WOLFSSL_POST_HANDSHAKE_AUTH) && \ + defined(HAVE_MANUAL_MEMIO_TESTS_DEPENDENCIES) && !defined(NO_CERTS) && \ + !defined(NO_RSA) && !defined(NO_WOLFSSL_CLIENT) && \ + !defined(NO_WOLFSSL_SERVER) && !defined(NO_FILESYSTEM) +#define TEST_CERT_REQ_CTX_RSL +/* Answer a post-handshake CertificateRequest whose context is reqCtxLen bytes + * while the peer's record_size_limit is 64. When refuse is set the answer must + * fail with BUFFER_E; otherwise it must go out and the server accept it. */ +static int test_tls13_cert_req_ctx_rsl_one(byte reqCtxLen, int refuse) +{ + EXPECT_DECLS; + WOLFSSL_CTX *ctx_c = NULL, *ctx_s = NULL; + WOLFSSL *ssl_c = NULL, *ssl_s = NULL; + struct test_memio_ctx test_ctx; + CertReqCtx* reqCtx = NULL; + char msg[] = "hello wolfssl!"; + char buf[64]; + /* The RFC 8449 minimum of 64, as TLSX_RecordSizeLimit_Parse() stores it + * at TLS 1.3: payload only, the content type byte already off. That + * leaves 63 - 4 = 59 bytes of the first fragment for a fixed header of + * 1 + reqCtxLen + 3 + 3. */ + const word16 peerLimit = 63; + + XMEMSET(&test_ctx, 0, sizeof(test_ctx)); + ExpectIntEQ(test_memio_setup(&test_ctx, &ctx_c, &ctx_s, &ssl_c, &ssl_s, + wolfTLSv1_3_client_method, wolfTLSv1_3_server_method), 0); + /* The client needs a certificate of its own, so the answer carries one + * and takes the branch that copies it. */ + ExpectIntEQ(wolfSSL_use_certificate_file(ssl_c, cliCertFile, + WOLFSSL_FILETYPE_PEM), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_use_PrivateKey_file(ssl_c, cliKeyFile, + WOLFSSL_FILETYPE_PEM), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_allow_post_handshake_auth(ssl_c), 0); + ExpectIntEQ(wolfSSL_CTX_load_verify_locations(ctx_s, cliCertFile, NULL), + WOLFSSL_SUCCESS); + wolfSSL_set_verify(ssl_s, WOLFSSL_VERIFY_PEER | + WOLFSSL_VERIFY_POST_HANDSHAKE, NULL); + ExpectIntEQ(test_memio_do_handshake(ssl_c, ssl_s, 10, NULL), 0); + + ExpectIntEQ(wolfSSL_request_certificate(ssl_s), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_write(ssl_s, msg, (int)sizeof(msg) - 1), + (int)sizeof(msg) - 1); + + /* Take the CertificateRequest without answering it, so the context it + * queued can be replaced by the one a different peer would have sent. */ + if (EXPECT_SUCCESS()) + ssl_c->options.handShakeState = CLIENT_FINISHED_COMPLETE; + ExpectIntEQ(wolfSSL_read(ssl_c, buf, sizeof(buf) - 1), + (int)sizeof(msg) - 1); + ExpectIntEQ(ssl_c->options.sendVerify, SEND_CERT); + ExpectNotNull(ssl_c->certReqCtx); + + /* DoTls13CertificateRequest() allocates and queues exactly this way for + * a context longer than one byte. */ + if (EXPECT_SUCCESS()) { + ExpectNotNull(reqCtx = (CertReqCtx*)XMALLOC( + sizeof(CertReqCtx) + reqCtxLen - 1, ssl_c->heap, + DYNAMIC_TYPE_TMP_BUFFER)); + } + if (EXPECT_SUCCESS() && (reqCtx != NULL)) { + reqCtx->next = ssl_c->certReqCtx; + reqCtx->len = reqCtxLen; + XMEMSET(&reqCtx->ctx, 0xA5, reqCtxLen); + ssl_c->certReqCtx = reqCtx; + ssl_c->peerRecordSizeLimit = peerLimit; + + /* What DoTls13CertificateRequest() does to answer a post-handshake + * request. */ + ssl_c->options.clientState = CLIENT_HELLO_COMPLETE; + ssl_c->options.connectState = FIRST_REPLY_DONE; + ssl_c->options.handShakeState = CLIENT_HELLO_COMPLETE; + ssl_c->options.processReply = 0; + if (refuse) { + ExpectIntNE(wolfSSL_connect_TLSv13(ssl_c), WOLFSSL_SUCCESS); + ExpectIntEQ(ssl_c->error, WC_NO_ERR_TRACE(BUFFER_E)); + } + else { + ExpectIntEQ(wolfSSL_connect_TLSv13(ssl_c), WOLFSSL_SUCCESS); + } + } + if (!refuse) { + /* The server reassembles the fragmented Certificate and parses it as + * far as the context, which it never sent: only the substitution + * above is refused, not the framing. */ + ExpectIntEQ(wolfSSL_read(ssl_s, buf, sizeof(buf) - 1), -1); + ExpectIntEQ(wolfSSL_get_error(ssl_s, -1), + WC_NO_ERR_TRACE(INVALID_CERT_CTX_E)); + } + + wolfSSL_free(ssl_c); + wolfSSL_free(ssl_s); + wolfSSL_CTX_free(ctx_c); + wolfSSL_CTX_free(ctx_s); + return EXPECT_RESULT(); +} +#endif + +int test_tls13_cert_req_ctx_record_size_limit(void) +{ + EXPECT_DECLS; +#ifdef TEST_CERT_REQ_CTX_RSL + /* Fixed header of 67 bytes: does not fit. */ + ExpectIntEQ(test_tls13_cert_req_ctx_rsl_one(60, 1), TEST_SUCCESS); + /* Fixed header of exactly 59 bytes: fits, but leaves no room for any + * certificate data, so the fragment loop could never advance. */ + ExpectIntEQ(test_tls13_cert_req_ctx_rsl_one(52, 1), TEST_SUCCESS); + /* One byte of room is enough to make progress. */ + ExpectIntEQ(test_tls13_cert_req_ctx_rsl_one(51, 0), TEST_SUCCESS); +#endif + return EXPECT_RESULT(); +} + +/* Test that a record larger than the limit this end advertised is refused. + * + * RFC 8449 Sect. 4: "A TLS endpoint that receives a record larger than its + * advertised limit MUST generate a fatal record_overflow alert." Both sides + * of the boundary are pinned, so a change that rejected legitimate records + * would fail here just as loudly as one that let oversized records through. + */ +int test_tls13_record_size_limit_overflow(void) +{ + EXPECT_DECLS; +#if defined(WOLFSSL_TLS13) && defined(HAVE_RECORD_SIZE_LIMIT) && \ + defined(HAVE_MANUAL_MEMIO_TESTS_DEPENDENCIES) && !defined(NO_CERTS) && \ + !defined(NO_RSA) && !defined(NO_WOLFSSL_CLIENT) && \ + !defined(NO_WOLFSSL_SERVER) && !defined(NO_FILESYSTEM) + const word16 ourLimit = 512; + int alertSent = 0; + int err; + + /* One byte past what the negotiated cipher can expand the limit to: + * refused at the record header, with an alert back to the peer. */ + err = RecordOfSize(ourLimit, 1, &alertSent); + ExpectIntEQ(err, WC_NO_ERR_TRACE(LENGTH_ERROR)); + ExpectIntEQ(alertSent, 1); + + /* Exactly at the allowance: the header check must let this through, so + * it fails later as undecryptable filler instead. Without this the test + * would still pass if the limit were applied far too strictly. */ + err = RecordOfSize(ourLimit, 0, NULL); + ExpectIntNE(err, WC_NO_ERR_TRACE(LENGTH_ERROR)); +#endif + return EXPECT_RESULT(); +} + +/* RFC 8449 Sect. 5: a client that receives both max_fragment_length and + * record_size_limit must abort - whichever order the server put them in. The + * order is the point: a check made while parsing one extension cannot see the + * other, so this fails in one direction only if it is done too early. + * + * A handshake runs first because the client only pushes record_size_limit + * into its extension list while building the ClientHello, and both have to be + * on that list or the unsolicited-response check rejects the message before + * the two ever meet. The synthetic EncryptedExtensions is then fed to the + * client object directly; no wolfSSL server would send one. + */ +int test_tls13_record_size_limit_both_exts(void) +{ + EXPECT_DECLS; +#if defined(WOLFSSL_TLS13) && defined(HAVE_RECORD_SIZE_LIMIT) && \ + defined(HAVE_MAX_FRAGMENT) && \ + defined(HAVE_MANUAL_MEMIO_TESTS_DEPENDENCIES) && !defined(NO_CERTS) && \ + !defined(NO_RSA) && !defined(NO_WOLFSSL_CLIENT) && \ + !defined(NO_WOLFSSL_SERVER) && !defined(NO_FILESYSTEM) + /* record_size_limit(28) = 512, then max_fragment_length(1) = 2^9. */ + static const byte rslFirst[] = { + 0x00, 0x1c, 0x00, 0x02, 0x02, 0x00, + 0x00, 0x01, 0x00, 0x01, 0x01 + }; + /* The same two the other way round. */ + static const byte mflFirst[] = { + 0x00, 0x01, 0x00, 0x01, 0x01, + 0x00, 0x1c, 0x00, 0x02, 0x02, 0x00 + }; + const byte* order[2]; + word16 orderSz[2]; + int i; + + order[0] = rslFirst; orderSz[0] = (word16)sizeof(rslFirst); + order[1] = mflFirst; orderSz[1] = (word16)sizeof(mflFirst); + + for (i = 0; i < 2; i++) { + WOLFSSL_CTX *ctx_c = NULL, *ctx_s = NULL; + WOLFSSL *ssl_c = NULL, *ssl_s = NULL; + struct test_memio_ctx test_ctx; + + XMEMSET(&test_ctx, 0, sizeof(test_ctx)); + ExpectIntEQ(test_memio_setup(&test_ctx, &ctx_c, &ctx_s, &ssl_c, &ssl_s, + wolfTLSv1_3_client_method, wolfTLSv1_3_server_method), 0); + ExpectIntEQ(wolfSSL_UseRecordSizeLimit(ssl_c, 512), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_UseMaxFragment(ssl_c, WOLFSSL_MFL_2_9), + WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_UseRecordSizeLimit(ssl_s, 512), WOLFSSL_SUCCESS); + + /* A client may offer both; RFC 8449 Sect. 5 has the server answer + * with record_size_limit and ignore the max_fragment_length, so this + * handshake completes. */ + ExpectIntEQ(test_memio_do_handshake(ssl_c, ssl_s, 10, NULL), 0); + + ExpectIntEQ(TLSX_Parse(ssl_c, order[i], orderSz[i], + encrypted_extensions, NULL), + WC_NO_ERR_TRACE(INVALID_PARAMETER)); + + wolfSSL_free(ssl_c); + wolfSSL_free(ssl_s); + wolfSSL_CTX_free(ctx_c); + wolfSSL_CTX_free(ctx_s); + } +#endif + return EXPECT_RESULT(); +} + +/* Which of the two record-size extensions governs when both are in play. + * The default limit must stand aside for an application that explicitly asked + * for max_fragment_length, because RFC 8449 Sect. 5 has the server ignore + * max_fragment_length whenever both appear - so advertising the default + * alongside would quietly disable the extension the application chose. An + * explicit record_size_limit still wins. */ +int test_tls13_record_size_limit_vs_mfl(void) +{ + EXPECT_DECLS; +#if defined(WOLFSSL_TLS13) && defined(HAVE_RECORD_SIZE_LIMIT) && \ + defined(HAVE_MAX_FRAGMENT) && \ + defined(HAVE_MANUAL_MEMIO_TESTS_DEPENDENCIES) && !defined(NO_CERTS) && \ + !defined(NO_RSA) && !defined(NO_WOLFSSL_CLIENT) && \ + !defined(NO_WOLFSSL_SERVER) && !defined(NO_FILESYSTEM) + WOLFSSL_CTX *ctx_c = NULL, *ctx_s = NULL; + WOLFSSL *ssl_c = NULL, *ssl_s = NULL; + struct test_memio_ctx test_ctx; + + /* Only max_fragment_length asked for: the default stays quiet and + * max_fragment_length negotiates as it always did. */ + XMEMSET(&test_ctx, 0, sizeof(test_ctx)); + ExpectIntEQ(test_memio_setup(&test_ctx, &ctx_c, &ctx_s, &ssl_c, &ssl_s, + wolfTLSv1_3_client_method, wolfTLSv1_3_server_method), 0); + ExpectIntEQ(wolfSSL_UseMaxFragment(ssl_c, WOLFSSL_MFL_2_9), + WOLFSSL_SUCCESS); + ExpectIntEQ(test_memio_do_handshake(ssl_c, ssl_s, 10, NULL), 0); + if (ssl_c != NULL) { + ExpectIntEQ(ssl_c->max_fragment, 512); + ExpectIntEQ(ssl_c->peerRecordSizeLimit, 0); + } + + wolfSSL_free(ssl_c); ssl_c = NULL; + wolfSSL_free(ssl_s); ssl_s = NULL; + wolfSSL_CTX_free(ctx_c); ctx_c = NULL; + wolfSSL_CTX_free(ctx_s); ctx_s = NULL; + + /* Both asked for explicitly: RFC 8449 Sect. 5 gives it to + * record_size_limit and the server drops the max_fragment_length. */ + XMEMSET(&test_ctx, 0, sizeof(test_ctx)); + ExpectIntEQ(test_memio_setup(&test_ctx, &ctx_c, &ctx_s, &ssl_c, &ssl_s, + wolfTLSv1_3_client_method, wolfTLSv1_3_server_method), 0); + ExpectIntEQ(wolfSSL_UseMaxFragment(ssl_c, WOLFSSL_MFL_2_9), + WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_UseRecordSizeLimit(ssl_c, 700), WOLFSSL_SUCCESS); + ExpectIntEQ(test_memio_do_handshake(ssl_c, ssl_s, 10, NULL), 0); + if (ssl_s != NULL) + ExpectIntEQ(ssl_s->peerRecordSizeLimit, 700); + if (ssl_c != NULL) + ExpectIntEQ(ssl_c->max_fragment, MAX_RECORD_SIZE); + + wolfSSL_free(ssl_c); + wolfSSL_free(ssl_s); + wolfSSL_CTX_free(ctx_c); + wolfSSL_CTX_free(ctx_s); +#endif + return EXPECT_RESULT(); +} + +/* A small negotiated record_size_limit forces EncryptedExtensions and + * NewSessionTicket across several records. Self-checking: the client enforces + * the limit it advertised on receipt, so an unfragmented message from the + * server fails the handshake or the ticket read right here. */ +int test_tls13_record_size_limit_fragment(void) +{ + EXPECT_DECLS; +#if defined(WOLFSSL_TLS13) && defined(HAVE_RECORD_SIZE_LIMIT) && \ + defined(HAVE_MANUAL_MEMIO_TESTS_DEPENDENCIES) && !defined(NO_CERTS) && \ + !defined(NO_RSA) && !defined(NO_WOLFSSL_CLIENT) && \ + !defined(NO_WOLFSSL_SERVER) && !defined(NO_FILESYSTEM) + /* 64 is the RFC 8449 Sect. 4 floor - every server flight has to be split + * at that size. 300 lands between the two: large enough for a handshake + * message to fit, small enough for a session ticket not to. */ + static const word16 limits[] = { 64, 300 }; + size_t i; + + for (i = 0; i < sizeof(limits) / sizeof(limits[0]); i++) { + WOLFSSL_CTX *ctx_c = NULL, *ctx_s = NULL; + WOLFSSL *ssl_c = NULL, *ssl_s = NULL; + struct test_memio_ctx test_ctx; + char readBuf[64]; + + XMEMSET(&test_ctx, 0, sizeof(test_ctx)); + ExpectIntEQ(test_memio_setup(&test_ctx, &ctx_c, &ctx_s, &ssl_c, &ssl_s, + wolfTLSv1_3_client_method, wolfTLSv1_3_server_method), 0); + /* Both ends: RFC 8449 Sect. 4 only negotiates the extension when + * both send it, and a server with no limit of its own stays silent. */ + ExpectIntEQ(wolfSSL_UseRecordSizeLimit(ssl_c, limits[i]), + WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_UseRecordSizeLimit(ssl_s, limits[i]), + WOLFSSL_SUCCESS); + /* Asking for a client certificate puts a CertificateRequest in the + * server's flight, which is the only message fragmented with + * hashOutput set - EncryptedExtensions is too, but NewSessionTicket + * is not, so without this the transcript-hashing side of + * SendTls13FragmentedMsg() goes unexercised. */ + ExpectTrue(wolfSSL_CTX_load_verify_locations(ctx_s, cliCertFile, 0) + == WOLFSSL_SUCCESS); + if (ssl_s != NULL) + wolfSSL_set_verify(ssl_s, WOLFSSL_VERIFY_PEER, NULL); + ExpectTrue(wolfSSL_use_certificate_file(ssl_c, cliCertFile, + CERT_FILETYPE) == WOLFSSL_SUCCESS); + ExpectTrue(wolfSSL_use_PrivateKey_file(ssl_c, cliKeyFile, + CERT_FILETYPE) == WOLFSSL_SUCCESS); + + /* Generous round count: at 64 bytes a certificate chain alone is + * dozens of records. */ + ExpectIntEQ(test_memio_do_handshake(ssl_c, ssl_s, 128, NULL), 0); + /* Proves the limit is actually in force on the server's send side + * rather than silently ignored. The limit is payload, so it is the + * output size directly. */ + ExpectIntEQ(wolfSSL_GetMaxOutputSize(ssl_s), limits[i]); + + /* Drives the post-handshake read so NewSessionTicket is parsed under + * the same enforcement. */ + ExpectIntEQ(wolfSSL_read(ssl_c, readBuf, (int)sizeof(readBuf)), -1); + ExpectIntEQ(wolfSSL_get_error(ssl_c, -1), WOLFSSL_ERROR_WANT_READ); - /* Corrupt the server-side cookie secret after HRR so CH2's cookie no longer - * verifies in TlsCheckCookie(). */ - if (EXPECT_SUCCESS()) { - ExpectNotNull(ssl_s->buffers.tls13CookieSecret.buffer); - ExpectIntGT(ssl_s->buffers.tls13CookieSecret.length, 0); - ssl_s->buffers.tls13CookieSecret.buffer[ - ssl_s->buffers.tls13CookieSecret.length - 1] ^= 0xFF; + wolfSSL_free(ssl_c); + wolfSSL_free(ssl_s); + wolfSSL_CTX_free(ctx_c); + wolfSSL_CTX_free(ctx_s); } - - /* Step 4: Server processes corrupted CH2 - should fail */ - ExpectIntNE(wolfSSL_accept(ssl_s), WOLFSSL_SUCCESS); - ExpectIntEQ(wolfSSL_get_error(ssl_s, WOLFSSL_FATAL_ERROR), - WC_NO_ERR_TRACE(HRR_COOKIE_ERROR)); - - wolfSSL_free(ssl_c); - wolfSSL_CTX_free(ctx_c); - wolfSSL_free(ssl_s); - wolfSSL_CTX_free(ctx_s); #endif return EXPECT_RESULT(); } -/* Run a handshake where the server sends a cookie in its HelloRetryRequest: - * the client must echo it back for the server to accept the second - * ClientHello. With noKeyShares the retry also asks for a different group, - * without it the cookie is the only thing the retry changes. */ -static int test_tls13_hrr_cookie_handshake_once(int noKeyShares) +/* Test the record_size_limit extension (RFC 8449). + * + * The client states the largest record it will accept, the server echoes its + * own in EncryptedExtensions, and from then on each end caps what it sends to + * the other's limit. The count covers the whole TLS 1.3 TLSInnerPlaintext, so + * a record's payload is one byte short of the limit. */ +int test_tls13_record_size_limit(void) { EXPECT_DECLS; -#if defined(WOLFSSL_TLS13) && \ - defined(HAVE_MANUAL_MEMIO_TESTS_DEPENDENCIES) && \ - defined(WOLFSSL_SEND_HRR_COOKIE) && \ - !defined(NO_WOLFSSL_CLIENT) && !defined(NO_WOLFSSL_SERVER) - WOLFSSL_CTX *ctx_c = NULL; - WOLFSSL_CTX *ctx_s = NULL; - WOLFSSL *ssl_c = NULL; - WOLFSSL *ssl_s = NULL; +#if defined(WOLFSSL_TLS13) && defined(HAVE_RECORD_SIZE_LIMIT) && \ + defined(HAVE_MANUAL_MEMIO_TESTS_DEPENDENCIES) && !defined(NO_CERTS) && \ + !defined(NO_RSA) && !defined(NO_WOLFSSL_CLIENT) && \ + !defined(NO_WOLFSSL_SERVER) && !defined(NO_FILESYSTEM) + WOLFSSL_CTX *ctx_c = NULL, *ctx_s = NULL; + WOLFSSL *ssl_c = NULL, *ssl_s = NULL; struct test_memio_ctx test_ctx; + /* An unsolicited response is an unsupported_extension abort: no + * ClientHello was built on this object, so nothing was offered yet. + * WOLFSSL_OLD_UNSUPPORTED_EXTENSION does not change that here: its + * leniency is for TLS 1.2 and earlier, and this is a TLS 1.3 client. */ + if (EXPECT_SUCCESS()) { + WOLFSSL_CTX* uctx = NULL; + WOLFSSL* ussl = NULL; + static const byte resp[] = { 0x00, 0x1c, 0x00, 0x02, 0x04, 0x00 }; + + ExpectNotNull(uctx = wolfSSL_CTX_new(wolfTLSv1_3_client_method())); + ExpectNotNull(ussl = wolfSSL_new(uctx)); + ExpectIntEQ(TLSX_Parse(ussl, resp, (word16)sizeof(resp), + encrypted_extensions, NULL), + WC_NO_ERR_TRACE(UNSUPPORTED_EXTENSION)); + wolfSSL_free(ussl); + wolfSSL_CTX_free(uctx); + } + + /* Malformed on the wire, on objects of their own: TLSX_Parse() records + * state on the object it is handed, so these must not share one with the + * handshakes below. A value under 64 is a fatal illegal_parameter + * (RFC 8449 Sect. 4) and a wrong length is a decode error. */ + if (EXPECT_SUCCESS()) { + WOLFSSL_CTX* pctx = NULL; + WOLFSSL* pssl = NULL; + static const byte tooSmall[] = { 0x00, 0x1c, 0x00, 0x02, 0x00, 0x3f }; + static const byte badLen[] = { 0x00, 0x1c, 0x00, 0x01, 0x02 }; + static const byte badLen3[] = { 0x00, 0x1c, 0x00, 0x03, 0x02, 0x00, + 0x00 }; + + ExpectNotNull(pctx = wolfSSL_CTX_new(wolfTLSv1_3_server_method())); + ExpectTrue(wolfSSL_CTX_use_certificate_file(pctx, svrCertFile, + CERT_FILETYPE)); + ExpectTrue(wolfSSL_CTX_use_PrivateKey_file(pctx, svrKeyFile, + CERT_FILETYPE)); + ExpectNotNull(pssl = wolfSSL_new(pctx)); + ExpectIntEQ(TLSX_Parse(pssl, tooSmall, (word16)sizeof(tooSmall), + client_hello, (Suites*)WOLFSSL_SUITES(pssl)), + WC_NO_ERR_TRACE(INVALID_PARAMETER)); + ExpectIntEQ(TLSX_Parse(pssl, badLen, (word16)sizeof(badLen), + client_hello, (Suites*)WOLFSSL_SUITES(pssl)), + WC_NO_ERR_TRACE(BUFFER_ERROR)); + ExpectIntEQ(TLSX_Parse(pssl, badLen3, (word16)sizeof(badLen3), + client_hello, (Suites*)WOLFSSL_SUITES(pssl)), + WC_NO_ERR_TRACE(BUFFER_ERROR)); + wolfSSL_free(pssl); + wolfSSL_CTX_free(pctx); + } + XMEMSET(&test_ctx, 0, sizeof(test_ctx)); ExpectIntEQ(test_memio_setup(&test_ctx, &ctx_c, &ctx_s, &ssl_c, &ssl_s, wolfTLSv1_3_client_method, wolfTLSv1_3_server_method), 0); - ExpectIntEQ(wolfSSL_send_hrr_cookie(ssl_s, NULL, 0), WOLFSSL_SUCCESS); - if (noKeyShares) { - ExpectIntEQ(wolfSSL_NoKeyShares(ssl_c), WOLFSSL_SUCCESS); - } + /* Out of range values are refused: below the RFC minimum of 64, and above + * the largest payload, 2^14 (the wire value adds the content type byte at + * TLS 1.3). */ + ExpectIntEQ(wolfSSL_UseRecordSizeLimit(NULL, 512), + WC_NO_ERR_TRACE(BAD_FUNC_ARG)); + ExpectIntEQ(wolfSSL_UseRecordSizeLimit(ssl_c, 63), + WC_NO_ERR_TRACE(BAD_FUNC_ARG)); + /* 0 is not "too small", it is the way to stop advertising. */ + ExpectIntEQ(wolfSSL_UseRecordSizeLimit(ssl_c, 0), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_UseRecordSizeLimit(ssl_c, + WOLFSSL_RECORD_SIZE_LIMIT_MAX + 1), WC_NO_ERR_TRACE(BAD_FUNC_ARG)); + ExpectIntEQ(wolfSSL_UseRecordSizeLimit(ssl_c, + WOLFSSL_RECORD_SIZE_LIMIT_MAX), WOLFSSL_SUCCESS); + + ExpectIntEQ(wolfSSL_UseRecordSizeLimit(ssl_c, 512), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_UseRecordSizeLimit(ssl_s, 1024), WOLFSSL_SUCCESS); ExpectIntEQ(test_memio_do_handshake(ssl_c, ssl_s, 10, NULL), 0); - /* Client saw a cookie and the server accepted the one echoed back. */ - ExpectIntEQ(ssl_c->options.hrrSentCookie, 1); - ExpectIntEQ(ssl_s->options.cookieGood, 1); - ExpectIntEQ(ssl_c->options.hrrSentKeyShare, noKeyShares ? 1 : 0); + /* Too late to change: the value was advertised and is being enforced, so + * tightening it now would reject records the peer is entitled to send. */ + ExpectIntEQ(wolfSSL_UseRecordSizeLimit(ssl_c, 256), + WC_NO_ERR_TRACE(BAD_FUNC_ARG)); + ExpectIntEQ(wolfSSL_UseRecordSizeLimit(ssl_s, 256), + WC_NO_ERR_TRACE(BAD_FUNC_ARG)); - wolfSSL_free(ssl_c); - wolfSSL_CTX_free(ctx_c); - wolfSSL_free(ssl_s); - wolfSSL_CTX_free(ctx_s); -#else - (void)noKeyShares; -#endif - return EXPECT_RESULT(); -} + /* Each end learned the other's limit. */ + if (ssl_c != NULL) + ExpectIntEQ(ssl_c->peerRecordSizeLimit, 1024); + if (ssl_s != NULL) + ExpectIntEQ(ssl_s->peerRecordSizeLimit, 512); -/* HelloRetryRequest carrying both a key share and a cookie. */ -int test_tls13_hrr_cookie_handshake(void) -{ - return test_tls13_hrr_cookie_handshake_once(1); -} + /* And caps what it sends to it. Both ends name the same number because + * the limit is a payload size at this level; the content type byte lives + * only in the extension's encoding. */ + ExpectIntEQ(wolfSSL_GetMaxOutputSize(ssl_s), 512); + ExpectIntEQ(wolfSSL_GetMaxOutputSize(ssl_c), 1024); -/* HelloRetryRequest whose only change is the cookie. This is what a server - * sends when it wants the client's address confirmed and the offered key - * share was already usable. */ -int test_tls13_hrr_cookie_only_handshake(void) -{ - return test_tls13_hrr_cookie_handshake_once(0); -} + wolfSSL_free(ssl_c); ssl_c = NULL; + wolfSSL_free(ssl_s); ssl_s = NULL; + wolfSSL_CTX_free(ctx_c); ctx_c = NULL; + wolfSSL_CTX_free(ctx_s); ctx_s = NULL; -/* Test that a client stores a cookie received in a HelloRetryRequest and - * writes it back out in the second ClientHello. Required of every TLS 1.3 - * client by RFC 8446 4.2.2, so it must hold without WOLFSSL_SEND_HRR_COOKIE, - * which only controls a server creating cookies. */ -int test_tls13_client_cookie_echo(void) -{ - EXPECT_DECLS; -#if defined(WOLFSSL_TLS13) && !defined(NO_WOLFSSL_CLIENT) - WOLFSSL_CTX* ctx = NULL; - WOLFSSL* ssl = NULL; - TLSX* ext = NULL; - Cookie* cookie = NULL; - word32 length = 0; - word32 offset = 0; - byte out[128]; - /* Cookie extension of a HelloRetryRequest: type, extension length, - * cookie length, cookie. */ - static const byte hrrExt[] = { - 0x00, 0x2c, 0x00, 0x08, 0x00, 0x06, 'w', 'o', 'l', 'f', 'S', 'L' - }; + /* The RFC minimum of 64 works end to end. It fragments the flight hard, + * so the exchange needs many more round trips than a normal handshake, + * which is the point of pinning it. */ + XMEMSET(&test_ctx, 0, sizeof(test_ctx)); + ExpectIntEQ(test_memio_setup(&test_ctx, &ctx_c, &ctx_s, &ssl_c, &ssl_s, + wolfTLSv1_3_client_method, wolfTLSv1_3_server_method), 0); + ExpectIntEQ(wolfSSL_UseRecordSizeLimit(ssl_c, + WOLFSSL_RECORD_SIZE_LIMIT_MIN), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_UseRecordSizeLimit(ssl_s, + WOLFSSL_RECORD_SIZE_LIMIT_MIN), WOLFSSL_SUCCESS); + ExpectIntEQ(test_memio_do_handshake(ssl_c, ssl_s, 200, NULL), 0); + ExpectIntEQ(wolfSSL_GetMaxOutputSize(ssl_c), + WOLFSSL_RECORD_SIZE_LIMIT_MIN); + ExpectIntEQ(wolfSSL_GetMaxOutputSize(ssl_s), + WOLFSSL_RECORD_SIZE_LIMIT_MIN); - XMEMSET(out, 0, sizeof(out)); + wolfSSL_free(ssl_c); ssl_c = NULL; + wolfSSL_free(ssl_s); ssl_s = NULL; + wolfSSL_CTX_free(ctx_c); ctx_c = NULL; + wolfSSL_CTX_free(ctx_s); ctx_s = NULL; - ExpectNotNull(ctx = wolfSSL_CTX_new(wolfTLSv1_3_client_method())); - ExpectNotNull(ssl = wolfSSL_new(ctx)); + /* Only this end advertises. The peer answers nothing, so the limits are + * not negotiated and must not be enforced: enforcing on advertisement + * alone terminated every handshake with a peer lacking RFC 8449, which is + * how OpenSSL and BoringSSL behave today. */ + XMEMSET(&test_ctx, 0, sizeof(test_ctx)); + ExpectIntEQ(test_memio_setup(&test_ctx, &ctx_c, &ctx_s, &ssl_c, &ssl_s, + wolfTLSv1_3_client_method, wolfTLSv1_3_server_method), 0); + ExpectIntEQ(wolfSSL_UseRecordSizeLimit(ssl_c, 512), WOLFSSL_SUCCESS); + /* A limit is advertised by default now, so the server is silenced + * explicitly with 0 rather than by leaving it unset. */ + ExpectIntEQ(wolfSSL_UseRecordSizeLimit(ssl_s, 0), WOLFSSL_SUCCESS); + ExpectIntEQ(test_memio_do_handshake(ssl_c, ssl_s, 10, NULL), 0); + if (ssl_c != NULL) { + ExpectIntEQ(ssl_c->recordSizeLimit, 512); + ExpectIntEQ(ssl_c->peerRecordSizeLimit, 0); + } + /* Nothing learned, so nothing capped. */ + ExpectIntEQ(wolfSSL_GetMaxOutputSize(ssl_c), MAX_RECORD_SIZE); + /* And the other direction, which is the half that looks like a bug and + * is not: the server saw the client's 512 but answered nothing, so + * RFC 8449 Sect. 4 leaves it unbound - "When the record_size_limit + * extension is negotiated, an endpoint MUST NOT generate a protected + * record with plaintext that is larger than the RecordSizeLimit value it + * receives from its peer", and "If this extension is not negotiated, + * endpoints can send records of any size permitted by the protocol". The + * duty follows negotiation, not receipt, so a server that declined to + * advertise keeps sending full records and does not retain the value. + * Retaining it would let any client shrink a server that never opted in + * down to 64-byte records. */ + if (ssl_s != NULL) + ExpectIntEQ(ssl_s->peerRecordSizeLimit, 0); + ExpectIntEQ(wolfSSL_GetMaxOutputSize(ssl_s), MAX_RECORD_SIZE); - ExpectIntEQ(TLSX_Parse(ssl, hrrExt, (word16)sizeof(hrrExt), - hello_retry_request, NULL), 0); + wolfSSL_free(ssl_c); ssl_c = NULL; + wolfSSL_free(ssl_s); ssl_s = NULL; + wolfSSL_CTX_free(ctx_c); ctx_c = NULL; + wolfSSL_CTX_free(ctx_s); ctx_s = NULL; - ExpectNotNull(ext = TLSX_Find(ssl->extensions, TLSX_COOKIE)); - if (EXPECT_SUCCESS()) { - ExpectNotNull(cookie = (Cookie*)ext->data); - } - if (EXPECT_SUCCESS()) { - ExpectIntEQ(cookie->len, sizeof(hrrExt) - 6); - ExpectBufEQ(cookie->data, hrrExt + 6, sizeof(hrrExt) - 6); - } + /* Turned off on both ends: nothing is advertised and nothing is capped. */ + XMEMSET(&test_ctx, 0, sizeof(test_ctx)); + ExpectIntEQ(test_memio_setup(&test_ctx, &ctx_c, &ctx_s, &ssl_c, &ssl_s, + wolfTLSv1_3_client_method, wolfTLSv1_3_server_method), 0); + ExpectIntEQ(wolfSSL_UseRecordSizeLimit(ssl_c, 0), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_UseRecordSizeLimit(ssl_s, 0), WOLFSSL_SUCCESS); + ExpectIntEQ(test_memio_do_handshake(ssl_c, ssl_s, 10, NULL), 0); + if (ssl_c != NULL) + ExpectIntEQ(ssl_c->peerRecordSizeLimit, 0); + ExpectIntEQ(wolfSSL_GetMaxOutputSize(ssl_c), MAX_RECORD_SIZE); - ExpectIntEQ(TLSX_GetRequestSize(ssl, client_hello, &length), 0); - ExpectIntGT(length, 0); - ExpectIntLE(length, (word32)sizeof(out)); - if (EXPECT_SUCCESS()) { - ExpectIntEQ(TLSX_WriteRequest(ssl, out, client_hello, &offset), 0); - ExpectIntEQ(offset, length); - } - if (EXPECT_SUCCESS()) { - int found = 0; - word32 i; + wolfSSL_free(ssl_c); ssl_c = NULL; + wolfSSL_free(ssl_s); ssl_s = NULL; + wolfSSL_CTX_free(ctx_c); ctx_c = NULL; + wolfSSL_CTX_free(ctx_s); ctx_s = NULL; - for (i = 0; i + sizeof(hrrExt) <= offset; i++) { - if (XMEMCMP(out + i, hrrExt, sizeof(hrrExt)) == 0) { - found = 1; - break; - } - } - ExpectIntEQ(found, 1); - } + /* Left alone, both ends advertise the default and negotiate it, which is + * what makes the extension useful without the application asking. */ + XMEMSET(&test_ctx, 0, sizeof(test_ctx)); + ExpectIntEQ(test_memio_setup(&test_ctx, &ctx_c, &ctx_s, &ssl_c, &ssl_s, + wolfTLSv1_3_client_method, wolfTLSv1_3_server_method), 0); + ExpectIntEQ(test_memio_do_handshake(ssl_c, ssl_s, 10, NULL), 0); + if (ssl_c != NULL) + ExpectIntEQ(ssl_c->peerRecordSizeLimit, + WOLFSSL_RECORD_SIZE_LIMIT_DEFAULT); + if (ssl_s != NULL) + ExpectIntEQ(ssl_s->peerRecordSizeLimit, + WOLFSSL_RECORD_SIZE_LIMIT_DEFAULT); + /* The default is a full record's worth of payload, and payload is the + * unit, so it survives the round trip unchanged. A default that cost a + * byte would fail here. */ + ExpectIntEQ(wolfSSL_GetMaxOutputSize(ssl_c), + WOLFSSL_RECORD_SIZE_LIMIT_DEFAULT); + ExpectIntEQ(wolfSSL_GetMaxOutputSize(ssl_c), MAX_RECORD_SIZE); + + wolfSSL_free(ssl_c); ssl_c = NULL; + wolfSSL_free(ssl_s); ssl_s = NULL; + wolfSSL_CTX_free(ctx_c); ctx_c = NULL; + wolfSSL_CTX_free(ctx_s); ctx_s = NULL; - wolfSSL_free(ssl); - wolfSSL_CTX_free(ctx); #endif return EXPECT_RESULT(); } -/* Test that a client rejects a HelloRetryRequest cookie larger than it is - * willing to store and echo back. RFC 8446 4.2.2 allows up to 2^16-1 bytes; - * WOLFSSL_MAX_TLS13_COOKIE_SZ is the smaller local cap tested here. - * One byte over the cap plus the six bytes of extension headers must still - * fit the word16 length TLSX_Parse() takes: 65535 - 1 - 6 = 65528. */ -int test_tls13_client_cookie_too_big(void) +/* Test that each extension added recently is refused in messages it is not + * listed for. + * + * Twice in developing these an extension leaked into EncryptedExtensions and + * only an interop run caught it, because a peer that ignores an unexpected + * extension will still complete the handshake. Checking the receive gate is + * the cheap half of that; a wolfSSL peer rejecting the message is what turns + * a send-side leak into a visible failure. */ +int test_tls13_new_ext_placement(void) { EXPECT_DECLS; -#if defined(WOLFSSL_TLS13) && !defined(NO_WOLFSSL_CLIENT) && \ - WOLFSSL_MAX_TLS13_COOKIE_SZ <= 65528 +#if defined(WOLFSSL_TLS13) && !defined(NO_WOLFSSL_SERVER) && \ + !defined(NO_FILESYSTEM) && !defined(NO_CERTS) && \ + (!defined(NO_RSA) || defined(HAVE_ECC)) WOLFSSL_CTX* ctx = NULL; WOLFSSL* ssl = NULL; - byte* hrrExt = NULL; - const word16 cookieLen = WOLFSSL_MAX_TLS13_COOKIE_SZ + 1; - const word16 extLen = cookieLen + OPAQUE16_LEN; - const word32 totalLen = (word32)extLen + OPAQUE16_LEN * 2; + Suites* suites = NULL; +#ifdef HAVE_SNI + /* server_name: CH, EE, CR. */ + static const byte sni[] = { + 0x00, 0x00, 0x00, 0x10, 0x00, 0x0e, 0x00, 0x00, 0x0b, + 'w', 'o', 'l', 'f', 's', 's', 'l', '.', 'c', 'o', 'm' + }; +#endif +#ifdef HAVE_RECORD_SIZE_LIMIT + /* record_size_limit: CH, EE. */ + static const byte rsl[] = { 0x00, 0x1c, 0x00, 0x02, 0x02, 0x00 }; +#endif - ExpectNotNull(ctx = wolfSSL_CTX_new(wolfTLSv1_3_client_method())); + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfTLSv1_3_server_method())); + /* The certificate exists only so wolfSSL_new() succeeds for a server + * object - nothing below sends one - so use whichever algorithm the + * build has. svrCertFile is RSA, which a build without RSA cannot + * load. */ +#ifndef NO_RSA + ExpectTrue(wolfSSL_CTX_use_certificate_file(ctx, svrCertFile, + CERT_FILETYPE)); + ExpectTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, svrKeyFile, + CERT_FILETYPE)); +#else + ExpectTrue(wolfSSL_CTX_use_certificate_file(ctx, eccCertFile, + CERT_FILETYPE)); + ExpectTrue(wolfSSL_CTX_use_PrivateKey_file(ctx, eccKeyFile, + CERT_FILETYPE)); +#endif ExpectNotNull(ssl = wolfSSL_new(ctx)); + if (ssl != NULL) + suites = (Suites*)WOLFSSL_SUITES(ssl); + /* Every use below sits behind one of the extension macros, so a build with + * none of them leaves this set and never read. */ + (void)suites; + +#ifdef HAVE_SNI + ExpectIntEQ(TLSX_Parse(ssl, sni, (word16)sizeof(sni), client_hello, + suites), 0); + ExpectIntEQ(TLSX_Parse(ssl, sni, (word16)sizeof(sni), session_ticket, + NULL), WC_NO_ERR_TRACE(EXT_NOT_ALLOWED)); +#endif +#ifdef HAVE_RECORD_SIZE_LIMIT + ExpectIntEQ(TLSX_Parse(ssl, rsl, (word16)sizeof(rsl), client_hello, + suites), 0); + /* Listed for CH and EE, so a CertificateRequest is refused. */ + ExpectIntEQ(TLSX_Parse(ssl, rsl, (word16)sizeof(rsl), certificate_request, + suites), WC_NO_ERR_TRACE(EXT_NOT_ALLOWED)); + ExpectIntEQ(TLSX_Parse(ssl, rsl, (word16)sizeof(rsl), session_ticket, + NULL), WC_NO_ERR_TRACE(EXT_NOT_ALLOWED)); +#endif - ExpectNotNull(hrrExt = (byte*)XMALLOC(totalLen, NULL, - DYNAMIC_TYPE_TMP_BUFFER)); - if (EXPECT_SUCCESS()) { - XMEMSET(hrrExt, 0, totalLen); - c16toa(TLSX_COOKIE, hrrExt); - c16toa(extLen, hrrExt + OPAQUE16_LEN); - c16toa(cookieLen, hrrExt + OPAQUE16_LEN * 2); - } - - ExpectIntEQ(TLSX_Parse(ssl, hrrExt, (word16)totalLen, hello_retry_request, - NULL), WC_NO_ERR_TRACE(HRR_COOKIE_ERROR)); - ExpectNull(TLSX_Find(ssl->extensions, TLSX_COOKIE)); - - XFREE(hrrExt, NULL, DYNAMIC_TYPE_TMP_BUFFER); wolfSSL_free(ssl); wolfSSL_CTX_free(ctx); #endif @@ -18078,6 +19327,56 @@ int test_tls13_export_server_ticket_after_import(void) return EXPECT_RESULT(); } +/* The export format does not carry the RFC 8449 limits, so a session whose + * limits restrict anything is refused rather than exported to be imported as + * a copy that ignores them. The defaults are the protocol maximum, which an + * imported copy enforces anyway, so they do not stop an export. */ +int test_tls13_record_size_limit_export(void) +{ + EXPECT_DECLS; +#if defined(TEST_TLS13_EXPORT) && defined(HAVE_RECORD_SIZE_LIMIT) + struct test_memio_ctx test_ctx; + WOLFSSL_CTX *ctx_c = NULL, *ctx_s = NULL; + WOLFSSL *ssl_c = NULL, *ssl_s = NULL; + unsigned char* session = NULL; + unsigned int sessionSz = 0; + + /* Default limits on both ends: exported as before. */ + ExpectIntEQ(test_tls13_export_connect(&test_ctx, &ctx_c, &ctx_s, &ssl_c, + &ssl_s), TEST_SUCCESS); + if (ssl_s != NULL) + ExpectIntNE(ssl_s->peerRecordSizeLimit, 0); + ExpectIntEQ(test_tls13_export_alloc(ssl_s, &session, &sessionSz), + TEST_SUCCESS); + XFREE(session, NULL, DYNAMIC_TYPE_TMP_BUFFER); + session = NULL; + wolfSSL_free(ssl_c); ssl_c = NULL; + wolfSSL_free(ssl_s); ssl_s = NULL; + wolfSSL_CTX_free(ctx_c); ctx_c = NULL; + wolfSSL_CTX_free(ctx_s); ctx_s = NULL; + + /* The client asks for 512 byte records: that binds the server's sends + * and the client's receives, so neither end can be exported. */ + XMEMSET(&test_ctx, 0, sizeof(test_ctx)); + ExpectIntEQ(test_memio_setup(&test_ctx, &ctx_c, &ctx_s, &ssl_c, &ssl_s, + wolfTLSv1_3_client_method, wolfTLSv1_3_server_method), 0); + ExpectIntEQ(wolfSSL_UseRecordSizeLimit(ssl_c, 512), WOLFSSL_SUCCESS); + ExpectIntEQ(test_memio_do_handshake(ssl_c, ssl_s, 10, NULL), 0); + sessionSz = 0; + ExpectIntEQ(wolfSSL_tls_export(ssl_s, NULL, &sessionSz), + WC_NO_ERR_TRACE(BAD_STATE_E)); + sessionSz = 0; + ExpectIntEQ(wolfSSL_tls_export(ssl_c, NULL, &sessionSz), + WC_NO_ERR_TRACE(BAD_STATE_E)); + + wolfSSL_free(ssl_c); + wolfSSL_free(ssl_s); + wolfSSL_CTX_free(ctx_c); + wolfSSL_CTX_free(ctx_s); +#endif + return EXPECT_RESULT(); +} + int test_tls13_export_client_ticket_after_import(void) { EXPECT_DECLS; diff --git a/tests/api/test_tls13.h b/tests/api/test_tls13.h index 7d5350a19e2..eb84b21960f 100644 --- a/tests/api/test_tls13.h +++ b/tests/api/test_tls13.h @@ -212,6 +212,7 @@ int test_tls13_early_secret_zeroized(void); int test_tls13_psk_key_zeroized(void); int test_tls13_export_server_ticket_after_import(void); int test_tls13_export_client_ticket_after_import(void); +int test_tls13_record_size_limit_export(void); int test_tls13_export_server_key_update(void); int test_tls13_export_client_key_update(void); int test_tls13_export_keeps_fatal_alert(void); @@ -222,6 +223,18 @@ int test_tls13_cks_hrr_reparse(void); int test_tls13_update_keys_want_write(void); int test_tls13_AEAD_limit_KeyUpdate_want_write(void); int test_tls13_exporter_suite_decision_coverage(void); +int test_tls13_record_size_limit_ctx(void); +int test_tls13_record_size_limit_early_data(void); +int test_tls13_record_size_limit_early_data_rejected(void); +int test_tls12_record_size_limit_overflow(void); +int test_tls12_record_size_limit_plaintext(void); +int test_tls13_cert_req_ctx_record_size_limit(void); +int test_tls13_record_size_limit_overflow(void); +int test_tls13_record_size_limit_both_exts(void); +int test_tls13_record_size_limit_vs_mfl(void); +int test_tls13_record_size_limit_fragment(void); +int test_tls13_record_size_limit(void); +int test_tls13_new_ext_placement(void); #define TEST_TLS13_DECLS \ TEST_DECL_GROUP("tls13", test_tls13_apis), \ @@ -410,6 +423,7 @@ int test_tls13_exporter_suite_decision_coverage(void); TEST_DECL_GROUP("tls13", test_tls13_psk_key_zeroized), \ TEST_DECL_GROUP("tls13", test_tls13_export_server_ticket_after_import), \ TEST_DECL_GROUP("tls13", test_tls13_export_client_ticket_after_import), \ + TEST_DECL_GROUP("tls13", test_tls13_record_size_limit_export), \ TEST_DECL_GROUP("tls13", test_tls13_export_server_key_update), \ TEST_DECL_GROUP("tls13", test_tls13_export_client_key_update), \ TEST_DECL_GROUP("tls13", test_tls13_export_keeps_fatal_alert), \ @@ -422,6 +436,19 @@ int test_tls13_exporter_suite_decision_coverage(void); TEST_DECL_GROUP("tls13", test_tls13_exporter_suite_decision_coverage), \ TEST_DECL_GROUP("tls13", test_tls13_ecdsa_scheme_curve_binding), \ TEST_DECL_GROUP("tls13", test_tls13_new_session_ticket_max_fragment), \ - TEST_DECL_GROUP("tls13", test_tls13_psk_cb_no_cipher_name) + TEST_DECL_GROUP("tls13", test_tls13_psk_cb_no_cipher_name), \ + TEST_DECL_GROUP("tls13", test_tls13_record_size_limit_ctx), \ + TEST_DECL_GROUP("tls13", test_tls13_record_size_limit_early_data), \ + TEST_DECL_GROUP("tls13", \ + test_tls13_record_size_limit_early_data_rejected), \ + TEST_DECL_GROUP("tls13", test_tls12_record_size_limit_overflow), \ + TEST_DECL_GROUP("tls13", test_tls12_record_size_limit_plaintext), \ + TEST_DECL_GROUP("tls13", test_tls13_cert_req_ctx_record_size_limit), \ + TEST_DECL_GROUP("tls13", test_tls13_record_size_limit_overflow), \ + TEST_DECL_GROUP("tls13", test_tls13_record_size_limit_both_exts), \ + TEST_DECL_GROUP("tls13", test_tls13_record_size_limit_vs_mfl), \ + TEST_DECL_GROUP("tls13", test_tls13_record_size_limit_fragment), \ + TEST_DECL_GROUP("tls13", test_tls13_record_size_limit), \ + TEST_DECL_GROUP("tls13", test_tls13_new_ext_placement) #endif /* WOLFCRYPT_TEST_TLS13_H */ diff --git a/tests/api/test_tls_ext.c b/tests/api/test_tls_ext.c index 5a02b320f1d..07cb0ddeb68 100644 --- a/tests/api/test_tls_ext.c +++ b/tests/api/test_tls_ext.c @@ -2962,6 +2962,12 @@ int test_wolfSSL_CTX_add_client_custom_ext(void) ExpectIntEQ(wolfSSL_CTX_add_client_custom_ext(ctx, 0x0000, test_custom_ext_add_cb, test_custom_ext_free_cb, NULL, test_custom_ext_parse_cb, NULL), 0); +#ifdef HAVE_RECORD_SIZE_LIMIT + /* As is record_size_limit (RFC 8449), when wolfSSL handles it. */ + ExpectIntEQ(wolfSSL_CTX_add_client_custom_ext(ctx, 0x001c, + test_custom_ext_add_cb, test_custom_ext_free_cb, NULL, + test_custom_ext_parse_cb, NULL), 0); +#endif /* free_cb without add_cb is rejected. */ ExpectIntEQ(wolfSSL_CTX_add_client_custom_ext(ctx, TEST_CUSTOM_EXT_TYPE, diff --git a/wolfssl/internal.h b/wolfssl/internal.h index 76e896fa59a..50132a911b2 100644 --- a/wolfssl/internal.h +++ b/wolfssl/internal.h @@ -3384,6 +3384,25 @@ typedef struct Keys { typedef struct Options Options; +#ifdef HAVE_RECORD_SIZE_LIMIT +/* The bound on the value as it appears on the wire, the one unit not exposed + * in ssl.h because no caller needs it: RFC 8449 Sect. 4 lets a TLS 1.3 + * endpoint state at most 2^14+1, the full TLSInnerPlaintext including its + * content type byte. Everything above the wire counts payload instead, and + * TLSX_RecordSizeLimit_Write() and _Parse() are the only places the two units + * meet. The payload-side range and the default live beside the setters in + * wolfssl/ssl.h, where an application can reach them. */ +#define WOLFSSL_RECORD_SIZE_LIMIT_MAX_13 (MAX_RECORD_SIZE + 1) +#endif + +/* The extension lives in the TLSX machinery, so a user_settings.h build + * that defines it without HAVE_TLS_EXTENSIONS gets a pile of undefined + * references rather than a statement of what is missing. configure and CMake + * add it for you; this catches the hand-written case. */ +#if defined(HAVE_RECORD_SIZE_LIMIT) && !defined(HAVE_TLS_EXTENSIONS) +#error "HAVE_RECORD_SIZE_LIMIT requires HAVE_TLS_EXTENSIONS" +#endif + /** TLS Extensions - RFC 6066 */ #ifdef HAVE_TLS_EXTENSIONS @@ -3402,6 +3421,7 @@ typedef struct Options Options; #define TLSXT_SERVER_CERTIFICATE 0x0014 /* RFC8446 */ #define TLSXT_ENCRYPT_THEN_MAC 0x0016 /* RFC 7366 */ #define TLSXT_EXTENDED_MASTER_SECRET 0x0017 /* HELLO_EXT_EXTMS */ +#define TLSXT_RECORD_SIZE_LIMIT 0x001c /* RFC 8449 */ #define TLSXT_CERT_WITH_EXTERN_PSK 0x0021 /* RFC 9973 */ #define TLSXT_SESSION_TICKET 0x0023 #define TLSXT_PRE_SHARED_KEY 0x0029 @@ -3449,6 +3469,9 @@ typedef enum { TLSX_ENCRYPT_THEN_MAC = TLSXT_ENCRYPT_THEN_MAC, #endif TLSX_EXTENDED_MASTER_SECRET = TLSXT_EXTENDED_MASTER_SECRET, +#ifdef HAVE_RECORD_SIZE_LIMIT + TLSX_RECORD_SIZE_LIMIT = TLSXT_RECORD_SIZE_LIMIT, +#endif TLSX_SESSION_TICKET = TLSXT_SESSION_TICKET, #ifdef WOLFSSL_TLS13 #ifdef WOLFSSL_EARLY_DATA @@ -4600,6 +4623,17 @@ struct WOLFSSL_CTX { #endif WOLFSSL_CERT_MANAGER* cm; /* our cert manager, ctx owns SSL will use */ #endif +/* Outside the NO_CERTS section above on purpose: the extension needs no + * certificate, at either version. A PSK-only TLS 1.3 server still sends + * EncryptedExtensions and NewSessionTicket, and record_size_limit governs + * both; a TLS 1.2 build negotiates the extension in the ServerHello with no + * certificate involved either. */ +#ifdef HAVE_RECORD_SIZE_LIMIT + word16 recordSizeLimit; /* largest record we will accept, 0 to + * not advertise a limit */ + byte recordSizeLimitSet; /* application chose it, not the + * default */ +#endif #ifdef KEEP_OUR_CERT WOLFSSL_X509* ourCert; /* keep alive a X509 struct of cert */ int ownOurCert; /* Dispose of certificate if we own */ @@ -7220,6 +7254,21 @@ struct WOLFSSL { word16 certHashSigAlgoSz; /* SigAlgoCert ext length in bytes */ byte* certHashSigAlgo; /* peer's cert sig/algo list */ #endif +#ifdef HAVE_RECORD_SIZE_LIMIT + /* RFC 8449. recordSizeLimit is what this end advertised and so enforces on + * arrival; peerRecordSizeLimit is what the peer advertised and so caps + * what this end sends. Both 0 when the extension was not exchanged. */ + word16 recordSizeLimit; + word16 peerRecordSizeLimit; + /* The value last written into this end's record_size_limit extension, + * including the TLS 1.3 content type byte when that was folded in. A + * client advertises before the version is settled, so this is the only + * record of what the peer was actually told; 0 until it is sent. */ + word16 recordSizeLimitSent; + /* Whether recordSizeLimit came from the application or is the built-in + * default, which decides who yields to max_fragment_length. */ + byte recordSizeLimitSet; +#endif #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) int eccVerifyRes; #endif diff --git a/wolfssl/ssl.h b/wolfssl/ssl.h index de8db68d4af..d7192271ec1 100644 --- a/wolfssl/ssl.h +++ b/wolfssl/ssl.h @@ -1461,7 +1461,23 @@ WOLFSSL_API int wolfSSL_get_peer_signature_type_nid(const WOLFSSL* ssl, WOLFSSL_API int wolfSSL_CTX_set1_sigalgs_list(WOLFSSL_CTX* ctx, const char* list); WOLFSSL_API int wolfSSL_set1_sigalgs_list(WOLFSSL* ssl, const char* list); +#endif /* OPENSSL_EXTRA */ +/* Declared outside the OpenSSL compatibility block: these have their own + * build options and no dependency on it. */ +#ifdef HAVE_RECORD_SIZE_LIMIT +/* Range accepted by the two setters below, in payload bytes, and the value + * that stops the extension being advertised at all. */ +#define WOLFSSL_RECORD_SIZE_LIMIT_OFF 0 +#define WOLFSSL_RECORD_SIZE_LIMIT_MIN 64 +#define WOLFSSL_RECORD_SIZE_LIMIT_MAX 16384 +/* Advertised unless a setter says otherwise. */ +#define WOLFSSL_RECORD_SIZE_LIMIT_DEFAULT WOLFSSL_RECORD_SIZE_LIMIT_MAX + +WOLFSSL_API int wolfSSL_UseRecordSizeLimit(WOLFSSL* ssl, unsigned short limit); +WOLFSSL_API int wolfSSL_CTX_UseRecordSizeLimit(WOLFSSL_CTX* ctx, + unsigned short limit); #endif + WOLFSSL_ABI WOLFSSL_API WOLFSSL* wolfSSL_new(WOLFSSL_CTX* ctx); WOLFSSL_API WOLFSSL_CTX* wolfSSL_get_SSL_CTX(const WOLFSSL* ssl); WOLFSSL_API WOLFSSL_X509_VERIFY_PARAM* wolfSSL_CTX_get0_param(WOLFSSL_CTX* ctx);