CVE-2024-29180 (published 2024-03-21T17:15Z)

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.\n\nDevelopers 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.


Weakness information:
cwe_id: NVD-CWE-noinfo
cwe_name: Insufficient Information
description: There is insufficient information about the issue to classify it; details are unkown or unspecified.
extended_description: Insufficient Information

Fix information:
repo_url: https://github.com/webpack/webpack-dev-middleware
commit_details: repo_url: https://github.com/webpack/webpack-dev-middleware
author: Alexander Akait
author_date: 2024-03-19 22:26:00+03:00
msg: fix(security): do not allow to read files above (#1771)
repository: repo_url: https://github.com/webpack/webpack-dev-middleware
repo_name: webpack/webpack-dev-middleware
description: A development middleware for webpack
repo_language: JavaScript
owner: webpack
file_changes: filename: .cspell.json
change_type: ModificationType.MODIFY
diff: @@ -18,7 +18,8 @@
     "configurated",
     "mycustom",
     "commitlint",
-    "nosniff"
+    "nosniff",
+    "deoptimize"
   ],
   "ignorePaths": [
     "CHANGELOG.md",

programming_language: CoffeeScript
filename: middleware.js
change_type: ModificationType.MODIFY
diff: @@ -80,6 +80,18 @@ function wrapper(context) {
         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();
 
@@ -164,6 +176,7 @@ function wrapper(context) {
             headers: {
               "Content-Range": res.getHeader("Content-Range"),
             },
+            modifyResponseData: context.options.modifyResponseData,
           });
 
           return;

programming_language: JavaScript
filename: compatibleAPI.js
change_type: ModificationType.MODIFY
diff: @@ -177,6 +177,8 @@ 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",
@@ -213,7 +215,7 @@ function sendError(req, res, status, options) {
 
   // 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");
 

programming_language: TypeScript
filename: getFilenameFromUrl.js
change_type: ModificationType.MODIFY
diff: @@ -43,11 +43,28 @@ const mem = (fn, { cache = new Map() } = {}) => {
 };
 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
@@ -85,22 +102,35 @@ function getFilenameFromUrl(context, url, extra = {}) {
       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 =

programming_language: TypeScript
filename: middleware.test.js
change_type: ModificationType.MODIFY
diff: @@ -99,6 +99,10 @@ describe.each([
             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",
@@ -183,6 +187,36 @@ describe.each([
           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"),
@@ -263,7 +297,7 @@ describe.each([
             `bytes */${codeLength}`,
           );
           expect(response.headers["content-type"]).toEqual(
-            "text/html; charset=UTF-8",
+            "text/html; charset=utf-8",
           );
           expect(response.text).toEqual(
             `<!DOCTYPE html>
@@ -447,6 +481,29 @@ describe.each([
             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', () => {
@@ -2032,7 +2089,7 @@ describe.each([
 
           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" +
@@ -2113,7 +2170,7 @@ describe.each([
 
           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" +
@@ -2575,6 +2632,7 @@ describe.each([
             output: {
               filename: "bundle.js",
               path: path.resolve(__dirname, "./outputs/write-to-disk-true"),
+              publicPath: "/public/",
             },
           });
 
@@ -2598,7 +2656,7 @@ describe.each([
 
         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);
@@ -2632,6 +2690,25 @@ describe.each([
               );
             });
         });
+
+        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`', () => {

programming_language: TypeScript
filename: getFilenameFromUrl.d.ts
change_type: ModificationType.MODIFY
diff: @@ -1,9 +1,5 @@
 /// <reference types="node" />
 export = getFilenameFromUrl;
-/**
- * @typedef {Object} Extra
- * @property {import("fs").Stats=} stats
- */
 /**
  * @template {IncomingMessage} Request
  * @template {ServerResponse} Response
@@ -25,6 +21,7 @@ declare namespace getFilenameFromUrl {
 }
 type Extra = {
   stats?: import("fs").Stats | undefined;
+  errorCode?: number | undefined;
 };
 type IncomingMessage = import("../index.js").IncomingMessage;
 type ServerResponse = import("../index.js").ServerResponse;

programming_language: TypeScript