CVE-2024-29180 (JavaScript, published 2024-03-21T17:15Z)
Description: 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.
Severity: nan (CVSS v3 base score: )
Weakness: NVD-CWE-noinfo \u2014 Insufficient Information
There is insufficient information about the issue to classify it; details are unkown or unspecified.
Repository: https://github.com/webpack/webpack-dev-middleware
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 message: fix(security): do not allow to read files above (#1771)



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;