-
Notifications
You must be signed in to change notification settings - Fork 3
/
EventMonkey.py
290 lines (265 loc) · 8.32 KB
/
EventMonkey.py
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import argparse
import logging
import multiprocessing
#From https://github.com/pyinstaller/pyinstaller/wiki/Recipe-Multiprocessing
try:
# Python 3.4+
if sys.platform.startswith('win'):
import multiprocessing.popen_spawn_win32 as forking
else:
import multiprocessing.popen_fork as forking
except ImportError:
import multiprocessing.forking as forking
if sys.platform.startswith('win'):
# First define a modified version of Popen.
class _Popen(forking.Popen):
def __init__(self, *args, **kw):
if hasattr(sys, 'frozen'):
# We have to set original _MEIPASS2 value from sys._MEIPASS
# to get --onefile mode working.
os.putenv('_MEIPASS2', sys._MEIPASS)
try:
super(_Popen, self).__init__(*args, **kw)
finally:
if hasattr(sys, 'frozen'):
# On some platforms (e.g. AIX) 'os.unsetenv()' is not
# available. In those cases we cannot delete the variable
# but only set it to the empty string. The bootloader
# can handle this case.
if hasattr(os, 'unsetenv'):
os.unsetenv('_MEIPASS2')
else:
os.putenv('_MEIPASS2', '')
# Second override 'Popen' class with our modified version.
forking.Popen = _Popen
import libem.WindowsEventManager as WindowsEventManager
import libem.Config as Config
from libem import Utilities
from gchelpers.db.DbHandler import DbConfig
from gchelpers.writers import XlsxHandler
from gchelpers.db import SqliteCustomFunctions
from gchelpers.ip.GeoDbManager import GeoDbManager
Config.Config.InitLoggers()
Config.Config.SetUiToCLI()
MAIN_LOGGER = logging.getLogger('Main')
def SetProcessingArguments(parser):
parser.add_argument(
'-n','--evidencename',
dest='evidencename',
required=True,
action="store",
type=unicode,
help=u'Name to prepend to output files'
)
parser.add_argument(
'-p','--path',
dest='events_path',
required=True,
action="store",
type=unicode,
help=u'Path to Event Files'
)
parser.add_argument(
'-o','--output_path',
dest='output_path',
required=True,
action="store",
type=unicode,
help='Output Path'
)
parser.add_argument(
'--threads',
dest='threads_to_use',
action="store",
type=int,
default=Config.Config.CPU_COUNT,
help='Number of threads to use (default is all [{}])'.format(Config.Config.CPU_COUNT)
)
parser.add_argument(
'--esconfig',
dest='esconfig',
action="store",
type=unicode,
default=None,
help='Elastic YAML Config File'
)
parser.add_argument(
'--esurl',
dest='esurl',
action="store",
type=unicode,
default=None,
help='Elastic RFC-1738 URL'
)
parser.add_argument(
'--eshost',
dest='eshost',
action="store",
type=str,
default=None,
help='Elastic Host IP'
)
parser.add_argument(
'--esuser',
dest='esuser',
action="store",
type=str,
default=None,
help='Elastic Host User'
)
parser.add_argument(
'--espass',
dest='espass',
action="store",
type=unicode,
default=None,
help='Elastic Password [if not supplied, will prompt]'
)
def SetReportingArguments(parser):
parser.add_argument(
'-d','--database',
dest='db_name',
required=True,
action="store",
type=unicode,
help=u'Database to run reports on'
)
parser.add_argument(
'-o','--output_path',
dest='output_path',
required=True,
action="store",
type=unicode,
help='Output Path'
)
def GetArguements():
'''Get needed options for processesing'''
usage = '''EventMonkey (A Windows Event Parsing Utility)'''
arguements = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description=(usage)
)
arguements.add_argument(
'-f','--templatefolder',
dest='templatefolder',
default=Utilities.GetResource(
'xlsx_templates',
'xlsx_templates',
''
),
action="store",
type=unicode,
help=u'Folder of Template Files'
)
subparsers = arguements.add_subparsers(
help='Either process or report command is required.',
dest='subparser_name'
)
processing_parser = subparsers.add_parser(
'process',
help='Processes eventfiles and then generate reports.',
)
SetProcessingArguments(
processing_parser
)
reporting_parser = subparsers.add_parser(
'report',
help='Generate reports from an existing EventMonkey database.',
)
SetReportingArguments(
reporting_parser
)
return arguements
def InitGeoDb(geodb_file):
geodb_path = os.path.dirname(geodb_file)
if not os.path.isdir(geodb_path):
os.makedirs(geodb_path)
if not os.path.isfile(geodb_file):
SqliteCustomFunctions.GEO_MANAGER.UpdateGoeIpDbs(
geodb_path=geodb_path
)
SqliteCustomFunctions.GEO_MANAGER.AttachGeoDbs(
geodb_path
)
def Main():
multiprocessing.freeze_support()
Config.Config.ClearLogs()
###GET OPTIONS###
arguements = GetArguements()
options = arguements.parse_args()
# Check if there is geodb if frozen
if getattr(sys,'frozen',False):
geodb_file = os.path.join(
'geodb',
'GeoLite2-City.mmdb'
)
if not os.path.isfile(geodb_file):
if GetYesNo(("There is no geodb found, would you like to download it? "
"This is required for using basic Geo IP support within the "
"report queries. If you choose not to use this functionality "
"expect errors for templates that use custom functions calling "
"geoip functions.")):
InitGeoDb(geodb_file)
else:
SqliteCustomFunctions.GEO_MANAGER.AttachGeoDbs('geodb')
if options.subparser_name == "process":
options.db_name = os.path.join(
options.output_path,
options.evidencename+'.db'
)
manager = WindowsEventManager.WindowsEventManager(
options
)
manager.ProcessEvents()
CreateReports(options)
elif options.subparser_name == "report":
CreateReports(options)
else:
raise(Exception("Unknown subparser: {}".format(options.subparser_name)))
def CreateReports(options):
db_config = DbConfig(
db_type='sqlite',
db=options.db_name
)
temp_manager = XlsxHandler.XlsxTemplateManager(
options.templatefolder
)
temp_manager.CreateReports(
db_config,
options.output_path
)
# Thanks to http://code.activestate.com/recipes/577058/
def GetYesNo(message, default="yes"):
"""Ask a yes/no question via raw_input() and return their answer.
"message" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is required of the user).
The "answer" return value is one of True or False.
"""
valid = {"yes":True, "y":True, "ye":True,
"no":False, "n":False}
if default == None:
prompt = " [y/n] "
elif default == "yes":
prompt = " [Y/n] "
elif default == "no":
prompt = " [y/N] "
else:
raise ValueError("invalid default answer: '%s'" % default)
while 1:
sys.stdout.write(message + prompt)
choice = raw_input().lower()
if default is not None and choice == '':
return default
elif choice in valid.keys():
return valid[choice]
else:
sys.stdout.write("Please respond with 'yes' or 'no' "\
"(or 'y' or 'n').\n")
if __name__ == '__main__':
Main()