...
This noncompliant code example demonstrates a less likely, though more pernicious form of OS command injection. The program spawns a shell (*nixPOSIX based platforms) or a command prompt (Windows) and allows passing arguments to external programs. Sometimes the shell or prompt is used to set an environment variable to a user defined value from within the program. The programName
string is expected to hold the program's name, as well as the arguments.
An adversary can terminate the command with a command separator (such as '&&' and '||') or cause to execute arbitrary commands. For example, the output of the program to can be piped to a sensitive file for the purpose of causing a denial of service, or even worse, redirect redirecting some sensitive output to a non sensitive location.
...
Code Block | ||
---|---|---|
| ||
Process proc; int filename = Integer.parseInt(System.getproperty("program.name")); // only allow integer choices Runtime runtime = Runtime.getRuntime(); switch(filename) { case 1: proc = runtime.exec("hardcoded\program1"); break; // Option 1 case 2: proc = runtime.exec("hardcoded\program2"); break; // Option 2 default: System.out.println("Invalid option!"); break; } |
This also prevents exposure of the file system structure.
Compliant Solution
An alternative is to read the file names from a source existing in a secure directory, inaccessible to an attacker. The security policy file may grant permissions to the application to read execute files from a specific directory. The security manager must be used when running the application (ENV02-J. Create a secure sandbox using a Security Manager). It is also possibe to define a custom permission to control access to specific programs and using a security manager to enforce this permission (SEC10-J. Define custom security permissions for fine grained security).The security manager's checkExec(String cmd)
method allows checking whether the program has the permissions to create the subprocess and execute the external program.
Wiki Markup |
---|
The security policy file must grant the {{java.io.FilePermission}} as follows: if {{cmd}} is an absolute path, {{java.io.FilePermission "\{cmd\}", "execute"}} ; else {{java.io.FilePermission "-", "execute";}} \[[Permissions 08|AA. Java References#Permissions 08]\]. However, in the latter case, all programs can be freely executed if the permission is granted. Consequently, permissions should be restricted per file only, by giving absolute paths. |
Risk Assessment
OS command injection can cause arbitrary programs to be executed.
...