Skip to content

Commit f16a4fa

Browse files
pi0claude
andcommitted
fix(route-rules): prevent open redirect via backslash and control characters in wildcard redirects
A wildcard `redirect` rule targeting `/**` copied the rest of the request path into `Location` and only collapsed a leading `//`. A remainder starting with `\` (raw or `%5C`) or `<TAB>/` (`%09/`) was emitted unchanged, which browsers resolve as protocol-relative `//evil.com` (GHSA-49p7-jc25-v5fc, incomplete fix of GHSA-9phm-9p8f-hw5m). - Move target resolution to a pure `resolveRedirectTarget()` helper - Collapse any leading run of `/`, `\`, C0 controls/space and their percent-encoded forms to a single `/` (with and without strip base) - Reject (400) remainders whose dot-segments would climb above a path-prefixed target base once normalized - For root targets, always emit a path-absolute `Location` (also fixes the empty `Location` redirect loop for `/old` with `/old/**`) Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 353eff5 commit f16a4fa

4 files changed

Lines changed: 318 additions & 4 deletions

File tree

‎src/runtime/internal/route-rules-utils.ts‎

Lines changed: 70 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { parseURL } from "ufo";
1+
import { getQuery, joinURL, parseURL, withQuery, withoutBase } from "ufo";
22

33
// Max percent-decoding passes (covers nested encodings like `%252f`, `%25%32%66`).
44
const MAX_DECODE_PASSES = 8;
@@ -104,3 +104,72 @@ export function isTargetInScope(target: string, targetBase: string): boolean {
104104
parseURL(targetBase).pathname || ""
105105
);
106106
}
107+
108+
// Leading run of path separators (`/`, `\`), C0 control characters and
109+
// space (U+0000-U+0020), and their single percent-encoded forms. This mirrors
110+
// WHATWG URL parsing: browsers treat `\` as `/` in special-scheme URLs and strip
111+
// C0 controls/space at the edges and tab/LF/CR anywhere, so
112+
// `/\evil.com` or `/<TAB>/evil.com` in a `Location` header resolve to the
113+
// protocol-relative `//evil.com`.
114+
const LEADING_SEPARATORS_RE =
115+
// eslint-disable-next-line no-control-regex
116+
/^(?:[\u0000-\u0020/\\]|%(?:2f|5c|[01][\da-f]|20))+/i;
117+
118+
// Collapse any leading separator run to a single `/` so a path-relative
119+
// redirect target can never become protocol-relative (cross-origin).
120+
export function normalizeRedirectPath(path: string): string {
121+
return path.replace(LEADING_SEPARATORS_RE, "/");
122+
}
123+
124+
/**
125+
* Resolve the `Location` for a `redirect` route rule.
126+
*
127+
* @param path - Request path, including the query string (h3 v1 `event.path`).
128+
* @param to - Configured redirect target (may end with `/**`).
129+
* @param stripBase - Base stripped from `path` (`/old` for `/old/**`). Only used for `/**` targets.
130+
* @returns The redirect target, or `undefined` if `path` escapes `stripBase`
131+
* or the remainder escapes the target base.
132+
*/
133+
export function resolveRedirectTarget(
134+
path: string,
135+
to: string,
136+
stripBase?: string
137+
): string | undefined {
138+
if (!to.endsWith("/**")) {
139+
return path.includes("?") ? withQuery(to, getQuery(path)) : to;
140+
}
141+
let targetPath = path;
142+
if (stripBase) {
143+
if (!isPathInScope(path.split("?")[0], stripBase)) {
144+
return undefined;
145+
}
146+
targetPath = withoutBase(targetPath, stripBase);
147+
}
148+
// Prevent open redirects via a leading `//`, `\`, encoded separators
149+
// or control characters
150+
targetPath = normalizeRedirectPath(targetPath);
151+
const targetBase = to.slice(0, -3);
152+
// Normalizing may expose dot-segments (`/\../x` -> `/../x`); the remainder
153+
// must never climb above a path-prefixed target base
154+
if (
155+
targetBase &&
156+
targetBase !== "/" &&
157+
!isPathInScope(joinURL("/_", targetPath.split("?")[0]), "/_")
158+
) {
159+
return undefined;
160+
}
161+
let target = joinURL(targetBase, targetPath);
162+
// Final guard: a root (`/**`) target must always be a same-origin,
163+
// path-absolute URL (also avoids an empty `Location` for `/old`)
164+
if (!targetBase || targetBase === "/") {
165+
target = normalizeRedirectPath(target);
166+
if (!target.startsWith("/")) {
167+
target = "/" + target;
168+
}
169+
}
170+
// Validate the final target, not only the incoming path (GHSA-jxc8-347r-cw9m)
171+
if (!isTargetInScope(target, targetBase)) {
172+
return undefined;
173+
}
174+
return target;
175+
}

‎src/runtime/internal/route-rules.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,11 @@ import type { NitroRouteRules } from "nitropack/types";
1111
import { createRouter as createRadixRouter, toRouteMatcher } from "radix3";
1212
import { getQuery, joinURL, withQuery, withoutBase } from "ufo";
1313
import { useRuntimeConfig } from "./config";
14-
import { isPathInScope, isTargetInScope } from "./route-rules-utils";
14+
import {
15+
isPathInScope,
16+
isTargetInScope,
17+
resolveRedirectTarget,
18+
} from "./route-rules-utils";
1519

1620
const config = useRuntimeConfig();
1721
const _routeRulesMatcher = toRouteMatcher(
@@ -30,11 +34,14 @@ export function createRouteRulesHandler(ctx: {
3034
}
3135
// Apply redirect options
3236
if (routeRules.redirect) {
33-
const target = resolveRuleTarget(
34-
event,
37+
const target = resolveRedirectTarget(
38+
event.path,
3539
routeRules.redirect.to,
3640
(routeRules.redirect as any)._redirectStripBase
3741
);
42+
if (target === undefined) {
43+
throw createError({ statusCode: 400 });
44+
}
3845
return sendRedirect(event, target, routeRules.redirect.statusCode);
3946
}
4047
// Apply proxy options

‎test/tests.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -293,6 +293,31 @@ export function testNitro(
293293
expect(legacy.status).toBe(307);
294294
expect(legacy.headers.location).not.toMatch(/^\/\//);
295295
expect(legacy.headers.location).toBe("/evil.com");
296+
297+
// backslashes (raw or encoded), encoded separators and control
298+
// characters must not produce a `Location` that browsers resolve cross-origin.
299+
for (const payload of [
300+
"%5Cevil.com",
301+
"%5c%5cevil.com",
302+
"%5C/evil.com",
303+
"%2F%2Fevil.com",
304+
"%09/evil.com",
305+
"%0A/evil.com",
306+
"%0D/evil.com",
307+
"%20/evil.com",
308+
]) {
309+
const res = await callHandler({
310+
url: `/rules/redirect/legacy/${payload}`,
311+
});
312+
expect(res.status, payload).toBe(307);
313+
expect(res.headers.location, payload).toBe("/evil.com");
314+
}
315+
316+
const legacyNormal = await callHandler({
317+
url: "/rules/redirect/legacy/foo?x=1",
318+
});
319+
expect(legacyNormal.status).toBe(307);
320+
expect(legacyNormal.headers.location).toBe("/foo?x=1");
296321
});
297322

298323
it("binary response", async () => {

‎test/unit/route-rules.test.ts‎

Lines changed: 213 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import { describe, expect, it } from "vitest";
22
import {
33
isPathInScope,
44
isTargetInScope,
5+
normalizeRedirectPath,
6+
resolveRedirectTarget,
57
} from "../../src/runtime/internal/route-rules-utils";
68

79
// Regression for GHSA-5w89-w975-hf9q: an encoded traversal like `..%2f` must
@@ -141,3 +143,214 @@ describe("isTargetInScope", () => {
141143
expect(isTargetInScope("http://up/a/b", "http://up/")).toBe(true);
142144
});
143145
});
146+
147+
// A wildcard redirect to `/**` must never emit a `Location` that browsers
148+
// resolve as protocol-relative (cross-origin).
149+
describe("normalizeRedirectPath", () => {
150+
const resolve = (location: string) =>
151+
new URL(location, "https://victim.example").origin;
152+
153+
it.each([
154+
["//evil.example", "/evil.example"],
155+
["///evil.example", "/evil.example"],
156+
["/\\evil.example", "/evil.example"],
157+
["/\\\\evil.example", "/evil.example"],
158+
["/\\/evil.example", "/evil.example"],
159+
["\\\\evil.example", "/evil.example"],
160+
["/%5Cevil.example", "/evil.example"],
161+
["/%5c%5cevil.example", "/evil.example"],
162+
["/%5C/evil.example", "/evil.example"],
163+
["/%2F%2Fevil.example", "/evil.example"],
164+
["/%01/evil.example", "/evil.example"],
165+
["/%1F/evil.example", "/evil.example"],
166+
["/\t/evil.example", "/evil.example"],
167+
["/\n/evil.example", "/evil.example"],
168+
["/\r/evil.example", "/evil.example"],
169+
["/%09/evil.example", "/evil.example"],
170+
["/%0A/evil.example", "/evil.example"],
171+
["/%0d/evil.example", "/evil.example"],
172+
["/ /evil.example", "/evil.example"],
173+
["/%20/evil.example", "/evil.example"],
174+
["/\u0000/evil.example", "/evil.example"],
175+
["/%5Cevil.example?next=x", "/evil.example?next=x"],
176+
])("collapses %j", (input, expected) => {
177+
const out = normalizeRedirectPath(input);
178+
expect(out).toBe(expected);
179+
expect(resolve(out)).toBe("https://victim.example");
180+
});
181+
182+
// Browsers never decode `Location` again nor strip non-ASCII whitespace,
183+
// so nested encodings and unicode spaces stay same-origin as-is.
184+
it.each([
185+
"/%252F%252Fevil.example",
186+
"/%255Cevil.example",
187+
"/%2520/evil.example",
188+
"/\u00A0/evil.example",
189+
"/\u00A0\\evil.example",
190+
"/\u3000/evil.example",
191+
"/\uFEFF/evil.example",
192+
])("preserves non-separator prefix %j", (input) => {
193+
const out = normalizeRedirectPath(input);
194+
expect(out).toBe(input);
195+
expect(resolve(out)).toBe("https://victim.example");
196+
});
197+
198+
it("keeps regular paths untouched", () => {
199+
expect(normalizeRedirectPath("/foo")).toBe("/foo");
200+
expect(normalizeRedirectPath("/foo?x=1")).toBe("/foo?x=1");
201+
expect(normalizeRedirectPath("/foo//bar\\baz")).toBe("/foo//bar\\baz");
202+
expect(normalizeRedirectPath("/")).toBe("/");
203+
expect(normalizeRedirectPath("")).toBe("");
204+
});
205+
});
206+
207+
// Inputs mirror h3 v1 `event.path`: `%5C`, `%09`, `%20`... are already decoded
208+
// to literal characters, while `%2F` stays encoded.
209+
describe("resolveRedirectTarget", () => {
210+
const origin = (location: string) =>
211+
new URL(location, "https://victim.example").origin;
212+
213+
const payloads = [
214+
"//evil.example",
215+
"///evil.example",
216+
"/\\evil.example",
217+
"/\\\\evil.example",
218+
"/\\/evil.example",
219+
"/%2F%2Fevil.example",
220+
"/\t/evil.example",
221+
"/\n/evil.example",
222+
"/\r/evil.example",
223+
"/ /evil.example",
224+
"/\t\\evil.example",
225+
"/\\\t\\evil.example",
226+
];
227+
228+
describe("strip base (`/old/**` -> `/**`)", () => {
229+
it.each(payloads)("stays same-origin for %j", (payload) => {
230+
const target = resolveRedirectTarget(`/old${payload}`, "/**", "/old");
231+
expect(target).toBe("/evil.example");
232+
expect(origin(target!)).toBe("https://victim.example");
233+
});
234+
235+
it("preserves query strings", () => {
236+
expect(
237+
resolveRedirectTarget("/old/\\evil.example?next=x", "/**", "/old")
238+
).toBe("/evil.example?next=x");
239+
});
240+
241+
it("redirects regular paths", () => {
242+
expect(resolveRedirectTarget("/old/foo", "/**", "/old")).toBe("/foo");
243+
expect(resolveRedirectTarget("/old/foo?x=1", "/**", "/old")).toBe(
244+
"/foo?x=1"
245+
);
246+
expect(resolveRedirectTarget("/old/a/b", "/new/**", "/old")).toBe(
247+
"/new/a/b"
248+
);
249+
});
250+
251+
// Intentional trade-off: the whole leading run is collapsed, including
252+
// whitespace and encoded separators that are harmless mid-URL.
253+
it("strips leading whitespace and encoded separators", () => {
254+
expect(resolveRedirectTarget("/old/ a", "/**", "/old")).toBe("/a");
255+
expect(resolveRedirectTarget("/old/%2Fa", "/**", "/old")).toBe("/a");
256+
expect(resolveRedirectTarget("/old/a%2Fb", "/**", "/old")).toBe("/a%2Fb");
257+
expect(resolveRedirectTarget("/old/a b", "/**", "/old")).toBe("/a b");
258+
});
259+
260+
it("never returns an empty location for the base itself", () => {
261+
expect(resolveRedirectTarget("/old", "/**", "/old")).toBe("/");
262+
expect(resolveRedirectTarget("/old/", "/**", "/old")).toBe("/");
263+
expect(resolveRedirectTarget("/old?x=1", "/**", "/old")).toBe("/?x=1");
264+
});
265+
266+
it("rejects paths escaping the base", () => {
267+
expect(
268+
resolveRedirectTarget("/old/..%2fadmin", "/**", "/old")
269+
).toBeUndefined();
270+
expect(
271+
resolveRedirectTarget("/old/../admin", "/**", "/old")
272+
).toBeUndefined();
273+
});
274+
});
275+
276+
describe("catch-all (`/**` -> `/**`)", () => {
277+
it.each(payloads)("stays same-origin for %j", (payload) => {
278+
const target = resolveRedirectTarget(payload, "/**");
279+
expect(target).toBe("/evil.example");
280+
expect(origin(target!)).toBe("https://victim.example");
281+
});
282+
283+
it("always returns a path-absolute location", () => {
284+
expect(resolveRedirectTarget("evil.example", "/**")).toBe(
285+
"/evil.example"
286+
);
287+
expect(resolveRedirectTarget("http://evil.example/", "/**")).toBe(
288+
"/http://evil.example/"
289+
);
290+
expect(resolveRedirectTarget("", "/**")).toBe("/");
291+
expect(resolveRedirectTarget("/foo?x=1", "/**")).toBe("/foo?x=1");
292+
});
293+
});
294+
295+
describe("targets with a host or path", () => {
296+
it("keeps an absolute target's origin", () => {
297+
const target = resolveRedirectTarget(
298+
"/abs/\\evil.example",
299+
"https://nitro.build/**",
300+
"/abs"
301+
);
302+
expect(target).toBe("https://nitro.build/evil.example");
303+
});
304+
305+
it("keeps an intentional protocol-relative target", () => {
306+
expect(
307+
resolveRedirectTarget("/cdn/x.js", "//cdn.example/**", "/cdn")
308+
).toBe("//cdn.example/x.js");
309+
});
310+
311+
it("keeps a path-prefixed target under its prefix", () => {
312+
expect(
313+
resolveRedirectTarget("/old/\\evil.example", "/new/**", "/old")
314+
).toBe("/new/evil.example");
315+
});
316+
317+
// Normalizing the leading run must not expose a dot-segment that climbs
318+
// above the target prefix (`/new/\../x` -> `/new/../x` -> `/x`)
319+
it.each([
320+
"/old/\\../x",
321+
"/old/\\\\../x",
322+
"/old/ /../x",
323+
"/old/\t/../x",
324+
"/old/%2F../x",
325+
"/old/%2F%2e%2e/x",
326+
"/old/%5C../x",
327+
"/old//../x",
328+
])("rejects prefix escape via %j", (path) => {
329+
expect(resolveRedirectTarget(path, "/new/**", "/old")).toBeUndefined();
330+
expect(
331+
resolveRedirectTarget(path, "https://x.example/sub/**", "/old")
332+
).toBeUndefined();
333+
expect(
334+
resolveRedirectTarget(path.slice(4), "/new/**", "")
335+
).toBeUndefined();
336+
});
337+
338+
it("allows dot-segments that stay under the target prefix", () => {
339+
expect(resolveRedirectTarget("/old/a/../b", "/new/**", "/old")).toBe(
340+
"/new/a/../b"
341+
);
342+
expect(resolveRedirectTarget("/old/\\a/../b", "/new/**", "/old")).toBe(
343+
"/new/a/../b"
344+
);
345+
});
346+
});
347+
348+
describe("non-wildcard targets", () => {
349+
it("returns the target and forwards the query", () => {
350+
expect(resolveRedirectTarget("/rules/redirect", "/base")).toBe("/base");
351+
expect(resolveRedirectTarget("/rules/redirect?a=1", "/base")).toBe(
352+
"/base?a=1"
353+
);
354+
});
355+
});
356+
});

0 commit comments

Comments
 (0)