Skip to content

Commit ab93382

Browse files
authored
fix(path): make sanitizers linear-time (#75)
1 parent 0206c4b commit ab93382

5 files changed

Lines changed: 194 additions & 9 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@
22

33
## Unreleased
44

5+
### Security and Correctness
6+
7+
- Replace backtracking-prone path-segment, temp-name, and Windows device-path sanitizers with linear scans to keep attacker-controlled inputs from causing excessive CPU use.
8+
59
### Docs and Tooling
610

711
- Publish only the validated release tarball after asserting its byte identity against the release manifest, and tolerate npm registry propagation with bounded exponential backoff.

‎src/device-path.ts‎

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,33 @@ const WINDOWS_RESERVED_DEVICE_NAMES = new Set([
6363
"LPT³",
6464
]);
6565

66+
const WINDOWS_SEPARATOR_CHAR_CODE = 0x5c;
67+
const WINDOWS_IGNORED_SPACE_CHAR_CODE = 0x20;
68+
const WINDOWS_IGNORED_DOT_CHAR_CODE = 0x2e;
69+
70+
function trimTrailingWindowsSeparators(value: string): string {
71+
let end = value.length;
72+
while (end > 0 && value.charCodeAt(end - 1) === WINDOWS_SEPARATOR_CHAR_CODE) {
73+
end -= 1;
74+
}
75+
return end === value.length ? value : value.slice(0, end);
76+
}
77+
78+
function trimTrailingWindowsIgnoredChars(value: string): string {
79+
let end = value.length;
80+
while (end > 0) {
81+
const charCode = value.charCodeAt(end - 1);
82+
if (
83+
charCode !== WINDOWS_IGNORED_SPACE_CHAR_CODE &&
84+
charCode !== WINDOWS_IGNORED_DOT_CHAR_CODE
85+
) {
86+
break;
87+
}
88+
end -= 1;
89+
}
90+
return end === value.length ? value : value.slice(0, end);
91+
}
92+
6693
function candidateReadPaths(filePath: string): string[] {
6794
if (!filePath.startsWith("file://")) {
6895
return [filePath];
@@ -97,10 +124,10 @@ function matchPosixDeviceReadPath(
97124
}
98125

99126
function normalizeWindowsDeviceBaseName(filePath: string): string {
100-
const normalized = filePath.replace(/\//g, "\\").replace(/[\\]+$/g, "");
127+
const normalized = trimTrailingWindowsSeparators(filePath.replace(/\//g, "\\"));
101128
const lastSegment = normalized.split("\\").filter(Boolean).at(-1) ?? normalized;
102129
const withoutStream = lastSegment.split(":")[0] ?? lastSegment;
103-
const withoutTrailingIgnoredChars = withoutStream.replace(/[ .]+$/g, "");
130+
const withoutTrailingIgnoredChars = trimTrailingWindowsIgnoredChars(withoutStream);
104131
return (withoutTrailingIgnoredChars.split(".")[0] ?? withoutTrailingIgnoredChars).toUpperCase();
105132
}
106133

‎src/safe-path-segment.ts‎

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,25 @@ import { FsSafeError } from "./errors.js";
22

33
const SAFE_PATH_SEGMENT_PATTERN = /^[A-Za-z0-9_-][A-Za-z0-9._-]*$/;
44
const SAFE_DOT_PREFIX_PATH_SEGMENT_PATTERN = /^[A-Za-z0-9._-]+$/;
5+
const HYPHEN_CHAR_CODE = 0x2d;
56

67
export type SafePathSegmentOptions = {
78
allowDotPrefix?: boolean;
89
label?: string;
910
};
1011

12+
function trimHyphenEdges(value: string): string {
13+
let start = 0;
14+
let end = value.length;
15+
while (start < end && value.charCodeAt(start) === HYPHEN_CHAR_CODE) {
16+
start += 1;
17+
}
18+
while (end > start && value.charCodeAt(end - 1) === HYPHEN_CHAR_CODE) {
19+
end -= 1;
20+
}
21+
return start === 0 && end === value.length ? value : value.slice(start, end);
22+
}
23+
1124
export function isSafePathSegment(
1225
segment: string,
1326
options: SafePathSegmentOptions = {},
@@ -50,10 +63,10 @@ export function sanitizeSafePathSegment(
5063
.trim()
5164
.replace(/[\\/]+/g, "-")
5265
.replace(/\0/g, "")
53-
.replace(/[^A-Za-z0-9._-]+/g, "-")
54-
.replace(/^-+|-+$/g, "");
55-
if (isSafePathSegment(sanitized, options)) {
56-
return sanitized;
66+
.replace(/[^A-Za-z0-9._-]+/g, "-");
67+
const trimmed = trimHyphenEdges(sanitized);
68+
if (isSafePathSegment(trimmed, options)) {
69+
return trimmed;
5770
}
5871
return assertSafePathSegment(fallback, { ...options, label: "fallback path segment" });
5972
}

‎src/temp-target.ts‎

Lines changed: 60 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,65 @@ export type TempFile = {
1313
[Symbol.asyncDispose](): Promise<void>;
1414
};
1515

16+
const HYPHEN_CHAR_CODE = 0x2d;
17+
const DOT_CHAR_CODE = 0x2e;
18+
const NUMBER_ZERO_CHAR_CODE = 0x30;
19+
const NUMBER_NINE_CHAR_CODE = 0x39;
20+
const UPPERCASE_A_CHAR_CODE = 0x41;
21+
const UPPERCASE_Z_CHAR_CODE = 0x5a;
22+
const UNDERSCORE_CHAR_CODE = 0x5f;
23+
const LOWERCASE_A_CHAR_CODE = 0x61;
24+
const LOWERCASE_Z_CHAR_CODE = 0x7a;
25+
26+
function trimHyphenEdges(value: string): string {
27+
let start = 0;
28+
let end = value.length;
29+
while (start < end && value.charCodeAt(start) === HYPHEN_CHAR_CODE) {
30+
start += 1;
31+
}
32+
while (end > start && value.charCodeAt(end - 1) === HYPHEN_CHAR_CODE) {
33+
end -= 1;
34+
}
35+
return start === 0 && end === value.length ? value : value.slice(start, end);
36+
}
37+
38+
function isExtensionCharCode(charCode: number): boolean {
39+
return (
40+
(charCode >= NUMBER_ZERO_CHAR_CODE && charCode <= NUMBER_NINE_CHAR_CODE) ||
41+
(charCode >= UPPERCASE_A_CHAR_CODE && charCode <= UPPERCASE_Z_CHAR_CODE) ||
42+
(charCode >= LOWERCASE_A_CHAR_CODE && charCode <= LOWERCASE_Z_CHAR_CODE) ||
43+
charCode === DOT_CHAR_CODE ||
44+
charCode === UNDERSCORE_CHAR_CODE ||
45+
charCode === HYPHEN_CHAR_CODE
46+
);
47+
}
48+
49+
function trailingExtensionChars(value: string): string {
50+
let start = value.length;
51+
while (start > 0 && isExtensionCharCode(value.charCodeAt(start - 1))) {
52+
start -= 1;
53+
}
54+
return start === value.length ? "" : value.slice(start);
55+
}
56+
57+
function trimLeadingExtensionPunctuation(value: string): string {
58+
let start = 0;
59+
while (start < value.length) {
60+
const charCode = value.charCodeAt(start);
61+
if (
62+
charCode !== DOT_CHAR_CODE &&
63+
charCode !== UNDERSCORE_CHAR_CODE &&
64+
charCode !== HYPHEN_CHAR_CODE
65+
) {
66+
break;
67+
}
68+
start += 1;
69+
}
70+
return start === 0 ? value : value.slice(start);
71+
}
72+
1673
function sanitizePrefix(prefix: string): string {
17-
const normalized = prefix.replace(/[^a-zA-Z0-9_-]+/g, "-").replace(/^-+|-+$/g, "");
74+
const normalized = trimHyphenEdges(prefix.replace(/[^a-zA-Z0-9_-]+/g, "-"));
1875
return normalized || "tmp";
1976
}
2077

@@ -23,8 +80,8 @@ function sanitizeExtension(extension?: string): string {
2380
return "";
2481
}
2582
const normalized = extension.startsWith(".") ? extension : `.${extension}`;
26-
const suffix = normalized.match(/[a-zA-Z0-9._-]+$/)?.[0] ?? "";
27-
const token = suffix.replace(/^[._-]+/, "");
83+
const suffix = trailingExtensionChars(normalized);
84+
const token = trimLeadingExtensionPunctuation(suffix);
2885
return token ? `.${token}` : "";
2986
}
3087

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
import path from "node:path";
2+
import { performance } from "node:perf_hooks";
3+
import { describe, expect, it } from "vitest";
4+
import { isUnsafeDeviceReadPath } from "../src/device-path.js";
5+
import { sanitizeSafePathSegment } from "../src/safe-path-segment.js";
6+
import { buildRandomTempFilePath } from "../src/temp-target.js";
7+
8+
const ADVERSARIAL_RUN_LENGTH = 100_000;
9+
const MAX_LINEAR_SCAN_MS = 1_000;
10+
11+
function expectBounded<T>(run: () => T): T {
12+
const startedAt = performance.now();
13+
const result = run();
14+
expect(performance.now() - startedAt).toBeLessThan(MAX_LINEAR_SCAN_MS);
15+
return result;
16+
}
17+
18+
describe("CodeQL ReDoS regressions", () => {
19+
it("handles long internal Windows separator runs in linear time", () => {
20+
const separators = "\\".repeat(ADVERSARIAL_RUN_LENGTH);
21+
22+
expect(
23+
expectBounded(() =>
24+
isUnsafeDeviceReadPath(`C:\\tmp\\${separators}normal.txt`, {
25+
platform: "win32",
26+
}),
27+
),
28+
).toBe(false);
29+
expect(
30+
expectBounded(() =>
31+
isUnsafeDeviceReadPath(`C:\\tmp\\${separators}NUL`, {
32+
platform: "win32",
33+
}),
34+
),
35+
).toBe(true);
36+
});
37+
38+
it("preserves long internal hyphen runs while trimming only edges", () => {
39+
const internalHyphens = `a${"-".repeat(ADVERSARIAL_RUN_LENGTH)}b`;
40+
41+
expect(
42+
expectBounded(() => sanitizeSafePathSegment(internalHyphens, "fallback")),
43+
).toBe(internalHyphens);
44+
expect(sanitizeSafePathSegment(`---${internalHyphens}---`, "fallback")).toBe(
45+
internalHyphens,
46+
);
47+
});
48+
49+
it("sanitizes long temp prefixes and extension candidates in linear time", () => {
50+
const internalHyphens = `a${"-".repeat(ADVERSARIAL_RUN_LENGTH)}b`;
51+
const prefixed = expectBounded(() =>
52+
buildRandomTempFilePath({
53+
rootDir: process.cwd(),
54+
prefix: internalHyphens,
55+
now: 1,
56+
uuid: "id",
57+
}),
58+
);
59+
expect(path.basename(prefixed)).toBe(`${internalHyphens}-1-id`);
60+
61+
const invalidExtension = expectBounded(() =>
62+
buildRandomTempFilePath({
63+
rootDir: process.cwd(),
64+
prefix: "tmp",
65+
extension: `${"a".repeat(ADVERSARIAL_RUN_LENGTH)}!`,
66+
now: 1,
67+
uuid: "id",
68+
}),
69+
);
70+
expect(path.basename(invalidExtension)).toBe("tmp-1-id");
71+
72+
expect(
73+
path.basename(
74+
buildRandomTempFilePath({
75+
rootDir: process.cwd(),
76+
prefix: "tmp",
77+
extension: `${".".repeat(ADVERSARIAL_RUN_LENGTH)}log`,
78+
now: 1,
79+
uuid: "id",
80+
}),
81+
),
82+
).toBe("tmp-1-id.log");
83+
});
84+
});

0 commit comments

Comments
 (0)