首页 > 编程技术 > php

php防止webshell 处理函数

发布时间:2016-11-25 15:25


import os
import sys
import re
import time
def listdir(dirs,liston='0'):
flog = open(os.getcwd()+"/check_php教程_shell.log","a+")
if not os.path.isdir(dirs):
print "directory %s is not exist"% (dirs)
return
lists = os.listdir(dirs)
for list in lists:
filepath = os.path.join(dirs,list)
if os.path.isdir(filepath):
if liston == '1':
listdir(filepath,'1')
elif os.path.isfile(filepath):
filename = os.path.basename(filepath)
if re.search(r".(?:php|inc|html?)$", filename, re.ignorecase):
i = 0
iname = 0
f = open(filepath)
while f:
file_contents = f.readline()
if not file_contents:
break
i += 1
match = re.search(r'''(?p<function>b(?:include|require)(?:_once)?b)s*(?s*["'](?p<filename>[^;]*(?<!.(?:php|inc)))["'])?s*;''', file_contents, re.ignorecase| re.multiline)
if match:
function = match.group("function")
filename = match.group("filename")
if iname == 0:
info = 'n[%s] :n'% (filepath)
else:
info = ''
info += 't|-- [%s] - [%s] line [%d] n'% (function,filename,i)
flog.write(info)
print info
iname += 1
match = re.search(r'b(?p<function>eval|proc_open|popen|shell_exec|exec|passthru|system|assert|fwrite|create_function)bs*(', file_contents, re.ignorecase| re.multiline)
if match:
function = match.group("function")
if iname == 0:
info = 'n[%s] :n'% (filepath)
else:
info = ''
info += 't|-- [%s] line [%d] n'% (function,i)
flog.write(info)
print info
iname += 1
match = re.search(r'(^|(?<=;))s*`(?p<shell>[^`]+)`s*;', file_contents, re.ignorecase)
if match:
shell = match.group("shell")
if iname == 0:
info = 'n[%s] :n'% (filepath)
else:
info = ''
info += 't|-- [``] command is [%s] in line [%d] n'% (shell,i)
flog.write(info)
print info
iname += 1
match = re.search(r'(?p<shell>$_(?:pos|ge|reques)t)s*[[^]]+]s*(', file_contents, re.ignorecase)
if match:
shell = match.group("shell")
if iname == 0:
info = 'n[%s] :n'% (filepath)
else:
info = ''
info += 't|-- [``] command is [%s] in line [%d] n'% (shell,i)
flog.write(info)
print info
iname += 1
f.close()
flog.close()
if '__main__' == __name__:
argvnum = len(sys.argv)
liston = '0'
if argvnum == 1:
action = os.path.basename(sys.argv[0])
print "command is like:n %s d:wwwroot n %s d:wwwroot 1 -- recurse subfolders"% (action,action)
quit()
elif argvnum == 2:
path = os.path.realpath(sys.argv[1])
listdir(path,liston)
else:
liston = sys.argv[2]
path = os.path.realpath(sys.argv[1])
listdir(path,liston)
flog = open(os.getcwd()+"/check_php_shell.log","a+")
isotimeformat='%y-%m-%d %x'
now_time = time.strftime(isotimeformat,time.localtime())
flog.write("n----------------------%s checked ---------------------n"% (now_time))
flog.close()

PHP 的 HTTP 认证机制仅在 PHP 以 Apache 模块方式运行时才有效,因此该功能不适用于 CGI 版本。在 Apache 模块的 PHP 脚本中,可以用 header() 函数来向客户端浏览器发送“Authentication Required”信息,使其弹出一个用户名/密码输入窗口。当用户输入用户名和密码后,包含有 URL 的 PHP 脚本将会再次和预定义变量 PHP_AUTH_USER、PHP_AUTH_PW 和 AUTH_TYPE 一起被调用,这三个变量分别被设定为用户名,密码和认证类型。预定义变量保存在 $_SERVER 或者 $HTTP_SERVER_VARS 数组中。系统仅支持“基本的”认证

<?php教程
   $authorized = FALSE;

   if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
      $authFile = file("./password.txt");

      foreach ($authFile as $login) {
         list($username, $password) = explode(":", $login);
         $password = trim($password);
         if (($username == $_SERVER['PHP_AUTH_USER']) && ($password == md5($_SERVER['PHP_AUTH_PW']))) {
            $authorized = TRUE;
            break;
         }
      }
   }

   // If not authorized, display authentication prompt or 401 error
   if (! $authorized) {
      header('WWW-Authenticate: Basic Realm="Secret Stash"');
      header('HTTP/1.0 401 Unauthorized');
      print('You must provide the proper credentials!');
      exit;
   }

?>


<!-- password.txt
joe:60d99e58d66a5e0f4f89ec3ddd1d9a80

-->

我们只要在php教程.ini增加

disable_functions =phpinfo


php.ini里引入了一项功能disable_functions , 这个功能比较有用,可以用它禁止一些函数。比如在php.ini里加上disable_functions = passthru exec system popen 那么在执行这些函数的时候将会提示warning: system() has been disabled for security reasons,同时程序终止运行


更多详细

查找disable_functions然后用下面的替换
disable_functions =phpinfo,exec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source


 

验证码生成与应用实例
在写用户验证页面,如注册,登录的时候,为了加强用户登录的安全性,添加验证码验证。
验证码通过gd生成png图片,并把$randval随机数字赋给$_session['login_check_num'],在通过用户输入的$_post进行比较,来判断是否正确。达到需要实现的功能,需要修改php教程.ini文件,使php支持gd库。

<?php
//调用此页面,如果下面的式子成立,则生成验证码图片
if($_get["action"]=="verifycode")
{
    rand_create();
}
//验证码图片生成
function rand_create()
{
    //通知浏览器将要输出png图片
    header("content-type: image/png");
    //准备好随机数发生器种子 
    srand((double)microtime()*1000000);
    //准备图片的相关参数  
    $im = imagecreate(62,20);
    $black = imagecolorallocate($im, 0,0,0);  //rgb黑色标识符
    $white = imagecolorallocate($im, 255,255,255); //rgb白色标识符
    $gray = imagecolorallocate($im, 200,200,200); //rgb灰色标识符
    //开始作图    
    imagefill($im,0,0,$gray);
    while(($randval=rand()%100000)<10000);{
        $_session["login_check_num"] = $randval;
        //将四位整数验证码绘入图片 
        imagestring($im, 5, 10, 3, $randval, $black);
    }
    //加入干扰象素   
    for($i=0;$i<200;$i++){
        $randcolor = imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255));
        imagesetpixel($im, rand()%70 , rand()%30 , $randcolor);
    }
    //输出验证图片
    imagepng($im);
    //销毁图像标识符
    imagedestroy($im);
}
//检验验证码
function rand_check()
{
    if($_post["reg_rand"] == $_session["login_check_num"]){
        return true;
    }
    else{
        exit("验证码输入错误");
    }
}
?>

 

验证码,是一种区分用户是计算机和人的公共全自动程序。在captcha测试中,作为服务器的计算机会自动生成一个问题由用户来解答。这个问题可以由计算机生成并评判,但是必须只有人类才能解答。由于计算机无法解答captcha的问题,所以回答出问题的用户就可以被认为是人类。

*/
session_start();
$string = null;
$im = imagecreatetruecolor(60,25);  //创建真彩图60*25
$bg = imagecolorallocate($im,255,255,255);//白色背景
imagefill($im,0,0,$bg);填充白色
$x = 5;//
$y = 0;//文字坐标
for($i=0 ; $i&lt;4 ;$i++)
{
$char = mt_rand(0,9);
$string .=$char;
$y = mt_rand(0,10);
$ccolor = imagecolorallocate($im,mt_rand(0,230),mt_rand(0,230),mt_rand(0,230));
imagechar($im,6,$x,$y,$char,$ccolor);//填充文字
$x += mt_rand(10,15);
}
for($i=0 ;$i
{
$x1 = mt_rand(0,80);
$x2 = mt_rand(0,80);
$y1 = mt_rand(0,30);
$y2 = mt_rand(0,30);
$x2 = $x1 +mt_rand(1,5);
$y2 = $y1 +mt_rand(1,5);
$lc = imagecolorallocate($im,mt_rand(0,230),mt_rand(0,230),mt_rand(0,230));
imageline($im,$x1,$y1,$x2,$y2,$lc);//填充线条
}
$_session['code'] = md5($string);
header("content-type:image/jpeg");
imagepng($im);
imagedestroy($im);

更多详细内容请查看:http://www.111cn.net/phper/php-cy/33707.htm


当然我们也可以能过同时我们可以明知php ajax来实例验证功能。

注意:以下代码需要打开php教程的gd库,修改php.in文件的配置,把已经注释掉的行之前的分号取消即可:extension=php_gd2.dll。

$width = 165;
        $height = 120;
        $image = imagecreatetruecolor($width,$height);
        $bg_color = imagecolorallocate($image,255,255,255);
        $tm = imagecolorallocate($image,255,0,0);
        imagefilledrectangle($image,0,0,$width,$height,$bg_color);
        imagefill($image,0,0,$bg_color);
        /*
        //$text = random_text(5);
        $text = "ffff";
        $font = 8;
        $struft=iconv("gbk","utf-8",$text);
        $x = imagesx($image);
        $y = imagesy($image);
        $fg_color = imagecolorallocate($image,233,14,91);
        imagestring($image,$font,$x,$y,$struft,$fg_color);
        $_session['captcha'] = $text;
        */
header("content-type:image/png");
        imagepng($image);
        imagedestroy($image);

实例二

validate.php

采用了session识别,稍微改进了一下目前网络上流传的php验证码,加入杂点,数字颜色随机显示,控制4位数字显示;

<?
session_start();
//生成验证码图片
header("content-type: image/png");
$im = imagecreate(44,18);
$back = imagecolorallocate($im, 245,245,245);
imagefill($im,0,0,$back); //背景

srand((double)microtime()*1000000);
//生成4位数字
for($i=0;$i<4;$i++){
$font = imagecolorallocate($im, rand(100,255),rand(0,100),rand(100,255));
$authnum=rand(1,9);
$vcodes.=$authnum;
imagestring($im, 5, 2+$i*10, 1, $authnum, $font);
}

for($i=0;$i<100;$i++) //加入干扰象素
{
$randcolor = imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255));
imagesetpixel($im, rand()%70 , rand()%30 , $randcolor);
}
imagepng($im);
imagedestroy($im);

$_session['vcode'] = $vcodes;
?>

下面看完整实例

<?php

    @header("content-type:text/html; charset=utf-8");

    //打开session

    session_start();

?>

<html>

    <head>

       <meta http-equiv="content-type" content="text/html; charset=utf-8" />

       <title>php验证码示例</title>

    </head>

    <body>

       验证码:<br/>

       <iframe id="iimg" height="100" width=300" width=100% src="img.php" frameborder="0" ></iframe>

       <br/>

       <input type=button value="看不清,换一张" onclick="iimg.location.reload();">

       <br>

       <form action="validate.php" method="post">

           输入验证码:<input name="imgid" style="width:60">

           <input type="submit" value="确定">

       </form>

    </body>

</html>

php判断用户输入的验证码是否与系统生成的一致

<?php @header("content-type:text/html; charset=utf-8");

    //开启session

    session_start();

    //得到用户输入的验证码,并转换成大写

    $imgid_req = $_request['imgid'];

    $imgid_req = strtoupper($imgid_req);

    //验证该字符串是否注册了session变量

    if (session_is_registered($imgid_req)) {

       echo "<font color=blue >通过验证!</font>";

    } else {

       echo "<font color=red >验证错误!</font>";

    }

    //关闭session,以清除所有注册过的变量

    session_destroy();

?>

标签:[!--infotagslink--]

您可能感兴趣的文章: