Skip to content

Commit 4dabdf7

Browse files
committed
perf(yara): Limit YARA mmap scans
If the suspicious section of view mapping already produced a rule match for the process, we don't keep running the scans for that process.
1 parent ad606f0 commit 4dabdf7

File tree

1 file changed

+16
-3
lines changed

1 file changed

+16
-3
lines changed

pkg/yara/scanner.go

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,8 @@ type scanner struct {
7272

7373
psnap ps.Snapshotter
7474

75-
rwxs map[uint32]va.Address // contains scanned and matched RWX process allocations
75+
rwxs map[uint32]va.Address // contains scanned and matched RWX process allocations
76+
mmaps map[uint32]va.Address // contains scanned and matched suspicious memory mappings
7677
}
7778

7879
// NewScanner creates a new YARA scanner.
@@ -141,6 +142,7 @@ func NewScanner(psnap ps.Snapshotter, config config.Config) (Scanner, error) {
141142
config: config,
142143
psnap: psnap,
143144
rwxs: make(map[uint32]va.Address),
145+
mmaps: make(map[uint32]va.Address),
144146
}, nil
145147
}
146148

@@ -173,7 +175,9 @@ func (s scanner) CanEnqueue() bool { return false }
173175
func (s *scanner) ProcessEvent(evt *kevent.Kevent) (bool, error) {
174176
if evt.IsTerminateProcess() {
175177
// cleanup
176-
delete(s.rwxs, evt.Kparams.MustGetPid())
178+
pid := evt.Kparams.MustGetPid()
179+
delete(s.rwxs, pid)
180+
delete(s.mmaps, pid)
177181
}
178182
return s.Scan(evt)
179183
}
@@ -292,7 +296,7 @@ func (s scanner) Scan(e *kevent.Kevent) (bool, error) {
292296
pid := e.Kparams.MustGetPid()
293297
prot := e.Kparams.MustGetUint32(kparams.MemProtect)
294298
size := e.Kparams.MustGetUint64(kparams.FileViewSize)
295-
if e.PID != 4 && size >= 4096 && ((prot&sys.SectionRX) != 0 && (prot&sys.SectionRWX) != 0) {
299+
if e.PID != 4 && size >= 4096 && ((prot&sys.SectionRX) != 0 && (prot&sys.SectionRWX) != 0) && !s.isMmapMatched(pid) {
296300
filename := e.GetParamAsString(kparams.FilePath)
297301
// skip mappings of signed images
298302
addr := e.Kparams.MustGetUint64(kparams.FileViewBase)
@@ -314,6 +318,9 @@ func (s scanner) Scan(e *kevent.Kevent) (bool, error) {
314318
e.GetParamAsString(kparams.FileViewBase))
315319
matches, err = s.scan(pid)
316320
}
321+
if len(matches) > 0 {
322+
s.mmaps[pid] = va.Address(addr)
323+
}
317324
mmapScans.Add(1)
318325
isScanned = true
319326
}
@@ -462,3 +469,9 @@ func (s *scanner) isRwxMatched(pid uint32) (ok bool) {
462469
_, ok = s.rwxs[pid]
463470
return ok
464471
}
472+
473+
// isMmapMatched returns true if the process already triggered suspicious mmap rule match.
474+
func (s *scanner) isMmapMatched(pid uint32) (ok bool) {
475+
_, ok = s.mmaps[pid]
476+
return ok
477+
}

0 commit comments

Comments
 (0)