前言概述
前面有文章介绍了如何利用开源(yara)搭建简易杀毒引擎和对应规则编写,当时是以官方编译好的二进制为例展开。今天接着之前的文章进一步扩展,把遗留的实时检测和防护响应两问题解决。
方案介绍
通过引入yara-python和watchdog库,编写python代码,监控文件改动并调度yara扫描,发现病毒则执行相应动作。使用pyinstaller打包python代码与解析器到一个exe文件,设置每次开机启动。下面以粗略测试代码说明:
#coding=utf-8
import os
import sys
import yara
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class MyYara(object):
def __init__(self, rule):
self.rule = rule
self.crule = "{}c".format(self.rule)
self.yar = None
@staticmethod
def mycallback(data):
return yara.CALLBACK_ABORT
def load(self):
if not os.path.isfile(self.rule):
return False
try:
r = yara.compile(self.rule)
r.save(self.crule)
self.yar = yara.load(self.crule)
return True
except Exception as e:
print("laod yara fail:{}".format(str(e)))
return False
def match(self, file):
try:
with open(file, 'rb') as fd:
matches = self.yar.match(data=fd.read(), callback=MyYara.mycallback, which_callbacks=yara.CALLBACK_MATCHES)
for i in matches:
print(i, type(i), dir(i))
except Exception as e:
print(str(e))
class MyEventHandler(FileSystemEventHandler):
def __init__(self, y):
self.yar = y
super(MyEventHandler, self).__init__()
def scan(self, event):
if event.is_directory:
return
self.yar.match(event.src_path)
def on_moved(self, event):
print("move")
print(event)
def on_created(self, event):
print("create")
print(event)
# self.scan(event)
def on_deleted(self, event):
print("delete")
print(event)
def on_modified(self, event):
print("modify")
print(event)
self.scan(event)
if __name__ == '__main__':
observer = Observer()
yy = MyYara('D:\\yara\\APT_Codoso.yar')
if not yy.load():
print("load rule fail, exit")
sys.exit(1)
file_handler = MyEventHandler(yy)
observer.schedule(file_handler, "D:\\one", True)
observer.schedule(file_handler, "D:\\two", False)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
observer.schedule()调用是监控一个目录,第三参数为recursive,标识是否递归监控子目录
yara扫描,默认匹配全部规则,通过设置match()函数指定callback回掉, 并设置which_callbacks=yara.CALLBACK_MATCHES限定匹配到规则才进入回掉,然后在canllback返回yara.CALLBACK_ABORT即可。
过程问题
Q1:安装yara-python无法成功
A1:通过pycharm community 2020.3使用pip install yara-python遇到不少问题,比如"There was a problem confirming the ssl certificate:"、"can not fund openssl/asn1.h"、"link error",确认是否开启了系统代理、使用pip install --global-option=build_ext --global-option="-I/path"指定头文件路径、确认安装的yara-python版本是否支持对应python解析器版本。笔者是关掉系统代理后把python3.5升级到python3.9解决问题。
遗留问题
Q1:文件改动发生次modified事件,导致被处理多次
A1:目前尚未解决
Q2:打包成exe前需要把python代码写成后台应用
A2:网上搜索参考即可
Q3:pyinstaller打包流程未走,开机启动未设置
A3:网上搜索参考即可
参考文献
[1] readthedocs 上的#yara doc文档#
[2] Microsoft 上#在Windows 10 中添加在启动时自动运行的应用#