AWD 文件监控工具:monitor-Go

admin 2024年5月14日23:24:59评论24 views字数 4554阅读15分10秒阅读模式

 

安全工具

01 工具介绍

攻击策略

用来监控文件以及其子目录下的所有文件的增删改

此脚本基于

# -*- coding: utf-8 -*-#use: python file_check.py ./import osimport hashlibimport shutilimport ntpathimport timeCWD = os.getcwd()FILE_MD5_DICT = {}      # 文件MD5字典ORIGIN_FILE_LIST = []# 特殊文件路径字符串Special_path_str = 'drops_JWI96TY7ZKNMQPDRUOSG0FLH41A3C5EXVB82'bakstring = 'bak_EAR1IBM0JT9HZ75WU4Y3Q8KLPCX26NDFOGVS'logstring = 'log_WMY4RVTLAJFB28960SC3KZX7EUP1IHOQN5GD'webshellstring = 'webshell_WMY4RVTLAJFB28960SC3KZX7EUP1IHOQN5GD'difffile = 'diff_UMTGPJO17F82K35Z0LEDA6QB9WH4IYRXVSCN'Special_string = 'drops_log'  # 免死金牌UNICODE_ENCODING = "utf-8"INVALID_UNICODE_CHAR_FORMAT = r"?%02x"# 文件路径字典spec_base_path = os.path.realpath(os.path.join(CWD, Special_path_str))Special_path = {    'bak' : os.path.realpath(os.path.join(spec_base_path, bakstring)),    'log' : os.path.realpath(os.path.join(spec_base_path, logstring)),    'webshell' : os.path.realpath(os.path.join(spec_base_path, webshellstring)),    'difffile' : os.path.realpath(os.path.join(spec_base_path, difffile)),}def isListLike(value):    return isinstance(value, (list, tuple, set))# 获取Unicode编码def getUnicode(value, encoding=None, noneToNull=False):    if noneToNull and value is None:        return NULL    if isListLike(value):        value = list(getUnicode(_, encoding, noneToNull) for _ in value)        return value    if isinstance(value, unicode):        return value    elif isinstance(value, basestring):        while True:            try:                return unicode(value, encoding or UNICODE_ENCODING)            except UnicodeDecodeError, ex:                try:                    return unicode(value, UNICODE_ENCODING)                except:                    value = value[:ex.start] + "".join(INVALID_UNICODE_CHAR_FORMAT % ord(_) for _ in value[ex.start:ex.end]) + value[ex.end:]    else:        try:            return unicode(value)        except UnicodeDecodeError:            return unicode(str(value), errors="ignore")# 目录创建def mkdir_p(path):    import errno    try:        os.makedirs(path)    except OSError as exc:        if exc.errno == errno.EEXIST and os.path.isdir(path):            pass        else: raise# 获取当前所有文件路径def getfilelist(cwd):    filelist = []    for root,subdirs, files in os.walk(cwd):        for filepath in files:            originalfile = os.path.join(root, filepath)            if Special_path_str not in originalfile:                filelist.append(originalfile)    return filelist# 计算机文件MD5值def calcMD5(filepath):    try:        with open(filepath,'rb') as f:            md5obj = hashlib.md5()            md5obj.update(f.read())            hash = md5obj.hexdigest()            return hash    except Exception, e:        print u'[!] getmd5_error : ' + getUnicode(filepath)        print getUnicode(e)        try:            ORIGIN_FILE_LIST.remove(filepath)            FILE_MD5_DICT.pop(filepath, None)        except KeyError, e:            pass# 获取所有文件MD5def getfilemd5dict(filelist = []):    filemd5dict = {}    for ori_file in filelist:        if Special_path_str not in ori_file:            md5 = calcMD5(os.path.realpath(ori_file))            if md5:                filemd5dict[ori_file] = md5    return filemd5dict# 备份所有文件def backup_file(filelist=[]):    # if len(os.listdir(Special_path['bak'])) == 0:    for filepath in filelist:        if Special_path_str not in filepath:            shutil.copy2(filepath, Special_path['bak'])if __name__ == '__main__':    print u'---------start------------'    for value in Special_path:        mkdir_p(Special_path[value])    # 获取所有文件路径,并获取所有文件的MD5,同时备份所有文件    ORIGIN_FILE_LIST = getfilelist(CWD)    FILE_MD5_DICT = getfilemd5dict(ORIGIN_FILE_LIST)    backup_file(ORIGIN_FILE_LIST) # TODO 备份文件可能会产生重名BUG    print u'[*] pre work end!'    while True:        file_list = getfilelist(CWD)        # 移除新上传文件        diff_file_list = list(set(file_list) ^ set(ORIGIN_FILE_LIST))        if len(diff_file_list) != 0:            # import pdb;pdb.set_trace()            for filepath in diff_file_list:                try:                    f = open(filepath, 'r').read()                except Exception, e:                    break                if Special_string not in f:                    try:                        print u'[*] webshell find : ' + getUnicode(filepath)                        shutil.move(filepath, os.path.join(Special_path['webshell'], ntpath.basename(filepath) + '.txt'))                    except Exception as e:                        print u'[!] move webshell error, "%s" maybe is webshell.'%getUnicode(filepath)                    try:                        f = open(os.path.join(Special_path['log'], 'log.txt'), 'a')                        f.write('newfile: ' + getUnicode(filepath) + ' : ' + str(time.ctime()) + 'n')                        f.close()                    except Exception as e:                        print u'[-] log error : file move error: ' + getUnicode(e)        # 防止任意文件被修改,还原被修改文件        md5_dict = getfilemd5dict(ORIGIN_FILE_LIST)        for filekey in md5_dict:            if md5_dict[filekey] != FILE_MD5_DICT[filekey]:                try:                    f = open(filekey, 'r').read()                except Exception, e:                    break                if Special_string not in f:                    try:                        print u'[*] file had be change : ' + getUnicode(filekey)                        shutil.move(filekey, os.path.join(Special_path['difffile'], ntpath.basename(filekey) + '.txt'))                        shutil.move(os.path.join(Special_path['bak'], ntpath.basename(filekey)), filekey)                    except Exception as e:                        print u'[!] move webshell error, "%s" maybe is webshell.'%getUnicode(filekey)                    try:                        f = open(os.path.join(Special_path['log'], 'log.txt'), 'a')                        f.write('diff_file: ' + getUnicode(filekey) + ' : ' + getUnicode(time.ctime()) + 'n')                        f.close()                    except Exception as e:                        print u'[-] log error : done_diff: ' + getUnicode(filekey)                        pass        time.sleep(2)        # print '[*] ' + getUnicode(time.ctime())

做出的改进:

  1. 不会删除原文件,避免因为某些意外情况而导致的原文件被删除
  2. 前端打印所有详细信息,包括文件路径、被修改的时间、内容等
  • 用法

在需要监控的目录下直接启动即可

monitor-Go.exe

AWD 文件监控工具:monitor-Go

02 工具下载

https://github.com/qi4L/monitor-Go/releases/tag/1.0

 

原文始发于微信公众号(夜组安全):AWD 文件监控工具

 

免责声明:文章中涉及的程序(方法)可能带有攻击性,仅供安全研究与教学之用,读者将其信息做其他用途,由读者承担全部法律及连带责任,本站不承担任何法律及连带责任;如有问题可邮件联系(建议使用企业邮箱或有效邮箱,避免邮件被拦截,联系方式见首页),望知悉。
  • 左青龙
  • 微信扫一扫
  • weinxin
  • 右白虎
  • 微信扫一扫
  • weinxin
admin
  • 本文由 发表于 2024年5月14日23:24:59
  • 转载请保留本文链接(CN-SEC中文网:感谢原作者辛苦付出):
                   AWD 文件监控工具:monitor-Gohttps://cn-sec.com/archives/2058238.html
                  免责声明:文章中涉及的程序(方法)可能带有攻击性,仅供安全研究与教学之用,读者将其信息做其他用途,由读者承担全部法律及连带责任,本站不承担任何法律及连带责任;如有问题可邮件联系(建议使用企业邮箱或有效邮箱,避免邮件被拦截,联系方式见首页),望知悉.

发表评论

匿名网友 填写信息