-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathyara_linux.go
112 lines (97 loc) · 2.28 KB
/
yara_linux.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
//go:build linux || cgo
// +build linux cgo
package YaraPerfTest
import (
"bytes"
"fmt"
"os"
"path"
"time"
"github.com/hillu/go-yara/v4"
log "github.com/sirupsen/logrus"
)
func printMatches(item string, m []yara.MatchRule, err error) {
if err != nil {
log.Printf("%s: error: %s", item, err)
return
}
if len(m) == 0 {
log.Printf("%s: no matches", item)
return
}
buf := &bytes.Buffer{}
fmt.Fprintf(buf, "%s: [", item)
for i, match := range m {
if i > 0 {
fmt.Fprint(buf, ", ")
}
fmt.Fprintf(buf, "%s:%s", match.Namespace, match.Rule)
}
fmt.Fprint(buf, "]")
log.Print(buf.String())
}
// RunYara - tests the yara rule against the files the given number of times
func RunYara(yaraRuleFile string, numTimes int, testFolder string) ([]YaraResult, error) {
//Create Yara Compiler
c, err := yara.NewCompiler()
if err != nil {
log.Warn("Failed to initialize YARA compiler")
return nil, err
}
//Load Rule files
f, err := os.Open(yaraRuleFile)
if err != nil {
log.Warn("Could not open rule file")
return nil, err
}
err = c.AddFile(f, "")
f.Close()
if err != nil {
log.Warn("Could not parse rule file")
return nil, err
}
//Compile Rules
start := time.Now()
r, err := c.GetRules()
elapsed := time.Since(start)
if err != nil {
log.Warn("Failed to compile rules")
return nil, err
}
log.Printf("Rule Compliation Time: %s", elapsed)
//Get files
files, err := os.ReadDir(testFolder)
if err != nil {
log.Warn("Failed to get files in folder")
return nil, err
}
results := make([]YaraResult, 0)
//Scan Files
for _, f := range files {
filename := path.Join(testFolder, f.Name())
log.Printf("Scanning file %s... ", filename)
times := make([]float64, numTimes)
var firstHit []yara.MatchRule
for i := 0; i < numTimes; i++ {
start := time.Now()
s, _ := yara.NewScanner(r)
var m yara.MatchRules
err := s.SetCallback(&m).ScanFile(filename)
printMatches(filename, m, err)
elapsed := time.Since(start)
if err != nil {
fmt.Printf("Error scanning file [%s]: %s\n", filename, err)
return nil, err
}
times[i] = float64(elapsed)
}
result := YaraResult{
File: filename,
Stats: Statistics{},
FirstHits: firstHit,
}
result.Stats.Calculate(times)
results = append(results, result)
}
return results, nil
}