Skip to content

Conversation

@odaysec
Copy link

@odaysec odaysec commented Apr 11, 2025

const { stderr } = await exec(`npx rollup ${module} -c ${rollupConf} --file ${destDir}/${locale}.js`)

fix the problem should avoid constructing the shell command as a single string and instead use the execFile function from the child_process module. This function allows us to pass the command and its arguments separately, which prevents the shell from interpreting special characters in the paths.

  • Replace the exec function call with execFile to separate the command and its arguments.
  • Update the import to use execFile instead of exec.

Dynamically constructing a shell command with values from the local environment, such as file paths, may inadvertently change the meaning of the shell command. Such changes can occur when an environment value contains characters that the shell interprets in a special way, for instance quotes and spaces. This can result in the shell command misbehaving, or even allowing a malicious user to execute arbitrary commands on the system.

POC

The following shows a dynamically constructed shell command that recursively removes a temporary directory that is located next to the currently executing JavaScript file. Such utilities are often found in custom build scripts.

var cp = require("child_process"),
  path = require("path");
function cleanupTemp() {
  let cmd = "rm -rf " + path.join(__dirname, "temp");
  cp.execSync(cmd); // BAD
}

The shell command will, however, fail to work as intended if the absolute path of the script's directory contains spaces. In that case, the shell command will interpret the absolute path as multiple paths, instead of a single path. For instance, if the absolute path of the temporary directory is /home/lichobile/important project/temp, then the shell command will recursively delete /home/lichobile/important and project/temp, where the latter path gets resolved relative to the working directory of the JavaScript process.

Even worse, although less likely, a malicious user could provide the path /home/username/; cat /etc/passwd #/important project/temp in order to execute the command cat /etc/passwd. To avoid such potentially catastrophic behaviors, provide the directory as an argument that does not get interpreted by a shell:

var cp = require("child_process"),
  path = require("path");
function cleanupTemp() {
  let cmd = "rm",
    args = ["-rf", path.join(__dirname, "temp")];
  cp.execFileSync(cmd, args); // GOOD
}

References

Command Injection
CWE-78
CWE-88

@odaysec odaysec closed this by deleting the head repository Sep 17, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant