命令注入是指应用程序执行命令的字符串或字符串的一部分来源于不可信赖的数据源,程序没有对这
些不可信赖的数据进行验证、过滤,导致程序执行恶意命令的一种攻击方式。
例 1 :以下代码通过 Runtime.exec() 方法调用 Windows 的 dir 命令,列出目录列表。
import java.io.*;
public class DirList {
public static void main(String[] str) throws Exception {
String dir = System.getProperty("dir");
Process proc = Runtime.getRuntime().exec("cmd.exe /c dir" + dir);
int result = proc.waitFor();
if (result != 0) {
System.out.println("process error: " + result);
}
InputStream in = (result == 0) ? proc.getInputStream() : proc.getErrorStream();
int c;
while ((c = in.read()) != -1) {
System.out.print((char) c);
}
}
}
攻击者可以通过以下命令利用该程序。
java -Ddir='dummy & echo bad' DirList
该命令实际上执行的是以下两条命令。
cmd.exe /c dir dummy & echo bad
例 2 :以下代码来自一个 Web 应用程序,该段代码通过运行 rmanDB.bat 脚本启动 Oracle 数据库备份,
然后运行 cleanup.bat 脚本删除一些临时文件。脚本文件 rmanDB.bat 接受一个命令行参数,其中指明需要
执行的备份类型。
...
String btype = request.getParameter("backuptype");
String cmd = new String("cmd.exe /K \"c:\\util\\rmanDB.bat "+btype+"&& c:\\utl\\cleanup.bat\"");
System.Runtime.getRuntime().exec(cmd);
...
该段代码没有对来自用户请求中的 backuptype 参数做任何校验。
通常情况下, Runtime.exec() 函数不会执行多条命令,但在以上代码中,为了执行多条命令,程序调用
Runtime.exec() 方法,首先运行了 cmd.exe 指令,因此能够执行用两个与号分隔的多条命令了。如果攻击者
传递了一个形式为 "&& del c:\\dbms\\*.*" 的字符串,那么该段代码将会在执行其他指定命令的同时执行这
条命令。