When you run an OS command, it is always important to protect yourself against the risk of accidental or malicious replacement of the executables
in the production system.
To do so, it is important to point to the specific executable that should be used.
For example, if you call git
(without specifying a path), the operating system will search for the executable in the directories
specified in the PATH
environment variable.
An attacker could have added, in a permissive directory covered by PATH
,
another executable called git
, but with a completely different behavior, for example exfiltrating data or exploiting a vulnerability in
your own code.
However, by calling /usr/bin/git
or ../git
(relative path) directly, the operating system will always use the intended
executable.
Note that you still need to make sure that the executable is not world-writeable and potentially overwritten. This is not the scope of
this rule.
Ask Yourself Whether
- The PATH environment variable only contains fixed, trusted directories.
There is a risk if you answered no to this question.
Recommended Secure Coding Practices
If you wish to rely on the PATH
environment variable to locate the OS command, make sure that each of its listed directories is fixed,
not susceptible to change, and not writable by unprivileged users.
If you determine that these folders cannot be altered, and that you are sure that the program you intended to use will be used, then you can
determine that these risks are under your control.
A good practice you can use is to also hardcode the PATH
variable you want to use, if you can do so in the framework you use.
If the previous recommendations cannot be followed due to their complexity or other requirements, then consider using the absolute path of the
command instead.
$ whereis git
git: /usr/bin/git /usr/share/man/man1/git.1.gz
$ ls -l /usr/bin/git
-rwxr-xr-x 1 root root 3376112 Jan 28 10:13 /usr/bin/git
Sensitive Code Example
Process p = new Process();
p.StartInfo.FileName = "binary"; // Sensitive
Compliant Solution
Process p = new Process();
p.StartInfo.FileName = @"C:\Apps\binary.exe";
See