CVE-2024-29180: Insufficient Information (NVD-CWE-noinfo)
value: Prior to versions 7.1.0, 6.1.2, and 5.3.4, the webpack-dev-middleware development middleware for devpack does not validate the supplied URL address sufficiently before returning the local file. It is possible to access any file on the developer's machine. The middleware can either work with the physical filesystem when reading the files or it can use a virtualized in-memory `memfs` filesystem. If `writeToDisk` configuration option is set to `true`, the physical filesystem is used. The `getFilenameFromUrl` method is used to parse URL and build the local file path. The public path prefix is stripped from the URL, and the `unsecaped` path suffix is appended to the `outputPath`. As the URL is not unescaped and normalized automatically before calling the midlleware, it is possible to use `%2e` and `%2f` sequences to perform path traversal attack.

Developers using `webpack-dev-server` or `webpack-dev-middleware` are affected by the issue. When the project is started, an attacker might access any file on the developer's machine and exfiltrate the content. If the development server is listening on a public IP address (or `0.0.0.0`), an attacker on the local network can access the local files without any interaction from the victim (direct connection to the port). If the server allows access from third-party domains, an attacker can send a malicious link to the victim. When visited, the client side script can connect to the local server and exfiltrate the local files. Starting with fixed versions 7.1.0, 6.1.2, and 5.3.4, the URL is unescaped and normalized before any further processing.
CWE description: There is insufficient information about the issue to classify it; details are unkown or unspecified.
Published: 2024-03-21T17:15Z
Repository: https://github.com/webpack/webpack-dev-middleware
Language: JavaScript
Files changed: .cspell.json, src/middleware.js, src/utils/compatibleAPI.js, src/utils/getFilenameFromUrl.js, test/middleware.test.js, types/utils/getFilenameFromUrl.d.ts
Commit date: 2024-03-19 22:26:00 +0300
Commit message: fix(security): do not allow to read files above (#1771)


Diff: diff --git a/.cspell.json b/.cspell.json
index 490b854..5fd2585 100644
--- a/.cspell.json
+++ b/.cspell.json
@@ -16,11 +16,12 @@
     "leadinghash",
     "myhtml",
     "configurated",
     "mycustom",
     "commitlint",
-    "nosniff"
+    "nosniff",
+    "deoptimize"
   ],
   "ignorePaths": [
     "CHANGELOG.md",
     "package.json",
     "dist/**",
diff --git a/src/middleware.js b/src/middleware.js
index a7de58d..fa507f8 100644
--- a/src/middleware.js
+++ b/src/middleware.js
@@ -78,10 +78,22 @@ function wrapper(context) {
         context,
         /** @type {string} */ (req.url),
         extra,
       );
 
+      if (extra.errorCode) {
+        if (extra.errorCode === 403) {
+          context.logger.error(`Malicious path "${filename}".`);
+        }
+
+        sendError(req, res, extra.errorCode, {
+          modifyResponseData: context.options.modifyResponseData,
+        });
+
+        return;
+      }
+
       if (!filename) {
         await goNext();
 
         return;
       }
@@ -162,10 +174,11 @@ function wrapper(context) {
 
           sendError(req, res, 416, {
             headers: {
               "Content-Range": res.getHeader("Content-Range"),
             },
+            modifyResponseData: context.options.modifyResponseData,
           });
 
           return;
         } else if (parsedRanges === -2) {
           context.logger.error(
diff --git a/src/utils/compatibleAPI.js b/src/utils/compatibleAPI.js
index e8e3f5b..b168f04 100644
--- a/src/utils/compatibleAPI.js
+++ b/src/utils/compatibleAPI.js
@@ -175,10 +175,12 @@ function destroyStream(stream, suppress) {
   }
 }
 
 /** @type {Record<number, string>} */
 const statuses = {
+  400: "Bad Request",
+  403: "Forbidden",
   404: "Not Found",
   416: "Range Not Satisfiable",
   500: "Internal Server Error",
 };
 
@@ -211,11 +213,11 @@ function sendError(req, res, status, options) {
     setHeadersForResponse(res, options.headers);
   }
 
   // Send basic response
   setStatusCode(res, status);
-  setHeaderForResponse(res, "Content-Type", "text/html; charset=UTF-8");
+  setHeaderForResponse(res, "Content-Type", "text/html; charset=utf-8");
   setHeaderForResponse(res, "Content-Security-Policy", "default-src 'none'");
   setHeaderForResponse(res, "X-Content-Type-Options", "nosniff");
 
   let byteLength = Buffer.byteLength(document);
 
diff --git a/src/utils/getFilenameFromUrl.js b/src/utils/getFilenameFromUrl.js
index 82fab74..82a5811 100644
--- a/src/utils/getFilenameFromUrl.js
+++ b/src/utils/getFilenameFromUrl.js
@@ -41,15 +41,32 @@ const mem = (fn, { cache = new Map() } = {}) => {
 
   return memoized;
 };
 const memoizedParse = mem(parse);
 
+const UP_PATH_REGEXP = /(?:^|[\\/])\.\.(?:[\\/]|$)/;
+
 /**
  * @typedef {Object} Extra
  * @property {import("fs").Stats=} stats
+ * @property {number=} errorCode
+ */
+
+/**
+ * decodeURIComponent.
+ *
+ * Allows V8 to only deoptimize this fn instead of all of send().
+ *
+ * @param {string} input
+ * @returns {string}
  */
 
+function decode(input) {
+  return querystring.unescape(input);
+}
+
+// TODO refactor me in the next major release, this function should return `{ filename, stats, error }`
 /**
  * @template {IncomingMessage} Request
  * @template {ServerResponse} Response
  * @param {import("../index.js").Context<Request, Response>} context
  * @param {string} url
@@ -83,26 +100,39 @@ function getFilenameFromUrl(context, url, extra = {}) {
     } catch (_ignoreError) {
       // eslint-disable-next-line no-continue
       continue;
     }
 
-    if (
-      urlObject.pathname &&
-      urlObject.pathname.startsWith(publicPathObject.pathname)
-    ) {
-      filename = outputPath;
+    const pathname = decode(urlObject.pathname);
+    const publicPathPathname = decode(publicPathObject.pathname);
+
+    if (pathname && pathname.startsWith(publicPathPathname)) {
+      // Null byte(s)
+      if (pathname.includes("\0")) {
+        // eslint-disable-next-line no-param-reassign
+        extra.errorCode = 400;
+
+        return;
+      }
+
+      // ".." is malicious
+      if (UP_PATH_REGEXP.test(path.normalize(`./${pathname}`))) {
+        // eslint-disable-next-line no-param-reassign
+        extra.errorCode = 403;
+
+        return;
+      }
 
       // Strip the `pathname` property from the `publicPath` option from the start of requested url
       // `/complex/foo.js` => `foo.js`
-      const pathname = urlObject.pathname.slice(
-        publicPathObject.pathname.length,
+      // and add outputPath
+      // `foo.js` => `/home/user/my-project/dist/foo.js`
+      filename = path.join(
+        outputPath,
+        pathname.slice(publicPathPathname.length),
       );
 
-      if (pathname) {
-        filename = path.join(outputPath, querystring.unescape(pathname));
-      }
-
       try {
         // eslint-disable-next-line no-param-reassign
         extra.stats =
           /** @type {import("fs").statSync} */
           (context.outputFileSystem.statSync)(filename);
diff --git a/test/middleware.test.js b/test/middleware.test.js
index 755b92f..79288d0 100644
--- a/test/middleware.test.js
+++ b/test/middleware.test.js
@@ -97,10 +97,14 @@ describe.each([
           });
           instance.context.outputFileSystem.writeFileSync(
             path.resolve(outputPath, "image.svg"),
             "svg image",
           );
+          instance.context.outputFileSystem.writeFileSync(
+            path.resolve(outputPath, "image image.svg"),
+            "svg image",
+          );
           instance.context.outputFileSystem.writeFileSync(
             path.resolve(outputPath, "byte-length.html"),
             "\u00bd + \u00bc = \u00be",
           );
           instance.context.outputFileSystem.mkdirSync(
@@ -181,10 +185,40 @@ describe.each([
             fileData.byteLength.toString(),
           );
           expect(response.headers["content-type"]).toEqual("image/svg+xml");
         });
 
+        it('should return the "200" code for the "GET" request to the "image.svg" file with "/../"', async () => {
+          const fileData = instance.context.outputFileSystem.readFileSync(
+            path.resolve(outputPath, "image.svg"),
+          );
+
+          const response = await req.get("/public/../image.svg");
+
+          expect(response.statusCode).toEqual(200);
+          expect(response.headers["content-length"]).toEqual(
+            fileData.byteLength.toString(),
+          );
+          expect(response.headers["content-type"]).toEqual("image/svg+xml");
+        });
+
+        it('should return the "200" code for the "GET" request to the "image.svg" file with "/../../../"', async () => {
+          const fileData = instance.context.outputFileSystem.readFileSync(
+            path.resolve(outputPath, "image.svg"),
+          );
+
+          const response = await req.get(
+            "/public/assets/images/../../../image.svg",
+          );
+
+          expect(response.statusCode).toEqual(200);
+          expect(response.headers["content-length"]).toEqual(
+            fileData.byteLength.toString(),
+          );
+          expect(response.headers["content-type"]).toEqual("image/svg+xml");
+        });
+
         it('should return the "200" code for the "GET" request to the directory', async () => {
           const fileData = fs.readFileSync(
             path.resolve(__dirname, "./fixtures/index.html"),
           );
 
@@ -261,11 +295,11 @@ describe.each([
           expect(response.statusCode).toEqual(416);
           expect(response.headers["content-range"]).toEqual(
             `bytes */${codeLength}`,
           );
           expect(response.headers["content-type"]).toEqual(
-            "text/html; charset=UTF-8",
+            "text/html; charset=utf-8",
           );
           expect(response.text).toEqual(
             `<!DOCTYPE html>
 <html lang="en">
 <head>
@@ -445,10 +479,33 @@ describe.each([
           );
           expect(fs.existsSync(path.resolve(outputPath, "bundle.js"))).toBe(
             false,
           );
         });
+
+        it('should return the "200" code for the "GET" request to the "image image.svg" file', async () => {
+          const fileData = instance.context.outputFileSystem.readFileSync(
+            path.resolve(outputPath, "image image.svg"),
+          );
+
+          const response = await req.get("/image image.svg");
+
+          expect(response.statusCode).toEqual(200);
+          expect(response.headers["content-length"]).toEqual(
+            fileData.byteLength.toString(),
+          );
+          expect(response.headers["content-type"]).toEqual("image/svg+xml");
+        });
+
+        it('should return the "404" code for the "GET" request to the "%FF" file', async () => {
+          const response = await req.get("/%FF");
+
+          expect(response.statusCode).toEqual(404);
+          expect(response.headers["content-type"]).toEqual(
+            "text/html; charset=utf-8",
+          );
+        });
       });
 
       describe('should not work with the broken "publicPath" option', () => {
         let compiler;
 
@@ -2030,11 +2087,11 @@ describe.each([
         it('should return the "500" code for the "GET" request to the "image.svg" file', async () => {
           const response = await req.get("/image.svg").set("Range", "bytes=0-");
 
           expect(response.statusCode).toEqual(500);
           expect(response.headers["content-type"]).toEqual(
-            "text/html; charset=UTF-8",
+            "text/html; charset=utf-8",
           );
           expect(response.text).toEqual(
             "<!DOCTYPE html>\n" +
               '<html lang="en">\n' +
               "<head>\n" +
@@ -2111,11 +2168,11 @@ describe.each([
         it('should return the "404" code for the "GET" request to the "image.svg" file', async () => {
           const response = await req.get("/image.svg").set("Range", "bytes=0-");
 
           expect(response.statusCode).toEqual(404);
           expect(response.headers["content-type"]).toEqual(
-            "text/html; charset=UTF-8",
+            "text/html; charset=utf-8",
           );
           expect(response.text).toEqual(
             "<!DOCTYPE html>\n" +
               '<html lang="en">\n' +
               "<head>\n" +
@@ -2573,10 +2630,11 @@ describe.each([
           compiler = getCompiler({
             ...webpackConfig,
             output: {
               filename: "bundle.js",
               path: path.resolve(__dirname, "./outputs/write-to-disk-true"),
+              publicPath: "/public/",
             },
           });
 
           instance = middleware(compiler, { writeToDisk: true });
 
@@ -2596,11 +2654,11 @@ describe.each([
           close(done);
         });
 
         it("should find the bundle file on disk", (done) => {
           request(app)
-            .get("/bundle.js")
+            .get("/public/bundle.js")
             .expect(200, (error) => {
               if (error) {
                 return done(error);
               }
 
@@ -2630,10 +2688,29 @@ describe.each([
                   done();
                 },
               );
             });
         });
+
+        it("should not allow to get files above root", async () => {
+          const response = await req.get("/public/..%2f../middleware.test.js");
+
+          expect(response.statusCode).toEqual(403);
+          expect(response.headers["content-type"]).toEqual(
+            "text/html; charset=utf-8",
+          );
+          expect(response.text).toEqual(`<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<title>Error</title>
+</head>
+<body>
+<pre>Forbidden</pre>
+</body>
+</html>`);
+        });
       });
 
       describe('should work with "true" value when the `output.clean` is `true`', () => {
         const outputPath = path.resolve(
           __dirname,
diff --git a/types/utils/getFilenameFromUrl.d.ts b/types/utils/getFilenameFromUrl.d.ts
index 7dfc803..0ab19b3 100644
--- a/types/utils/getFilenameFromUrl.d.ts
+++ b/types/utils/getFilenameFromUrl.d.ts
@@ -1,11 +1,7 @@
 /// <reference types="node" />
 export = getFilenameFromUrl;
-/**
- * @typedef {Object} Extra
- * @property {import("fs").Stats=} stats
- */
 /**
  * @template {IncomingMessage} Request
  * @template {ServerResponse} Response
  * @param {import("../index.js").Context<Request, Response>} context
  * @param {string} url
@@ -23,8 +19,9 @@ declare function getFilenameFromUrl<
 declare namespace getFilenameFromUrl {
   export { Extra, IncomingMessage, ServerResponse };
 }
 type Extra = {
   stats?: import("fs").Stats | undefined;
+  errorCode?: number | undefined;
 };
 type IncomingMessage = import("../index.js").IncomingMessage;
 type ServerResponse = import("../index.js").ServerResponse;

Vulnerable code:     "nosniff"
  setHeaderForResponse(res, "Content-Type", "text/html; charset=UTF-8");
    if (
      urlObject.pathname &&
      urlObject.pathname.startsWith(publicPathObject.pathname)
    ) {
      filename = outputPath;
      const pathname = urlObject.pathname.slice(
        publicPathObject.pathname.length,
      if (pathname) {
        filename = path.join(outputPath, querystring.unescape(pathname));
      }

            "text/html; charset=UTF-8",
            "text/html; charset=UTF-8",
            "text/html; charset=UTF-8",
            .get("/bundle.js")
/**
 * @typedef {Object} Extra
 * @property {import("fs").Stats=} stats
 */
Fixed code:     "nosniff",
    "deoptimize"
      if (extra.errorCode) {
        if (extra.errorCode === 403) {
          context.logger.error(`Malicious path "${filename}".`);
        }

        sendError(req, res, extra.errorCode, {
          modifyResponseData: context.options.modifyResponseData,
        });

        return;
      }

            modifyResponseData: context.options.modifyResponseData,
  400: "Bad Request",
  403: "Forbidden",
  setHeaderForResponse(res, "Content-Type", "text/html; charset=utf-8");
const UP_PATH_REGEXP = /(?:^|[\\/])\.\.(?:[\\/]|$)/;

 * @property {number=} errorCode
 */

/**
 * decodeURIComponent.
 *
 * Allows V8 to only deoptimize this fn instead of all of send().
 *
 * @param {string} input
 * @returns {string}
function decode(input) {
  return querystring.unescape(input);
}

// TODO refactor me in the next major release, this function should return `{ filename, stats, error }`
    const pathname = decode(urlObject.pathname);
    const publicPathPathname = decode(publicPathObject.pathname);

    if (pathname && pathname.startsWith(publicPathPathname)) {
      // Null byte(s)
      if (pathname.includes("\0")) {
        // eslint-disable-next-line no-param-reassign
        extra.errorCode = 400;

        return;
      }

      // ".." is malicious
      if (UP_PATH_REGEXP.test(path.normalize(`./${pathname}`))) {
        // eslint-disable-next-line no-param-reassign
        extra.errorCode = 403;

        return;
      }
      // and add outputPath
      // `foo.js` => `/home/user/my-project/dist/foo.js`
      filename = path.join(
        outputPath,
        pathname.slice(publicPathPathname.length),
          instance.context.outputFileSystem.writeFileSync(
            path.resolve(outputPath, "image image.svg"),
            "svg image",
          );
        it('should return the "200" code for the "GET" request to the "image.svg" file with "/../"', async () => {
          const fileData = instance.context.outputFileSystem.readFileSync(
            path.resolve(outputPath, "image.svg"),
          );

          const response = await req.get("/public/../image.svg");

          expect(response.statusCode).toEqual(200);
          expect(response.headers["content-length"]).toEqual(
            fileData.byteLength.toString(),
          );
          expect(response.headers["content-type"]).toEqual("image/svg+xml");
        });

        it('should return the "200" code for the "GET" request to the "image.svg" file with "/../../../"', async () => {
          const fileData = instance.context.outputFileSystem.readFileSync(
            path.resolve(outputPath, "image.svg"),
          );

          const response = await req.get(
            "/public/assets/images/../../../image.svg",
          );

          expect(response.statusCode).toEqual(200);
          expect(response.headers["content-length"]).toEqual(
            fileData.byteLength.toString(),
          );
          expect(response.headers["content-type"]).toEqual("image/svg+xml");
        });

            "text/html; charset=utf-8",

        it('should return the "200" code for the "GET" request to the "image image.svg" file', async () => {
          const fileData = instance.context.outputFileSystem.readFileSync(
            path.resolve(outputPath, "image image.svg"),
          );

          const response = await req.get("/image image.svg");

          expect(response.statusCode).toEqual(200);
          expect(response.headers["content-length"]).toEqual(
            fileData.byteLength.toString(),
          );
          expect(response.headers["content-type"]).toEqual("image/svg+xml");
        });

        it('should return the "404" code for the "GET" request to the "%FF" file', async () => {
          const response = await req.get("/%FF");

          expect(response.statusCode).toEqual(404);
          expect(response.headers["content-type"]).toEqual(
            "text/html; charset=utf-8",
          );
        });
            "text/html; charset=utf-8",
            "text/html; charset=utf-8",
              publicPath: "/public/",
            .get("/public/bundle.js")

        it("should not allow to get files above root", async () => {
          const response = await req.get("/public/..%2f../middleware.test.js");

          expect(response.statusCode).toEqual(403);
          expect(response.headers["content-type"]).toEqual(
            "text/html; charset=utf-8",
          );
          expect(response.text).toEqual(`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Forbidden</pre>
</body>
</html>`);
        });
  errorCode?: number | undefined;