[php]网页WAF

仅供学习参考,禁止用于其他非法途径

**Apache环境:**
创建.htaccess文件

    cd /tmp
    vi .htaccess
    php_value auto_prepend_file /tmp/waf.php

创建waf.php
    cd /var/www/html/
    vi waf.php
    
    <?php
    //流量抓取
    function get_http_raw() {
        $raw = '';
        $raw.= $_SERVER['REQUEST_METHOD'] . ' ' . $_SERVER['REQUEST_URI'] . ' ' . $_SERVER['SERVER_PROTOCOL'] . "\r\n";
        foreach ($_SERVER as $key => $value) {
            if (substr($key, 0, 5) === 'HTTP_') {
                $key = substr($key, 5);
                $key = str_replace('_', '-', $key);
                $raw.= $key . ': ' . $value . "\r\n";
            }
        }
        $raw.= "\r\n";
        $raw.= file_get_contents('php://input');
        return $raw;
    }
    
    function write_attack_log() {
        $data = date("Y/m/d H:i:s") . " --" . "\r\n" . get_http_raw() . "\r\n\r\n";
        $ffff = fopen('llog.txt', 'a'); //保存的文件名,可以指定一个位置
        fwrite($ffff, $data);
        fclose($ffff);
        }
    
    //参数过滤
    function filter($a){
            foreach($a as $key => $value)
           {
              $b=str_split($value);
              foreach($b as $str)
              {
                     if($str==""){continue;}
                      if(!preg_match('/\w|\.|\&|\//',$str))         //过滤的第一层,网页错误需要修改
                     {
                             die("error!!");
                             break;
                     }
              }
               if(preg_match('/flag|log/',$value)){die("hacker!!");} 
           }
    }
    
    //文件上传修改
    function filefilter($x)
    {
            foreach($x as $key => $a)
            {
                    $_FILES[$key]['content']=file_get_contents($_FILES[$key]['tmp_name']);
                    fwrite(fopen('/var/www/html/p.txt','a'),$_FILES[$key]['content']."\r\n\r\n");
                    file_put_contents($_FILES[$key]['tmp_name'],"<?php require_once('/var/www/html/file.php');?>");
            }
    }
    
    if(isset($_FILES))
    {
            filefilter($_FILES);
    }
    
    write_attack_log();
    
    if(isset($_REQUEST))
    {
           filter($_REQUEST);
    }
    
    ?>

**其他环境:**

    sed -ri "1 i\<?php include('/tmp/waf.php');?>" `grep -rl "<?php" .`
    sed -i 1d `grep -rl "<?php" .`