Debian Codegraph @

bin/grokevt-builddb

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
•1 #!/usr/bin/python3
2
3 # This script builds message databases for use by grokevt-parselog.
4 #
5 # Copyright (C) 2005-2008,2011 Timothy D. Morgan
6 #
7 # This program is free software; you can redistribute it and/or
8 # modify it under the terms of the GNU General Public License
9 # as published by the Free Software Foundation version 3 of the
10 # License.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # vi:set tabsize=4:
18 # $Id: grokevt-builddb 118 2011-06-20 16:06:43Z tim $
19
20
21 import sys
22 import os
23 import re
24 import subprocess
25 import dbm
26 import select
27 import pyregfi
28 import grokevt
29
30
31 # XXX: should these be changed to absolute paths discovered at install time?
32 CURRENT_DB_VERSION=2
33 PATH_RIPDLL='grokevt-ripdll'
34
35 missing_dlls = {}
36
37 def usage():
38 sys.stderr.write("USAGE:\n")
39 sys.stderr.write(" %s [-v] [-c CSID] <CONFIG_PROFILE> <OUTPUT_DIR>\n\n"
40 % os.path.basename(sys.argv[0]))
41 sys.stderr.write("grokevt-builddb builds a database tree based on a\n")
42 sys.stderr.write("single windows system for the purpose of event log\n")
43 sys.stderr.write("conversion. Please see the man page for more\n")
44 sys.stderr.write("information.\n")
45
46
47 def unquoteString(s):
48 chunks = re.split("\\\\x([0-9A-F]{2})", s);
49
50 for i in range(1,len(chunks),2):
51 chunks[i] = "%c" % int(chunks[i], 16)
52
53 return ''.join(chunks)
54
55
56 def resolveCaseSensitivePath(prefix, insensitive):
57 if len(insensitive) == 0:
58 return prefix
59
60 for sub in os.listdir(prefix):
61 if sub.lower() == insensitive[0]:
62 return resolveCaseSensitivePath("%s/%s" % (prefix, sub),
63 insensitive[1:])
64
65
66 def windowsPathToUnixPath(path_list, variables, drives):
67 paths = path_list.lower().split(';')
68 for i in range(0,len(paths)):
69 for var,value in variables.items():
70 paths[i] = paths[i].replace(var.lower(),
71 value.lower()).replace("\\","/")
72 # Some paths have been found with trailing nulls and garbage.
73 paths[i] = paths[i].split('\x00')[0]
74
75 ret_val = []
76 for p in paths:
77 for letter,upath in drives.items():
78 if p.startswith(letter.lower()):
79 p = resolveCaseSensitivePath(upath, p[len(letter)+1:].split('/'))
80 break
81 if p != None:
82 ret_val.append(p)
83
84 return ret_val
85
86
87 def pyregfiPrintMessages():
88 messages = pyregfi.getLogMessages()
89 if messages != '' and messages != None:
90 lines = messages.split('\n')
91 for l in lines:
92 sys.stderr.write("WARN: pyregfi reported: %s\n" % l)
93
94 def ripdllStderrHandler(e, args):
95 sys.stderr.write(("WARNING: while reading %s and writing %s.db,"
96 +" grokevt-ripdll returned: %s")\
97 % (args[0], args[1], e.decode('utf-8', 'replace')))
98
99
100 class procWrapper:
101 child = None
102 exe_name = None
103
104 def __init__(self, args):
105 self.exe_name = args[0]
106 self.child = subprocess.Popen(args, shell=False, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
107
108 def readline(self):
109 return self.child.stdout.readline()
110
111 def wait(self):
112 while self.readline() != b'':
113 continue
114 child_ret = self.child.wait()
115 if child_ret > 0:
116 sys.stderr.write("WARNING: %s returned code: %d. Is it in your path?"
117 % (self.exe_name, child_ret))
118 return child_ret
119
120
121 def buildShortNamesPathsDicts(paths):
122 ret_val1 = {}
123 ret_val2 = {}
124 for p in paths.keys():
125 if os.path.isfile(p):
126 sn = os.path.basename(p).replace(':','_')
127 ext = ''
128 i = 2
129 while (sn+ext) in ret_val1:
130 ext = '_%d' % i
131 i += 1
132
133 ret_val1[sn+ext] = p
134 ret_val2[p] = sn+ext
135 else:
136 # XXX: this might be handy later
137 #missing_dlls[p] = paths[p]
138 sys.stderr.write("WARNING: %s doesn't exist.\n" % p
139 + "WARNING: (This may affect log output "
140 + "for the following services: %s)\n" % paths[p])
141
142 return (ret_val1, ret_val2)
143
144
145 def makeOutputDirectories(topdir, logs):
146 dirs = []
147 for log in logs:
148 dirs.append('%s/services/%s' % (topdir,log))
149 dirs.append('%s/messages' % topdir)
150 dirs.append('%s/logs' % topdir)
151
152 for p in dirs:
153 if os.path.exists(p):
154 if not os.path.isdir(p) or not os.access(p, os.W_OK):
155 sys.stderr.write("ERROR: Access denied to '%s'.\n" % p)
156 sys.exit(os.EX_CANTCREAT)
157 else:
158 os.makedirs(p, 0o755)
159
160 # Write DB version
161 vf = open('%s/version' % topdir, 'w+b')
162 vf.write(('%d\n' % CURRENT_DB_VERSION).encode('utf-8'))
163 vf.close()
164
165
166 def writeServiceMapping(topdir, maps):
167 for lt in maps.keys():
168 for t in maps[lt].keys():
169 db_file = "%s/services/%s/%s"%(topdir,lt,t)
170 db = dbm.open(db_file, "n", 0o644)
171 for k,v in maps[lt][t].items():
172 if len(v) != 0:
173 db[k] = v
174 db.close()
175
176
177 def writeDBFiles(topdir, names2paths):
178 for npi in names2paths.items():
179 outdb = "%s/messages/%s" % (topdir, npi[0])
180 db_call = (PATH_RIPDLL, npi[1], outdb)
181 ripdll_proc = procWrapper(db_call)
182
183 l = ripdll_proc.readline()
184 while l != b'':
185 ripdllStderrHandler(l, (npi[1], outdb))
186 l = ripdll_proc.readline()
187 ripdll_proc.wait()
188
189
190
191 # Parse command line arguments
192 CONTROL_SET_ID = None
193 print_verbose = 0
194 next_is_cid = 0
195 argv_len = len(sys.argv)
196 if argv_len < 3:
197 usage()
198 sys.stderr.write("ERROR: Requires at least 2 arguments.\n")
199 sys.exit(os.EX_USAGE)
200 else:
201 for option in sys.argv[1:argv_len-2]:
202 if next_is_cid:
203 CONTROL_SET_ID = int(option)
204 if CONTROL_SET_ID < 1:
205 usage()
206 sys.stderr.write("ERROR: CONTROL_SET_ID must be positive.\n")
207 sys.exit(os.EX_USAGE)
208 next_is_cid = 0
209 elif option == '-v':
210 print_verbose = 1
211 elif option == '-c':
212 next_is_cid = 1
213 else:
214 usage()
215 sys.stderr.write("ERROR: Unrecognized option '%s'.\n" % option)
216 sys.exit(os.EX_USAGE)
217
218 if next_is_cid:
219 usage()
220 sys.stderr.write("ERROR: -c requires parameter.\n")
221 sys.exit(os.EX_USAGE)
222
223
224 CONFIG_PROFILE=sys.argv[argv_len-2]
225 PATH_OUTPUT=sys.argv[argv_len-1]
226
227
228 if print_verbose:
229 sys.stderr.write("INFO: Loading configuration...\n")
230 config = grokevt.grokevtConfig(grokevt.PATH_CONFIG, CONFIG_PROFILE)
231 system_hive = pyregfi.openHive(config.registry_path)
232 pyregfiPrintMessages()
233
234 if print_verbose:
235 sys.stderr.write("INFO: Reading system registry for service information...\n")
236
237 # Need to determine correct 'CurrentControlSet', if not specified at
238 # command line
239 if not CONTROL_SET_ID:
240 try:
241 csid_key = system_hive.root.subkeys['Select']
242 CONTROL_SET_ID = int(csid_key.values['Current'].fetch_data())
243 del csid_key
244 pyregfiPrintMessages()
245 except Exception as e:
246 sys.stderr.write("ERROR: Could not automatically "
247 +"determine CONTROL_SET_ID\n")
248 sys.exit(os.EX_IOERR)
249
250 if print_verbose:
251 sys.stderr.write("INFO: Detected CONTROL_SET_ID=%d\n" % CONTROL_SET_ID)
252
253 EVENTLOG_PATH=('ControlSet%.3d' % CONTROL_SET_ID, 'Services', 'Eventlog')
254
255 # Next, identify all log types by grabbing all keys under the eventlog key
256 log_types = {}
257 evt_files = {}
258 files = {}
259 eventlog_key = system_hive.subtree(EVENTLOG_PATH).current_key()
260 for ltype in eventlog_key.subkeys:
261 lt = ltype.name
262 log_types[lt] = {}
263
264 # Obtain path to .evt file
265 try:
266 data = ltype.values['File'].fetch_data()
267 evt_files[lt] = windowsPathToUnixPath(unquoteString(data),
268 config.path_vars,
269 config.drive_mapping)[0]
270 pyregfiPrintMessages()
271 except Exception as e:
272 if print_verbose:
273 sys.stderr.write('WARNING: Event log file path not found'
274 +' for log type "%s". Removing this type.\n' % lt)
275 del log_types[lt]
276 continue
277
278 # Collect list of sources/services under this log type
279 log_types[lt]["event"] = {}
280 log_types[lt]["category"] = {}
281 log_types[lt]["parameter"] = {}
282 try:
283 sources = ltype.values['Sources'].fetch_data()
284 if len(data) == 0 and print_verbose:
285 sys.stderr.write('WARNING: No sources found for log type "%s".\n' % lt)
286
287 pyregfiPrintMessages()
288 except Exception as e:
289 sys.stderr.write('WARNING: Could not obtain list of sources'
290 +' for log type "%s". Removing this type.\n' % lt)
291 del log_types[lt]
292 continue
293
294 # For each source under this log type, compile the list of paths for various
295 # message files
296 for s in sources:
297 source_key = ltype.subkeys[s]
298
299 log_types[lt]["event"][s] = []
300 value = source_key.values.get('EventMessageFile', None)
301 if value != None:
302 log_types[lt]["event"][s] = windowsPathToUnixPath(value.fetch_data(),
303 config.path_vars,
304 config.drive_mapping)
305 log_types[lt]["category"][s] = []
306 value = source_key.values.get('CategoryMessageFile', None)
307 if value != None:
308 log_types[lt]["category"][s] = windowsPathToUnixPath(value.fetch_data(),
309 config.path_vars,
310 config.drive_mapping)
311 log_types[lt]["parameter"][s] = []
312 value = source_key.values.get('ParameterMessageFile', None)
313 if value != None:
314 log_types[lt]["parameter"][s] = windowsPathToUnixPath(value.fetch_data(),
315 config.path_vars,
316 config.drive_mapping)
317
318 # Retain unique list of file names and their associated services
319 for f in (log_types[lt]['event'][s]
320 + log_types[lt]['category'][s]
321 + log_types[lt]['parameter'][s]):
322 if f in files:
323 files[f] = files[f]+","+s
324 else:
325 files[f] = s
326 pyregfiPrintMessages()
327
328 (names2paths,paths2names) = buildShortNamesPathsDicts(files)
329
330
331 # Convert path lists to named path strings. Filter out any unusable resources
332 # and any services that have no remaining resources.
333 for lt in log_types.keys():
334 for t in log_types[lt].keys():
335 for s in log_types[lt][t].keys():
336 if len(log_types[lt][t][s]) > 0:
337 tmp_str = ''
338 for i in range(0,len(log_types[lt][t][s])):
339 if log_types[lt][t][s][i] in paths2names:
340 tmp_str += ':' + paths2names[log_types[lt][t][s][i]]
341 log_types[lt][t][s] = tmp_str.lstrip(':')
342
343 if print_verbose:
344 sys.stderr.write("INFO: Writing service mappings...\n")
345 makeOutputDirectories(PATH_OUTPUT, log_types.keys())
346 writeServiceMapping(PATH_OUTPUT, log_types)
347
348 if print_verbose:
349 sys.stderr.write("INFO: Writing DLL databases...\n")
350 writeDBFiles(PATH_OUTPUT, names2paths)
351
352 if print_verbose:
353 sys.stderr.write("INFO: Copying log files...\n")
354 try:
355 for ei in evt_files.items():
356 o = open("%s/logs/%s.evt" % (PATH_OUTPUT,ei[0]), "w+b")
357 i = open(ei[1], "rb")
358 buf = i.read(4096)
359 while buf != b'':
360 o.write(buf)
361 buf = i.read(4096)
362 o.close()
363 i.close()
364 except Exception as inst:
365 sys.stderr.write("ERROR: %s\n" % inst)
366 sys.stderr.write("ERROR: could not copy all log files.\n")
367 sys.exit(os.EX_IOERR)
368
369 if print_verbose:
370 sys.stderr.write("INFO: Done.\n")