Shiro550 流程分析

发布于 2025-10-05 · 技术


拉去shiro项目

cuuemo@cuuemo ~ % git clone https://github.com/apache/shiro.git
正克隆到 'shiro'...
remote: Enumerating objects: 68477, done.
remote: Counting objects: 100% (738/738), done.
remote: Compressing objects: 100% (276/276), done.
remote: Total 68477 (delta 670), reused 462 (delta 462), pack-reused 67739 (from 4)
接收对象中: 100% (68477/68477), 30.61 MiB | 170.00 KiB/s, 完成.
处理 delta 中: 100% (34406/34406), 完成.
cuuemo@cuuemo ~ % cd shiro
cuuemo@cuuemo shiro % git checkout shiro-root-1.2.4
注意:正在切换到 'shiro-root-1.2.4'。

您正处于分离头指针状态。您可以查看、做试验性的修改及提交,并且您可以在切换
回一个分支时,丢弃在此状态下所做的提交而不对分支造成影响。

如果您想要通过创建分支来保留在此状态下所做的提交,您可以通过在 switch 命令
中添加参数 -c 来实现(现在或稍后)。例如:

  git switch -c <新分支名>

或者撤销此操作:

  git switch -

通过将配置变量 advice.detachedHead 设置为 false 来关闭此建议

HEAD 目前位于 9549384b0 configure toolchains plugin to require jdk 1.6 while being able to deploy with a newer jdk because of https://issues.apache.org/jira/browse/BUILDS-85. Bump jdk version requirement from 1.5 to 1.6

编辑shiro/samples/web目录下的pom.xml,将jstl的版本修改为1.2

<dependency>  
    <groupId>javax.servlet</groupId>  
    <artifactId>jstl</artifactId>  
    <scope>runtime</scope>  
</dependency>

改成

<dependency>  
    <groupId>javax.servlet</groupId>  
    <artifactId>jstl</artifactId>  
    <version>1.2</version>  
    <scope>runtime</scope>  
</dependency>

然后配tomcat 部署工件选samples-web:war exploded,jdk版本jdk1.8,http端口8089 然后运行,浏览器就打开了然后点Login

Username Password
root secret
presidentskroob 12345
darkhelmet ludicrousspeed
lonestarr vespa
钩上Remember Me,抓包用root登录
POST /samples_web_war_exploded/login.jsp;jsessionid=1A08E934410C485750DEB4DCD99B6F43 HTTP/1.1
Host: localhost:8089
Content-Length: 56
Cache-Control: max-age=0
sec-ch-ua: "Not:A-Brand";v="24", "Chromium";v="134"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "macOS"
Accept-Language: zh-CN,zh;q=0.9
Origin: http://localhost:8089
Content-Type: application/x-www-form-urlencoded
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Referer: http://localhost:8089/samples_web_war_exploded/login.jsp;jsessionid=1A08E934410C485750DEB4DCD99B6F43
Accept-Encoding: gzip, deflate, br
Cookie: JSESSIONID=1A08E934410C485750DEB4DCD99B6F43
Connection: keep-alive

username=root&password=secret&rememberMe=on&submit=Login

右键,拦截->拦截该请求的响应

HTTP/1.1 302 Found
Server: Apache-Coyote/1.1
Set-Cookie: rememberMe=deleteMe; Path=/samples_web_war_exploded; Max-Age=0; Expires=Sat, 04-Oct-2025 08:36:05 GMT
Set-Cookie: rememberMe=AhGl24AIzBoayZDToxPNUTl5NvkHzJa7myo6CHX3jAUIUCCK2flCmzq2xEHrAajQ/c1HdLT5vb5wZT6lxkM/gfVvm1VfVxAebtEJJOwBXE/kCRkel8A9ekl61xoZSCWC8cMfcEiIA2SdZRoEy4B4oFYzSzk2aOFRriu1NSyjnbLHGu5ZrKHffCcmTp7R46AuRtV3LkmQ9MIbW2r/SQyq3RdUkbVQEcs2F64fgMME46Ce3d9VDKEMWPbDy2Hl4840hvsDc0redJtXBpocUsz90eMXNpCSbvqwjw3whK2Z9LflkZ1yU/ilCc9JX7kaYPfTPAymnMc4TRwo9De1W86MU0+vEYYKJfCjsWknbb4htB+6BKJJAY4zFmMaPEzKwq783kZZIPBXTsHF9g29yMBziefyrsfrJF1DSyO0Q0gQp0F9hBXaL/SPwPEmA/b2R7ncpxCFwdZiuu6nzH2gSUgUTNd0S45vgfaygS1HcjXEWiSn+T8op4Ynbu10o/VZ3k4x; Path=/samples_web_war_exploded; Max-Age=31536000; Expires=Mon, 05-Oct-2026 08:36:05 GMT; HttpOnly
Location: /samples_web_war_exploded/
Content-Length: 0
Date: Sun, 05 Oct 2025 08:36:05 GMT


可以看到Set-Cookie:rememberMe,后面的请求都带上了

GET /samples_web_war_exploded/ HTTP/1.1
Host: localhost:8089
Cache-Control: max-age=0
Accept-Language: zh-CN,zh;q=0.9
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
sec-ch-ua: "Not:A-Brand";v="24", "Chromium";v="134"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "macOS"
Referer: http://localhost:8089/samples_web_war_exploded/login.jsp;jsessionid=1A08E934410C485750DEB4DCD99B6F43
Accept-Encoding: gzip, deflate, br
Cookie: JSESSIONID=1A08E934410C485750DEB4DCD99B6F43; rememberMe=AhGl24AIzBoayZDToxPNUTl5NvkHzJa7myo6CHX3jAUIUCCK2flCmzq2xEHrAajQ/c1HdLT5vb5wZT6lxkM/gfVvm1VfVxAebtEJJOwBXE/kCRkel8A9ekl61xoZSCWC8cMfcEiIA2SdZRoEy4B4oFYzSzk2aOFRriu1NSyjnbLHGu5ZrKHffCcmTp7R46AuRtV3LkmQ9MIbW2r/SQyq3RdUkbVQEcs2F64fgMME46Ce3d9VDKEMWPbDy2Hl4840hvsDc0redJtXBpocUsz90eMXNpCSbvqwjw3whK2Z9LflkZ1yU/ilCc9JX7kaYPfTPAymnMc4TRwo9De1W86MU0+vEYYKJfCjsWknbb4htB+6BKJJAY4zFmMaPEzKwq783kZZIPBXTsHF9g29yMBziefyrsfrJF1DSyO0Q0gQp0F9hBXaL/SPwPEmA/b2R7ncpxCFwdZiuu6nzH2gSUgUTNd0S45vgfaygS1HcjXEWiSn+T8op4Ynbu10o/VZ3k4x
Connection: keep-alive


这个cookie很大,正常来说都很短,这么大应该是保存了比较多的信息,一般保存信息的方式就是序列化反序列化。 去看看代码这个cookie是怎么处理的 按两下Shift搜cookie选Classes把跟cookie名字有关的类都列出来,然后看看那个是在shiro包的 看到org.apache.shiro.web.mgt包的CookieRememberMeManager类 看里面的方法 这个看名字是序列化的操作

protected void rememberSerializedIdentity(Subject subject, byte[] serialized) {  
    // 这个方法将序列化后的身份信息保存到cookie中
    // 参数1: subject - 当前的用户主体对象
    // 参数2: serialized - 已经序列化好的身份信息字节数组
  
    if (!WebUtils.isHttp(subject)) {  
        // 检查Subject是否在HTTP环境中(因为需要操作HTTP的request和response)
        
        if (log.isDebugEnabled()) {  
            // 如果启用了debug日志级别
            
            String msg = "Subject argument is not an HTTP-aware instance.  This is required to obtain a servlet " +  
                    "request and response in order to set the rememberMe cookie. Returning immediately and " +  
                    "ignoring rememberMe operation.";  
            // 构造日志消息:说明必须是HTTP环境才能设置rememberMe cookie
            
            log.debug(msg);  
            // 输出debug日志
        }  
        
        return;  
        // 如果不是HTTP环境,直接返回,不执行后续操作
    }  
  
  
    HttpServletRequest request = WebUtils.getHttpRequest(subject);  
    // 从Subject中提取HTTP请求对象
    
    HttpServletResponse response = WebUtils.getHttpResponse(subject);  
    // 从Subject中提取HTTP响应对象
  
    //base 64 encode it and store as a cookie:  
    // 注释说明:将序列化数据进行Base64编码,然后存储为cookie
    
    String base64 = Base64.encodeToString(serialized);  
    // ★关键点1:将序列化后的字节数组进行Base64编码,转换为字符串
    // 因为cookie只能存储文本,不能直接存储二进制数据
    // serialized参数就是已经序列化好的Java对象字节数组
  
    Cookie template = getCookie(); 
    // 获取cookie模板(包含cookie的名称、路径、域名、过期时间等配置)
    // 这个模板定义了rememberMe cookie的基本属性
    
    //the class attribute is really a template for the outgoing cookies  
    // 注释说明:这个类属性实际上是出站cookie的模板
    
    Cookie cookie = new SimpleCookie(template);  
    // 根据模板创建一个新的SimpleCookie对象
    // SimpleCookie是Shiro自己实现的Cookie包装类
    
    cookie.setValue(base64);  
    // ★关键点2:将Base64编码后的字符串设置为cookie的值
    // 这个值就是:序列化对象 → Base64编码 的结果
    // 如果Shiro配置了加密,在传入这个函数之前serialized参数已经被加密过了
    
    cookie.saveTo(request, response);  
    // ★关键点3:将cookie保存到HTTP响应中,发送给客户端浏览器
    // 浏览器会在后续请求中自动带上这个cookie(如果用户勾选了"记住我")
}

这个应该是反序列化的操作,把信息读出来,重点就看看反序列化的函数

protected byte[] getRememberedSerializedIdentity(SubjectContext subjectContext) {  
    // 这个方法从cookie中获取记住的序列化身份信息,返回字节数组
  
    if (!WebUtils.isHttp(subjectContext)) {  
        // 检查当前上下文是否是HTTP环境(因为需要操作HTTP的cookie)
        
        if (log.isDebugEnabled()) {  
            // 如果启用了debug日志级别
            
            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.";  
            // 构造日志消息:说明必须是HTTP环境才能获取rememberMe cookie
            
            log.debug(msg);  
            // 输出debug日志
        }  
        return null;  
        // 如果不是HTTP环境,直接返回null,不处理
    }  
  
    WebSubjectContext wsc = (WebSubjectContext) subjectContext;  
    // 将SubjectContext强制转换为WebSubjectContext(HTTP环境的上下文)
    
    if (isIdentityRemoved(wsc)) {  
        // 检查身份信息是否已被移除(比如用户主动登出)
        return null;  
        // 如果已移除,返回null
    }  
  
    HttpServletRequest request = WebUtils.getHttpRequest(wsc);  
    // 从上下文中获取HTTP请求对象
    
    HttpServletResponse response = WebUtils.getHttpResponse(wsc);  
    // 从上下文中获取HTTP响应对象
  
    String base64 = getCookie().readValue(request, response);  
    // ★关键点1:从cookie中读取rememberMe的值(这个值是Base64编码的)
    
    // Browsers do not always remove cookies immediately (SHIRO-183)  
    // 浏览器不总是立即删除cookie(这是Shiro的一个已知问题SHIRO-183)
    
    // ignore cookies that are scheduled for removal    
    if (Cookie.DELETED_COOKIE_VALUE.equals(base64)) return null;  
    // 如果cookie的值是删除标记(通常是"deleteMe"),忽略并返回null
  
    if (base64 != null) {  
        // 如果成功读取到了Base64字符串
        
        base64 = ensurePadding(base64);  
        // 确保Base64字符串有正确的填充(Base64编码要求长度是4的倍数,不足补'=')
        
        if (log.isTraceEnabled()) {  
            // 如果启用了trace级别日志(最详细的日志)
            log.trace("Acquired Base64 encoded identity [" + base64 + "]");  
            // 记录获取到的Base64编码的身份信息
        }  
        
        byte[] decoded = Base64.decode(base64);  
        // ★关键点2:对Base64字符串进行解码,得到原始的字节数组
        // ★这个字节数组就是序列化后的对象数据,后续会被反序列化
        // ★这里就是Shiro反序列化漏洞的入口点!攻击者可以构造恶意的序列化数据
        
        if (log.isTraceEnabled()) {  
            log.trace("Base64 decoded byte array length: " + (decoded != null ? decoded.length : 0) + " bytes.");  
            // 记录解码后的字节数组长度
        }  
        
        return decoded;  
        // ★返回解码后的字节数组,这个数据会被传递给反序列化函数进行反序列化
        // ★如果Shiro使用的是不安全的反序列化方式,攻击者就可以RCE(远程代码执行)
        
    } else {  
        //no cookie set - new site visitor?  
        // 如果没有读取到cookie值(可能是新访客,还没有勾选"记住我")
        return null;  
        // 返回null
    }  
}

这函数知识解码了base64并返回了,我们往上找那个调用了这个函数,用idea的查找用法getRememberedSerializedIdentity

public PrincipalCollection getRememberedPrincipals(SubjectContext subjectContext) {
    // 方法声明:获取记住的用户身份集合(Principal是"主体",代表用户身份)
    // public:公开方法,可以被任何类调用
    // PrincipalCollection:返回类型,是一个用户身份的集合对象
    //                      包含了用户的所有身份信息(用户名、角色、权限等)
    // SubjectContext:参数,当前请求的主体上下文
    
    PrincipalCollection principals = null;
    // 声明并初始化变量principals为null
    // 这个变量将用来存储从cookie中恢复出来的用户身份信息
    // 初始化为null是防御性编程,如果后续操作失败,返回null表示没有记住的身份
    
    try {
        // try块:尝试执行可能抛出异常的代码
        // 为什么需要try-catch?因为反序列化过程可能出错:
        // - cookie数据被篡改
        // - 解密失败
        // - 反序列化失败
        // - 类不存在等
        
        byte[] bytes = getRememberedSerializedIdentity(subjectContext);
        // ★★★调用前面分析过的方法,从cookie中获取字节数组★★★
        // 这个方法做了:
        // 1. 检查HTTP环境
        // 2. 从cookie读取rememberMe的值(Base64字符串)
        // 3. Base64解码得到字节数组
        // bytes:可能是加密的序列化数据,也可能是未加密的序列化数据
        //        取决于Shiro的配置
        
        //SHIRO-138 - only call convertBytesToPrincipals if bytes exist:
        // Shiro官方注释:SHIRO-138问题 - 只有当字节数组存在时才调用convertBytesToPrincipals
        // SHIRO-138是一个bug编号,说明这里曾经有问题,现在已修复
        // 修复内容:增加了null检查和长度检查,避免对空数据进行处理
        
        if (bytes != null && bytes.length > 0) {
            // bytes != null:字节数组不为null(cookie存在且成功解码)
            // bytes.length > 0:字节数组长度大于0(不是空数组)
            
            principals = convertBytesToPrincipals(bytes, subjectContext);
            // 把解码的base64传进去了,关键应该在这个方法
            // 看名字是认证信息
        }
        
    } catch (RuntimeException re) {
        // catch块:捕获运行时异常
        // RuntimeException:运行时异常的基类,包括:
        // - NullPointerException:空指针异常
        // - ClassCastException:类型转换异常
        // - IllegalArgumentException:非法参数异常
        // - 以及反序列化可能抛出的各种异常
        //
        // 为什么只捕获RuntimeException而不是Exception?
        // 因为Shiro只想处理运行时的异常,让其他受检异常向上传播
        
        principals = onRememberedPrincipalFailure(re, subjectContext);
        // 调用失败处理方法
        // onRememberedPrincipalFailure:当"记住我"功能失败时的处理逻辑
        // 参数1:re - 捕获到的异常对象
        // 参数2:subjectContext - 当前上下文
    }

    return principals;
    // 返回用户身份集合:
    // - 成功:返回包含用户信息的PrincipalCollection对象
    // - 失败:返回null
    // - 攻击:返回null或垃圾对象(但恶意代码已经执行)
    //
    // 调用方会根据返回值判断:
    // - 如果不为null:自动登录用户
    // - 如果为null:要求用户重新登录
}

看convertBytesToPrincipals方法

protected abstract byte[] getRememberedSerializedIdentity(SubjectContext subjectContext);
// 抽象方法声明:获取记住的序列化身份
// protected abstract:保护级别的抽象方法,子类必须实现
// 这是一个模板方法模式:父类定义流程,子类实现具体细节
// 这个方法就是前面我们分析过的那个从cookie读取Base64并解码的方法
// 它在子类CookieRememberMeManager中有具体实现

/**
 * If a {@link #getCipherService() cipherService} is available, it will be used to first decrypt the byte array.
 * Then the bytes are then {@link #deserialize(byte[]) deserialized} and then returned.
 *
 * JavaDoc注释翻译:
 * 如果有可用的加密服务(cipherService),它会首先用来解密字节数组。
 * 然后这些字节会被反序列化,最后返回结果。
 * 
 * 这段注释清楚地说明了这个方法的两个步骤:
 * 1. 解密(如果配置了加密)
 * 2. 反序列化(★漏洞触发点★)
 *
 * @param bytes          the bytes to decrypt if necessary and then deserialize.
 *                       参数说明:需要解密(如果必要)然后反序列化的字节数组
 *                       这个bytes就是从cookie中读取并Base64解码后的数据
 *
 * @param subjectContext the contextual data, usually provided by a {@link Subject.Builder} implementation, that
 *                       is being used to construct a {@link Subject} instance.
 *                       参数说明:上下文数据,通常由Subject.Builder提供,用于构建Subject实例
 *
 * @return the de-serialized and possibly decrypted principals
 *         返回值说明:反序列化的、可能已解密的用户身份集合
 */
protected PrincipalCollection convertBytesToPrincipals(byte[] bytes, SubjectContext subjectContext) {
    // 方法声明:将字节数组转换为用户身份集合
    // protected:保护级别,子类和同包类可访问
    // PrincipalCollection:返回用户身份集合对象
    // 参数1:bytes - 从cookie中获取的字节数组(可能已加密)
    // 参数2:subjectContext - 当前请求的上下文
    
    if (getCipherService() != null) {
        // 判断:如果配置了加密服务(CipherService不为null)
        // getCipherService():获取配置的加密服务对象
        //                     如果Shiro配置文件中设置了加密,这里会返回AesCipherService对象
        //                     如果没有配置加密,返回null
        bytes = decrypt(bytes);
        // ★解密操作:将加密的字节数组解密★
        // decrypt(bytes)方法内部会:
        // 1. 使用AES算法
        // 2. 使用配置的密钥(或默认硬编码密钥)
        // 3. 将加密的字节数组解密为原始的序列化数据
        // 解密后的bytes:就是纯粹的Java序列化数据
    }
    
    return deserialize(bytes);
    // deserialize(bytes):将字节数组反序列化为Java对象
}

一个是解密一个是反序列化操作,先看deserialize方法

protected PrincipalCollection deserialize(byte[] serializedIdentity) {  
    return getSerializer().deserialize(serializedIdentity);  
}

继续看deserialize

public interface Serializer<T> {  
    // 序列化器接口,T是泛型类型(在Shiro中通常是PrincipalCollection)
  
    byte[] serialize(T o) throws SerializationException;  
    // 序列化方法:对象 → 字节数组
  
    T deserialize(byte[] serialized) throws SerializationException;  
    // 反序列化方法:字节数组 → 对象
}

是个接口左边有个绿色的I看看实现方法在DefaultSerializer类,这里调了原生的反序列化,这里如果有cc或者cb等能构造链子的依赖就可以打漏洞了

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);  
        // 创建对象输入流(Shiro自定义的ObjectInputStream)
        
        @SuppressWarnings({"unchecked"})  
        T deserialized = (T) ois.readObject();  
        // 调用readObject()进行反序列化
        
        ois.close();  
        // 关闭流
        
        return deserialized;  
        // 返回反序列化后的对象
        
    } catch (Exception e) {  
        // 捕获异常
        String msg = "Unable to deserialze argument byte array.";  
        throw new SerializationException(msg, e);  
    }  
}

现在看解密的方法

protected byte[] decrypt(byte[] encrypted) {
    // 解密方法,参数是从cookie中Base64解码后的加密字节数组
    
    byte[] serialized = encrypted;
    // 默认将加密数据赋值给serialized(如果没有配置加密服务,直接返回)
    
    CipherService cipherService = getCipherService();
    // 获取加密服务对象(通常是AesCipherService,如果配置了的话)
    
    if (cipherService != null) {
        // 如果配置了加密服务
        
        ByteSource byteSource = cipherService.decrypt(encrypted, getDecryptionCipherKey());
        // 使用AES解密,getDecryptionCipherKey()返回密钥
        
        serialized = byteSource.getBytes();
        // 将解密后的ByteSource转换为字节数组
    }
    
    return serialized;
    // 返回解密后的序列化数据(如果没加密就返回原始数据)
}

看解密方法cipherService.decrypt,是个接口,参数第一个是解密的字段,第二个是key

ByteSource decrypt(byte[] encrypted, byte[] decryptionKey) throws CryptoException;

可实现代码

public ByteSource decrypt(byte[] ciphertext, byte[] key) throws CryptoException {
    // AES解密方法,参数:密文字节数组和密钥

    byte[] encrypted = ciphertext;
    // 初始化加密数据变量(默认整个参数都是密文)

    //No IV, check if we need to read the IV from the stream:
    byte[] iv = null;
    // 初始化IV(初始化向量)为null,IV用于AES的CBC模式

    if (isGenerateInitializationVectors(false)) {
        // 检查是否启用了自动生成IV(Shiro默认启用)
        
        try {
            //We are generating IVs, so the ciphertext argument array is not actually 100% cipher text.  Instead, it
            //is:
            // - the first N bytes is the initialization vector, where N equals the value of the
            // 'initializationVectorSize' attribute.
            // - the remaining bytes in the method argument (arg.length - N) is the real cipher text.
            // 注释说明:如果生成了IV,密文数组的结构是 [IV][真实密文]

            //So we need to chunk the method argument into its constituent parts to find the IV and then use
            //the IV to decrypt the real ciphertext:
            // 需要将密文数组分割成IV部分和真实密文部分

            int ivSize = getInitializationVectorSize();
            // 获取IV的大小(位数,默认128位)
            
            int ivByteSize = ivSize / BITS_PER_BYTE;
            // 将位数转换为字节数(128位 / 8 = 16字节)

            //now we know how large the iv is, so extract the iv bytes:
            iv = new byte[ivByteSize];
            // 创建IV字节数组(长度16字节)
            
            System.arraycopy(ciphertext, 0, iv, 0, ivByteSize);
            // 从密文的前16字节提取IV(源数组,源起始位置,目标数组,目标起始位置,长度)

            //remaining data is the actual encrypted ciphertext.  Isolate it:
            int encryptedSize = ciphertext.length - ivByteSize;
            // 计算真实密文的长度(总长度 - IV长度)
            
            encrypted = new byte[encryptedSize];
            // 创建真实密文的字节数组
            
            System.arraycopy(ciphertext, ivByteSize, encrypted, 0, encryptedSize);
            // 从密文的第16字节开始提取真实密文(跳过前面的IV部分)
            
        } catch (Exception e) {
            String msg = "Unable to correctly extract the Initialization Vector or ciphertext.";
            throw new CryptoException(msg, e);
            // 提取IV或密文失败时抛出异常
        }
    }

    return decrypt(encrypted, key, iv);
    // 调用重载的decrypt方法进行实际的AES解密(真实密文,密钥,IV)
}

继续跟decrypt

private ByteSource decrypt(byte[] ciphertext, byte[] key, byte[] iv) throws CryptoException {
    // 私有解密方法,参数:密文、密钥、IV(初始化向量)
    
    if (log.isTraceEnabled()) {
        // 如果启用了trace日志
        log.trace("Attempting to decrypt incoming byte array of length " +
                (ciphertext != null ? ciphertext.length : 0));
        // 记录要解密的字节数组长度
    }
    
    byte[] decrypted = crypt(ciphertext, key, iv, javax.crypto.Cipher.DECRYPT_MODE);
    // 调用crypt方法进行解密,DECRYPT_MODE表示解密模式
    
    return decrypted == null ? null : ByteSource.Util.bytes(decrypted);
    // 将解密后的字节数组包装成ByteSource对象返回
}

继续跟crypt

private byte[] crypt(byte[] bytes, byte[] key, byte[] iv, int mode) throws IllegalArgumentException, CryptoException {
    // 加密/解密核心方法,mode决定是加密(1)还是解密(2)
    
    if (key == null || key.length == 0) {
        // 检查密钥是否为空
        throw new IllegalArgumentException("key argument cannot be null or empty.");
        // 密钥为空则抛出异常
    }
    
    javax.crypto.Cipher cipher = initNewCipher(mode, key, iv, false);
    // 初始化Java标准的Cipher对象(配置AES/CBC/PKCS5Padding,mode=2时为解密模式)
    
    return crypt(cipher, bytes);
    // 调用重载方法执行实际的加密/解密操作,返回结果字节数组
}

跟进initNewCipher

private javax.crypto.Cipher initNewCipher(int jcaCipherMode, byte[] key, byte[] iv, boolean streaming)  
        throws CryptoException {  
  
    javax.crypto.Cipher cipher = newCipherInstance(streaming);  
    java.security.Key jdkKey = new SecretKeySpec(key, getAlgorithmName());  
    IvParameterSpec ivSpec = null;  
    if (iv != null && iv.length > 0) {  
        ivSpec = new IvParameterSpec(iv);  
    }  
  
    init(cipher, jcaCipherMode, jdkKey, ivSpec, getSecureRandom());  
  
    return cipher;  
}

跟newCipherInstance

private javax.crypto.Cipher newCipherInstance(boolean streaming) throws CryptoException {  
    String transformationString = getTransformationString(streaming);  
    try {  
        return javax.crypto.Cipher.getInstance(transformationString);  
    } catch (Exception e) {  
        String msg = "Unable to acquire a Java JCA Cipher instance using " +  
                javax.crypto.Cipher.class.getName() + ".getInstance( \"" + transformationString + "\" ). " +  
                getAlgorithmName() + " under this configuration is required for the " +  
                getClass().getName() + " instance to function.";  
        throw new CryptoException(msg, e);  
    }  
}

跟进getTransformationString

protected String getTransformationString(boolean streaming) {  
    return getAlgorithmName();  
}

跟进algorithmName

public String getAlgorithmName() {  
    return algorithmName;  
}

是个常量

private String algorithmName;

跟进哪里写了

public String getAlgorithmName() {  
    return algorithmName;  
}

跟进algorithmName

/**  
 * Creates a new {@code JcaCipherService} instance which will use the specified cipher {@code algorithmName}  
 * for all encryption, decryption, and key operations.  Also, the following defaults are set: * <ul>  
 * <li>{@link #setKeySize keySize} = 128 bits</li>  
 * <li>{@link #setInitializationVectorSize(int) initializationVectorSize} = 128 bits</li>  
 * <li>{@link #setStreamingBufferSize(int) streamingBufferSize} = 512 bytes</li>  
 * </ul>  
 *  
 * @param algorithmName the name of the cipher algorithm to use for all encryption, decryption, and key operations  
 */
protected JcaCipherService(String algorithmName) {  
    if (!StringUtils.hasText(algorithmName)) {  
        throw new IllegalArgumentException("algorithmName argument cannot be null or empty.");  
    }  
    this.algorithmName = algorithmName;  
    this.keySize = DEFAULT_KEY_SIZE;  
    this.initializationVectorSize = DEFAULT_KEY_SIZE; //default to same size as the key size (a common algorithm practice)  
    this.streamingBufferSize = DEFAULT_STREAMING_BUFFER_SIZE;  
    this.generateInitializationVectors = true;  
}

algorithmName是传进来的查找全部用法JcaCipherService

public abstract class AbstractSymmetricCipherService extends JcaCipherService {
	protected AbstractSymmetricCipherService(String algorithmName) {  
	    super(algorithmName);  
	}
...

查找全部用法AbstractSymmetricCipherService

	/**  
	 * Creates a new {@link DefaultBlockCipherService} using the specified block cipher {@code algorithmName}.  Per this  
	 * class's JavaDoc, this constructor also sets the following defaults: * <ul>  
	 * <li>{@code streamingMode} = {@link OperationMode#CBC CBC}</li>  
	 * <li>{@code streamingPaddingScheme} = {@link PaddingScheme#NONE none}</li>  
	 * <li>{@code streamingBlockSize} = 8</li>  
	 * </ul>  
	 * All other attributes are null/unset, indicating the JCA Provider defaults will be used.  
	 * * @param algorithmName the block cipher algorithm to use when encrypting and decrypting  
	 */
	public DefaultBlockCipherService(String algorithmName) {  
	    super(algorithmName);  
	  
	    this.modeName = OperationMode.CBC.name();  
	    this.paddingSchemeName = PaddingScheme.PKCS5.getTransformationName();  
	    this.blockSize = DEFAULT_BLOCK_SIZE; //0 = use the JCA provider's default  
	  
	    this.streamingModeName = OperationMode.CBC.name();  
	    this.streamingPaddingSchemeName = PaddingScheme.PKCS5.getTransformationName();  
	    this.streamingBlockSize = DEFAULT_STREAMING_BLOCK_SIZE;  
	}

这里已经很明显是AES了,继续查找全部用法DefaultBlockCipherService

public AesCipherService() {  
    super(ALGORITHM_NAME);  
}

跟进ALGORITHM_NAME

public class AesCipherService extends DefaultBlockCipherService {
...
	private static final String ALGORITHM_NAME = "AES";

现在回去跟key

protected byte[] decrypt(byte[] encrypted) {
    // 解密方法,参数是从cookie中Base64解码后的加密字节数组
    
    byte[] serialized = encrypted;
    // 默认将加密数据赋值给serialized(如果没有配置加密服务,直接返回)
    
    CipherService cipherService = getCipherService();
    // 获取加密服务对象(通常是AesCipherService,如果配置了的话)
    
    if (cipherService != null) {
        // 如果配置了加密服务
        
        ByteSource byteSource = cipherService.decrypt(encrypted, getDecryptionCipherKey());
        // 使用AES解密,getDecryptionCipherKey()返回密钥
        
        serialized = byteSource.getBytes();
        // 将解密后的ByteSource转换为字节数组
    }
    
    return serialized;
    // 返回解密后的序列化数据(如果没加密就返回原始数据)
}

跟进去这个函数getDecryptionCipherKey(),看看密钥怎么生成的

	/**  
	 * Returns the decryption cipher key to use for decryption operations. * * @return the cipher key to use for decryption operations.  
	 * @see #setCipherService for a description of the various {@code get/set*Key} methods.  
	 */
	public byte[] getDecryptionCipherKey() {  
	    return decryptionCipherKey;  
	}

跟进decryptionCipherKey的定义

	/**  
	 * Cipher decryption key to use with the Cipher when decrypting data 
	 */
	private byte[] decryptionCipherKey;

是个常量,我们看哪里写了decryptionCipherKey,查找全部用法,主要看写入值

	/**  
	 * Sets the decryption key to use for decryption operations. * * @param decryptionCipherKey the decryption key to use for decryption operations.  
	 * @see #setCipherService for a description of the various {@code get/set*Key} methods.  
	*/
	public void setDecryptionCipherKey(byte[] decryptionCipherKey) {  
	    this.decryptionCipherKey = decryptionCipherKey;  
	}

发现是setDecryptionCipherKey函数跟进函数

	/**  
	 * Sets the decryption key to use for decryption operations. * * @param decryptionCipherKey the decryption key to use for decryption operations.  
	 * @see #setCipherService for a description of the various {@code get/set*Key} methods.  
	 */
	 public void setDecryptionCipherKey(byte[] decryptionCipherKey) {  
	    this.decryptionCipherKey = decryptionCipherKey;  
	}
	/**  
	 * Convenience method that sets the cipher key to use for <em>both</em> encryption and decryption.  
	 * <p/>  
	 * <b>N.B.</b> This method can only be called if the underlying {@link #getCipherService() cipherService} is a  
	 * symmetric CipherService?which by definition uses the same key for both encryption and decryption.  If using an * asymmetric CipherService?(such as a public/private key pair), you cannot use this method, and should instead use * the {@link #setEncryptionCipherKey(byte[])} and {@link #setDecryptionCipherKey(byte[])} methods individually.  
	 * <p/>  
	 * The default {@link AesCipherService} instance is a symmetric CipherService, so this method can be used if you  
	 * are using the default. * * @param cipherKey the symmetric cipher key to use for both encryption and decryption.  
	 */
	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函数

	/**  
	 * Default constructor that initializes a {@link DefaultSerializer} as the {@link #getSerializer() serializer} and  
	 * an {@link AesCipherService} as the {@link #getCipherService() cipherService}.  
	 */
	public AbstractRememberMeManager() {  
	    this.serializer = new DefaultSerializer<PrincipalCollection>();  
	    this.cipherService = new AesCipherService();  
	    setCipherKey(DEFAULT_CIPHER_KEY_BYTES);  
	}

是DEFAULT_CIPHER_KEY_BYTES这个常量,这是一个固定的值

private static final byte[] DEFAULT_CIPHER_KEY_BYTES = Base64.decode("kPH+bIxk5D2deZiIxcaaaA==");

还差一个iv没跟,就不跟了把逻辑是把传进去的前几个字节当作iv,可以自己取 也就是说在shiro1.2.4版本的加密都是一个固定的key去加密,然后加密算法是aes 流程是base64->Aes然后反序列化. 默认是自带cc3.2.1的但是实际上直接打是打不了的,因为很多的库都是[test]包实际上编译运行[compile]和[runtime],cc实际上是test所以实际上是打不了的,能打的是cb链。

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <groupId>org.example</groupId>
  <artifactId>cc_dubug</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>cc_dubug</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <!--
      cc start
    -->

    <!-- https://mvnrepository.com/artifact/commons-collections/commons-collections -->
    <!--
    <dependency>
      <groupId>commons-collections</groupId>
      <artifactId>commons-collections</artifactId>
      <version>3.2.1</version>
    </dependency>
    -->

    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-collections4</artifactId>
      <version>4.0</version>
    </dependency>

    <dependency>
      <groupId>commons-collections</groupId>
      <artifactId>commons-collections</artifactId>
      <version>3.1</version>
    </dependency>

    <!--
      cc end
    -->

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

    <!--
      cb start
    -->

    <dependency>
      <groupId>commons-beanutils</groupId>
      <artifactId>commons-beanutils</artifactId>
      <version>1.9.2</version>
      <exclusions>
        <exclusion>
          <groupId>commons-collections</groupId>
          <artifactId>commons-collections</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

    <dependency>
      <groupId>org.javassist</groupId>
      <artifactId>javassist</artifactId>
      <version>3.25.0-GA</version>
    </dependency>

    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version>1.2</version>
    </dependency>

    <!--
      cb end
    -->
  </dependencies>

</project>

登录选上Remember Me

POST /samples_web_war_exploded/login.jsp HTTP/1.1
Host: localhost:8090
Content-Length: 56
Cache-Control: max-age=0
sec-ch-ua: "Chromium";v="143", "Not A(Brand";v="24"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "macOS"
Accept-Language: zh-CN,zh;q=0.9
Origin: http://localhost:8090
Content-Type: application/x-www-form-urlencoded
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Referer: http://localhost:8090/samples_web_war_exploded/login.jsp
Accept-Encoding: gzip, deflate, br
Cookie: JSESSIONID=10E18FE7EE997DE0D94389E6D1D461B5
Connection: keep-alive

username=root&password=secret&rememberMe=on&submit=Login

« 返回首页