命令注入是指通过提交恶意构造的参数破坏命令语句的结构,达到非法执行命令的手段。
我将从易到难对不同难度的命令注入尝试
简单难度程序关键代码:
<?php
if( isset( $_POST[ \'Submit\' ] ) )
{
$target = $_REQUEST[ \'ip\' ];
if( stristr( php_uname( \'s\' ), \'Windows NT\' ) )
{
$cmd = shell_exec( \'ping \' . $target );
}
else {
$cmd = shell_exec( \'ping -c 4 \' . $target );
}
echo "<pre>{$cmd}</pre>";
}
?>
从程序中可以看出对于输入数据,除了对空的输入有作区别,没有对输入的数据进行任何处理
输入127.0.0.1&&net user
可以看到除了显示合法的信息还包含了非法信息,所以要对输入的内容进行过滤
困难难度关键代码
<?php
if( isset( $_POST[ \'Submit\' ] ) ) {
$target = $_REQUEST[ \'ip\' ];
$substitutions = array(
\'&&\' => \'\',
\';\' => \'\',
);
$target = str_replace( array_keys( $substitutions ), $substitutions, $target );
if( stristr( php_uname( \'s\' ), \'Windows NT\' ) ) {
$cmd = shell_exec( \'ping \' . $target );
}
else {
$cmd = shell_exec( \'ping -c 4 \' . $target );
}
echo "<pre>{$cmd}</pre>";
}
?>
程序使用str_replace将“&&”和“;”转换成了空,所以无法使用&&和;进行有效注入;
但在命令行中有许多的特殊符号,所以可以用其他符号绕过过滤
输入127.0.0.1&;&ipconfig
按照规则中删除;正好执行命令127.0.0.1&&ipconfig,说明过滤的不严格
再次升级,过滤部分程序如图所示
$substitutions = array(
\'&\' => \'\',
\';\' => \'\',
\'|\' => \'\',
\'-\' => \'\',
\'$\' => \'\',
\'(\' => \'\',
\')\' => \'\',
\'`\' => \'\',
\'||\' => \'\',
);
命令行中各个符号的含义:
\'&\':Command 1&Command 2,先执行Command 1,不管是否成功,都会执行Command 2
\';\' 标记语句结束
\'|\' Command 1|Command 2,Command 1的输出作为Command 2的输入,并且只打印Command 2执行的结果
\'-\'
\'$\' 变量替换(Variable Substitution)的代表符号。
\'(\' \'()\'指令群组部分内容
\')\' 同上
\'`\' 返回当前命令执行结果
\'||\' A||B表示A执行成功后,B就不会再执行了;A失败或不执行,B才能执行。
将所有的能够在shell引起执行停止和条件执行的符号都进过滤,并且对两个分符号的单独符号也进行过滤,就能有效避免命令注入,防止严重后果的发生。
此时输入127.0.0.1|&;&|ipconfig
结果不显示: