forked from hillu/go-yara
-
Notifications
You must be signed in to change notification settings - Fork 4
/
rules_test.go
322 lines (299 loc) · 9 KB
/
rules_test.go
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
// Copyright © 2015-2020 Hilko Bengen <[email protected]>
// All rights reserved.
//
// Use of this source code is governed by the license that can be
// found in the LICENSE file.
package yara
import (
"bytes"
"compress/bzip2"
"fmt"
"io/ioutil"
"os"
"os/exec"
"reflect"
"runtime"
"testing"
)
func makeRules(t *testing.T, rule string) *Rules {
c, err := NewCompiler()
if c == nil || err != nil {
t.Fatal("NewCompiler():", err)
}
if err = c.AddString(rule, ""); err != nil {
t.Fatal("AddString():", err)
}
r, err := c.GetRules()
if err != nil {
t.Fatal("GetRules:", err)
}
return r
}
func TestSimpleMatch(t *testing.T) {
r := makeRules(t,
"rule test : tag1 { meta: author = \"Hilko Bengen\" strings: $a = \"abc\" fullword condition: $a }")
var m MatchRules
err := r.ScanMem([]byte(" abc "), 0, 0, &m)
if err != nil {
t.Errorf("ScanMem: %s", err)
}
t.Logf("Matches: %+v", m)
}
func TestSimpleFileMatch(t *testing.T) {
r, _ := Compile(
"rule test : tag1 { meta: author = \"Hilko Bengen\" strings: $a = \"abc\" fullword condition: $a }",
nil)
tf, _ := ioutil.TempFile("", "TestSimpleFileMatch")
defer os.Remove(tf.Name())
tf.Write([]byte(" abc "))
tf.Close()
var m MatchRules
err := r.ScanFile(tf.Name(), 0, 0, &m)
if err != nil {
t.Errorf("ScanFile(%s): %s", tf.Name(), err)
}
t.Logf("Matches: %+v", m)
}
func TestSimpleFileDescriptorMatch(t *testing.T) {
r, _ := Compile(
"rule test : tag1 { meta: author = \"Hilko Bengen\" strings: $a = \"abc\" fullword condition: $a }",
nil)
tf, _ := ioutil.TempFile("", "TestSimpleFileMatch")
defer os.Remove(tf.Name())
tf.Write([]byte(" abc "))
tf.Seek(0, os.SEEK_SET)
var m MatchRules
err := r.ScanFileDescriptor(tf.Fd(), 0, 0, &m)
if err != nil {
t.Errorf("ScanFileDescriptor(%s): %s", tf.Name(), err)
}
t.Logf("Matches: %+v", m)
}
func TestEmpty(t *testing.T) {
r, _ := Compile("rule test { condition: true }", nil)
r.ScanMem([]byte{}, 0, 0, nil)
t.Log("Scan of null-byte slice did not crash. Yay.")
}
func assertTrueRules(t *testing.T, rules []string, data []byte) {
for _, rule := range rules {
r := makeRules(t, rule)
var m MatchRules
if err := r.ScanMem(data, 0, 0, &m); len(m) == 0 {
t.Errorf("Rule < %s > did not match data < %v >", rule, data)
} else if err != nil {
t.Errorf("Error %s", err)
}
}
}
func assertFalseRules(t *testing.T, rules []string, data []byte) {
for _, rule := range rules {
r := makeRules(t, rule)
var m MatchRules
if err := r.ScanMem(data, 0, 0, &m); len(m) > 0 {
t.Errorf("Rule < %s > matched data < %v >", rule, data)
} else if err != nil {
t.Errorf("Error %s", err)
}
}
}
func TestLoad(t *testing.T) {
r, err := LoadRules(compiledTestRulesPath)
if r == nil || err != nil {
t.Fatalf("LoadRules: %s", err)
}
}
func TestReader(t *testing.T) {
rd, err := os.Open(compiledTestRulesPath)
if err != nil {
t.Fatalf("os.Open: %s", err)
}
r, err := ReadRules(rd)
if err != nil {
t.Fatalf("ReadRules: %+v", err)
}
var m MatchRules
if err := r.ScanMem([]byte(" abc "), 0, 0, &m); err != nil {
t.Errorf("ScanMem: %s", err)
}
t.Logf("Matches: %+v", m)
}
func TestWriter(t *testing.T) {
rd, err := os.Open(compiledTestRulesPath)
if err != nil {
t.Fatalf("os.Open: %s", err)
}
compareBuf, _ := ioutil.ReadAll(rd)
r, _ := Compile("rule test : tag1 { meta: author = \"Hilko Bengen\" strings: $a = \"abc\" fullword condition: $a }",
nil)
wr := bytes.Buffer{}
if err := r.Write(&wr); err != nil {
t.Fatal(err)
}
newBuf := wr.Bytes()
if len(compareBuf) != len(newBuf) {
t.Errorf("len(compareBuf) = %d, len(newBuf) = %d", len(compareBuf), len(newBuf))
}
if bytes.Compare(compareBuf, newBuf) != 0 {
t.Error("buffers are not equal")
}
}
// in Go 1.8 this code does not work in go-yara 1.0.2
// go 1.8/debian stretch panics
// go 1.8/darwin produces stack overflow
func TestWriterBuffer(t *testing.T) {
rulesBuf := bytes.NewBuffer(nil)
for i := 0; i < 10000; i++ {
fmt.Fprintf(rulesBuf, "rule test%d : tag%d { meta: author = \"Hilko Bengen\" strings: $a = \"abc\" fullword condition: $a }", i, i)
}
r, _ := Compile(string(rulesBuf.Bytes()), nil)
buf := new(bytes.Buffer)
if err := r.Write(buf); err != nil {
t.Fatalf("write to bytes.Buffer: %s", err)
}
}
// compress/bzip2 seems to return short reads which apparently leads
// to YARA complaining about corrupt files. Tested with Go 1.4, 1.5.
func TestReaderBZIP2(t *testing.T) {
rulesBuf := bytes.NewBuffer(nil)
for i := 0; i < 10000; i++ {
fmt.Fprintf(rulesBuf, "rule test%d : tag%d { meta: author = \"Hilko Bengen\" strings: $a = \"abc\" fullword condition: $a }", i, i)
}
r, err := Compile(string(rulesBuf.Bytes()), nil)
if err != nil {
t.Fatalf("compile text for bzip2 rule compression: %s", err)
}
cmd := exec.Command("bzip2", "-c")
compressStream, _ := cmd.StdinPipe()
buf := bytes.NewBuffer(nil)
cmd.Stdout = buf
if err := cmd.Start(); err != nil {
t.Fatalf("start bzip2 process: %s", err)
}
if err := r.Write(compressStream); err != nil {
t.Fatalf("pipe to bzip2 process: %s", err)
}
compressStream.Close()
if err := cmd.Wait(); err != nil {
t.Fatalf("wait for bzip2 process: %s", err)
}
if _, err := ReadRules(bzip2.NewReader(bytes.NewReader(buf.Bytes()))); err != nil {
t.Fatalf("read using compress/bzip2: %s", err)
}
}
// See https://github.com/hillu/go-yara/issues/5
func TestScanMemCgoPointer(t *testing.T) {
r := makeRules(t,
"rule test : tag1 { meta: author = \"Hilko Bengen\" strings: $a = \"abc\" fullword condition: $a }")
buf := &bytes.Buffer{}
buf.Write([]byte(" abc "))
if err := func() (p interface{}) {
defer func() { p = recover() }()
r.ScanMem(buf.Bytes(), 0, 0, nil)
return nil
}(); err != nil {
t.Errorf("ScanMem panicked: %s", err)
}
}
type rule struct {
identifier string
tags []string
metas []Meta
private, global bool
}
func TestRule(t *testing.T) {
rs := makeRules(t, `
rule t1 : tag1 { meta: author = "Author One" strings: $a = "abc" fullword condition: $a }
rule t2 : tag2 x y { meta: author = "Author Two" strings: $b = "def" condition: $b }
rule t3 : tag3 x y z { meta: author = "Author Three" strings: $c = "ghi" condition: $c }
rule t4 { strings: $d = "qwe" condition: $d }
private rule t5 { condition: false }
global rule t6 { condition: false }`)
expected := []rule{
rule{"t1", []string{"tag1"}, []Meta{{"author", "Author One"}}, false, false},
rule{"t2", []string{"tag2", "x", "y"}, []Meta{{"author", "Author Two"}}, false, false},
rule{"t3", []string{"tag3", "x", "y", "z"}, []Meta{{"author", "Author Three"}}, false, false},
rule{"t4", nil, nil, false, false},
rule{"t5", nil, nil, true, false},
rule{"t6", nil, nil, false, true},
}
var got []rule
for _, r := range rs.GetRules() {
got = append(got, rule{identifier: r.Identifier(), metas: r.Metas(), tags: r.Tags(), private: r.IsPrivate(), global: r.IsGlobal()})
}
if !reflect.DeepEqual(got, expected) {
t.Errorf("Got %+v , expected %+v", got, expected)
}
}
type testCallback struct {
t *testing.T
finished bool
modules map[string]struct{}
matched map[string]struct{}
notMatched map[string]struct{}
}
func newTestCallback(t *testing.T) *testCallback {
return &testCallback{
t, false,
make(map[string]struct{}),
make(map[string]struct{}),
make(map[string]struct{}),
}
}
func (c *testCallback) RuleMatching(_ *ScanContext, r *Rule) (bool, error) {
c.t.Logf("RuleMatching callback called: rule=%s", r.Identifier())
c.matched[r.Identifier()] = struct{}{}
return false, nil
}
func (c *testCallback) RuleNotMatching(_ *ScanContext, r *Rule) (bool, error) {
c.t.Logf("RuleNotMatching callback called: rule=%s", r.Identifier())
c.notMatched[r.Identifier()] = struct{}{}
return false, nil
}
func (c *testCallback) ScanFinished(*ScanContext) (bool, error) {
c.t.Log("ScanFinished callback called")
c.finished = true
return false, nil
}
func (c *testCallback) ImportModule(_ *ScanContext, s string) ([]byte, bool, error) {
c.t.Logf("ImportModule callback called: module=%s", s)
c.modules[s] = struct{}{}
if s == "tests" {
return []byte("callback-data-for-tests-module"), false, nil
}
return nil, false, nil
}
func (c *testCallback) ModuleImported(*ScanContext, *Object) (bool, error) {
c.t.Log("ModuleImported callback called")
return false, nil
}
func TestImportDataCallback(t *testing.T) {
cb := newTestCallback(t)
r := makeRules(t, `
import "tests"
import "pe"
rule t1 { condition: true }
rule t2 { condition: false }
rule t3 {
condition: tests.module_data == "callback-data-for-tests-module"
}`)
if err := r.ScanMem([]byte(""), 0, 0, cb); err != nil {
t.Error(err)
}
for _, module := range []string{"tests", "pe"} {
if _, ok := cb.modules[module]; !ok {
t.Errorf("ImportModule was not called for %s", module)
}
}
for _, rule := range []string{"t1", "t3"} {
if _, ok := cb.matched["t1"]; !ok {
t.Errorf("RuleMatching was not called for %s", rule)
}
}
if _, ok := cb.notMatched["t2"]; !ok {
t.Errorf("RuleNotMatching was not called for %s", "t2")
}
if !cb.finished {
t.Errorf("ScanFinished was not called")
}
runtime.GC()
}