forked from eReader/detekt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdetector.py
More file actions
executable file
·154 lines (129 loc) · 5.03 KB
/
Copy pathdetector.py
File metadata and controls
executable file
·154 lines (129 loc) · 5.03 KB
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
# Copyright (C) 2014 Claudio Guarnieri.
# This file is part of Detekt - https://github.com/botherder/detekt
# See the file 'LICENSE' for copying permission.
import os
import time
import yara
import logging
import threading
import messages
from abstracts import DetectorError
from config import Config, DEBUG
from service import Service, destroy
from memory import Memory
from utils import get_resource, hexdump
# Configure logging for our main application.
log = logging.getLogger('detekt')
log.propagate = 0
fh = logging.FileHandler(os.path.join(os.getcwd(), 'detekt.log'))
sh = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s [%(name)s] %(levelname)s: %(message)s')
fh.setFormatter(formatter)
sh.setFormatter(formatter)
log.addHandler(fh)
log.addHandler(sh)
log.setLevel(logging.DEBUG)
def scan(queue_results):
# Find Yara signatures, if file is not available, we need to terminate.
yara_path = os.path.join(os.getcwd(), 'signatures.yar')
if not os.path.exists(yara_path):
yara_path = get_resource(os.path.join('rules', 'signatures.yar'))
if not os.path.exists(yara_path):
raise DetectorError("Unable to find a valid Yara signatures file!")
log.info("Selected Yara signature file at %s", yara_path)
# Compile Yara signatures.
rules = yara.compile(yara_path)
# Instantiate memory crawler.
memory = Memory()
counter = 1
matched = []
# Perform a Yara scan on each chunk of memory that is retrieved from
# the memory ranges crawler.
for data in memory.get_memory_chunks():
# If debug is enabled, dump the matched rule
if DEBUG:
if not os.path.exists('segments'):
os.makedirs('segments')
with open(os.path.join('segments', 'segment_{0}.bin'.format(counter)), 'wb') as dump:
dump.write(data)
# For each Yara signature that is matched...
for hit in rules.match(data=data):
log.debug("Matched: %s, in segment #%d", hit.rule, counter)
# For each matched string let's log some details.
counter = 1
for entry in hit.strings:
# Log offset.
log.warning("\t(%s) %s:", counter, entry[0])
# Log a short hexdump of the interested segment.
hexdata = hexdump(data[entry[0]:], maxlines=10)
for line in hexdata:
log.debug("\t\t%s", line)
counter += 1
# We only store unique results, it's pointless to store results
# for the same rule.
if not hit.rule in matched:
# Add rule to the list of unique matches.
matched.append(hit.rule)
# Add match to the list of results.
queue_results.put(dict(
rule=hit.rule,
detection=hit.meta.get('detection'),
description=hit.meta.get('description')
))
# Increment segment counter.
counter += 1
log.info("Total number of unique matched rules: %d", len(matched))
def main(queue_results, queue_errors):
# Generate configuration values.
cfg = Config()
# Obtain the path to the driver to load. At this point, this check should
# not fail, but you never know.
if not cfg.get_driver_path():
log.error("Unable to find a proper winpmem driver")
queue_errors.put(messages.NO_DRIVER)
return
log.info("Selected Driver: {0}".format(cfg.driver))
# This is the ugliest black magic ever, but somehow helps.
# Just tries to brutally destroy the winpmem service if there is one
# lying around before trying to launch a new one again.
destroyer = threading.Thread(target=destroy, args=(cfg.driver, cfg.service_name))
destroyer.start()
destroyer.join()
# Initialize the winpmem service.
try:
service = Service(driver=cfg.driver, service=cfg.service_name)
service.create()
service.start()
except DetectorError as e:
log.critical("Unable to start winpmem service: %s", e)
queue_errors.put(messages.SERVICE_NO_START)
return
else:
log.info("Service started")
# Launch the scanner.
try:
log.info("Starting yara scanner...")
#scanner = threading.Thread(target=scan, args=(queue_results,))
#scanner.start()
#scanner.join()
scan(queue_results)
except DetectorError as e:
log.critical("Yara scanning failed: %s", e)
queue_errors.put(messages.SCAN_FAILED)
else:
log.info("Scanning finished")
# Stop the winpmem service and unload the driver. At this point we should
# have cleaned up everything left on the system.
try:
service.stop()
service.delete()
except DetectorError as e:
log.error("Unable to stop winpmem service: %s", e)
else:
log.info("Service stopped")
log.info("Analysis finished")
if __name__ == '__main__':
from Queue import Queue
results = Queue()
errors = Queue()
main(results, errors)