Skip to content

Commit 4036867

Browse files
committed
fix(@angular/ssr): prevent open redirect via protocol-relative pathname
The `Location` header for a server-side navigation was built by joining the `PlatformLocation` pathname with the search and hash. A pathname may start with `//`, which as a `Location` value is a protocol-relative URL to another origin. The router serializes `/.;/(//example.com)` to `/.//example.com`, dot-segment removal leaves `//example.com`, and a single unauthenticated `GET` returned `302 Location: //example.com`. Any route with a parameter in the first segment and a wildcard child is affected, with no redirect logic in the application. Collapse the leading slashes of the pathname before using it as a location, and normalize the same way in `createRedirectResponse()`, which also prefixes a slash so the value cannot resolve anywhere but the current origin. The collapse consumes tab, line feed and carriage return too: the WHATWG URL parser removes them before parsing, so a client reads `/\t/example.com` as `//example.com`. Tab is a legal header value character and reaches the wire, and prefixing a slash would otherwise turn a leading tab, which the header layer trims, into an inner one that it does not.
1 parent 73f6bbb commit 4036867

6 files changed

Lines changed: 293 additions & 4 deletions

File tree

‎packages/angular/ssr/src/utils/ng.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,13 @@ import {
2424
} from '@angular/platform-server';
2525
import { ActivatedRoute, Router } from '@angular/router';
2626
import { Console } from '../console';
27-
import { addTrailingSlash, joinUrlParts, stripIndexHtmlFromURL, stripTrailingSlash } from './url';
27+
import {
28+
addTrailingSlash,
29+
collapseLeadingSlashes,
30+
joinUrlParts,
31+
stripIndexHtmlFromURL,
32+
stripTrailingSlash,
33+
} from './url';
2834

2935
/**
3036
* Represents the bootstrap mechanism for an Angular application.
@@ -133,7 +139,10 @@ export async function renderAngular(
133139
const urlToRenderString = constructSerializedUrl(router, urlToRender, requestPrefix);
134140

135141
if (urlToRenderString !== finalUrl) {
136-
redirectTo = [pathname, search, hash].join('');
142+
// The pathname is used as-is to preserve its encoding, as re-serializing it can alter it.
143+
// Its leading slashes are collapsed because a pathname is allowed to start with `//`,
144+
// which as a `Location` value is a protocol-relative URL pointing to another origin.
145+
redirectTo = [collapseLeadingSlashes(pathname), search, hash].join('');
137146
}
138147
}
139148

‎packages/angular/ssr/src/utils/redirect.ts‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
* found in the LICENSE file at https://angular.dev/license
77
*/
88

9+
import { addLeadingSlash, collapseLeadingSlashes } from './url';
10+
911
/**
1012
* An set of HTTP status codes that are considered valid for redirect responses.
1113
*/
@@ -26,7 +28,9 @@ export function isValidRedirectResponseCode(code: number): boolean {
2628
/**
2729
* Creates an HTTP redirect response with a specified location and status code.
2830
*
29-
* @param location - The URL to which the response should redirect.
31+
* @param location - The path to which the response should redirect. It is normalized to an
32+
* absolute path, as a `Location` value is resolved against the request URL and
33+
* must therefore not be able to point to another origin.
3034
* @param status - The HTTP status code for the redirection. Defaults to 302 (Found).
3135
* See: https://developer.mozilla.org/en-US/docs/Web/API/Response/redirect_static#status
3236
* @param headers - Additional headers to include in the response.
@@ -44,6 +48,18 @@ export function createRedirectResponse(
4448
);
4549
}
4650

51+
// A `Location` value is resolved against the request URL. Only a path that starts with a single
52+
// slash is guaranteed to resolve to the current origin: two leading slashes make it a
53+
// protocol-relative URL, and a missing leading slash can make it an absolute URL.
54+
const normalizedLocation = addLeadingSlash(collapseLeadingSlashes(location));
55+
if (ngDevMode && normalizedLocation !== location) {
56+
// eslint-disable-next-line no-console
57+
console.warn(
58+
`Location "${location}" is not an absolute path and was rewritten to "${normalizedLocation}" ` +
59+
`to keep the redirect on the current origin.`,
60+
);
61+
}
62+
4763
const resHeaders = headers instanceof Headers ? headers : new Headers(headers);
4864
if (ngDevMode && resHeaders.has('location')) {
4965
// eslint-disable-next-line no-console
@@ -64,7 +80,7 @@ export function createRedirectResponse(
6480
}
6581

6682
resHeaders.set('Vary', [...varySet].join(', '));
67-
resHeaders.set('Location', location);
83+
resHeaders.set('Location', normalizedLocation);
6884

6985
return new Response(null, {
7086
status,

‎packages/angular/ssr/src/utils/url.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,53 @@ export function addTrailingSlash(url: string): string {
7878
return url.at(-1) === '/' ? url : `${url}/`;
7979
}
8080

81+
/**
82+
* Characters that cannot be left at the start of a path, because a client parsing the path as a
83+
* URL would read them as the start of an authority.
84+
*
85+
* `/` and `\` are the two authority delimiters. Tab, line feed and carriage return are included
86+
* because the WHATWG URL parser removes them from its input *before* parsing it, so they do not
87+
* separate the delimiters around them: `/\t/example.com` is parsed as `//example.com`.
88+
*/
89+
const AUTHORITY_DELIMITERS: ReadonlySet<string> = new Set(['/', '\\', '\t', '\n', '\r']);
90+
91+
/**
92+
* Collapses the leading slashes of a URL path into a single slash.
93+
*
94+
* A path that starts with two or more slashes or backslashes is parsed as a protocol-relative
95+
* URL (for example, `//example.com` resolves to `https://example.com`), which points to a
96+
* different origin. Collapsing the leading slashes keeps the path relative to the current origin.
97+
*
98+
* Characters that the URL parser strips are collapsed along with the slashes, as a path is
99+
* resolved by the client and not by this function: leaving them in place would let
100+
* `/\t/example.com` be parsed as `//example.com` after the collapse has run.
101+
*
102+
* @param pathname - The URL path to collapse the leading slashes of.
103+
* @returns The URL path with at most one leading slash.
104+
*
105+
* @example
106+
* ```js
107+
* collapseLeadingSlashes('//example.com'); // '/example.com'
108+
* collapseLeadingSlashes('/\\example.com'); // '/example.com'
109+
* collapseLeadingSlashes('/\t/example.com'); // '/example.com'
110+
* collapseLeadingSlashes('/path'); // '/path'
111+
* ```
112+
*/
113+
export function collapseLeadingSlashes(pathname: string): string {
114+
// Use a "Pointer" to avoid intermediate slices
115+
let start = 0;
116+
while (start < pathname.length && AUTHORITY_DELIMITERS.has(pathname[start])) {
117+
start++;
118+
}
119+
120+
// Nothing to collapse when the path already starts with at most one forward slash.
121+
if (start === 0 || (start === 1 && pathname[0] === '/')) {
122+
return pathname;
123+
}
124+
125+
return `/${pathname.slice(start)}`;
126+
}
127+
81128
/**
82129
* Joins URL parts into a single URL string.
83130
*

‎packages/angular/ssr/test/app_spec.ts‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -435,6 +435,92 @@ describe('AngularServerApp', () => {
435435
expect(response?.status).toBe(302);
436436
});
437437

438+
describe('protocol-relative redirects', () => {
439+
/**
440+
* Installs a route tree where the first URL segment is a parameter with a wildcard child.
441+
* This allows the router to match a URL such as `/.;/(//example.com)`, which the router
442+
* serializes with an empty leading segment.
443+
*/
444+
function setupWildcardChildManifest(): AngularServerApp {
445+
setAngularAppTestingManifest(
446+
[
447+
{
448+
path: ':slug',
449+
children: [{ path: '**', component: HomeComponent }],
450+
},
451+
],
452+
[{ path: '**', renderMode: RenderMode.Server }],
453+
);
454+
455+
return new AngularServerApp();
456+
}
457+
458+
afterEach(() => {
459+
setupManifest();
460+
});
461+
462+
it('should not redirect to another origin when the final URL has an empty leading segment', async () => {
463+
const customApp = setupWildcardChildManifest();
464+
const response = await customApp.handle(
465+
new Request('http://localhost/.;/(//example.com)'),
466+
);
467+
468+
expect(response?.status).toBe(302);
469+
expect(response?.headers.get('location')).toBe('/example.com');
470+
});
471+
472+
it('should keep the query string and userinfo on the current origin', async () => {
473+
const customApp = setupWildcardChildManifest();
474+
const response = await customApp.handle(
475+
new Request('http://localhost/.;/(//user@example.com:8080/login)?session=abc'),
476+
);
477+
478+
expect(response?.status).toBe(302);
479+
expect(response?.headers.get('location')).toBe(
480+
'/user@example.com:8080/login?session=abc',
481+
);
482+
});
483+
484+
it('should not redirect again when the redirect location is requested', async () => {
485+
const customApp = setupWildcardChildManifest();
486+
const response = await customApp.handle(new Request('http://localhost/example.com'));
487+
488+
expect(response?.status).toBe(200);
489+
expect(await response?.text()).toContain('Home works');
490+
});
491+
492+
it('should not redirect to another origin for any X-Forwarded-Prefix', async () => {
493+
// `AngularAppEngine` rejects these headers before they reach here, but it is not the
494+
// only caller: the development server drives `AngularServerApp` directly through
495+
// `ɵgetOrCreateAngularServerApp`, without that validation.
496+
const prefixes = [
497+
'//evil.test',
498+
'///evil.test',
499+
'/\\evil.test',
500+
'\\\\evil.test',
501+
// A tab is a legal header value character, and the URL parser removes it before
502+
// parsing, so these describe the same protocol-relative URL as the ones above.
503+
'/\t/evil.test',
504+
'/\t\\evil.test',
505+
'\t//evil.test',
506+
'/\t\t/evil.test',
507+
];
508+
509+
for (const prefix of prefixes) {
510+
const response = await app.handle(
511+
new Request('http://localhost/redirect', {
512+
headers: { 'X-Forwarded-Prefix': prefix },
513+
}),
514+
);
515+
516+
const location = response?.headers.get('location') ?? '';
517+
expect(new URL(location, 'http://localhost').origin)
518+
.withContext(`X-Forwarded-Prefix: ${JSON.stringify(prefix)} -> ${location}`)
519+
.toBe('http://localhost');
520+
}
521+
});
522+
});
523+
438524
it('should work with complex and encoded URLs', async () => {
439525
const urls = [
440526
'http://localhost/home?email=xyz%40xyz.com',

‎packages/angular/ssr/test/utils/redirect_spec.ts‎

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,86 @@ describe('Redirect Utils', () => {
4646
expect(response.headers.get('Vary')).toBe('X-Forwarded-Prefix, Host');
4747
});
4848

49+
it('should normalize the Location header to an absolute path', () => {
50+
const locations = {
51+
'//example.com': '/example.com',
52+
'///example.com': '/example.com',
53+
'/\\example.com': '/example.com',
54+
'\\\\example.com': '/example.com',
55+
// A tab, line feed or carriage return is removed by the URL parser before it parses, so
56+
// one between the slashes still yields a protocol-relative URL unless it is collapsed too.
57+
'/\t/example.com': '/example.com',
58+
'/\t\\example.com': '/example.com',
59+
'\t//example.com': '/example.com',
60+
'/\n/example.com': '/example.com',
61+
'/\r/example.com': '/example.com',
62+
'https://example.com/path': '/https://example.com/path',
63+
'': '/',
64+
};
65+
66+
for (const [location, expected] of Object.entries(locations)) {
67+
const response = createRedirectResponse(location);
68+
expect(response.headers.get('Location'))
69+
.withContext(`Location: "${location}"`)
70+
.toBe(expected);
71+
}
72+
});
73+
74+
it('should never emit a Location header that resolves to another origin', () => {
75+
const origin = 'https://example.com';
76+
77+
// The guarantee is about every string, so the inputs are generated rather than listed: a
78+
// hand-written list only covers the escapes that were thought of when it was written.
79+
// These are the characters that can begin an authority once a client parses the value,
80+
// either directly or because the URL parser removes them first.
81+
const separators = ['/', '\\', '\t', '\n', '\r', ' ', '.', ';', '@', '%2f', '%5c', '%09'];
82+
const locations = new Set([
83+
'https://evil.test/path',
84+
'evil.test:8080/path',
85+
'javascript:alert(1)',
86+
'',
87+
]);
88+
89+
for (const first of separators) {
90+
for (const second of separators) {
91+
for (const third of separators) {
92+
locations.add(`${first}${second}${third}evil.test`);
93+
}
94+
}
95+
}
96+
97+
const escapes: string[] = [];
98+
for (const location of locations) {
99+
let emitted: string | null;
100+
try {
101+
emitted = createRedirectResponse(location).headers.get('Location');
102+
} catch {
103+
// A value the Headers layer rejects, such as one containing a line feed, can never be
104+
// emitted in the first place.
105+
continue;
106+
}
107+
108+
if (new URL(emitted ?? '', origin).origin !== origin) {
109+
escapes.push(`${JSON.stringify(location)} -> ${JSON.stringify(emitted)}`);
110+
}
111+
}
112+
113+
expect(escapes)
114+
.withContext(`Locations that left the origin: ${escapes.join(', ')}`)
115+
.toEqual([]);
116+
});
117+
118+
it('should warn if the Location is rewritten in dev mode', () => {
119+
// @ts-expect-error accessing global
120+
globalThis.ngDevMode = true;
121+
const warnSpy = spyOn(console, 'warn');
122+
createRedirectResponse('//example.com');
123+
expect(warnSpy).toHaveBeenCalledWith(
124+
'Location "//example.com" is not an absolute path and was rewritten to "/example.com" ' +
125+
'to keep the redirect on the current origin.',
126+
);
127+
});
128+
49129
it('should warn if Location header is provided in extra headers in dev mode', () => {
50130
// @ts-expect-error accessing global
51131
globalThis.ngDevMode = true;

‎packages/angular/ssr/test/utils/url_spec.ts‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
addLeadingSlash,
1111
addTrailingSlash,
1212
buildPathWithParams,
13+
collapseLeadingSlashes,
1314
joinUrlParts,
1415
stripIndexHtmlFromURL,
1516
stripLeadingSlash,
@@ -84,6 +85,56 @@ describe('URL Utils', () => {
8485
});
8586
});
8687

88+
describe('collapseLeadingSlashes', () => {
89+
it('should collapse multiple leading slashes into a single slash', () => {
90+
expect(collapseLeadingSlashes('//example.com')).toBe('/example.com');
91+
expect(collapseLeadingSlashes('///example.com')).toBe('/example.com');
92+
});
93+
94+
it('should replace leading backslashes with a single slash', () => {
95+
expect(collapseLeadingSlashes('\\example.com')).toBe('/example.com');
96+
expect(collapseLeadingSlashes('\\\\example.com')).toBe('/example.com');
97+
expect(collapseLeadingSlashes('/\\example.com')).toBe('/example.com');
98+
expect(collapseLeadingSlashes('\\/example.com')).toBe('/example.com');
99+
});
100+
101+
it('should collapse characters the URL parser removes along with the slashes', () => {
102+
// The WHATWG URL parser removes tab, line feed and carriage return from its input before
103+
// parsing it, so these all describe the same protocol-relative URL as `//example.com`.
104+
expect(collapseLeadingSlashes('/\t/example.com')).toBe('/example.com');
105+
expect(collapseLeadingSlashes('/\n/example.com')).toBe('/example.com');
106+
expect(collapseLeadingSlashes('/\r/example.com')).toBe('/example.com');
107+
expect(collapseLeadingSlashes('\t//example.com')).toBe('/example.com');
108+
expect(collapseLeadingSlashes('/\t\\example.com')).toBe('/example.com');
109+
expect(collapseLeadingSlashes('/\t\t/example.com')).toBe('/example.com');
110+
});
111+
112+
it('should not modify a path with a single leading slash', () => {
113+
expect(collapseLeadingSlashes('/path/to/resource')).toBe('/path/to/resource');
114+
});
115+
116+
it('should preserve a removable character that is not leading', () => {
117+
// Once a path segment has started, a later tab cannot reopen an authority.
118+
expect(collapseLeadingSlashes('/path/\t/to')).toBe('/path/\t/to');
119+
});
120+
121+
it('should not modify a path without a leading slash', () => {
122+
expect(collapseLeadingSlashes('path/to/resource')).toBe('path/to/resource');
123+
});
124+
125+
it('should preserve slashes that are not leading', () => {
126+
expect(collapseLeadingSlashes('/path//to///resource')).toBe('/path//to///resource');
127+
});
128+
129+
it('should handle a path containing only slashes', () => {
130+
expect(collapseLeadingSlashes('//')).toBe('/');
131+
});
132+
133+
it('should handle an empty path', () => {
134+
expect(collapseLeadingSlashes('')).toBe('');
135+
});
136+
});
137+
87138
describe('joinUrlParts', () => {
88139
it('should join multiple URL parts with normalized slashes', () => {
89140
expect(joinUrlParts('', 'path/', '/to/resource')).toBe('/path/to/resource');

0 commit comments

Comments
 (0)