Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
fix: secure resource loader SSRF (#6497)
Oleg Isonen54d720b18582
diff --git a/apps/builder/app/routes/rest.resources-loader.ts b/apps/builder/app/routes/rest.resources-loader.tsindex dea10bceee..febf46125b 100644--- a/apps/builder/app/routes/rest.resources-loader.ts+++ b/apps/builder/app/routes/rest.resources-loader.ts@@ -1,4 +1,5 @@import { type ActionFunctionArgs, data, json } from "@remix-run/server-runtime";+import { authorizeProject } from "@webstudio-is/trpc-interface/index.server";import { isLocalResource } from "@webstudio-is/sdk/runtime";import { parseBuilderUrl } from "@webstudio-is/protocol";import { loader as siteMapLoader } from "../shared/$resources/sitemap.xml.server";@@ -8,7 +9,9 @@ import { executeAssetQuery } from "../shared/$resources/assets-query.server";import { loader as assetsOpenApiLoader } from "./rest.assets.openapi[.]json";import { preventCrossOriginCookie } from "~/services/no-cross-origin-cookie";import { checkCsrf } from "~/services/csrf-session.server";+import { safeResourceFetch } from "~/services/safe-resource-fetch.server";import { privateNoStoreResponseHeaders } from "~/services/cache-control.server";+import { createContext } from "~/shared/context.server";import {loadResourceRequestList,resourceRequestListSchema,@@ -16,6 +19,29 @@ import {export const action = async ({ request }: ActionFunctionArgs) => {preventCrossOriginCookie(request);+ const { projectId, sourceOrigin } = parseBuilderUrl(request.url);+ if (projectId === undefined) {+ throw new Response("Project ID is not defined", { status: 404 });+ }++ const context = await createContext(request);+ if (+ context.authorization.type === "anonymous" ||+ context.authorization.type === "service"+ ) {+ throw new Response("Authentication required", { status: 401 });+ }+ if (+ (await authorizeProject.hasProjectPermit(+ { projectId, permit: "view" },+ context+ )) === false+ ) {+ throw new Response("You don't have access to this project", {+ status: 403,+ });+ }+await checkCsrf(request);const includeDiagnostics =new URL(request.url).searchParams.get("diagnostics") === "true";@@ -23,7 +49,9 @@ export const action = async ({ request }: ActionFunctionArgs) => {// Hope Remix will have customFetch by default, see https://kit.svelte.dev/docs/load#making-fetch-requestsconst customFetch: typeof fetch = (input, init) => {if (typeof input !== "string") {- return fetch(input, init);+ return Promise.reject(+ new TypeError("Resource loader requires a URL string")+ );}if (isLocalResource(input, "sitemap.xml")) {@@ -51,11 +79,10 @@ export const action = async ({ request }: ActionFunctionArgs) => {return assetsOpenApiLoader({ request });}- return fetch(input, init);+ return safeResourceFetch(input, init);};const requestJson = await request.json();- const { sourceOrigin } = parseBuilderUrl(request.url);const requestList = resourceRequestListSchema.safeParse(requestJson);if (requestList.success === false) {diff --git a/apps/builder/app/services/safe-resource-fetch.server.ts b/apps/builder/app/services/safe-resource-fetch.server.tsnew file mode 100644index 0000000000..6ca765b98e--- /dev/null+++ b/apps/builder/app/services/safe-resource-fetch.server.ts@@ -0,0 +1,146 @@+import { lookup as dnsLookup, type LookupAddress } from "node:dns";+import { BlockList, isIP } from "node:net";+import { Agent, buildConnector, fetch as undiciFetch } from "undici";++const blockedIPv4 = new BlockList();+for (const [subnet, prefix] of [+ ["0.0.0.0", 8],+ ["10.0.0.0", 8],+ ["100.64.0.0", 10],+ ["127.0.0.0", 8],+ ["169.254.0.0", 16],+ ["172.16.0.0", 12],+ ["192.0.0.0", 24],+ ["192.0.2.0", 24],+ ["192.88.99.0", 24],+ ["192.168.0.0", 16],+ ["198.18.0.0", 15],+ ["198.51.100.0", 24],+ ["203.0.113.0", 24],+ ["224.0.0.0", 4],+ ["240.0.0.0", 4],+] as const) {+ blockedIPv4.addSubnet(subnet, prefix, "ipv4");+}++const blockedIPv6 = new BlockList();+const globallyRoutableIPv6 = new BlockList();+globallyRoutableIPv6.addSubnet("2000::", 3, "ipv6");+blockedIPv6.addSubnet("2001::", 23, "ipv6");+blockedIPv6.addSubnet("2001:db8::", 32, "ipv6");+blockedIPv6.addSubnet("2002::", 16, "ipv6");+blockedIPv6.addSubnet("3fff::", 20, "ipv6");++const isPublicAddress = (address: string, family: number) => {+ if (family === 4) {+ // Builder E2E fixtures run on loopback; production never enables this.+ if (+ process.env.E2E_ALLOW_LOCAL_RESOURCE_URLS === "true" &&+ blockedIPv4.check(address, "ipv4") &&+ address.startsWith("127.")+ ) {+ return true;+ }+ return blockedIPv4.check(address, "ipv4") === false;+ }+ if (+ process.env.E2E_ALLOW_LOCAL_RESOURCE_URLS === "true" &&+ address === "::1"+ ) {+ return true;+ }+ return (+ globallyRoutableIPv6.check(address, "ipv6") &&+ blockedIPv6.check(address, "ipv6") === false+ );+};++type LookupOptions =+ | { all?: boolean; family?: number | "IPv4" | "IPv6" }+ | number;+type LookupCallback = (+ error: NodeJS.ErrnoException | null,+ address: string | LookupAddress[],+ family?: number+) => void;++// Validate DNS answers in the socket connector so the checked address is the+// address used for the connection. The connector also checks literal IPs,+// including on redirect hops.+const lookupPublicAddress = (+ hostname: string,+ options: LookupOptions,+ callback: LookupCallback+) => {+ dnsLookup(hostname, { all: true, verbatim: true }, (cause, addresses) => {+ if (cause !== null) {+ callback(cause, typeof options === "object" && options.all ? [] : "", 0);+ return;+ }++ const requestedFamily =+ typeof options === "number" ? options : options.family;+ const family =+ requestedFamily === "IPv4"+ ? 4+ : requestedFamily === "IPv6"+ ? 6+ : requestedFamily;+ const candidates =+ family === undefined || family === 0+ ? addresses+ : addresses.filter((address) => address.family === family);++ if (+ candidates.length === 0 ||+ addresses.some(+ ({ address, family }) => isPublicAddress(address, family) === false+ )+ ) {+ const error = Object.assign(new Error("Host is not publicly routable"), {+ code: "ENOTFOUND",+ });+ callback(error, typeof options === "object" && options.all ? [] : "", 0);+ return;+ }++ if (typeof options === "object" && options.all) {+ callback(null, candidates);+ return;+ }+ const selected = candidates[0];+ callback(null, selected.address, selected.family);+ });+};++const connector = buildConnector({ lookup: lookupPublicAddress as never });+const safeConnector: ReturnType<typeof buildConnector> = (+ options,+ callback+) => {+ const hostname = options.hostname.replace(/^\[|\]$/g, "");+ const family = isIP(hostname);+ if (family !== 0 && isPublicAddress(hostname, family) === false) {+ callback(new Error("Host is not publicly routable"), null);+ return;+ }+ connector(options, callback);+};++const dispatcher = new Agent({+ connections: 10,+ maxOrigins: 100,+ connect: safeConnector,+});++/** Fetch an external resource only when its connection uses a public IP. */+export const safeResourceFetch = async (+ input: string,+ init?: RequestInit+): Promise<Response> => {+ const response = await undiciFetch(input, {+ ...init,+ dispatcher,+ } as unknown as Parameters<typeof undiciFetch>[1]);+ return response as unknown as Response;+};diff --git a/apps/builder/e2e/serve-built-remix.ts b/apps/builder/e2e/serve-built-remix.tsindex 50625e7edc..39c503aaaf 100644--- a/apps/builder/e2e/serve-built-remix.ts+++ b/apps/builder/e2e/serve-built-remix.ts@@ -11,6 +11,9 @@ import { pathToFileURL } from "node:url";installGlobals({ nativeFetch: true });const start = async () => {+ // Resource E2E fixtures use loopback URLs. Keep this exception limited to+ // the dedicated test server; production uses the public-address guard.+ process.env.E2E_ALLOW_LOCAL_RESOURCE_URLS = "true";const serverDirectory = path.resolve("build/server");const builds = await Promise.all(readdirSync(serverDirectory, { withFileTypes: true })diff --git a/apps/builder/package.json b/apps/builder/package.jsonindex 880e050cad..e6c1f65cb8 100644--- a/apps/builder/package.json+++ b/apps/builder/package.json@@ -141,6 +141,7 @@"strip-indent": "^4.0.0","tiny-invariant": "^1.3.3","title-case": "^4.3.2",+ "undici": "^7.29.0","urlpattern-polyfill": "^10.1.0","use-debounce": "^10.0.4","valid-filename": "^4.0.0",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex e266683863..ec6d9ab84d 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -448,6 +448,9 @@ importers:title-case:specifier: ^4.3.2version: 4.3.2+ undici:+ specifier: ^7.29.0+ version: 7.29.0urlpattern-polyfill:specifier: ^10.1.0version: 10.1.0@@ -11912,10 +11915,6 @@ packages:resolution: {integrity: sha512-uROZWze0R0itiAKVPsYhFov9LxrPMHLMEQFszeI2gCN6bnIIZ8twzBCJcN2LJrBBLfrP0t1FW0g+JmKVl8Vk1g==}engines: {node: '>=18.17'}- resolution: {integrity: sha512-cRZYrTDwWznlnRiPjggAGxZXanty6M8RV1ff8Wm4LWXBp7/IG8v5DnOm74DtUBp9OONpK75YlPnIjQqX0dBDtA==}- engines: {node: '>=20.18.1'}-resolution: {integrity: sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==}engines: {node: '>=20.18.1'}@@ -22220,7 +22219,7 @@ snapshots:tailwind-merge: 3.6.0ts-morph: 26.0.0tsconfig-paths: 4.2.0- undici: 7.28.0+ undici: 7.29.0validate-npm-package-name: 7.0.2zod: 3.25.76zod-to-json-schema: 3.25.2([email protected])@@ -22779,8 +22778,6 @@ snapshots:- [email protected]: {}-