-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathgene.go
452 lines (398 loc) · 11.9 KB
/
gene.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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
package main
import (
"encoding/json"
"flag"
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"runtime/pprof"
"sort"
"sync"
"time"
"github.com/0xrawsec/gene/v2/engine"
"github.com/0xrawsec/gene/v2/reducer"
"github.com/0xrawsec/gene/v2/template"
"github.com/0xrawsec/golang-evtx/evtx"
"github.com/0xrawsec/golang-utils/args"
"github.com/0xrawsec/golang-utils/datastructs"
"github.com/0xrawsec/golang-utils/fsutil"
"github.com/0xrawsec/golang-utils/log"
"github.com/0xrawsec/golang-utils/progress"
"github.com/0xrawsec/golang-utils/readers"
)
//////////////////////////// Utilities //////////////////////////////
func matchEvent(e *engine.Engine, evt engine.Event) {
matches, criticality, filtered := e.MatchOrFilter(evt)
// if we don't want to display filtered events
if flNoFilter && len(matches) == 0 && filtered {
return
}
// We print only if we are not in test mode
if (len(matches) > 0 || filtered) && !flTest {
// Prints out the events with timestamp or not
if flShowTimestamp && (criticality >= criticalityThresh || filtered) {
fmt.Printf("%d: %s\n", evt.Timestamp().Unix(), string(evtx.ToJSON(evt)))
} else {
if criticality >= criticalityThresh || filtered {
fmt.Println(string(evtx.ToJSON(evt)))
}
}
} else if flAllEvents || (flTest && len(matches) == 0) {
if flShowTimestamp {
fmt.Printf("%d: %s\n", evt.Timestamp().Unix(), string(evtx.ToJSON(evt)))
} else {
fmt.Println(string(evtx.ToJSON(evt)))
}
}
}
func jsonEventGenerator() (ec chan *evtx.GoEvtxMap) {
ec = make(chan *evtx.GoEvtxMap)
prog := progress.New(128)
prog.SetPre("Event Processed")
go func() {
defer close(ec)
eventCnt, cntChunk, oldEventCnt := 0, 100, 100
for _, jsonFile := range flag.Args() {
var f *os.File
var err error
if jsonFile != "-" {
log.Infof("Processing: %s", jsonFile)
f, err = os.Open(jsonFile)
if err != nil {
log.Error(err)
}
} else {
jsonFile = "stdin"
f = os.Stdin
}
// Setting progress message
prog.SetPre(filepath.Base(jsonFile))
d := json.NewDecoder(f)
start := time.Now()
for {
event := evtx.GoEvtxMap{}
if err := d.Decode(&event); err != nil {
if err == io.EOF {
break
}
log.Error(err)
break
}
// Printing Progress
eventCnt++
if flShowProgress && eventCnt >= oldEventCnt {
delta := time.Since(start)
prog.Update(fmt.Sprintf("%d (%2.f EPS)", eventCnt, float64(eventCnt)/delta.Seconds()))
prog.Print()
oldEventCnt = eventCnt + cntChunk
}
//matchEvent(&e, &event)
ec <- &event
}
//log.Infof("Count Rules Used (loaded + generated): %d", e.Count())
}
}()
return
}
func evtxEventGenerator() (ec chan *evtx.GoEvtxMap) {
ec = make(chan *evtx.GoEvtxMap)
prog := progress.New(128)
prog.SetPre("Event Processed")
go func() {
defer close(ec)
eventCnt, cntChunk, oldEventCnt := 0, 100, 100
for _, evtxFile := range flag.Args() {
log.Infof("Processing: %s", evtxFile)
ef, err := evtx.OpenDirty(evtxFile)
if err != nil {
log.Error(err)
}
// Init Progress
prog.SetPre(filepath.Base(evtxFile))
start := time.Now()
for event := range ef.UnorderedEvents() {
eventCnt++
if flShowProgress && eventCnt >= oldEventCnt {
delta := time.Since(start)
prog.Update(fmt.Sprintf("%d (%2.f EPS)", eventCnt, float64(eventCnt)/delta.Seconds()))
prog.Print()
oldEventCnt = eventCnt + cntChunk
}
//matchEvent(&e, event)
ec <- event
}
}
}()
return
}
func printInfo(writer io.Writer) {
fmt.Fprintf(writer, "Version: %s\nCommit: %s\nCopyright: %s\nLicense: %s\n\n", version, commitID, copyright, license)
}
var (
sigPath = evtx.Path("/Event/GeneInfo/Signature")
computerPath = evtx.Path("/Event/System/Computer")
)
func reduce(e *engine.Engine) {
reducer := reducer.NewReducer(e)
wg := sync.WaitGroup{}
events := jsonEventGenerator()
for i := 0; i < jobs; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for e := range events {
computer, err := e.GetString(&computerPath)
if err != nil {
continue
}
iArray, err := e.Get(&sigPath)
if err != nil {
continue
}
sigs := make([]string, 0, len((*iArray).([]interface{})))
for _, s := range (*iArray).([]interface{}) {
sigs = append(sigs, s.(string))
}
reducer.Update(e.TimeCreated(), computer, sigs)
}
}()
}
wg.Wait()
reducer.Print()
}
/////////////////////////////// Main //////////////////////////////////
const (
exitFail = 1
exitSuccess = 0
copyright = "Gene Copyright (C) 2017 RawSec SARL (@0xrawsec)"
license = "License GPLv3: This program comes with ABSOLUTELY NO WARRANTY.\nThis is free software, and you are welcome to redistribute it under certain conditions;"
)
var (
flDebug bool
flShowTimestamp bool
flAllEvents bool
flShowProgress bool
flJSONFormat bool
flTemplate bool
flVerify bool
flListTags bool
flVersion bool
flReduce bool
flShowAttack bool
flTest bool
flNoFilter bool
cpuprofile string
tags []string
names []string
tagsVar args.ListVar
namesVar args.ListVar
dumpsVar args.ListVar
criticalityThresh int
whitelist string
blacklist string
rulesPath string
ruleExts = args.ListVar{".gen", ".gene"}
jobs = 1
// set with -ldflags at compile time
version string
commitID string
)
func main() {
flag.BoolVar(&flDebug, "debug", flDebug, "Enable debug mode")
flag.BoolVar(&flShowTimestamp, "t", flShowTimestamp, "Show the timestamp of the event when printing")
flag.BoolVar(&flAllEvents, "all", flAllEvents, "Print all events (even the one not matching rules)")
flag.BoolVar(&flShowProgress, "progress", flShowProgress, "Show progress")
flag.BoolVar(&flJSONFormat, "j", flJSONFormat, "Input is in JSON format")
flag.BoolVar(&flTemplate, "template", flTemplate, "Prints a rule template")
flag.BoolVar(&flVerify, "verify", flVerify, "Verify the rules and exit")
flag.BoolVar(&flListTags, "list-tags", flListTags, "List tags of rules loaded into the engine")
flag.BoolVar(&flVersion, "version", flVersion, "Show version information and exit")
flag.BoolVar(&flReduce, "reduce", flReduce, "Aggregate the results of already processed events and outputs condensed information")
flag.BoolVar(&flShowAttack, "a", flShowAttack, "Show Mitre ATT&CK information in matching events")
flag.BoolVar(&flTest, "test", flTest, "Test mode. Prints non matching events and returns a non zero status code if not all events match")
flag.BoolVar(&flNoFilter, "no-filter", flNoFilter, "Don't display filtered events")
flag.StringVar(&rulesPath, "r", rulesPath, "Rule file or directory")
flag.StringVar(&cpuprofile, "cpuprofile", cpuprofile, "Profile CPU")
flag.StringVar(&whitelist, "whitelist", whitelist, "File containing values to insert into the whitelist")
flag.StringVar(&blacklist, "blacklist", blacklist, "File containing values to insert into the blacklist")
flag.IntVar(&criticalityThresh, "c", criticalityThresh, "Criticality treshold. Prints only if criticality above threshold")
flag.IntVar(&jobs, "jobs", jobs, "Number of parallel jobs to run. It may result in events printed in different order than provided (use -t to print timestamp and re-order). If <= 0 takes all available processors")
flag.Var(&ruleExts, "e", "Rule file extensions to load")
flag.Var(&tagsVar, "tags", "Tags to select rules to compile (comma separated)")
flag.Var(&namesVar, "n", "Rule names to match against (comma separated)")
flag.Var(&dumpsVar, "dump", "Dumps the rules matching the regex provided (comma separated) and then exits. Usefull to verify if regexp template is correctly applied")
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "%s: %[1]s -r RULES [OPTIONS] FILES...\n", filepath.Base(os.Args[0]))
flag.PrintDefaults()
os.Exit(0)
}
flag.Parse()
if cpuprofile != "" {
f, err := os.Create(cpuprofile)
if err != nil {
log.Abort(exitFail, err)
}
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
}
// Enable debugging mode if needed
if flDebug {
log.InitLogger(log.LDebug)
}
// If version switch
if flVersion {
printInfo(os.Stderr)
os.Exit(exitSuccess)
}
// Handling job parameter
// If jobs is not in affordable range
if jobs <= 0 || jobs > runtime.NumCPU() {
jobs = runtime.NumCPU()
}
// Display rule template and exit if template flag
if flTemplate {
r := engine.Rule{}
json.Unmarshal([]byte(template.RuleTemplate), &r)
// marshaling the stuff out
b, err := json.Marshal(r)
if err != nil {
log.Abort(exitFail, err)
}
fmt.Println(string(b))
os.Exit(exitSuccess)
}
// Control parameters
if rulesPath == "" {
log.Abort(exitFail, "No rule file to load")
}
// Initialization
e := engine.NewEngine()
setRuleExts := datastructs.NewSyncedSet()
tags = []string(tagsVar)
names = []string(namesVar)
// Enable rule dumping on engine side
e.SetDumpRaw(len(dumpsVar) > 0)
// Enable showing Mitre ATT&CK information
e.SetShowAttck(flShowAttack)
// Validation
if len(tags) > 0 && len(names) > 0 {
log.Abort(exitFail, "Cannot search by tags and names at the same time")
}
e.SetFilters(names, tags)
// Initializes the set of rule extensions
for _, e := range ruleExts {
setRuleExts.Add(e)
}
// We have to load the containers befor the rules
// For the Whitelist
if whitelist != "" {
wlf, err := os.Open(whitelist)
if err != nil {
log.Abort(exitFail, err)
}
for line := range readers.Readlines(wlf) {
e.Whitelist(string(line))
}
wlf.Close()
}
log.Infof("Size of whitelist container: %d", e.WhitelistLen())
// For the Blacklist
if blacklist != "" {
blf, err := os.Open(blacklist)
if err != nil {
log.Abort(exitFail, err)
}
for line := range readers.Readlines(blf) {
e.Blacklist(string(line))
}
blf.Close()
}
log.Infof("Size of blacklist container: %d", e.BlacklistLen())
// Loading the rules and templates
// we first prepare the rules path
realPath, err := fsutil.ResolveLink(rulesPath)
if err != nil {
log.Abort(exitFail, err)
}
// actual rule loading
if err := e.LoadDirectory(realPath); err != nil {
log.Abort(exitFail, fmt.Errorf("failed at loading rule directory %s: %s", realPath, err))
}
// Show message about successfuly compiled rules
log.Infof("Loaded %d rules", e.Count())
// If we just wanted to verify the rules, we should exit whatever
// the status of the compilation
if flVerify {
log.Infof("Rule(s) compilation: SUCCESSFUL")
os.Exit(exitSuccess)
}
// If we want to reduce
if flReduce {
reduce(e)
os.Exit(exitSuccess)
}
// If we want to dump rules
if len(dumpsVar) > 0 {
for _, nameRegex := range dumpsVar {
for json := range e.GetRawRule(nameRegex) {
fmt.Println(json)
}
}
os.Exit(exitSuccess)
}
// If we list the tags available
if flListTags {
fmt.Println("Tags of rules loaded:")
tags := e.Tags()
sort.Strings(tags)
for _, t := range tags {
fmt.Printf("\t%s\n", t)
}
os.Exit(exitSuccess)
}
// Scanning the files
var events chan *evtx.GoEvtxMap
wg := sync.WaitGroup{}
if flJSONFormat {
events = jsonEventGenerator()
} else {
events = evtxEventGenerator()
}
for i := 0; i < jobs; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for evt := range events {
ge := engine.GenericEvent(*evt)
matchEvent(e, ge)
}
}()
}
// Waiting all the jobs to finish
wg.Wait()
log.Infof("Count Rules Used (loaded + generated): %d", e.Count())
log.Infof("Event Scanned: %d", e.Stats.Scanned)
log.Infof("Positives: %d", e.Stats.Positives)
// if we were in test mode
if flTest {
if e.Count() == 0 {
log.Error("Test: UNSUCCESSFUL")
log.Infof("No rule loaded")
os.Exit(exitFail)
}
if e.Stats.Scanned == 0 {
log.Error("Test: UNSUCCESSFUL")
log.Infof("No event scanned")
os.Exit(exitFail)
}
if e.Stats.Scanned != e.Stats.Positives {
log.Error("Test: UNSUCCESSFUL")
log.Infof("Some events did not match any rule, events not passing the test have been printed")
os.Exit(exitFail)
} else {
log.Infof("Test: SUCCESSFULL")
}
}
}