{"id":13778956,"url":"https://github.com/lcatro/webshell-detect-by-machine-learning","last_synced_at":"2025-05-11T12:32:19.533Z","repository":{"id":94690776,"uuid":"108221657","full_name":"lcatro/WebShell-Detect-By-Machine-Learning","owner":"lcatro","description":"使用机器学习识别WebShell","archived":false,"fork":false,"pushed_at":"2017-10-26T09:18:06.000Z","size":104,"stargazers_count":126,"open_issues_count":1,"forks_count":31,"subscribers_count":9,"default_branch":"master","last_synced_at":"2024-11-17T14:41:07.520Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/lcatro.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-10-25T04:59:46.000Z","updated_at":"2024-10-14T08:22:09.000Z","dependencies_parsed_at":"2023-03-14T00:15:36.564Z","dependency_job_id":null,"html_url":"https://github.com/lcatro/WebShell-Detect-By-Machine-Learning","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lcatro%2FWebShell-Detect-By-Machine-Learning","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lcatro%2FWebShell-Detect-By-Machine-Learning/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lcatro%2FWebShell-Detect-By-Machine-Learning/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lcatro%2FWebShell-Detect-By-Machine-Learning/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/lcatro","download_url":"https://codeload.github.com/lcatro/WebShell-Detect-By-Machine-Learning/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253567021,"owners_count":21928767,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-03T18:00:59.471Z","updated_at":"2025-05-11T12:32:19.232Z","avatar_url":"https://github.com/lcatro.png","language":"Python","funding_links":[],"categories":["\u003ca id=\"39e5bd43766abbdbc518390d86b3a0a5\"\u003e\u003c/a\u003eWebshell检测"],"sub_categories":[],"readme":"\n## 使用机器学习识别WebShell\n\n  学习样本在**shell** 目录,目前样本较少,疏漏之处在所难免,测试结果如下:\n  \n  ![pic/test.png](pic/test.png)\n\n## 实现原理\n\n  实现原理是使用朴素贝叶斯进行文本分类.分类的样本包含正常的代码与WebShell 代码,为了方便后面的阅读,可以先阅读下面两个链接:\n  \n  [朴素贝叶斯原理](http://blog.csdn.net/u012162613/article/details/48323777)\n  [朴素贝叶斯分类文本](http://www.cnblogs.com/XBWer/archive/2014/07/13/3840736.html)\n  \n  站在朴素贝叶斯算法来看,代码其实就是一串文本,我们要做的第一件事就是要对文本进行处理,变成算法可以处理的形式\n  \n```python\n\n    def code_word_to_vector(php_code) :\n        filter_flag_list = ['@','[',']','(',')','{','}','\\'','\"',',',';','=','.','\\t','\\n','\\r\\n']\n        keyword = ['$_GET','$_POST','$_REQUEST','$_COOKIE']\n\n        for filter_flag_index in filter_flag_list :\n            php_code = php_code.replace(filter_flag_index,' ')\n\n        vector = php_code.split(' ')\n\n        for index in range(len(vector)) :  #  filter $ variant\n            if vector[index].startswith('$') and not vector[index] in keyword :\n                vector[index] = ''\n            elif vector[index] in keyword :\n                vector[index] = '$'\n\n        while vector.count('') :  #  filter empty item ..\n            vector.remove('')\n\n        return vector\n\n```\n  \n  预处理代码的算法做下面的工作:\n  \n  1.`filter_flag_list` 只的是即将要过滤掉的字符,把它们替换成空格;`keyword` 的意思是,只保留这些关键的全局变量,那些无用的变量全部去除掉,否则变量名的文本在样本中和被检测的代码中也出现的话会影响概率计算结果\u003cbr/\u003e\n  2.以空格字符作为分隔符,分割出所有的文本\u003cbr/\u003e\n  3.过滤PHP 变量,只允许全局变量($_GET ,$_POST ,$_REQUEST ,$_COOKIE )的出现\u003cbr/\u003e\n  4.从已经处理好的文本列表里面去除空内容(这里受到空格分隔符的影响,会有很多这样的空白内容)\n  \n  代码处理后的效果\n  \n  ![](pic/vector.png)\n  \n  处理完成代码之后,下一步就是加载数据集,来看看代码\n  \n```python\n\n    def load_and_train_model(data_set_path = 'shell') :\n        file_list = os.listdir(data_set_path)\n        shell_sample = {}          #  classfy set ..\n\n        for file_index in file_list :\n            try :\n                file_information = file_index.split('-')\n                classfy_type = file_information[0] + '-' + file_information[1] + '-' + file_information[2]\n                php_code_vector = shell_detect.code_word_to_vector(shell_detect.read_file(data_set_path + '\\\\' + file_index))\n\n                if not shell_sample.has_key(classfy_type) :\n                    shell_sample[classfy_type] = []\n\n                shell_sample[classfy_type].append(php_code_vector)\n            except :\n                print 'Error Shell Sample File !' , file_index\n                print 'Sample File Name Format :'\n                print ' normal-%shell_language%-%shell_type%-%shell_index%.php or '\n                print ' shell-%shell_language%-%shell_type%-%shell_index%.php '\n\n        return shell_sample\n        \n```\n  \n  加载数据集的代码主要做下面的工作:\n  \n  1.根据指定的样本目录来读取训练的样本数据\u003cbr/\u003e\n  2.样本数据文件的命名中包含了正常的代码和WebShell 的类型,命名规则为:**样本类型-语言-代码类型-序号.拓展名**,命名为normal-php-code-0.php 的文件的意思是这个样本文件是正常的PHP 代码文件,最后的0 代表着样本文件序号;命名为shell-php-eval-0.php 的意思是PHP 的eval() 函数的WebShell 样本文件\u003cbr/\u003e\n  3.把这些样本文件读取出来预处理一下再放到样本集中\n  \n  样本数据加载完成之后,接下来就是要对我们需要检测的文件做一个分类,思路是判断检测文件在各个样本中出现的概率,找到最大概率的那个就是对应的代码类别\n  \n```python\n\n    def try_classify(self,php_code) :\n        php_code_vector = shell_detect.code_word_to_vector(php_code)\n        alpha = 1\n        p_list = {}\n\n        for key_index in self.shell_sample.keys() :\n            max_p_value = 0\n\n            for shell_sample_index in self.shell_sample[key_index] :\n                found_vector_in_shell_sample_count = 0\n\n                for php_code_vector_index in php_code_vector :\n                    if php_code_vector_index in shell_sample_index :\n                        found_vector_in_shell_sample_count += shell_sample_index.count(php_code_vector_index)\n\n                p_value = (found_vector_in_shell_sample_count + alpha) / float(len(shell_sample_index) * 2 + alpha)\n                \n                if p_value \u003e= max_p_value :\n                    max_p_value = p_value\n\n            p_list[key_index] = max_p_value\n            \n        max_p_value = 0\n        max_p_type_name = ''\n\n        for p_type_name_index in p_list.keys() :\n            p_value = p_list[p_type_name_index]\n\n            if p_value \u003e= max_p_value :\n                max_p_value = p_value\n                max_p_type_name = p_type_name_index\n                \n    return max_p_type_name\n  \n```\n  \n  分类函数的逻辑如下:\n  \n  1.对要检测的代码进行预处理\u003cbr/\u003e\n  2.遍历所有的样本文件,使用朴素贝叶斯算法对所有的样本进行概率计算\u003cbr/\u003e\n  3.找到概率最大的那个样本的类别\u003cbr/\u003e\n  4.返回最后分类的结果\n  \n  代码处理与分类算法已经介绍完,样本也是重要的一部分,接下来我们来看一下样本的构造\n  \n```php\n\n//  shell-php-eval-0.php\n\n\u003c?php\n\n    eval($_GET['test']);\n\n?\u003e\n\n\n//  shell-php-eval-4.php\n\n\u003c?php eval(str_rot13('riny($_CBFG[cntr]);')); ?\u003e\n\n\n//  shell-php-create_function-3.php\n\n\u003c?php\n\n    $function = create_function('$code','eval($_GET[\"asd\"]);');\n\n    $function();\n\n?\u003e\n\n\n//  shell-php-assert-1.php\n\n\u003c?php array_map(\"ass\\x65rt\",(array)$_REQUEST['expdoor']);?\u003e\n\n\n//  shell-php-preg_replace-1.php\n\n\u003c?php\n\n    $page = $_POST['page'];\n    preg_replace(\"/[errorpage]/e\",$page,\"saft\");\n\n?\u003e\n\n\n//  normal-php-code-0.php\n\n\u003c?php\n\n    echo '123';\n\n?\u003e\n\n\n//  normal-php-code-2.php\n\n\u003c?php\n\n    $sum = 0;\n\n    for ($index = 1;$index \u003c 10 ;$index++)\n        $sum += $index;\n\n?\u003e\n\n```\n  \n  样本的构造基本上是使用已知的WebShell 并且做一个归类.正常的代码这里只使用一些简单的PHP 语句,如果没有正常的代码,会导致概率的判断全部都会归类到WebShell 代码的范畴.\n  \n  测试样本\n  \n```python\n\n        print 'Shell Type :' , model.try_classify('\u003c?php eval($_GET[\"exp\"]); ?\u003e')\n        print 'Shell Type :' , model.try_classify('\u003c?php assert($_GET[\"exp\"]); ?\u003e')\n        print 'Shell Type :' , model.try_classify('\u003c?php system($_GET[\"exp\"]); ?\u003e')\n        print 'Shell Type :' , model.try_classify('\u003c?php systen(\"ifconfig\"); ?\u003e')\n        print 'Shell Type :' , model.try_classify('\u003c?php echo \"123\"; ?\u003e')\n        print 'Shell Type :' , model.try_classify('\u003c?php $b=1+1; ?\u003e')\n        print 'Shell Type :' , model.try_classify('\u003c?php phpinfo(); ?\u003e')\n        print 'Shell Type :' , model.try_classify('\u003c?php $a=create_function(\\'\\',\\'ev\\',\\'al\\'.\\'($\\'.\\'_GET[\"e\"]);\\'); $a(); ?\u003e')\n        print 'Shell Type :' , model.try_classify('\u003c?php include($_COOKIE[\\'s\\']); ?\u003e')\n        print 'Shell Type :' , model.try_classify('\u003c?php require_once($_POST[\\'s\\']); ?\u003e')\n\n```\n  \n  测试结果\n  \n  ![](pic/sample_test.png)\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flcatro%2Fwebshell-detect-by-machine-learning","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flcatro%2Fwebshell-detect-by-machine-learning","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flcatro%2Fwebshell-detect-by-machine-learning/lists"}