Skip to content

Commit 94d76c3

Browse files
authored
fix: harden archive extraction validation (#102)
Stress testing archive extraction found six defects. Drive-relative and NUL archive paths bypassed validation entirely, so a ZIP entry named C:secret.txt or nested/C:secret.txt was accepted — the archive-side sibling of the drive-relative aliasing closed for Root and FileStore in #97. Explicit zero limits silently became defaults, so maxEntries: 0 did not mean zero, and NaN disabled the bounded stream cap. The JavaScript ZIP reader and bounded reads accepted CRC and size mismatches. The JavaScript TAR reader ignored stripped entries when enforcing maxEntries while the native reader counted them. Duplicate names and post-strip output collisions behaved differently depending on which backend ran. Documentation implied secret readers enforce 0o600. They do not: writes enforce modes, and permission-checked reading is readSecureFile. Walk cycle prevention and failedDirs, secret hardlink and pinned-read ordering, secure temp name generation and mode-at-creation, and trash confinement were all verified clean.
1 parent 4696341 commit 94d76c3

18 files changed

Lines changed: 372 additions & 29 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
- Keep the POSIX parent-directory no-follow identity check active for synchronous atomic-replacement adapters that omit `fchmodSync`, preventing the documented default adapter path from writing through a symlinked parent.
88
- Synchronize the actual destination after descriptor-bound mode application when atomic rename uses copy fallback, and include both bytes and mode in bounded fallback restoration.
99
- Continue accepting legacy atomic-replacement adapter literals that expose pathname `chmod` or `chmodSync` methods while keeping those methods unused.
10+
- Reject archive NUL names, drive-relative path segments, duplicate output names (including collisions introduced by `stripComponents`), and ZIP CRC or declared-size mismatches before publishing output. Explicit zero archive limits now remain zero, and stripped TAR entries count toward `maxEntries`, keeping the native and JavaScript policies aligned.
1011

1112
- Reject non-file sidecars without spinning, and read contended async and synchronous sidecar locks through bounded, no-follow, identity-checked descriptors; keep valid `createdAt` timestamps authoritative under filesystem clock skew; fail closed when fallback Windows ACL inspection returns no verifiable access entries; preserve synchronous stale-reclaim guards owned by another acquirer; and share one process-exit cleanup listener across file-lock manager domains.
1213

‎docs/archive.md‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ type ArchiveExtractLimits = {
122122
};
123123
```
124124

125-
Defaults exist for each (`DEFAULT_MAX_ARCHIVE_BYTES_ZIP`, `DEFAULT_MAX_ENTRIES`, `DEFAULT_MAX_EXTRACTED_BYTES`, `DEFAULT_MAX_ENTRY_BYTES`, `DEFAULT_MAX_META_ENTRY_BYTES`, `DEFAULT_MAX_ENTRY_PATH_COMPONENTS`). The path-component default is 256. It is evaluated after `stripComponents` and before TypeScript accepts an entry for either JavaScript or native extraction, so rejected entries cannot cause implicit parent-directory creation. The 1 MiB metadata default matches node-tar's `maxMetaEntrySize`; fs-safe passes the same resolved value to node-tar and the native TAR meter.
125+
Defaults exist for each (`DEFAULT_MAX_ARCHIVE_BYTES_ZIP`, `DEFAULT_MAX_ENTRIES`, `DEFAULT_MAX_EXTRACTED_BYTES`, `DEFAULT_MAX_ENTRY_BYTES`, `DEFAULT_MAX_META_ENTRY_BYTES`, `DEFAULT_MAX_ENTRY_PATH_COMPONENTS`). An explicit zero remains zero rather than selecting the default. `maxEntries` counts every archive entry, including entries removed by `stripComponents` or an explicit filter. The path-component default is 256. It is evaluated after `stripComponents` and before TypeScript accepts an entry for either JavaScript or native extraction, so rejected entries cannot cause implicit parent-directory creation. The 1 MiB metadata default matches node-tar's `maxMetaEntrySize`; fs-safe passes the same resolved value to node-tar and the native TAR meter.
126126

127127
A limit violation throws `ArchiveLimitError`. Its constant and string code are:
128128

@@ -148,10 +148,12 @@ codes remain `"destination-not-directory"`, `"destination-symlink"`, and
148148

149149
## What it defends against
150150

151-
- **Path traversal:** entries with `..`, absolute paths, or Windows drive prefixes are rejected (`ArchiveSecurityError`).
151+
- **Path traversal:** entries with `..`, absolute paths, NUL bytes, or Windows drive-relative segments such as `C:secret` and `nested/C:secret` are rejected (`ArchiveSecurityError`).
152152
- **Symlink/hardlink entries:** rejected by default. Some archives ship symlink/hardlink entries that point outside the destination once resolved; `extractArchive` does not follow them.
153+
- **Ambiguous output names:** duplicate names and distinct names that collide after `stripComponents` are rejected instead of relying on backend-specific overwrite order.
153154
- **TOCTOU during merge:** extraction first writes to a private temp dir, then merges into `destDir` using the same boundary checks as `root().write()`. Destination symlink swaps are checked with the selected platform mechanism; non-Linux routes retain the best-effort race window documented in the [security model](security-model.md#containment-guarantees-by-platform).
154155
- **Zip bombs:** `maxExtractedBytes` and `maxEntryBytes` apply to *post-decompression* bytes, so highly-compressed payloads hit the cap before they exhaust disk.
156+
- **Corrupt ZIP payloads:** streamed output must match both the central-directory CRC and declared uncompressed size before it can leave private staging.
155157
- **Slow-loris archives:** `timeoutMs` is a hard wall-clock budget. Extraction is aborted on overrun.
156158
- **Metadata bombs:** a fixed-header pass-through reader rejects oversized PAX, GNU long-name, and GNU long-link bodies before either TAR implementation buffers them. It understands octal and base-256 size fields without interpreting metadata content.
157159

@@ -208,7 +210,8 @@ await extractArchive({
208210

209211
`readArchiveEntry(archivePath, entryPath, { maxBytes, kind? })` reads one
210212
regular-file entry into a bounded `Buffer` without extracting a tree. It pins
211-
and privately stages the archive input, rejects link and directory entries,
213+
and privately stages the archive input, rejects link, directory, and duplicate
214+
entries, verifies ZIP CRC and declared size,
212215
and throws `ArchiveLimitError` if decompressed bytes exceed `maxBytes`. ZIP
213216
inputs retain the archive subpath's 256 MiB compressed-input ceiling.
214217
With a native binding it uses the same Rust decoders as extraction, including
@@ -252,11 +255,11 @@ import {
252255
} from "@openclaw/fs-safe/archive";
253256
```
254257

255-
- `validateArchiveEntryPath(raw, opts)` — throws `ArchiveSecurityError` for `..`, absolute, drive-prefixed, or otherwise unsafe entry paths.
256-
- `normalizeArchiveEntryPath(raw)` — POSIX-normalizes the entry path (forward slashes, no `.` segments).
258+
- `validateArchiveEntryPath(raw, opts)` — throws `ArchiveSecurityError` for `..`, absolute, NUL-containing, drive-relative, or otherwise unsafe entry paths.
259+
- `normalizeArchiveEntryPath(raw)` — converts backslashes in the entry path to forward slashes.
257260
- `stripArchivePath(entryPath, n)` — strip the leading N path components, returning `null` if not enough remain.
258261
- `resolveArchiveOutputPath({ destDir, entryPath })` — combines the entry path with the destination, after validation.
259-
- `isWindowsDrivePath(value)` — detects `C:\…` style entries that should be rejected.
262+
- `isWindowsDrivePath(value)` — detects drive-relative segments such as `C:secret` or `nested/C:secret` that should be rejected.
260263

261264
## Common patterns
262265

‎docs/secret-file.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,12 @@ itself must not be an alias. Hardlinks are rejected by default so another
7979
in-tree name cannot alias the credential; pass `rejectHardlinks: false` only
8080
when you explicitly trust that layout.
8181

82+
These readers do not enforce ownership or mode bits on an existing file. Their
83+
read contract covers pinned identity, file type, link policy, and byte bounds;
84+
the `0o600` guarantee belongs to the write helpers below. Use
85+
[`readSecureFile`](secure-file.md) when reading an externally managed
86+
credential must also fail on broad permissions or unexpected ownership.
87+
8288
`readSecretFile()` and `tryReadSecretFile()` are asynchronous counterparts with
8389
the same pinned-handle validation, byte cap, trimming, error codes, and strict
8490
versus missing-is-undefined naming semantics.

‎src/archive-entry.ts‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@ import { ArchiveSecurityError } from "./archive-errors.js";
33
import { resolveSafeBaseDir } from "./path.js";
44

55
export function isWindowsDrivePath(value: string): boolean {
6-
return /^[a-zA-Z]:[\\/]/.test(value);
6+
return normalizeArchiveEntryPath(value)
7+
.split("/")
8+
.some((segment) => /^[a-zA-Z]:/.test(segment));
79
}
810

911
export function normalizeArchiveEntryPath(raw: string): string {
@@ -20,6 +22,12 @@ export function validateArchiveEntryPath(
2022
if (isWindowsDrivePath(entryPath)) {
2123
throw new ArchiveSecurityError("entry-path", `archive entry uses a drive path: ${entryPath}`);
2224
}
25+
if (entryPath.includes("\0")) {
26+
throw new ArchiveSecurityError(
27+
"entry-path",
28+
`archive entry contains a NUL byte: ${entryPath}`,
29+
);
30+
}
2331
const normalized = path.posix.normalize(normalizeArchiveEntryPath(entryPath));
2432
const escapeLabel = params?.escapeLabel ?? "destination";
2533
if (normalized === ".." || normalized.startsWith("../")) {
@@ -49,6 +57,20 @@ export function stripArchivePath(entryPath: string, stripComponents: number): st
4957
return result;
5058
}
5159

60+
export function createArchiveOutputPathTracker(): (entryPath: string, originalPath: string) => void {
61+
const seen = new Set<string>();
62+
return (entryPath, originalPath) => {
63+
const normalized = path.posix.normalize(normalizeArchiveEntryPath(entryPath));
64+
if (seen.has(normalized)) {
65+
throw new ArchiveSecurityError(
66+
"entry-path",
67+
`archive entries collide at output path ${normalized}: ${originalPath}`,
68+
);
69+
}
70+
seen.add(normalized);
71+
};
72+
}
73+
5274
export function resolveArchiveOutputPath(params: {
5375
rootDir: string;
5476
relPath: string;

‎src/archive-limits.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ function clampLimit(value: number | undefined): number | undefined {
6868
return undefined;
6969
}
7070
const v = Math.floor(value);
71-
return v > 0 ? v : undefined;
71+
return v >= 0 ? v : undefined;
7272
}
7373

7474
export function resolveExtractLimits(

‎src/archive-native.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
11
import { constants as fsConstants } from "node:fs";
22
import fs from "node:fs/promises";
33
import { ArchiveFormatError, ArchiveSecurityError } from "./archive-errors.js";
4-
import { resolveArchiveOutputPath, stripArchivePath, validateArchiveEntryPath } from "./archive-entry.js";
4+
import {
5+
createArchiveOutputPathTracker,
6+
resolveArchiveOutputPath,
7+
stripArchivePath,
8+
validateArchiveEntryPath,
9+
} from "./archive-entry.js";
510
import type { ExtractionDeadline } from "./archive-deadline.js";
611
import { stageArchiveFileForExtraction } from "./archive-input.js";
712
import type { ArchiveKind } from "./archive-kind.js";
@@ -79,6 +84,7 @@ export async function extractNativeArchive(params: {
7984
assertArchiveEntryCountWithinLimit(manifest.length, limits);
8085
const strip = Math.max(0, Math.floor(params.stripComponents ?? 0));
8186
const budget = createByteBudgetTracker(limits);
87+
const trackOutputPath = createArchiveOutputPathTracker();
8288
const plan: Array<{
8389
index: number;
8490
path: string;
@@ -94,6 +100,7 @@ export async function extractNativeArchive(params: {
94100
if (!relPath) continue;
95101
validateArchiveEntryPath(relPath);
96102
assertArchiveEntryPathComponentsWithinLimit(relPath, limits);
103+
trackOutputPath(relPath, entry.path);
97104
resolveArchiveOutputPath({ rootDir: stagingDir, relPath, originalPath: entry.path });
98105
const kind = policyKind(entry.kind);
99106
if (

‎src/archive-read.ts‎

Lines changed: 29 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import fsSync from "node:fs";
22
import fs from "node:fs/promises";
33
import { Readable } from "node:stream";
44
import { readFileHandleBounded } from "./bounded-read.js";
5-
import { ArchiveFormatError } from "./archive-errors.js";
5+
import { ArchiveFormatError, ArchiveSecurityError } from "./archive-errors.js";
66
import {
77
normalizeArchiveEntryPath,
88
validateArchiveEntryPath,
@@ -19,19 +19,13 @@ import { readTarEntryInfo } from "./archive-tar.js";
1919
import { preflightTarMetadata } from "./archive-tar-meta.js";
2020
import { importOptionalTar } from "./archive-tar-runtime.js";
2121
import { loadZipArchiveWithPreflight } from "./archive-zip-preflight.js";
22+
import { createZipIntegrityTransform } from "./archive-zip-integrity.js";
23+
import type { ZipEntry } from "./archive-zip-entry.js";
2224
import { FsSafeError } from "./errors.js";
2325
import { sameFileIdentity } from "./file-identity.js";
2426
import { getNativeBinding } from "./native.js";
2527
import { tempFile } from "./temp-target.js";
2628

27-
type ZipEntry = {
28-
name: string;
29-
dir: boolean;
30-
unixPermissions?: number;
31-
nodeStream?: () => NodeJS.ReadableStream;
32-
async(type: "nodebuffer"): Promise<Buffer>;
33-
};
34-
3529
const ZIP_UNIX_FILE_TYPE_MASK = 0o170000;
3630
const ZIP_UNIX_SYMLINK_TYPE = 0o120000;
3731

@@ -142,7 +136,7 @@ async function readZipEntry(buffer: Buffer, entryPath: string, maxBytes: number)
142136
typeof entry.nodeStream === "function"
143137
? entry.nodeStream()
144138
: Readable.from(await entry.async("nodebuffer"));
145-
return await readStreamBounded(stream, maxBytes);
139+
return await readStreamBounded(stream.pipe(createZipIntegrityTransform(entry)), maxBytes);
146140
}
147141

148142
async function readTarEntry(archivePath: string, entryPath: string, maxBytes: number): Promise<Buffer> {
@@ -152,6 +146,8 @@ async function readTarEntry(archivePath: string, entryPath: string, maxBytes: nu
152146
maxMetaEntryBytes: DEFAULT_MAX_META_ENTRY_BYTES,
153147
});
154148
let matched: Promise<Buffer> | undefined;
149+
let entryError: Error | undefined;
150+
const seenPaths = new Set<string>();
155151
await tar.t({
156152
file: archivePath,
157153
strict: true,
@@ -160,25 +156,37 @@ async function readTarEntry(archivePath: string, entryPath: string, maxBytes: nu
160156
const info = readTarEntryInfo(entry);
161157
validateArchiveEntryPath(info.path, { escapeLabel: "archive root" });
162158
const normalized = normalizeArchiveEntryPath(info.path).replace(/^\.\//, "");
159+
if (seenPaths.has(normalized)) {
160+
entryError ??= new ArchiveSecurityError(
161+
"entry-path",
162+
`archive contains duplicate entry path: ${normalized}`,
163+
);
164+
entry.resume();
165+
return;
166+
}
167+
seenPaths.add(normalized);
163168
if (normalized !== entryPath) {
164169
entry.resume();
165170
return;
166171
}
167172
if (info.type !== "File" && info.type !== "OldFile" && info.type !== "ContiguousFile") {
168-
matched = Promise.reject(new Error(`archive entry is not a file: ${entryPath}`));
173+
entryError ??= new Error(`archive entry is not a file: ${entryPath}`);
169174
entry.resume();
170175
return;
171176
}
172177
if (info.size > maxBytes) {
173-
matched = Promise.reject(
174-
new ArchiveLimitError(ARCHIVE_LIMIT_ERROR_CODE.ENTRY_EXTRACTED_SIZE_EXCEEDS_LIMIT),
178+
entryError ??= new ArchiveLimitError(
179+
ARCHIVE_LIMIT_ERROR_CODE.ENTRY_EXTRACTED_SIZE_EXCEEDS_LIMIT,
175180
);
176181
entry.resume();
177182
return;
178183
}
179184
matched = readStreamBounded(entry, maxBytes);
180185
},
181186
});
187+
if (entryError) {
188+
throw entryError;
189+
}
182190
if (!matched) {
183191
throw new Error(`archive entry not found: ${entryPath}`);
184192
}
@@ -213,15 +221,22 @@ export async function readArchiveEntry(
213221
signal,
214222
);
215223
let rawEntryPath: string | undefined;
224+
const seenPaths = new Set<string>();
216225
for (const entry of manifest) {
217226
validateArchiveEntryPath(entry.path, { escapeLabel: "archive root" });
218227
const normalized = normalizeArchiveEntryPath(entry.path).replace(/^\.\//, "");
228+
if (seenPaths.has(normalized)) {
229+
throw new ArchiveSecurityError(
230+
"entry-path",
231+
`archive contains duplicate entry path: ${normalized}`,
232+
);
233+
}
234+
seenPaths.add(normalized);
219235
if (normalized === requestedEntry) {
220236
if (entry.kind !== "file") {
221237
throw new Error(`archive entry is not a file: ${entryPath}`);
222238
}
223239
rawEntryPath = entry.path;
224-
break;
225240
}
226241
}
227242
if (!rawEntryPath) throw new Error(`archive entry not found: ${entryPath}`);

‎src/archive-tar.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import {
2+
createArchiveOutputPathTracker,
23
resolveArchiveOutputPath,
34
stripArchivePath,
45
validateArchiveEntryPath,
@@ -68,8 +69,11 @@ export function createTarEntryPreflightChecker(params: {
6869
const limits = resolveExtractLimits(params.limits);
6970
let entryCount = 0;
7071
const budget = createByteBudgetTracker(limits);
72+
const trackOutputPath = createArchiveOutputPathTracker();
7173

7274
return (entry: TarEntryInfo) => {
75+
entryCount += 1;
76+
assertArchiveEntryCountWithinLimit(entryCount, limits);
7377
validateArchiveEntryPath(entry.path, { escapeLabel: params.escapeLabel });
7478

7579
const relPath = stripArchivePath(entry.path, strip);
@@ -78,16 +82,14 @@ export function createTarEntryPreflightChecker(params: {
7882
}
7983
validateArchiveEntryPath(relPath, { escapeLabel: params.escapeLabel });
8084
assertArchiveEntryPathComponentsWithinLimit(relPath, limits);
85+
trackOutputPath(relPath, entry.path);
8186
resolveArchiveOutputPath({
8287
rootDir: params.rootDir,
8388
relPath,
8489
originalPath: entry.path,
8590
escapeLabel: params.escapeLabel,
8691
});
8792

88-
entryCount += 1;
89-
assertArchiveEntryCountWithinLimit(entryCount, limits);
90-
9193
const kind = archiveEntryKindFromTarType(entry.type);
9294
if (
9395
!shouldExtractArchiveEntry({

‎src/archive-zip-entry.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ export type ZipEntry = {
77
name: string;
88
dir: boolean;
99
unixPermissions?: number;
10-
_data?: { uncompressedSize?: number };
10+
_data?: { crc32?: number; uncompressedSize?: number };
1111
nodeStream?: () => NodeJS.ReadableStream;
1212
async: (type: "nodebuffer") => Promise<Buffer>;
1313
};

‎src/archive-zip-integrity.ts‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import { Transform } from "node:stream";
2+
import { ArchiveFormatError } from "./archive-errors.js";
3+
import type { ZipEntry } from "./archive-zip-entry.js";
4+
5+
const CRC32_TABLE = Array.from({ length: 256 }, (_, index) => {
6+
let value = index;
7+
for (let bit = 0; bit < 8; bit += 1) {
8+
value = (value & 1) !== 0 ? 0xedb88320 ^ (value >>> 1) : value >>> 1;
9+
}
10+
return value >>> 0;
11+
});
12+
13+
function updateCrc32(previous: number, buffer: Buffer): number {
14+
let crc = previous ^ -1;
15+
for (const byte of buffer) {
16+
crc = (crc >>> 8) ^ (CRC32_TABLE[(crc ^ byte) & 0xff] ?? 0);
17+
}
18+
return (crc ^ -1) >>> 0;
19+
}
20+
21+
export function createZipIntegrityTransform(entry: ZipEntry): Transform {
22+
const expectedCrc32 = entry._data?.crc32;
23+
const expectedSize = entry._data?.uncompressedSize;
24+
if (
25+
typeof expectedCrc32 !== "number" ||
26+
!Number.isInteger(expectedCrc32) ||
27+
typeof expectedSize !== "number" ||
28+
!Number.isSafeInteger(expectedSize) ||
29+
expectedSize < 0
30+
) {
31+
throw new ArchiveFormatError(`zip entry has invalid integrity metadata: ${entry.name}`);
32+
}
33+
34+
let actualCrc32 = 0;
35+
let actualSize = 0;
36+
return new Transform({
37+
transform(chunk, _encoding, callback) {
38+
const buffer = chunk instanceof Buffer ? chunk : Buffer.from(chunk as Uint8Array);
39+
actualCrc32 = updateCrc32(actualCrc32, buffer);
40+
actualSize += buffer.byteLength;
41+
callback(null, buffer);
42+
},
43+
flush(callback) {
44+
if (actualSize !== expectedSize || actualCrc32 !== (expectedCrc32 >>> 0)) {
45+
callback(new ArchiveFormatError(`zip entry integrity check failed: ${entry.name}`));
46+
return;
47+
}
48+
callback();
49+
},
50+
});
51+
}

0 commit comments

Comments
 (0)