fix: validate the url to avoid SSRF

This commit is contained in:
Fred 2024-06-24 14:31:50 +08:00
parent 78e7ea72dc
commit 9fb8fbcc65
No known key found for this signature in database
GPG Key ID: 4DABDA85EF70EC71
1 changed files with 17 additions and 3 deletions

View File

@ -9,6 +9,14 @@ const mergedAllowedWebDavEndpoints = [
...config.allowedWebDevEndpoints,
].filter((domain) => Boolean(domain.trim()));
const normalizeUrl = (url: string) => {
try {
return new URL(url);
} catch (err) {
return null;
}
};
async function handle(
req: NextRequest,
{ params }: { params: { path: string[] } },
@ -24,9 +32,15 @@ async function handle(
// Validate the endpoint to prevent potential SSRF attacks
if (
!mergedAllowedWebDavEndpoints.some(
(allowedEndpoint) => endpoint?.startsWith(allowedEndpoint),
)
!endpoint ||
!mergedAllowedWebDavEndpoints.some((allowedEndpoint) => {
const normalizedAllowedEndpoint = normalizeUrl(allowedEndpoint);
const normalizedEndpoint = normalizeUrl(endpoint as string);
return normalizedEndpoint &&
normalizedEndpoint.hostname === normalizedAllowedEndpoint?.hostname &&
normalizedEndpoint.pathname.startsWith(normalizedAllowedEndpoint.pathname);
})
) {
return NextResponse.json(
{