<?php

/*
*	Copyright VeryIDE,2007-2010
*	http://www.veryide.com/
*
*	$Id: veryide_files.php,v2 19:47 2008-2-21 Lay $
*/

require '../../include/loader.php';
require_once("../../function/client.php");

html_start("安全中心 - VeryIDE");
?>

<!--body start-->

	<?php
	
    //loader
    require('include/naver.secure.php');
    
    $action = getgpc('action');
    
    $log = VI_ROOT.$_G['project']['cache']."system/files.secure.php";
    
    if(!$action){
		
		$last = (file_exists($log) ? '上一次扫描是：<span class="text-yes">'.date("Y-m-d H:i:s",filemtime($log)).'</span>':'<span class="text-no">注意：从未进行安全扫描</span>');
    
        echo '
        <div id="state" class="'.( file_exists($log) ? "" : "failure" ).'">
            '.$last.'
        </div>
        ';
    }
    ?>

    <?php
    
		// 以下地址不视为外链

		$hostname = $_SERVER['HTTP_HOST'];
		$hostname = substr($hostname, in_array(substr($hostname, 0, 4), array('www.', 'bbs.')) ? 3 : 0);
		$hostip = preg_match('/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/', $hostname);

		$safeurls = array
			(
			0 => '.alipay.com',
			1 => '.taobao.com',
			2 => '.discuz.net',
			3 => '.comsenz.com',
			4 => '.7dps.com',
			5 => '.manyou.com',
			6 => '.qihoo.com',
			7 => '.qq.com',
			8 => '.live.com',
			9 => '.veryide.com',
			// 如果您需要添加其它的安全外链, 请附加在这里
			);
        
        //检查链接
        function scanurl($url) {

            global $hostip, $hostname, $safeurls;
            $hostnamelen = strlen($hostname);

            $url = substr($url, substr($url, 0, 7) == 'http://' ? 7 : 0);
            $url = strpos($url, '/') === false ? $url : substr($url, 0, strpos($url, '/'));

            if($hostip && $url == $hostname) {
                return true;
            } elseif (!$hostip && substr($url, -$hostnamelen) == $hostname) {
                return true;
            }

            foreach($safeurls as $safeurl) {
                if(substr($url, -strlen($safeurl)) == $safeurl || $url == substr($safeurl, 1)) {
                    return true;
                }
            }

            return false;

        }
        
        //扫描文件
        function get_all_files( $path ){
            $list = array();
            foreach( glob( $path . '/*') as $item ){
                if( is_dir( $item ) ){
                 $list = array_merge( $list , get_all_files( $item ) );
                }
                else{
                 $list[] = $item;
                }
            }
            return $list;
        }
        
        function get_all_errors($file,$msg,$txt){
        
            $result = '<tr class="red">';
                $result.= '<td><img src="'.VI_BASE.'image/icon/warning.png" /> '.$file.'</td>';
                $result.= '<td title="'.$txt.'">'.format_url($txt,50).'</td>';
                $result.= '<td>'.$msg.'</td>';
                $result.= '<td>'.date("Y-m-d H:i:s",filemtime($file)).'</td>';
            $result.= '</tr>';
            
            return $result;
        
        }
        
        //扫描附件
        function scanfiles(){
        
            $list = get_all_files(VI_ROOT.'attach');
            
            $result = '';
            
            foreach($list as $file) {

                $ext = fileext($file, -4);
                
                if(in_array($ext, array('php', 'php3', 'php4', 'asp', 'aspx', 'asa', 'cdx', 'js', 'htm', 'html', 'shtml'))) {
                
                    $result .= get_all_errors($file,'附件文件夹发现可执行的 PHP/ASP 文件, 请检查其安全性!','');
                    
                }
            
            }

            return $result;
        }
        
        // 扫描引擎函数
        function scanwebshell($path) {
        
            $list = get_all_files($path);
            
            $result = '';
            
            foreach($list as $file) {

                $filename = basename($file);
                $filesize = filesize($file);
    
                $suggestion1 = '该文件发现 Webshell, 请立即删除!';
                $suggestion2 = '该文件有非法代码, 请立即删除!';
    
                if(substr($filename, 0, 10) != 'usergroup_' && substr($filename, 0, 6) != 'style_') {
                    $result .= '';
                }
    
                if(!$fp = @fopen($file, 'r')) {
                    //return '读取该文件失败, 无法进行检查.';
                    $result .= get_all_errors($file,'读取该文件失败, 无法进行检查.',$src);
                }
    
                if(!$filedata = fread($fp, $filesize)) {
                    //return '';
                    $result .= '';
                }
    
                if(preg_match('/\$_(post|get)([ \t\n\r]*)\[/i', $filedata,$matches)) {
                    //return $suggestion1;
                    $result .= get_all_errors($file,$suggestion1,$matches[0]);
                } elseif (strpos($filedata, 'define(\'\',\'\');') !== false) {
                    return $suggestion2;
                    $result .= get_all_errors($file,$suggestion2,$src);
                } else {
                    $result .= '';
                }
            
            }
            
            return $result;

        }
        
        //扫描缓存
        function scantemplate($path) {
        
            if(!$html = new DOMDocument()) {
                return '服务器不支持 DOM，无法检查模板文件。';
            }
        
            $list = get_all_files($path);
            
            $result = '';
            
            //print_r($list);
            
            foreach($list as $file) {
            
                //echo $file.'<br />';

                $suggestion1 = '该文件有通过脚本调用外链地址的代码, 请自行检查!';
                $suggestion2 = '该文件有通过框架调用外链地址的代码, 请自行检查!';

                $html = new DOMDocument();
                @$html->loadHTMLFile($file);

                $scripts = $html->getElementsByTagName('script');
                foreach($scripts as $script) {
                    if(($src = $script->getAttribute('src')) && substr($src, 0, 7) == 'http://') {
                        if(!scanurl($src)) {
                            $result .= get_all_errors($file,$suggestion1,$src);
                        }
                    }
                    if($data = $script->nodeValue) {
                        preg_match_all('/(http:\/\/)([^\/\'"]+)/i', $data, $urls);
                        if($urls && is_array($urls)) {
                            foreach($urls[0] as $url) {
                                if(!scanurl($url)) {
                                    //return $suggestion1;
                                    $result .= get_all_errors($file,$suggestion1,$src);
                                }
                            }
                        }
                    }
                }

                $iframes = $html->getElementsByTagName('iframe');
                foreach($iframes as $iframe) {
                    if(($src = $iframe->getAttribute('src')) && substr($src, 0, 7) == 'http://') {
                        if(!scanurl($src)) {
                            //return $suggestion2;
                            $result .= get_all_errors($file,$suggestion2,$src);
                        }
                    }
                }

                unset($html);
                //return $file;
            
            }
            
            return $result;

        }
        
    ?>
    
    <script type="text/javascript">
		Mo("#wrapper").attr({"class":"snugly"});
		Mo.reader(function(){
			
			Mo("#bind_secure").bind("submit",function(){
				Mo.Message("info", "正在执行扫描，请稍后……" , 20, { "unique" : "message", "center":true } );
			});
			
		});
	</script>
    
    <?php
    if($action){
    ?>
    <div id="box">

        <div class="item">危险代码扫描结果</div>
    
        <table width="100%" border="0" cellpadding="1" cellspacing="1" class="table">
            <tr class="title">
                <td>位置</td>
                <td>包含可疑内容</td>
                <td>行为描述</td>
                <td>文件最后修改</td>
            </tr>

            <?php

            if($_GET["attachments"]){

                echo '<tr class="item"><td colspan="1">上传附件</td><td colspan="3">位置：'.$_G['project']['upload'].'</td></tr>';

                $result = scanfiles($_G['project']['upload']);

                if($result){
                    echo $result;
                }else{
                    echo '<tr class="green"><td colspan="4"><img src="'.VI_BASE.'image/icon/tick.png" /> 未发现异常</td></tr>';
                }

            }

            if($_GET["webshell"]){

                echo '
                <tr class="item"><td colspan="1">系统缓存中扫描 Webshell</td><td colspan="3">位置：'.$_G['project']['cache'].'</td></tr>';

                $result = scanwebshell($_G['project']['cache']);

                if($result){
                    echo $result;
                }else{
                    echo '<tr class="green"><td colspan="4"><img src="'.VI_BASE.'image/icon/tick.png" /> 未发现异常</td></tr>';
                }

                echo '
                <tr class="item"><td colspan="1">模板缓存中扫描 Webshell</td><td colspan="3">位置：static/</td></tr>';

                $result = scanwebshell( VI_ROOT.'static' );

                if($result){
                    echo $result;
                }else{
                    echo '<tr class="green"><td colspan="4"><img src="'.VI_BASE.'image/icon/tick.png" /> 未发现异常</td></tr>';
                }

            }

            if($_GET["templates"]){

                echo '<tr class="item"><td colspan="1">模块缓存中扫描不安全外链</td><td colspan="3">位置：'.$_G['project']['cache'].'</td></tr>';

                $result = '';

                foreach( $_CACHE['system']['module'] as $appid ){
                    $result .= scantemplate($_G['project']['cache'].'/'.$appid);
                }

                if($result){
                    echo $result;
                }else{
                    echo '<tr class="green"><td colspan="4"><img src="'.VI_BASE.'image/icon/tick.png" /> 未发现异常</td></tr>';
                }

            }

            //echo '<pre>';

            create_file( $log ,date("Y-m-d H:i:s"));


            //echo(get_all_files('./'));
            //echo '</pre>';
            //$('show').value = '恭喜您, 程序没有发现任何危险代码, 网站安全.';
            ?>
       </table>

    </div>	
    <?php
    }else{
    ?>
    <div id="box">

        <form id="bind_secure" action="?" method="get">        
        
        <table cellpadding="0" cellspacing="0" class="form">

            <tr><td class="section"><strong>危险代码扫描程序</strong></td></tr>

            <tr>
                <td>
                
                    <p>
                    <ul>
                        <li><input type="checkbox" class="checkbox" name="webshell" id="webshell" checked /> <label for="webshell">扫描系统缓存文件中的 Webshell</label><br /></li>
                        <li><input type="checkbox" class="checkbox" name="templates" id="templates" <?php echo (!new DOMDocument() ? 'disabled' : 'checked');?> /> <label for="templates">扫描页面缓存/模板文件中的不安全外链 (仅 PHP5 或更新版本)</label><br /></li>
                        <li><input type="checkbox" class="checkbox" name="attachments" id="attachments" checked /> <label for="attachments">扫描上传附件目录中存在的 PHP/ASP 文件</label><br /></li>
                        <!--input type="checkbox" class="checkbox" name="database" id="database" checked /> <label for="database">扫描数据表中存在的非法代码</label><br /-->
                    </ul>
                </p>
                
                <input type="hidden" name="action" value="check" />
    
                <p><input type="submit" class="submit" value="开始扫描" /></p>
    
                <p>扫描引擎版本: <?php echo $_G['product']['version'];?>, 程序版本: <?php echo $_G['product']['version'];?></p>
                
                </td>
            </tr>
            
         </table>
        
        </form>

    </div>		
    <?php
    }
    ?>

<!--body end-->

<?php html_close();?>