• Stars
    star
    127
  • Rank 281,133 (Top 6 %)
  • Language
    Python
  • Created almost 7 years ago
  • Updated almost 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

使用机器学习识别WebShell

使用机器学习识别WebShell

学习样本在shell 目录,目前样本较少,疏漏之处在所难免,测试结果如下:

pic/test.png

实现原理

实现原理是使用朴素贝叶斯进行文本分类.分类的样本包含正常的代码与WebShell 代码,为了方便后面的阅读,可以先阅读下面两个链接:

朴素贝叶斯原理 朴素贝叶斯分类文本

站在朴素贝叶斯算法来看,代码其实就是一串文本,我们要做的第一件事就是要对文本进行处理,变成算法可以处理的形式

    def code_word_to_vector(php_code) :
        filter_flag_list = ['@','[',']','(',')','{','}','\'','"',',',';','=','.','\t','\n','\r\n']
        keyword = ['$_GET','$_POST','$_REQUEST','$_COOKIE']

        for filter_flag_index in filter_flag_list :
            php_code = php_code.replace(filter_flag_index,' ')

        vector = php_code.split(' ')

        for index in range(len(vector)) :  #  filter $ variant
            if vector[index].startswith('$') and not vector[index] in keyword :
                vector[index] = ''
            elif vector[index] in keyword :
                vector[index] = '$'

        while vector.count('') :  #  filter empty item ..
            vector.remove('')

        return vector

预处理代码的算法做下面的工作:

1.filter_flag_list 只的是即将要过滤掉的字符,把它们替换成空格;keyword 的意思是,只保留这些关键的全局变量,那些无用的变量全部去除掉,否则变量名的文本在样本中和被检测的代码中也出现的话会影响概率计算结果
2.以空格字符作为分隔符,分割出所有的文本
3.过滤PHP 变量,只允许全局变量($_GET ,$_POST ,$_REQUEST ,$_COOKIE )的出现
4.从已经处理好的文本列表里面去除空内容(这里受到空格分隔符的影响,会有很多这样的空白内容)

代码处理后的效果

处理完成代码之后,下一步就是加载数据集,来看看代码

    def load_and_train_model(data_set_path = 'shell') :
        file_list = os.listdir(data_set_path)
        shell_sample = {}          #  classfy set ..

        for file_index in file_list :
            try :
                file_information = file_index.split('-')
                classfy_type = file_information[0] + '-' + file_information[1] + '-' + file_information[2]
                php_code_vector = shell_detect.code_word_to_vector(shell_detect.read_file(data_set_path + '\\' + file_index))

                if not shell_sample.has_key(classfy_type) :
                    shell_sample[classfy_type] = []

                shell_sample[classfy_type].append(php_code_vector)
            except :
                print 'Error Shell Sample File !' , file_index
                print 'Sample File Name Format :'
                print ' normal-%shell_language%-%shell_type%-%shell_index%.php or '
                print ' shell-%shell_language%-%shell_type%-%shell_index%.php '

        return shell_sample
        

加载数据集的代码主要做下面的工作:

1.根据指定的样本目录来读取训练的样本数据
2.样本数据文件的命名中包含了正常的代码和WebShell 的类型,命名规则为:样本类型-语言-代码类型-序号.拓展名,命名为normal-php-code-0.php 的文件的意思是这个样本文件是正常的PHP 代码文件,最后的0 代表着样本文件序号;命名为shell-php-eval-0.php 的意思是PHP 的eval() 函数的WebShell 样本文件
3.把这些样本文件读取出来预处理一下再放到样本集中

样本数据加载完成之后,接下来就是要对我们需要检测的文件做一个分类,思路是判断检测文件在各个样本中出现的概率,找到最大概率的那个就是对应的代码类别

    def try_classify(self,php_code) :
        php_code_vector = shell_detect.code_word_to_vector(php_code)
        alpha = 1
        p_list = {}

        for key_index in self.shell_sample.keys() :
            max_p_value = 0

            for shell_sample_index in self.shell_sample[key_index] :
                found_vector_in_shell_sample_count = 0

                for php_code_vector_index in php_code_vector :
                    if php_code_vector_index in shell_sample_index :
                        found_vector_in_shell_sample_count += shell_sample_index.count(php_code_vector_index)

                p_value = (found_vector_in_shell_sample_count + alpha) / float(len(shell_sample_index) * 2 + alpha)
                
                if p_value >= max_p_value :
                    max_p_value = p_value

            p_list[key_index] = max_p_value
            
        max_p_value = 0
        max_p_type_name = ''

        for p_type_name_index in p_list.keys() :
            p_value = p_list[p_type_name_index]

            if p_value >= max_p_value :
                max_p_value = p_value
                max_p_type_name = p_type_name_index
                
    return max_p_type_name
  

分类函数的逻辑如下:

1.对要检测的代码进行预处理
2.遍历所有的样本文件,使用朴素贝叶斯算法对所有的样本进行概率计算
3.找到概率最大的那个样本的类别
4.返回最后分类的结果

代码处理与分类算法已经介绍完,样本也是重要的一部分,接下来我们来看一下样本的构造

//  shell-php-eval-0.php

<?php

    eval($_GET['test']);

?>


//  shell-php-eval-4.php

<?php eval(str_rot13('riny($_CBFG[cntr]);')); ?>


//  shell-php-create_function-3.php

<?php

    $function = create_function('$code','eval($_GET["asd"]);');

    $function();

?>


//  shell-php-assert-1.php

<?php array_map("ass\x65rt",(array)$_REQUEST['expdoor']);?>


//  shell-php-preg_replace-1.php

<?php

    $page = $_POST['page'];
    preg_replace("/[errorpage]/e",$page,"saft");

?>


//  normal-php-code-0.php

<?php

    echo '123';

?>


//  normal-php-code-2.php

<?php

    $sum = 0;

    for ($index = 1;$index < 10 ;$index++)
        $sum += $index;

?>

样本的构造基本上是使用已知的WebShell 并且做一个归类.正常的代码这里只使用一些简单的PHP 语句,如果没有正常的代码,会导致概率的判断全部都会归类到WebShell 代码的范畴.

测试样本

        print 'Shell Type :' , model.try_classify('<?php eval($_GET["exp"]); ?>')
        print 'Shell Type :' , model.try_classify('<?php assert($_GET["exp"]); ?>')
        print 'Shell Type :' , model.try_classify('<?php system($_GET["exp"]); ?>')
        print 'Shell Type :' , model.try_classify('<?php systen("ifconfig"); ?>')
        print 'Shell Type :' , model.try_classify('<?php echo "123"; ?>')
        print 'Shell Type :' , model.try_classify('<?php $b=1+1; ?>')
        print 'Shell Type :' , model.try_classify('<?php phpinfo(); ?>')
        print 'Shell Type :' , model.try_classify('<?php $a=create_function(\'\',\'ev\',\'al\'.\'($\'.\'_GET["e"]);\'); $a(); ?>')
        print 'Shell Type :' , model.try_classify('<?php include($_COOKIE[\'s\']); ?>')
        print 'Shell Type :' , model.try_classify('<?php require_once($_POST[\'s\']); ?>')

测试结果

More Repositories

1

Source-and-Fuzzing

一些阅读源码和Fuzzing 的经验,涵盖黑盒与白盒测试..
C++
970
star
2

Machine-Learning-Note

机器学习笔记
Python
426
star
3

Fuzzing-ImageMagick

OpenSource My ImageMagick Fuzzer ..
Mask
295
star
4

PHP-WebShell-Bypass-WAF

分享PHP WebShell 绕过WAF 的一些经验 Share some experience about PHP WebShell bypass WAF and Anti-AV
PHP
282
star
5

network_backdoor_scanner

This is a backdoor about discover network device ,and it can hidden reverse connecting the hacker's server with encrypt commuication 后渗透后门程序,适合在已经攻陷的内网中做下一步的网络信息扫描..
C++
182
star
6

vuln_javascript

模拟一个存在漏洞的JavaScript 运行环境,用来学习浏览器漏洞原理和练习如何编写Shellcode (a JavaScript Execute Envirment which study browser vuln and how to write Shellcode ) ..
C++
180
star
7

PHP_Source_Audit_Tools

PHP 白盒分析工具,结合AST 和数据流跟踪分析代码,达到自动化白盒审计功能
Python
146
star
8

Hacker_Document

收集一些以前看过对于入门和进阶很有用的攻击原理文档..
142
star
9

browser_vuln_check

browser_vuln_check ,利用已知的浏览器漏洞PoC 来快速检测Webview 和浏览器环境是否存在安全漏洞,只需要访问run.html 即可获取所有扫描结果,适用场景包含:APP 发布之前的内部安全测试,第三方Webview 漏洞检测等(browser_vuln_check framework using some known browser vulnerabilities PoC to quick automate aduit WebView or Browser security ,apply to application security before issue and detecting third-part WebView security)..
Python
117
star
10

SISE_Traning_CTF_RE

SNST Traning RE Project .华软网络安全小组逆向工程训练营,尝试以CTF 的形式来使大家可以动手训练快速提升自己的逆向工程水平.CTF 的训练程序又浅到深,没有使用太复杂的算法,在逆向的过程中遇到的难关都是在分析病毒和破解中遇到的实际情况,注重于实用.训练营还包含有源代码文件,训练程序和思路.希望可以帮助小伙伴们入门逆向工程这个神奇的世界..
C++
110
star
11

CVE-2017-7269-Echo-PoC

CVE-2017-7269 回显PoC ,用于远程漏洞检测..
Python
88
star
12

Think-in-Security

从二进制到WEB ,分享我在安全路上的思考与点滴,后面会不断地更新..
76
star
13

Angr-CTF-Learn-Note

The learn note of Angr-CTF ..
49
star
14

qemu-fuzzer

Qemu Fuzzer.针对Qemu模拟设备的模糊测试工具,主要思路是Host生成种子Data,然后传递给Guest中转程序,由中转程序访问MMIO,以达到和模拟设备的交互,不同于qtest自带的fuzzer.
C
43
star
15

XSS-hunter

XSS hunter 收集Webview 页面上存在的反射,储存型XSS ,方便应急APP 和前端页面在发布时遇到XSS 安全问题..
PHP
42
star
16

etherum_rpc_steal

The Etherum RPC Steal Toolset and honeypot .以太坊"偷渡"漏洞利用和蜜罐工具集.
Python
40
star
17

Kite

Browser Fuzzing Framework ,浏览器Fuzzing 框架..
HTML
31
star
18

klee-fl

KLEE-fl : Compile Project to Bitcode and Try Fuzzing with KLEE .
C++
27
star
19

my-blog

我的技术博客,记录成长
C++
26
star
20

Aurora_CAPTCHA

极光验证码,为反爬虫而生
Python
25
star
21

My_PoC

Collect some PoC that I writted .记录自己写过的PoC ..
Python
23
star
22

KiMi-VulnBot_Framework

KiMi 漏洞感知机器人扫描框架 @KiMi-VulnBot @KiMiThreatPerception
Python
22
star
23

cve_diff_checker

快速对自己项目中引入的第三方开源库进行1day patch检索,patch数据每天晚上11点更新
Roff
20
star
24

FreeWebpilotInChatGPT35

非付费的chatgpt3.5 用户也可以使用付费的chatgpt4 Webpilot 插件. Free ChatGPT 3.5 users can also use the paid ChatGPT 4 Webpilot plugin.
JavaScript
19
star
25

dns_hijack_server

A dns server that use to hijack other dns request in a wifi network for redirect to your custem http server ..
C++
16
star
26

browser_xss_auditor_fuzzing

浏览器XSS 过滤器Fuzzing 框架 (browser xss aduit fuzzing framework )..
HTML
15
star
27

blue_fariy

github 项目代码加密,在不创建github 私有项目的前提下使用github 更新代码又不希望自己的核心代码公开,bule_fariy.py 可以在git push 之前自动加密所有代码(Encrypt your Github repository code before git push )
Python
15
star
28

Python_CookieLib_0day

Using This 0-day to Anti-Python-Spider ..
PHP
14
star
29

Supplicant_Exploit_Kit

Sise supplicant exploit kit -- 华软蝴蝶漏洞利用工具包..
C++
13
star
30

Ethereum_Similar_Contract_Classify

Python
12
star
31

blockchain_story

酒剑论江湖,区块有故事..
12
star
32

BitLeague

聚合交易平台BitLeague
Python
11
star
33

pseudo-protocals-digger

system pseudo protocals digger for windows -- Windows 系统下的伪协议查看工具
Python
11
star
34

cross_domain_postmessage_vuln_dig

WEB 跨域postMessage() 漏洞挖掘工具,基本原理:使用AJAX 获取页面代码,结合iframe 和data 协议构造测试环境,然后在iframe 下的window.onmessage 中插入hook 监控onmessage 的参数,最后通过能否被原来的onmessage 逻辑引用参数中的data 属性来判断是否可以跨域传递数据..
HTML
11
star
35

Big_Project

我就笑笑不说话,哈哈哈哈..
7
star
36

Distributed-Task-Queue

Dynamic Expand Distributed Task Queue (分布式任务队列框架)
Python
7
star
37

ethereum_solidity_symbol_execute

Ethereum Solidity Symblo Execute Demo -- Check Vuln and Auto Build Payload ..
Python
6
star
38

supplicant_getadaptersinfo_dll

Bypass for supplicant server NAT validate .蝴蝶NAT 认证绕过DLL ..
C++
5
star
39

DCpp_Exploit_Kit

Sise DC++ exploit kit -- 华软DC++ 漏洞利用工具包..
C++
5
star
40

file_crypter

A Simple Malware Example About File Crypter Like CTB-locker ;文件劫持病毒实例代码,就像CTB-Locker 一样加劫持用户交钱恢复被加密的文件..
C
4
star
41

Vending_Machine

2012 的开发代表作品,自动售货机,那年开始从底层出发到硬件设计,这些都是乐趣所在,做一些很酷的东西一直都是追求的目标,从自动售货机的开发过程中开始逐渐萌生出Small System 的雏形,但是由于很多种原因没有办法继续开发下去,最后完成自动售货机是在2013 年的冬天也就是高三,那四天的日子也是我在科技协会一直记住的美好时光,感谢你们的支持,虽然你们可能看不到我在这里所写的东西,如果没有你们设计箱子做电路也就没有后面的故事,谢谢你们..
C
4
star
42

PyDbg_Document

This document is collect interface's using in PyDbg.py and conver to markdown for anybody convenient reading ..
Python
3
star
43

quick_scan_virus

a security tool for quick scan some virus and APT
Python
3
star
44

JPEG-Locker

2013 的开发代表作品,JPEG 保护者.Protect your JPEG picture and more important information .WARNING ! If you want to use my code ,please update the module - PictureLock.bas .I tested patch a key jmp and bypass the valid program could using arbitrarily string to decrypt protecting file .So I hope you can rewrite this module and all encrypt input file with password and XOR .
Visual Basic
2
star
45

USB-firewall

2011 的开发代表作品,2010 年吃了很多苦头才有点入门Windows 系统编程,U 盘防火墙是看了很多VB VC 病毒编写的代码和原理才写的,毕竟10 年一半的时间在学习编程一半时间在学习黑客技术,虽然一次都没有黑成功,但是积累了很多在以后都挺实用的理论.U 盘防火墙可以在一定程度上防止U 盘上的病毒入侵到主机..
Visual Basic
2
star
46

Lap-Game

2010 的开发代表作品,这是刚开始学写程序的第一年,是一个拥有智能AI 的圈叉游戏,AI 不仅可以防守,而且还可以进攻,当年写这段代码还没放到电脑上运行的时候是写在笔记本上面一步步在脑里面运行的,曾经现场运行这段代码来和真人对抗,诚然,现在早已忘记开发的乐趣,那个夕阳西下的时候,我曾经对未来拥有多大的憧憬,但是最后得到了经验,得到了技术,却早已失去掉曾经的乐趣,我想,最悲哀的故事也莫过于此吧,这就是在大学为什么不打算走开发而是做逆向工程的原因,人,最痛苦的事情就是挑起他最不愿意的担子去做他最喜爱的事情..
Visual Basic
2
star
47

python_compiler

Python 指令编译工具(Python Instruction Compiler )..
Python
1
star