Passing unvalidated user input into the environment variables of a subprocess can allow an attacker to execute malicious code.

If possible, use hard-coded string literals to specify the environment variable or its value. Instead of passing the user input directly to the process or library function, examine the user input and then choose among hard-coded string literals.

If the applicable environment variables cannot be determined at compile time, then add code to verify that the user input string is safe before using it.

In the following (BAD) example, the environment variable PATH is set to the value of the user input path without validation.

In the following (BAD) example, an environment variable is set with a name that is derived from the user input var without validation.

In the following (GOOD) example, the user's input is validated before being used to set the environment variable.

In the following (GOOD) example, the user's input is checked and used to determine an environment variable to add.

  • The Java Tutorials: Environment Variables.
  • OWASP: Command injection.