0%

Yara规则学习-01

官方demo

https://github.com/VirusTotal/yara

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
rule silent_banker : banker
{
meta:
description = "This is just an example"
threat_level = 3
in_the_wild = true

strings:
$a = {6A 40 68 00 30 00 00 6A 14 8D 91}
$b = {8D 4D B0 2B C1 83 C0 27 99 6A 4E 59 F7 F9}
$c = "UVODFRYSIHLNWPEJXQZAKCBGMT" //样本中出现的机器码或者字符串

condition:
$a or $b or $c // 满足其中一个条件即可进行匹配
}c


Yara规则语法

一般包含3部分,分别为 meta string condition

1
2
3
4
5
6
rule RuleName
{
meta: //该规则的基础信息
strings: //用来定义字符串
condition: //编写表达式处理strings中的字符串
}

rule命名规则

1
2
3
4
5
1.英文或字母组成的字符串
2.可以使用下划线
3.第一个字符禁止为数字
4.大小写敏感
5.不可以大于128个字符长度

Yara规则支持字符串、正则表达式、十六进制进行匹配。

1
2
3
4
5
6
7
8
9
10
字符串:定义一个变量 $a = “字符串内容”

正则表达式:定义一个变量 $a = /正则表达式内容/

十六进制:定义一个变量 $a = {十六进制内容}
#可以使用 ? 作为通配符
$hex1 = { EF E4 ?8 D8 ?? FB}
#不定长字符串可以用 [3-5]表示 无限长可以用[-]表示
$hex2 = { EF E4 [-] A2 FB}
$hex3 = { EF E4 [2-4] D8 A2 FB}

Yara规则常用修饰符

1
2
3
4
nocase:不区分大小写
base64:base64字符串
xor:异或字符串
wide:宽字符

Yara规则条件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 布尔运算
and:与 or:或 not:非
all of them: //匹配所有条件即告警
any of them: //匹配到其中一个条件即告警
$a and $b and $c: //同时匹配到abc即告警
($a and $b) or $c: //匹配到a和b或c即告警
$a and $b and $c: //同时匹配到abc即告警
($a and $b) or $c: //匹配到a和b或c即告警

# 文件大小
filesize > 200KB

# 访问指定位置数据
unint16(0) and unit32(unit32(0x3c)) == 0x00004550

Yara编写

先略过 后续有时间再搞一下


使用

pip install yara-python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import yara
import os

# 获取目录内的yara规则文件
# 将yara规则编译
def getRules(path):
filepath = {}
for index, file in enumerate(os.listdir(path)):
rupath = os.path.join(path, file)
key = "rule" + str(index)
filepath[key] = rupath
print(rupath)

yararule = yara.compile(filepaths=filepath)
print(filepath)
print(yararule)
return yararule

# 扫描函数
def scan(rule, path):
for file in os.listdir(path):
mapath = os.path.join(path, file)
print (malpath+"\\"+file)
fp = open(malpath+"\\"+file, 'rb')
matches = rule.match(data=fp.read())
if len(matches) > 0:
print (file, matches)

if __name__ == '__main__':
rulepath = "F:\\yara\\rules" # yara规则目录
malpath ="F:\\yara\\samples" # simple目录
# yara规则编译函数调用
yararule = getRules(rulepath)
# 扫描函数调用
scan(yararule, malpath)


References

1
2
3
https://lengjibo.github.io/yara/
https://zhuanlan.kanxue.com/article-17369.htm
https://toutiao.io/posts/05scc8/preview

欢迎关注我的其它发布渠道

------------- 💖 🌞 本 文 结 束 😚 感 谢 您 的 阅 读 🌞 💖 -------------