Php Aes加密类程序代码分享

 更新时间:2016年11月25日 15:23  点击:1411
今天没事与了一个Php Aes加密类程序,适用于Yii的扩展如果不用在Yii框架中,把代码中Yii::app()->params[\'encryptKey\'] 换成你对应的默认key就可以了。

AES加密算法 – 算法原理

AES 算法基于排列和置换运算。排列是对数据重新进行安排,置换是将一个数据单元替换为另一个。AES 使用几种不同的方法来执行排列和置换运算。
AES 是一个迭代的、对称密钥分组的密码,它可以使用128、192 和 256 位密钥,并且用 128 位(16字节)分组加密和解密数据。与公共密钥密码使用密钥对不同,对称密钥密码使用相同的密钥加密和解密数据。通过分组密码返回的加密数据的位数与输入数据相同。迭代加密使用一个循环结构,在该循环中重复置换和替换输入数据。

 代码如下 复制代码

<?php
/**
* php AES加解密类
* 因为java只支持128位加密,所以php也用128位加密,可以与java互转。
* 同时AES的标准也是128位。只是RIJNDAEL算法可以支持128,192和256位加密。
*
* @author Terry
*
*/
class PhpAes
{
/**
* This was AES-128 / CBC / ZeroBytePadding encrypted.
* return base64_encode string
* @author Terry
* @param string $plaintext
* @param string $key
*/
public static function AesEncrypt($plaintext,$key = null)
{
if ($plaintext == '') return '';
if(!extension_loaded('mcrypt'))
throw new CException(Yii::t('yii','AesEncrypt requires PHP mcrypt extension to be loaded in order to use data encryption feature.'));
$size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$plaintext = self::PKCS5Padding($plaintext, $size);
$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
$key=self::substr($key===null ? Yii::app()->params['encryptKey'] : $key, 0, mcrypt_enc_get_key_size($module));
/* Create the IV and determine the keysize length, use MCRYPT_RAND
* on Windows instead */
$iv = substr(md5($key),0,mcrypt_enc_get_iv_size($module));
/* Intialize encryption */
mcrypt_generic_init($module, $key, $iv);

/* Encrypt data */
$encrypted = mcrypt_generic($module, $plaintext);

/* Terminate encryption handler */
mcrypt_generic_deinit($module);
mcrypt_module_close($module);
return base64_encode(trim($encrypted));
}

/**
* This was AES-128 / CBC / ZeroBytePadding decrypted.
* @author Terry
* @param string $encrypted base64_encode encrypted string
* @param string $key
* @throws CException
* @return string
*/
public static function AesDecrypt($encrypted, $key = null)
{
if ($encrypted == '') return '';
if(!extension_loaded('mcrypt'))
throw new CException(Yii::t('yii','AesDecrypt requires PHP mcrypt extension to be loaded in order to use data encryption feature.'));

$ciphertext_dec = base64_decode($encrypted);
$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
$key=self::substr($key===null ? Yii::app()->params['encryptKey'] : $key, 0, mcrypt_enc_get_key_size($module));

$iv = substr(md5($key),0,mcrypt_enc_get_iv_size($module));

/* Initialize encryption module for decryption */
mcrypt_generic_init($module, $key, $iv);

/* Decrypt encrypted string */
$decrypted = mdecrypt_generic($module, $ciphertext_dec);

/* Terminate decryption handle and close module */
mcrypt_generic_deinit($module);
mcrypt_module_close($module);
return self::UnPKCS5Padding($decrypted);
}


private static function strlen($string)
{
return extension_loaded('mbstring') ? mb_strlen($string,'8bit') : strlen($string);
}

private static function substr($string,$start,$length)
{
return extension_loaded('mbstring') ? mb_substr($string,$start,$length,'8bit') : substr($string,$start,$length);
}

private static function PKCS5Padding ($text, $blocksize) {
$pad = $blocksize - (self::strlen($text) % $blocksize);
return $text . str_repeat(chr($pad), $pad);
}

private static function UnPKCS5Padding($text)
{
$pad = ord($text{self::strlen($text)-1});
if ($pad > self::strlen($text)) return false;
if (strspn($text, chr($pad), self::strlen($text) - $pad) != $pad) return false;
return substr($text, 0, -1 * $pad);
}
}

使用方法

 代码如下 复制代码

<?php
require_once('./AES.php');
//$aes = new AES();
$aes = new AES(true);// 把加密后的字符串按十六进制进行存储
//$aes = new AES(true,true);// 带有调试信息且加密字符串按十六进制存储
$key = "this is a 32 byte key";// 密钥
$keys = $aes->makeKey($key);
$encode = "123456";// 被加密的字符串
$ct = $aes->encryptString($encode, $keys);
echo "encode = ".$ct."<br>";
$cpt = $aes->decryptString($ct, $keys);
echo "decode = ".$cpt;
?>

php网站被挂木马修复是次要的最要的是怎么修复之后不再让木马再注入到你的网站才是重要的,下面我来总结一下php网站被挂木马修复与之后防止网站再次给挂木马的方法。

在linux中我们可以使用命令来搜查木马文件,到代码安装目录执行下面命令

 代码如下 复制代码

find ./ -iname "*.php" | xargs grep -H -n "eval(base64_decode"

搜出来接近100条结果,这个结果列表很重要,木马都在里面,要一个一个文件打开验证是否是木马,如果是,马上删除掉

最后找到10个木马文件,存放在各种目录,都是php webshell,功能很齐全,用base64编码

如果你在windows中查找目录直接使用windows文件搜索就可以了,可以搜索eval或最近修改文件,然后如果是dedecms我们要查看最新dedecms漏洞呀然后修补。


下面给个php木马查找工具,直接放到你站点根目录

 代码如下 复制代码

<?php

/**************PHP Web木马扫描器************************/

/* [+] 作者: alibaba */

/* [+] QQ: 1499281192 * www.111cn.net/

/* [+] MSN: weeming21@hotmail.com */

/* [+] 首发: t00ls.net , 转载请注明t00ls */

/* [+] 版本: v1.0 */

/* [+] 功能: web版php木马扫描工具*/

/* [+] 注意: 扫描出来的文件并不一定就是后门, */

/* 请自行判断、审核、对比原文件。*/

/* 如果你不确定扫出来的文件是否为后门,*/

/* 欢迎你把该文件发给我进行分析。*/

/*******************************************************/

ob_start();

set_time_limit(0);

$username = "t00ls"; //设置用户名

$password = "t00ls"; //设置密码

$md5 = md5(md5($username).md5($password));

$version = "PHP Web木马扫描器v1.0";

 

PHP Web 木马扫描器

$realpath = realpath('./');

$selfpath = $_SERVER['PHP_SELF'];

$selfpath = substr($selfpath, 0, strrpos($selfpath,'/'));

define('REALPATH', str_replace('//','/',str_replace('\','/',substr($realpath, 0, strlen($realpath) - strlen($selfpath)))));

define('MYFILE', basename(__FILE__));

define('MYPATH', str_replace('\', '/', dirname(__FILE__)).'/');

define('MYFULLPATH', str_replace('\', '/', (__FILE__)));

define('HOST', "http://".$_SERVER['HTTP_HOST']);

?>

<html>

<head>

<title><?php echo $version?></title>

<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />

<style>

body{margin:0px;}

body,td{font: 12px Arial,Tahoma;line-height: 16px;}

a {color: #00f;text-decoration:underline;}

a:hover{color: #f00;text-decoration:none;}

.alt1 td{border-top:1px solid #fff;border-bottom:1px solid #ddd;background:#f1f1f1;padding:5px 10px 5px 5px;}

.alt2 td{border-top:1px solid #fff;border-bottom:1px solid #ddd;background:#f9f9f9;padding:5px 10px 5px 5px;}

.focus td{border-top:1px solid #fff;border-bottom:1px solid #ddd;background:#ffffaa;padding:5px 10px 5px 5px;}

.head td{border-top:1px solid #fff;border-bottom:1px solid #ddd;background:#e9e9e9;padding:5px 10px 5px 5px;font-weight:bold;}

.head td span{font-weight:normal;}

</style>

</head>

<body>

<?php

if(!(isset($_COOKIE['t00ls']) && $_COOKIE['t00ls'] == $md5) && !(isset($_POST['username']) && isset($_POST['password']) && (md5(md5($_POST['username']).md5($_POST['password']))==$md5)))

{

echo '<form id="frmlogin" name="frmlogin" method="post" action="">用户名: <input type="text" name="username" id="username" /> 密码: <input type="password" name="password" id="password" /> <input type="submit" name="btnLogin" id="btnLogin" value="登陆" /></form>';

}

elseif(isset($_POST['username']) && isset($_POST['password']) && (md5(md5($_POST['username']).md5($_POST['password']))==$md5))

{

setcookie("t00ls", $md5, time()+60*60*24*365,"/");

echo "登陆成功!";

header( 'refresh: 1; url='.MYFILE.'?action=scan' );

exit();

}

else

{

setcookie("t00ls", $md5, time()+60*60*24*365,"/");

$setting = getSetting();

$action = isset($_GET['action'])?$_GET['action']:"";

 

if($action=="logout")

{

setcookie ("t00ls", "", time() - 3600);

Header("Location: ".MYFILE);

exit();

}

if($action=="download" && isset($_GET['file']) && trim($_GET['file'])!="")

{

$file = $_GET['file'];

ob_clean();

if (@file_exists($file)) {

header("Content-type: application/octet-stream");

header("Content-Disposition: filename="".basename($file).""");

echo file_get_contents($file);

}

exit();

}

?>

<table border="0" cellpadding="0" cellspacing="0" width="100%">

<tbody><tr class="head">

<td><?php echo $_SERVER['SERVER_ADDR']?><span style="float: right; font-weight:bold;"><?php echo "<a href='http://www.t00ls.net/'>$version</a>"?></span></td>

</tr>

<tr class="alt1">

<td><span style="float: right;"><?=date("Y-m-d H:i:s",mktime())?></span>

<a href="?action=scan">扫描</a> |

<a href="?action=setting">设定</a> |

<a href="?action=logout">登出</a>

</td>

</tr>

</tbody></table>

<br>

<?php

if($action=="setting")

{

if(isset($_POST['btnsetting']))

{

$Ssetting = array();

$Ssetting['user']=isset($_POST['checkuser'])?$_POST['checkuser']:"php | php? | phtml";

$Ssetting['all']=isset($_POST['checkall'])&&$_POST['checkall']=="on"?1:0;

$Ssetting['hta']=isset($_POST['checkhta'])&&$_POST['checkhta']=="on"?1:0;

setcookie("t00ls_s", base64_encode(serialize($Ssetting)), time()+60*60*24*365,"/");

echo "设置完成!";

header( 'refresh: 1; url='.MYFILE.'?action=setting' );

exit();

}

?>

<form name="frmSetting" method="post" action="?action=setting">

<FIELDSET style="width:400px">

<LEGEND>扫描设定</LEGEND>

<table width="100%" border="0" cellspacing="0" cellpadding="0">

<tr>

<td width="60">文件后缀:</td>

<td width="300"><input type="text" name="checkuser" id="checkuser" style="width:300px;" value="<?php echo $setting['user']?>"></td>

</tr>

<tr>

<td><label for="checkall">所有文件</label></td>

<td><input type="checkbox" name="checkall" id="checkall" <?php if($setting['all']==1) echo "checked"?>></td>

</tr>

<tr>

<td><label for="checkhta">设置文件</label></td>

<td><input type="checkbox" name="checkhta" id="checkhta" <?php if($setting['hta']==1) echo "checked"?>></td>

</tr>

<tr>

<td>&nbsp;</td>

<td>

<input type="submit" name="btnsetting" id="btnsetting" value="提交">

</td>

</tr>

</table>

</fieldset>

</form>

<?php

}

else

{

$dir = isset($_POST['path'])?$_POST['path']:MYPATH;

$dir = substr($dir,-1)!="/"?$dir."/":$dir;

?>

<form name="frmScan" method="post" action="">

<table width="100%%" border="0" cellspacing="0" cellpadding="0">

<tr>

<td width="35" style="vertical-align:middle; padding-left:5px;">扫描路径:</td>

<td width="690">

<input type="text" name="path" id="path" style="width:600px" value="<?php echo $dir?>">

&nbsp;&nbsp;<input type="submit" name="btnScan" id="btnScan" value="开始扫描"></td>

</tr>

</table>

</form>

<?php

if(isset($_POST['btnScan']))

{

$start=mktime();

$is_user = array();

$is_ext = "";

$list = "";

 

if(trim($setting['user'])!="")

{

$is_user = explode("|",$setting['user']);

if(count($is_user)>0)

{

foreach($is_user as $key=>$value)

$is_user[$key]=trim(str_replace("?","(.)",$value));

$is_ext = "(.".implode("($|.))|(.",$is_user)."($|.))";

}

}

if($setting['hta']==1)

{

$is_hta=1;

$is_ext = strlen($is_ext)>0?$is_ext."|":$is_ext;

$is_ext.="(^.htaccess$)";

}

if($setting['all']==1 || (strlen($is_ext)==0 && $setting['hta']==0))

{

$is_ext="(.+)";

}

 

$php_code = getCode();

if(!is_readable($dir))

$dir = MYPATH;

$count=$scanned=0;

scan($dir,$is_ext);

$end=mktime();

$spent = ($end - $start);

?>

<div style="padding:10px; background-color:#ccc">扫描: <?php echo $scanned?> 文件| 发现: <?php echo $count?> 可疑文件| 耗时: <?php echo $spent?> 秒</div>

<table width="100%" border="0" cellspacing="0" cellpadding="0">

<tr class="head">

<td width="15" align="center">No.</td>

<td width="48%">文件</td>

<td width="12%">更新时间</td>

<td width="10%">原因</td>

<td width="20%">特征</td>

<td>动作</td>

</tr>

<?php echo $list?>

</table>

<?php

}

}

}

ob_flush();

?>

</body>

</html>

<?php

function scan($path = '.',$is_ext){

global $php_code,$count,$scanned,$list;

$ignore = array('.', '..' );

$replace=array(" ","n","r","t");

$dh = @opendir( $path );

 

 

while(false!==($file=readdir($dh))){

if( !in_array( $file, $ignore ) ){

if( is_dir( "$path$file" ) ){

scan("$path$file/",$is_ext);

} else {

$current = $path.$file;

if(MYFULLPATH==$current) continue;

if(!preg_match("/$is_ext/i",$file)) continue;

if(is_readable($current))

{

$scanned++;

$content=file_get_contents($current);

$content= str_replace($replace,"",$content);

foreach($php_code as $key => $value)

{

if(preg_match("/$value/i",$content))

{

$count++;

$j = $count % 2 + 1;

$filetime = date('Y-m-d H:i:s',filemtime($current));

$reason = explode("->",$key);

$url = str_replace(REALPATH,HOST,$current);

preg_match("/$value/i",$content,$arr);

$list.="

<tr class='alt$j' onmouseover='this.className="focus";' onmouseout='this.className="alt$j";'>

<td>$count</td>

<td><a href='$url' target='_blank'>$current</a></td>

<td>$filetime</td>

<td><font color=red>$reason[0]</font></td>

<td><font color=#090>$reason[1]</font></td>

<td><a href='?action=download&file=$current' target='_blank'>下载</a></td>

</tr>";

//echo $key . "-" . $path . $file ."(" . $arr[0] . ")" ."<br />";

//echo $path . $file ."<br />";

break;

}

}

}

}

}

}

closedir( $dh );

}

function getSetting()

{

$Ssetting = array();

if(isset($_COOKIE['t00ls_s']))

{

$Ssetting = unserialize(base64_decode($_COOKIE['t00ls_s']));

$Ssetting['user']=isset($Ssetting['user'])?$Ssetting['user']:"php | php? | phtml | shtml";

$Ssetting['all']=isset($Ssetting['all'])?intval($Ssetting['all']):0;

$Ssetting['hta']=isset($Ssetting['hta'])?intval($Ssetting['hta']):1;

}

else

{

$Ssetting['user']="php | php? | phtml | shtml";

$Ssetting['all']=0;

$Ssetting['hta']=1;

setcookie("t00ls_s", base64_encode(serialize($Ssetting)), time()+60*60*24*365,"/");

}

return $Ssetting;

}

function getCode()

{

return array(

'后门特征->cha88.cn'=>'cha88.cn',

'后门特征->c99shell'=>'c99shell',

'后门特征->phpspy'=>'phpspy',

'后门特征->Scanners'=>'Scanners',

'后门特征->cmd.php'=>'cmd.php',

'后门特征->str_rot13'=>'str_rot13',

'后门特征->webshell'=>'webshell',

'后门特征->EgY_SpIdEr'=>'EgY_SpIdEr',

'后门特征->tools88.com'=>'tools88.com',

'后门特征->SECFORCE'=>'SECFORCE',

'后门特征->eval("?>'=>'eval(('|")?>',

'可疑代码特征->system('=>'system(',

'可疑代码特征->passthru('=>'passthru(',

'可疑代码特征->shell_exec('=>'shell_exec(',

'可疑代码特征->exec('=>'exec(',

'可疑代码特征->popen('=>'popen(',

'可疑代码特征->proc_open'=>'proc_open',

'可疑代码特征->eval($'=>'eval(('|"|s*)\$',

'可疑代码特征->assert($'=>'assert(('|"|s*)\$',

'危险MYSQL代码->returns string soname'=>'returnsstringsoname',

'危险MYSQL代码->into outfile'=>'intooutfile',

'危险MYSQL代码->load_file'=>'select(s+)(.*)load_file',

'加密后门特征->eval(gzinflate('=>'eval(gzinflate(',

'加密后门特征->eval(base64_decode('=>'eval(base64_decode(',

'加密后门特征->eval(gzuncompress('=>'eval(gzuncompress(',

'加密后门特征->eval(gzdecode('=>'eval(gzdecode(',

'加密后门特征->eval(str_rot13('=>'eval(str_rot13(',

'加密后门特征->gzuncompress(base64_decode('=>'gzuncompress(base64_decode(',

'加密后门特征->base64_decode(gzuncompress('=>'base64_decode(gzuncompress(',

'一句话后门特征->eval($_'=>'eval(('|"|s*)\$_(POST|GET|REQUEST|COOKIE)',

'一句话后门特征->assert($_'=>'assert(('|"|s*)\$_(POST|GET|REQUEST|COOKIE)',

'一句话后门特征->require($_'=>'require(('|"|s*)\$_(POST|GET|REQUEST|COOKIE)',

'一句话后门特征->require_once($_'=>'require_once(('|"|s*)\$_(POST|GET|REQUEST|COOKIE)',

'一句话后门特征->include($_'=>'include(('|"|s*)\$_(POST|GET|REQUEST|COOKIE)',

'一句话后门特征->include_once($_'=>'include_once(('|"|s*)\$_(POST|GET|REQUEST|COOKIE)',

'一句话后门特征->call_user_func("assert"'=>'call_user_func(("|')assert("|')',

'一句话后门特征->call_user_func($_'=>'call_user_func(('|"|s*)\$_(POST|GET|REQUEST|COOKIE)',

'一句话后门特征->$_POST/GET/REQUEST/COOKIE[?]($_POST/GET/REQUEST/COOKIE[?]'=>'$_(POST|GET|REQUEST|COOKIE)[([^]]+)](('|"|s*)\$_(POST|GET|REQUEST|COOKIE)[',

'一句话后门特征->echo(file_get_contents($_POST/GET/REQUEST/COOKIE'=>'echo(file_get_contents(('|"|s*)\$_(POST|GET|REQUEST|COOKIE)',

'上传后门特征->file_put_contents($_POST/GET/REQUEST/COOKIE,$_POST/GET/REQUEST/COOKIE'=>'file_put_contents(('|"|s*)\$_(POST|GET|REQUEST|COOKIE)[([^]]+)],('|"|s*)\$_(POST|GET|REQUEST|COOKIE)',

'上传后门特征->fputs(fopen("?","w"),$_POST/GET/REQUEST/COOKIE['=>'fputs(fopen((.+),('|")w('|")),('|"|s*)\$_(POST|GET|REQUEST|COOKIE)[',

'.htaccess插马特征->SetHandler application/x-httpd-php'=>'SetHandlerapplication/x-httpd-php',

'.htaccess插马特征->php_value auto_prepend_file'=>'php_valueauto_prepend_file',

'.htaccess插马特征->php_value auto_append_file'=>'php_valueauto_append_file'

);

}

?>

在使用xml-rpc的时候,server端获取client数据,主要是通过php输入流input,而不是$_POST数组。所以,这里主要探讨php输入流php://input

对一php://input介绍,PHP官方手册文档有一段话对它进行了很明确地概述。

“php://input allows you to read raw POST data. It is a less memory intensive alternative to $HTTP_RAW_POST_DATA and does not need any special php.ini directives. php://input is not available with enctype=”multipart/form-data”.

翻译过来,是这样:

“php://input可以读取没有处理过的POST数据。相较于$HTTP_RAW_POST_DATA而言,它给内存带来的压力较小,并且不需要特殊的php.ini设置。php://input不能用于enctype=multipart/form-data”


我们应该怎么去理解这段概述呢?!我把它划分为三部分,逐步去理解。

读取POST数据
不能用于multipart/form-data类型
php://input VS $HTTP_RAW_POST_DATA
读取POST数据
PHPer们一定很熟悉$_POST这个内置变量。$_POST与php://input存在哪些关联与区别呢?另外,客户端向服务端交互数据,最常用的方法除了POST之外,还有GET。既然php://input作为PHP输入流,它能读取GET数据吗?这二个问题正是我们这节需要探讨的主要内容。
经验告诉我们,从测试与观察中总结,会是一个很凑效的方法。这里,我写了几个脚本来帮助我们测试。

@file 192.168.0.6:/phpinput_server.php 打印出接收到的数据
@file 192.168.0.8:/phpinput_post.php 模拟以POST方法提交表单数据
@file 192.168.0.8:/phpinput_xmlrpc.php 模拟以POST方法发出xmlrpc请求.
@file 192.168.0.8:/phpinput_get.php 模拟以GET方法提交表单表数
phpinput_server.php与phpinput_post.php

 

 代码如下 复制代码
<?php
//@file phpinput_server.php
$raw_post_data = file_get_contents('php://input', 'r');
echo "-------$_POST------------------n";
echo var_dump($_POST) . "n";
echo "-------php://input-------------n";
echo $raw_post_data . "n";
?>
 
<?php
//@file phpinput_post.php
$http_entity_body = 'n=' . urldecode('perfgeeks') . '&amp;p=' . urldecode('7788');
$http_entity_type = 'application/x-www-form-urlencoded';
$http_entity_length = strlen($http_entity_body);
$host = '192.168.0.6';
$port = 80;
$path = '/phpinput_server.php';
$fp = fsockopen($host, $port, $error_no, $error_desc, 30);
if ($fp) {
  fputs($fp, "POST {$path} HTTP/1.1rn");
  fputs($fp, "Host: {$host}rn");
  fputs($fp, "Content-Type: {$http_entity_type}rn");
  fputs($fp, "Content-Length: {$http_entity_length}rn");
  fputs($fp, "Connection: closernrn");
  fputs($fp, $http_entity_body . "rnrn");
 
  while (!feof($fp)) {
    $d .= fgets($fp, 4096);
  }
  fclose($fp);
  echo $d;
}
?>


我们可以通过使用工具ngrep抓取http请求包(因为我们需要探知的是php://input,所以我们这里只抓取http Request数据包)。我们来执行测试脚本phpinput_post.php

 代码如下 复制代码
@php /phpinput_post.php
HTTP/1.1 200 OK
Date: Thu, 08 Apr 2010 03:23:36 GMT
Server: Apache/2.2.3 (CentOS)
X-Powered-By: PHP/5.1.6
Content-Length: 160
Connection: close
Content-Type: text/html; charset=UTF-8
-------$_POST------------------
array(2) {
  ["n"]=> string(9) "perfgeeks"
  ["p"]=> string(4) "7788"
}
-------php://input-------------
n=perfgeeks&p=7788

通过ngrep抓到的http请求包如下:

T 192.168.0.8:57846 -> 192.168.0.6:80 [AP]
  POST /phpinput_server.php HTTP/1.1..
  Host: 192.168.0.6..Content-Type: application/x-www-form-urlencoded..Co
  ntent-Length: 18..Connection: close....n=perfgeeks&p=7788....
仔细观察,我们不难发现
1,$_POST数据,php://input 数据与httpd entity body数据是“一致”的
2,http请求中的Content-Type是application/x-www-form-urlencoded ,它表示http请求body中的数据是使用http的post方法提交的表单数据,并且进行了urlencode()处理。
(注:注意加粗部分内容,下文不再提示).

表单提交如果安全做得不好就很容易因为这个表单提交导致网站被攻击了,下面我来分享两个常用的php 过滤表单提交的危险代码的实例,各位有需要的朋友可参考。

例1

 

 代码如下 复制代码

function uhtml($str) 

    $farr = array( 
        "/s+/", //过滤多余空白 
         //过滤 <script>等可能引入恶意内容或恶意改变显示布局的代码,如果不需要插入flash等,还

可以加入<object>的过滤 
        "/<(/?)(script|i?frame|style|html|body|title|link|meta|?|%)([^>]*?)>/isU",
        "/(<[^>]*)on[a-zA-Z]+s*=([^>]*>)/isU",//过滤javascript的on事件 
   ); 
   $tarr = array( 
        " ", 
        "<123>",//如果要直接清除不安全的标签,这里可以留空 
        "12", 
   ); 
  $str = preg_replace( $farr,$tarr,$str); 
   return $str; 
}

例2
或者这样操作

 代码如下 复制代码

//get post data
 function PostGet($str,$post=0)
 {
  empty($str)?die('para is null'.$str.'!'):'';
  
  if( $post )
  {
   if( get_magic_quotes_gpc() )
   {
    return htmlspecialchars(isset($_POST[$str])?$_POST

[$str]:'');
   }
   else
   {
    return addslashes(htmlspecialchars(isset($_POST[$str])?

$_POST[$str]:''));
   }
   
  }
  else
  {
   if( get_magic_quotes_gpc() )
   {
    return htmlspecialchars(isset($_GET[$str])?$_GET[$str]:''); 
   }
   else
   {
    return addslashes(htmlspecialchars(isset($_GET[$str])?

$_GET[$str]:'')); 
   }
  }
 }

CC攻击就是对方利用程序或一些代理对您的网站进行不间断的访问,造成您的网站处理不了而处于当机状态,下面我们来总结一些防CC攻击的php实例代码,各位朋友可参考。

例1

 代码如下 复制代码

//代理IP直接退出
empty($_SERVER['HTTP_VIA']) or exit('Access Denied');
//防止快速刷新
session_start();
$seconds = '3'; //时间段[秒]
$refresh = '5'; //刷新次数
//设置监控变量
$cur_time = time();
if(isset($_SESSION['last_time'])){
    $_SESSION['refresh_times'] += 1;
}else{
    $_SESSION['refresh_times'] = 1;
    $_SESSION['last_time'] = $cur_time;
}
//处理监控结果
if($cur_time - $_SESSION['last_time'] < $seconds){
    if($_SESSION['refresh_times'] >= $refresh){
        //跳转至攻击者服务器地址
        header(sprintf('Location:%s', 'http://127.0.0.1'));
        exit('Access Denied');
    }
}else{
    $_SESSION['refresh_times'] = 0;
    $_SESSION['last_time'] = $cur_time;
}

例二

 

 代码如下 复制代码

$P_S_T = $t_array[0] + $t_array[1];
$timestamp = time();

session_start();
$ll_nowtime = $timestamp ;
if (session_is_registered('ll_lasttime')){
$ll_lasttime = $_SESSION['ll_lasttime'];
$ll_times = $_SESSION['ll_times'] + 1;
$_SESSION['ll_times'] = $ll_times;
}else{
$ll_lasttime = $ll_nowtime;
$ll_times = 1;
$_SESSION['ll_times'] = $ll_times;
$_SESSION['ll_lasttime'] = $ll_lasttime;
}
if (($ll_nowtime - $ll_lasttime)<3){
if ($ll_times>=5){
header(sprintf("Location: %s",'http://127.0.0.1'));
exit;
}
}else{
$ll_times = 0;
$_SESSION['ll_lasttime'] = $ll_nowtime;
$_SESSION['ll_times'] = $ll_times;
}

一个实例我自己亲测的

日志分析

[2011-04-16 03:03:13] [client 61.217.192.39] /index.php
[2011-04-16 03:03:13] [client 61.217.192.39] /index.php
[2011-04-16 03:03:13] [client 61.217.192.39] /index.php
[2011-04-16 03:03:13] [client 61.217.192.39] /index.php
[2011-04-16 03:03:12] [client 61.217.192.39] /index.php
[2011-04-16 03:03:12] [client 61.217.192.39] /index.php
[2011-04-16 03:03:12] [client 61.217.192.39] /index.php
[2011-04-16 03:03:11] [client 61.217.192.39] /index.php
[2011-04-16 03:03:11] [client 61.217.192.39] /index.php
[2011-04-16 03:03:11] [client 61.217.192.39] /index.php
[2011-04-16 03:03:10] [client 61.217.192.39] /index.php
[2011-04-16 03:03:10] [client 61.217.192.39] /index.php

下面是PHP方法:将以下代码另存为php文件,然后首行include入你的common.php文件中。

 代码如下 复制代码

<?php
/*
 * 防CC攻击郁闷到死,不死版。
 *
 * 如果每秒内网站刷新次数超过2次,延迟5秒后访问。
 */
 
$cc_min_nums = '1';                    //次,刷新次数
$cc_url_time = '5';                    //秒,延迟时间
//$cc_log = 'cc_log.txt';                //启用本行为记录日志
$cc_forward = 'http://localhost';    //释放到URL

//--------------------------------------------

//返回URL
$cc_uri = $_SERVER['REQUEST_URI']?$_SERVER['REQUEST_URI']:($_SERVER['PHP_SELF']?$_SERVER['PHP_SELF']:$_SERVER['SCRIPT_NAME']);
$site_url = 'http://'.$_SERVER ['HTTP_HOST'].$cc_uri;

//启用session
if( !isset( $_SESSION ) ) session_start();
$_SESSION["visiter"] = true;
if ($_SESSION["visiter"] <> true){
 echo "<script>setTimeout("window.location.href ='$cc_forward';", 1);</script>";
 //header("Location: ".$cc_forward);
 exit;
}

$timestamp = time();
$cc_nowtime = $timestamp ;
if (session_is_registered('cc_lasttime')){
 $cc_lasttime = $_SESSION['cc_lasttime'];
 $cc_times = $_SESSION['cc_times'] + 1;
 $_SESSION['cc_times'] = $cc_times;
}else{
 $cc_lasttime = $cc_nowtime;
 $cc_times = 1;
 $_SESSION['cc_times'] = $cc_times;
 $_SESSION['cc_lasttime'] = $cc_lasttime;
}

//获取真实IP
if (isset($_SERVER)){
 $real_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}else{
 $real_ip = getenv("HTTP_X_FORWARDED_FOR");
}

//print_r($_SESSION);

//释放IP
if (($cc_nowtime - $cc_lasttime)<=0){
 if ($cc_times>=$cc_min_nums){       
 if(!empty($cc_log))    cc_log(get_ip(), $real_ip, $cc_log, $cc_uri);    //产生log
 echo "Wait please, try again later!<script>setTimeout("window.location.href ='$site_url';", 5000);</script>";
 //printf('您的刷新过快,请稍后。');
 //header("Location: ".$cc_forward);
 exit;
 }
}else{
 $cc_times = 0;
 $_SESSION['cc_lasttime'] = $cc_nowtime;
 $_SESSION['cc_times'] = $cc_times;
}

//记录cc日志
function cc_log($client_ip, $real_ip, $cc_log, $cc_uri){   
 $temp_time = date("Y-m-d H:i:s", time() + 3600*8);
 
 $temp_result = "[".$temp_time."] [client ".$client_ip."] ";   
 if($real_ip) $temp_result .= " [real ".$real_ip."] ";
 $temp_result .= $cc_uri . "rn";
 
 $handle = fopen ("$cc_log", "rb");
 $oldcontent = fread($handle,filesize("$cc_log"));
 fclose($handle);
 
 $newcontent = $temp_result . $oldcontent;
 $fhandle=fopen("$cc_log", "wb");
 fwrite($fhandle,$newcontent,strlen($newcontent));
 fclose($fhandle);
}

//获取在线IP
function get_ip() {
 global $_C;
 
 if(empty($_C['client_ip'])) {
 if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
 $client_ip = getenv('HTTP_CLIENT_IP');
 } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
 $client_ip = getenv('HTTP_X_FORWARDED_FOR');
 } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
 $client_ip = getenv('REMOTE_ADDR');
 } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
 $client_ip = $_SERVER['REMOTE_ADDR'];
 }
 $_C['client_ip'] = $client_ip ? $client_ip : 'unknown';
 }
 return $_C['client_ip'];
}
?>

这样就可以基础工业防止了,但是如果更高级占的就没办法,大家可尝试使用相关硬件防火强来设置。

[!--infotagslink--]

相关文章

  • 图解PHP使用Zend Guard 6.0加密方法教程

    有时为了网站安全和版权问题,会对自己写的php源码进行加密,在php加密技术上最常用的是zend公司的zend guard 加密软件,现在我们来图文讲解一下。 下面就简单说说如何...2016-11-25
  • Photoshop火龙变冰龙制作教程分享

    今天小编在这里就来给Photoshop的这一款软件的使用者们来说下火龙变冰龙的制作教程,各位想知道具体的制作步骤的使用者们,那么下面就快来跟着小编一起看看制作教程吧。...2016-09-14
  • 不打开网页直接查看网站的源代码

      有一种方法,可以不打开网站而直接查看到这个网站的源代码..   这样可以有效地防止误入恶意网站...   在浏览器地址栏输入:   view-source:http://...2016-09-20
  • php 调用goolge地图代码

    <?php require('path.inc.php'); header('content-Type: text/html; charset=utf-8'); $borough_id = intval($_GET['id']); if(!$borough_id){ echo ' ...2016-11-25
  • JS基于Mootools实现的个性菜单效果代码

    本文实例讲述了JS基于Mootools实现的个性菜单效果代码。分享给大家供大家参考,具体如下:这里演示基于Mootools做的带动画的垂直型菜单,是一个初学者写的,用来学习Mootools的使用有帮助,下载时请注意要将外部引用的mootools...2015-10-23
  • JS+CSS实现分类动态选择及移动功能效果代码

    本文实例讲述了JS+CSS实现分类动态选择及移动功能效果代码。分享给大家供大家参考,具体如下:这是一个类似选项卡功能的选择插件,与普通的TAb区别是加入了动画效果,多用于商品类网站,用作商品分类功能,不过其它网站也可以用,...2015-10-21
  • JS实现自定义简单网页软键盘效果代码

    本文实例讲述了JS实现自定义简单网页软键盘效果。分享给大家供大家参考,具体如下:这是一款自定义的简单点的网页软键盘,没有使用任何控件,仅是为了练习JavaScript编写水平,安全性方面没有过多考虑,有顾虑的可以不用,目的是学...2015-11-08
  • Illustrator渐变网格工具绘制可爱的卡通小猪教程分享

    今天小编在这里就来给Illustrator的这一款软件的使用者们来说一说渐变网格工具绘制可爱的卡通小猪的教程,各位想知道具体制作方法的使用者们,那么下面就快来跟着小编一...2016-09-14
  • php 取除连续空格与换行代码

    php 取除连续空格与换行代码,这些我们都用到str_replace与正则函数 第一种: $content=str_replace("n","",$content); echo $content; 第二种: $content=preg_replac...2016-11-25
  • php简单用户登陆程序代码

    php简单用户登陆程序代码 这些教程很对初学者来讲是很有用的哦,这款就下面这一点点代码了哦。 <center> <p>&nbsp;</p> <p>&nbsp;</p> <form name="form1...2016-11-25
  • PHP实现清除wordpress里恶意代码

    公司一些wordpress网站由于下载的插件存在恶意代码,导致整个服务器所有网站PHP文件都存在恶意代码,就写了个简单的脚本清除。恶意代码示例...2015-10-23
  • Photoshop功夫熊猫电影海报制作步骤分享

    不知不觉功夫熊猫这部电影已经出到3了,今天小编在这里要教大家的是用Photoshop制作功夫熊猫3的海报,各位想知道制作方法的,那么下面就来跟着小编一起看看吧。 给各...2016-09-14
  • js识别uc浏览器的代码

    其实挺简单的就是if(navigator.userAgent.indexOf('UCBrowser') > -1) {alert("uc浏览器");}else{//不是uc浏览器执行的操作}如果想测试某个浏览器的特征可以通过如下方法获取JS获取浏览器信息 浏览器代码名称:navigator...2015-11-08
  • JS实现双击屏幕滚动效果代码

    本文实例讲述了JS实现双击屏幕滚动效果代码。分享给大家供大家参考,具体如下:这里演示双击滚屏效果代码的实现方法,不知道有觉得有用处的没,现在网上还有很多还在用这个特效的呢,代码分享给大家吧。运行效果截图如下:在线演...2015-10-30
  • vue接口请求加密实例

    这篇文章主要介绍了vue接口请求加密实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-08-12
  • photoshop日系小清新通透人像调色教程分享

    今天小编在这里就来给photoshop的这一款软件的使用者们来说一说日系小清新通透人像的调色教程,各位想知道具体的调色步骤的使用者们,那么下面就快来跟着小编一起看一看...2016-09-14
  • JS日期加减,日期运算代码

    一、日期减去天数等于第二个日期function cc(dd,dadd){//可以加上错误处理var a = new Date(dd)a = a.valueOf()a = a - dadd * 24 * 60 * 60 * 1000a = new Date(a)alert(a.getFullYear() + "年" + (a.getMonth() +...2015-11-08
  • PHP开发微信支付的代码分享

    微信支付,即便交了保证金,你还是处理测试阶段,不能正式发布。必须到你通过程序测试提交订单、发货通知等数据到微信的系统中,才能申请发布。然后,因为在微信中是通过JS方式调用API,必须在微信后台设置支付授权目录,而且要到...2014-05-31
  • AES加密解密的例子小结

    关于AES加密的算法我们就不说了,这里主要给各位演示了三个关于AES算法实现的加密例子,希望本文章能给你带来帮助。 话不多说,先放上代码,一共有两个文件:AES.php(aes算...2016-11-25
  • PHP常用的小程序代码段

    本文实例讲述了PHP常用的小程序代码段。分享给大家供大家参考,具体如下:1.计算两个时间的相差几天$startdate=strtotime("2009-12-09");$enddate=strtotime("2009-12-05");上面的php时间日期函数strtotime已经把字符串...2015-11-24