首页
社区
课程
招聘
[原创]linux主机安全审计追溯分析脚本
发表于: 2016-10-27 13:51 5480

[原创]linux主机安全审计追溯分析脚本

2016-10-27 13:51
5480

linux主机安全审计分析脚本
1、非工作时间段是否有登录行为
2、当日是否有新建/登录失败纪录
3、指定监控目录是否有webshell文件
4、查看是否有新建非法用户
5、查看是否有外联异常端口
6、检测access日志,分析当天攻击行为

#!/usr/bin/python
# -*- coding: utf-8 -*-

import os
import sys
import re

TRUST_USER = ['root','piaox']
TRUST_IP =['10.0.211.71']
FILE_PATH=['/var/www/html','/tmp','/var/tmp','/home']
FILE_LIST =[]
ACCESS_LOG = '/var/log/httpd/access_log'
php_Features_list = [
      '(\$_(?:GET|POST|REQUEST)\[.*?](\s|\n)*\((\s|\n)*\$_(?:GET|POST|REQUEST)\[.*?\](\s|\n)*\))',
      '(?:base64_decode)\([\'"][\w\+/=]{200,}[\'"]\)',
      'function\_exists\s*\(\s*[\'"](popen|exec|proc\_open|system|passthru)+[\'"]\s*\)',
      '@?(eval\_?r?|assert|include|require|include\_once|require\_once|array\_map|array\_walk)+\s*\(\s*\$\_(GET|POST|REQUEST|COOKIE|SERVER|SESSION)+\[?(.*)\]?\s*\)',
      'eval\s*\(\s*\(\s*\$\$(\w+)',
      '(\$[\w_]{0,15}(\s|\n)*\((\s|\n)*\$_(?:POST|GET|REQUEST)\[.*?\](\s|\n)*\))',
      '(ReDuh|silic)',
      '(?:call_user_func)(\s|\n)*\(.{0,15}\$_(?:GET|POST|REQUEST)',
      '(?:wscript)\.(?:shell)',
      '(?:cmd)\.(?:exe)',
    '(?:shell)\.(?:application)',
    '(?:documents)\s+(?:and)\s+(?:settings)',
      '(?:system32)',
      '(?:serv\-u)',
      '(?:phpspy)',
      '(?:webshell)',
    '(?:Program)\s+(?:Files)',
    '(?:include|require)(?:_once)?\s*["\']?\(?\s*\$?\w+["\']?\)?\s*\;?',
    'ec38fe2a8497e0a8d6d349b3533038cb|88f078ec861a3e4baeb858e1b4308ef0|7Zt/TBNnGMfflrqBFnaes|\\x50\\x4b\\x05\\x06\\x00\\x00\\x00\\x00|9c3a9720372fdfac053882f578e65846|silic1234',
    '((udp|tcp)\://(.*)\;)+',
    'preg\_replace\s*\((.*)/e(.*)\,\s*\$\_\[?(.*)\]?\,(.*)\)',
    'preg\_replace\s*\((.*)\(base64\_decode\(\$',
    '.*?\$\_\w+.*?@?preg_replace\(("|\').*?/e("|\'),.*?,.*?\)',
    '(eval|assert|include|require|include\_once|require\_once)+\s*\(\s*(base64\_decode|str\_rot13|gz(\w+)|file\_(\w+)\_contents|(.*)php\://input)+',
    '(include|require|include\_once|require\_once)+\s*\(\s*[\'"](\w+)\.(jpg|gif|ico|bmp|png|txt|zip|rar|htm|css|js)+[\'"]\s*\)',
    '\$\_(\w+)\s*=?\s*(eval|assert|include|require|include\_once|require\_once)+\s*\(\s*\$(\w+)\s*\)',
    '\(\s*\$\_FILES\[(.*)\]\[(.*)\]\s*\,\s*\$\_(GET|POST|REQUEST|FILES)+\[(.*)\]\[(.*)\]\s*\)',
    '(fopen|fwrite|fputs|file\_put\_contents)+\s*\((.*)\$\_(GET|POST|REQUEST|COOKIE|SERVER)+\[(.*)\](.*)\)',
    '(fopen|fwrite|fputs|file\_put\_contents)+\s*\(\$\_(GET|POST|REQUEST|COOKIE|SERVER)+\[(.*)\](.*)\)',
    'echo\s*curl\_exec\s*\(\s*\$(\w+)\s*\)',
    'new com\s*\(\s*[\'"]shell(.*)[\'"]\s*\)',
    '\$(.*)\s*\((.*)\/e(.*)\,\s*\$\_(.*)\,(.*)\)',
    '\$\_\=(.*)\$\_',
    '\$\_(GET|POST|REQUEST|COOKIE|SERVER)+\[(.*)\]\(\s*\$(.*)\)',
    '\$(\w+)\s*\(\s*\$\_(GET|POST|REQUEST|COOKIE|SERVER)+\[(.*)\]\s*\)',
    '\$(\w+)\s*\(\s*\$\{(.*)\}',
    '\$(\w+)\s*\(\s*chr\(\d+\)',
    '\$\w*\s*\=\s*\$\_(GET|POST|REQUEST|COOKIE|SERVER|SESSION)\[.*?\]\;\s*include\s+\(\s*\$(.*?)\s*\)\;',
    '\$\w+\s*\=\s*\$\_\w+\[.*?\]\;\s*@eval\(.*?\)',
    '\$\w+\s*\=\s*base64_decode\(\$\_\w+\[(.*?)\]\);\s*@eval\(.*?\)',
    '\$\_\w+\[.*?\]\s*\(\s*\$\_\w+\[.*?\]\s*\)\;',
    '\(\$\_\=@\$\_\w+\[.*?\]\s*\)\.@\$\_\(\$\_\w+\[.*?\]\s*\)',
    '\$\_\w+\[.*?\]\s*\(\s*\$\_\w+\[.*?\]\s*,\$\_\w+\[.*?\]\)',
    '\$\{\'\_\'.\$\_}\[\'\_\'\]\(\$\{\'\_\'.\$\_\}\[\'\_\_\'\]\)\;',
    '\_\_angel\_1111111111\_eof\_\_',
    'xx.php\?pwd=e',
    '687474703a2f2f377368656c6c2e676f6f676c65636f64652e636f6d2f73766e2f6d616b652e6a7067',
    'Changed by pnkoo.cn|Jakub Vrana|blackbap.org|Code By isosky|16jTwyAtIHBocCZNeVNRTMr9vt2/4rG4t925pL7fIC0g']

asp_Features_list = [
    '(?:eval|execute)(\s|\n)*(?:request)(\s|\n)*\((\s|\n)*(.*?)(\s|\n)*\)',
    '(?:eval)(\s|\n)*\((\s|\n)*(?:Request)(\s|\n)*\.(\s|\n)*(?:Item)(\s|\n)*\[(\s|\n)*(.*?)(\s|\n)*\]',
    '(?:ExecuteStatement)\(.*?request',
    'FromBase64String\("UmVxdWVzdC5JdGVtWyJ6Il0="\)',
    'tseuqer\s*lave.*',
    'Request.form(.*)eval(.*)',
    '<SCRIPT\s*RUNAT=SERVER\s*LANGUAGE=JAVASCRIPT>(.*)eval',
    'reDuh(.*)',
    'PublicKeyToken\=B03F5F7F11D50A3A',
    '20132165414621325641311254123112512',
    '#@~\^oHMBAA==@#@&@#@&"\+kwW',
    '(Client/Login\.xml\?Command=Login&Sync=1227081437828)|(因为serv-u的userid变化我搞不懂)',
    'aspmuma|(免杀去后门版\s*by\s*UnKnown)',
    '芝麻开门|F4ck|1c1f81a8b0a630f530f52fa9aa9dda1b|法客论坛|F4ckTeam',
    'silicname|silicpass|命令行执行',
    'server.mappath\("go.asp"\)',
    'MSSQL语句执行工具',
    'gif89a(\s|\n)*<%@?',
    'UJ@!z\(G9X@\*@!z4Y:\^@\*ryglpAA==\^#~@',
    'clsid:72C24DD5-D70A-438B-8A42-98424B88AFB8',
    'WebSniff(.*?)Powered\s*by',
    '11\.asp',
    'mssql导库|闪电小子|\_tysan|MYSQL Manager',
    '#@~\^bGsBAA==@#@&AC13`DV{J@!8D@\*@!8D@\*@!\^n']

jsp_Features_list = [
  'reDuh',
  '没有权限执行该操作',
  '(chopper|QQ\(cs,z1,z2,sb\)|caicaihk|Alanwalker|(by\s*n1nty)|(Code\s*By\s*Ninty)|JspSpyPwd|JspSpy|6625108|(charles\s*QQ\s*77707777))',
  '((21,25,80,110,1433,1723,3306,3389,4899,5631,43958,65500)|(192.168.230.1\s*4444))',
  '1decc1ce886d1b2f9f91ecb39967832d05f8e8b8',
  'JFolder\.jsp|Steven\s*Cee|JFileMan\.jsp|hack520\s*by|mailto\:hack520@77169\.org|by\s*Bagheera|luoluonet|Recoding\s*by\s*Juliet|lovehacker|webshell\.jsp|Hacker|jsp\s*File\s*Browser|jshell|ceshi2009']

other_Features_list = ['System32\\cmd\.exe|cmd|CFM\s*shell',
  '俺的门门',
  'Gamma Web Shell']

attack__Features_list = {"\.\./":"目录穿越攻击",
    "select.+(from|limit)":"SQL注入攻击",
    "(?:(union(.*?)select))":"SQL注入攻击",
        "having|rongjitest":"SQL注入攻击",
    "sleep\((\s*)(\d*)(\s*)\)":"SQL注入攻击",
    "benchmark\((.*)\,(.*)\)":"SQL注入攻击",
        "base64_decode\(":"SQL注入攻击",
    "(?:from\W+information_schema\W)":"SQL注入攻击",
    "(?:(?:current_)user|database|schema|connection_id)\s*\(":"SQL注入攻击",
    "(?:etc\/\W*passwd)":"敏感文件操作",
    "into(\s+)+(?:dump|out)file\s*":"SQL注入攻击",
    "group\s+by.+\(":"SQL注入攻击",
    "xwork.MethodAccessor":"命令注入攻击",
    "xwork\.MethodAccessor":"命令注入攻击",
    "(gopher|doc|php|glob|file|phar|zlib|ftp|ldap|dict|ogg|data)\:\/":"敏感文件操作",
    "\<(iframe|script|body|img|layer|div|meta|style|base|object|input)":"XSS跨站脚本",
        "(alert|confirm|prompt)":"XSS跨站脚本",
    "(onmouseover|onerror|onload)\=":"XSS跨站脚本",
    "java\.lang":"命令注入攻击",
    "\.(svn|htaccess|bash_history)":"敏感文件访问",
    "\.(bak|inc|old|mdb|sql|backup|java|class)$":"敏感文件访问",
    "(vhost|bbs|host|wwwroot|www|site|root|hytop|flashfxp).*\.rar":"敏感文件访问",
    "(phpmyadmin|jmx-console|jmxinvokerservlet)":"管理控制台探测行为",
    "/(attachments|upimg|images|css|uploadfiles|html|uploads|templets|static|template|data|inc|forumdata|upload|includes|cache|avatar)/(\\w+).(php|jsp)":"敏感文件访问",
    "(HTTrack|harvest|audit|dirbuster|pangolin|nmap|sqln|-scan|hydra|Parser|libwww|BBBike|sqlmap|w3af|owasp|Nikto|fimap|havij|PycURL|zmeu|BabyKrokodil|netsparker|httperf|bench| SF/)":"Web扫描器扫描"
    }

def Un_worktime_login(localday):
    if os.popen("last |grep -v 'reboot' |grep " + "'" + localday.strip() + "'" + "|awk '($7>=\"12:00\" && $7<=\"14:00\") || ($7>=\"00:00\" && $7<=\"06:00\")'").readlines():
        print '[+] Un_worktime_login ------------------------------------ [ DONE ]'
        for bb in os.popen("last |grep -v 'reboot' |grep " + "'" + localday.strip() + "'" + "|awk '($7>=\"12:00\" && $7<=\"14:00\") || ($7>=\"00:00\" && $7<=\"06:00\")'").readlines():
            print bb.strip()
        return True
    else:
        return False

def Faild_user(localday):
  print '\n[+] Faild_user ------------------------------------ [ DONE ]'
  os.system("egrep '(new user: name=)|(Failed password for)' /var/log/secure*|grep " + "'" + localday + "'")

def Un_trust_user():
    all_user = os.popen("grep '/bin/bash' /etc/passwd | awk -F ':' '{print $1}'").readlines()
    print '\n[+] Un_trust_user ------------------------------------ [ DONE ]'
    for l in all_user:
        if l.strip() not in TRUST_USER:
            os.system("grep "+l.strip()+" /etc/passwd")

def Dubious_netstat():
    print '\n[+] Dubious_netstat ------------------------------------ [ DONE ]'
    for ip in TRUST_IP:
        os.system("netstat -antp|egrep -v ':::*' |egrep 'ESTABLISHED|LISTEN'|awk '$5 !~ /"+ip.strip()+"/' | awk '$5 ~/:(21|22|443|80|8080|7001|8443|9080)$/{print}'")

def Dubious_files(filepath):
  for f in os.listdir(filepath):
    path = os.path.join(filepath, f)
    if os.path.isfile(path):
      FILE_LIST.append(path)
    if os.path.isdir(path):
      Dubious_files(path)

def Webshell_detect(filename,rulename):
  f1 = open(filename).read()
  for rule in rulename:
    result = re.compile(rule).findall(f1)
    if result:
      print "============================================"
      print 'Risk file:' + filename
      print 'Risk code:' + str(result[0])
      os.system("stat " +str(filename)+ " |grep 'Modify'")

def Attack_analysis():
  f2 = open(ACCESS_LOG).readlines()
  print "\n[+] Attack_analysis ------------------------------------ [ DONE ]"
  for line in f2:
    for r in attack__Features_list:
      result = re.compile(r).findall(line)
      if result:
        print '匹配特征:' + '[' + str(result[0]) + ']' + '===>' + line.strip()
        print '攻击类型:' + '[' + attack__Features_list[r] + ']'

if __name__=='__main__':
  localday = os.popen("env LANG=en_US.UTF-8 date |awk '{print $2,$3}'").readline().strip()
  Un_worktime_login(localday)
  Faild_user(localday)
  Un_trust_user()
  Dubious_netstat()
  for file in FILE_PATH:
    Dubious_files(file.strip())
  print '\n[+] Webshell_detect ------------------------------------ [ DONE ]'
  for f in FILE_LIST:
    if str(f).lower().endswith(".php"):
      Webshell_detect(f, php_Features_list)
    elif str(f).lower().endswith(".jsp"):
      Webshell_detect(f, jsp_Features_list)
    elif str(f).lower().endswith(".aspx"):
      Webshell_detect(f, asp_Features_list)
  Attack_analysis()

效果预览:


[注意]传递专业知识、拓宽行业人脉——看雪讲师团队等你加入!

上传的附件:
收藏
免费 0
支持
分享
最新回复 (3)
雪    币: 57
活跃值: (13)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
2
给力!有.sh版就完美了
2016-10-27 15:15
0
雪    币: 202
活跃值: (40)
能力值: ( LV5,RANK:60 )
在线值:
发帖
回帖
粉丝
3
搞出这几个Features_list,要有深厚的功底哦
2016-10-27 15:52
0
雪    币:
能力值: ( LV1,RANK:0 )
在线值:
发帖
回帖
粉丝
4
版主 联系我 18925967789 有急事找您
2019-12-1 22:36
0
游客
登录 | 注册 方可回帖
返回
//