1 | #!/usr/bin/env python
|
---|
2 |
|
---|
3 | ## @package pyregfi
|
---|
4 | # Python interface to the regfi library.
|
---|
5 | #
|
---|
6 |
|
---|
7 | ## @mainpage API Documentation
|
---|
8 | #
|
---|
9 | # The pyregfi module provides a Python interface to the @ref regfi Windows
|
---|
10 | # registry library.
|
---|
11 | #
|
---|
12 | # The library operates on registry hives, each of which is contained within a
|
---|
13 | # single file. To get started, one must first open the registry hive file with
|
---|
14 | # the open() or file() Python built-in functions (or equivalent) and then pass
|
---|
15 | # the resulting file object to pyregfi. For example:
|
---|
16 | # @code
|
---|
17 | # >>> import pyregfi
|
---|
18 | # >>> fh = open('/mnt/win/c/WINDOWS/system32/config/system', 'rb')
|
---|
19 | # >>> myHive = pyregfi.Hive(fh)
|
---|
20 | # @endcode
|
---|
21 | #
|
---|
22 | # Using this Hive object, one can begin investigating what top-level keys
|
---|
23 | # exist by starting with the root Key attribute:
|
---|
24 | # @code
|
---|
25 | # >>> for key in myHive.root.subkeys:
|
---|
26 | # ... print(key.name)
|
---|
27 | # ControlSet001
|
---|
28 | # ControlSet003
|
---|
29 | # LastKnownGoodRecovery
|
---|
30 | # MountedDevices
|
---|
31 | # Select
|
---|
32 | # Setup
|
---|
33 | # WPA
|
---|
34 | # @endcode
|
---|
35 | #
|
---|
36 | # From there, accessing subkeys and values by name is a simple matter of:
|
---|
37 | # @code
|
---|
38 | # >>> myKey = myHive.root.subkeys['Select']
|
---|
39 | # >>> myValue = myKey.values['Current']
|
---|
40 | # @endcode
|
---|
41 | #
|
---|
42 | # The data associated with a Value can be obtained through the fetch_data()
|
---|
43 | # method:
|
---|
44 | # @code
|
---|
45 | # >>> print(myValue.fetch_data())
|
---|
46 | # 1
|
---|
47 | # @endcode
|
---|
48 | #
|
---|
49 | # While useful for simple exercises, using the subkeys object for deeply nested
|
---|
50 | # paths is not efficient and doesn't make for particularly attractive code.
|
---|
51 | # Instead, a special-purpose HiveIterator class is provided for simplicity of
|
---|
52 | # use and fast access to specific known paths:
|
---|
53 | # @code
|
---|
54 | # >>> myIter = pyregfi.HiveIterator(myHive)
|
---|
55 | # >>> myIter.descend(['ControlSet001','Control','NetworkProvider','HwOrder'])
|
---|
56 | # >>> myKey = myIter.current_key()
|
---|
57 | # >>> print(myKey.values['ProviderOrder'].fetch_data())
|
---|
58 | # RDPNP,LanmanWorkstation,WebClient
|
---|
59 | # @endcode
|
---|
60 | #
|
---|
61 | # The first two lines above can be simplified in some "syntactic sugar" provided
|
---|
62 | # by the Hive.subtree() method. Also, as one might expect, the HiveIterator
|
---|
63 | # also acts as an iterator, producing keys in a depth-first order.
|
---|
64 | # For instance, to traverse all keys under the ControlSet003\\Services key,
|
---|
65 | # printing their names as we go, we could do:
|
---|
66 | # @code
|
---|
67 | # >>> for key in Hive.subtree(['ControlSet003','Services']):
|
---|
68 | # >>> print(key.name)
|
---|
69 | # Services
|
---|
70 | # Abiosdsk
|
---|
71 | # abp480n5
|
---|
72 | # Parameters
|
---|
73 | # PnpInterface
|
---|
74 | # ACPI
|
---|
75 | # [...]
|
---|
76 | # @endcode
|
---|
77 | #
|
---|
78 | # Note that "Services" was printed first, since the subtree is traversed as a
|
---|
79 | # "preordering depth-first" search starting with the HiveIterator's current_key().
|
---|
80 | # As one might expect, traversals of subtrees stops when all elements in a
|
---|
81 | # specific subtree (and none outside of it) have been traversed.
|
---|
82 | #
|
---|
83 | # For more information, peruse the various attributes and methods available on
|
---|
84 | # the Hive, HiveIterator, Key, Value, and Security classes.
|
---|
85 | #
|
---|
86 | # @note @ref regfi is a read-only library by design and there
|
---|
87 | # are no plans to implement write support.
|
---|
88 | #
|
---|
89 | # @note At present, pyregfi has been tested with Python versions 2.6 and 3.1
|
---|
90 | #
|
---|
91 | # @note Developers strive to make pyregfi thread-safe.
|
---|
92 | #
|
---|
93 | # @note Key and Value names are case-sensitive in regfi and pyregfi
|
---|
94 | #
|
---|
95 | import sys
|
---|
96 | import time
|
---|
97 | import weakref
|
---|
98 | from pyregfi.structures import *
|
---|
99 |
|
---|
100 | import ctypes
|
---|
101 | import ctypes.util
|
---|
102 |
|
---|
103 | ## An enumeration of registry Value data types
|
---|
104 | #
|
---|
105 | # @note This is a static class, there is no need to instantiate it.
|
---|
106 | # Just access its attributes directly as DATA_TYPES.SZ, etc
|
---|
107 | class DATA_TYPES(object):
|
---|
108 | ## None / Unknown
|
---|
109 | NONE = 0
|
---|
110 | ## String
|
---|
111 | SZ = 1
|
---|
112 | ## String with %...% expansions
|
---|
113 | EXPAND_SZ = 2
|
---|
114 | ## Binary buffer
|
---|
115 | BINARY = 3
|
---|
116 | ## 32 bit integer (little endian)
|
---|
117 | DWORD = 4 # DWORD, little endian
|
---|
118 | ## 32 bit integer (little endian)
|
---|
119 | DWORD_LE = 4
|
---|
120 | ## 32 bit integer (big endian)
|
---|
121 | DWORD_BE = 5 # DWORD, big endian
|
---|
122 | ## Symbolic link
|
---|
123 | LINK = 6
|
---|
124 | ## List of strings
|
---|
125 | MULTI_SZ = 7
|
---|
126 | ## Unknown structure
|
---|
127 | RESOURCE_LIST = 8
|
---|
128 | ## Unknown structure
|
---|
129 | FULL_RESOURCE_DESCRIPTOR = 9
|
---|
130 | ## Unknown structure
|
---|
131 | RESOURCE_REQUIREMENTS_LIST = 10
|
---|
132 | ## 64 bit integer
|
---|
133 | QWORD = 11 # 64-bit little endian
|
---|
134 |
|
---|
135 |
|
---|
136 | def _buffer2bytearray(char_pointer, length):
|
---|
137 | if length == 0 or char_pointer == None:
|
---|
138 | return None
|
---|
139 |
|
---|
140 | ret_val = bytearray(length)
|
---|
141 | for i in range(0,length):
|
---|
142 | ret_val[i] = char_pointer[i][0]
|
---|
143 |
|
---|
144 | return ret_val
|
---|
145 |
|
---|
146 |
|
---|
147 | def _strlist2charss(str_list):
|
---|
148 | ret_val = []
|
---|
149 | for s in str_list:
|
---|
150 | ret_val.append(s.encode('utf-8', 'replace'))
|
---|
151 |
|
---|
152 | ret_val = (ctypes.c_char_p*(len(str_list)+1))(*ret_val)
|
---|
153 | # Terminate the char** with a NULL pointer
|
---|
154 | ret_val[-1] = 0
|
---|
155 |
|
---|
156 | return ret_val
|
---|
157 |
|
---|
158 |
|
---|
159 | def _charss2strlist(chars_pointer):
|
---|
160 | ret_val = []
|
---|
161 | i = 0
|
---|
162 | s = chars_pointer[i]
|
---|
163 | while s != None:
|
---|
164 | ret_val.append(s.decode('utf-8', 'replace'))
|
---|
165 | i += 1
|
---|
166 | s = chars_pointer[i]
|
---|
167 |
|
---|
168 | return ret_val
|
---|
169 |
|
---|
170 |
|
---|
171 | ## Retrieves messages produced by regfi during parsing and interpretation
|
---|
172 | #
|
---|
173 | # The regfi C library may generate log messages stored in a special thread-safe
|
---|
174 | # global data structure. These messages should be retrieved periodically or
|
---|
175 | # after each major operation by callers to determine if any errors or warnings
|
---|
176 | # should be reported to the user. Failure to retrieve these could result in
|
---|
177 | # excessive memory consumption.
|
---|
178 | def GetLogMessages():
|
---|
179 | msgs = regfi.regfi_log_get_str()
|
---|
180 | if msgs == None:
|
---|
181 | return ''
|
---|
182 | return msgs.decode('utf-8')
|
---|
183 |
|
---|
184 |
|
---|
185 | ## Abstract class for most objects returned by the library
|
---|
186 | class _StructureWrapper(object):
|
---|
187 | _hive = None
|
---|
188 | _base = None
|
---|
189 |
|
---|
190 | def __init__(self, hive, base):
|
---|
191 | if not hive:
|
---|
192 | raise Exception("Could not create _StructureWrapper,"
|
---|
193 | + " hive is NULL. Current log:\n"
|
---|
194 | + GetLogMessages())
|
---|
195 | if not base:
|
---|
196 | raise Exception("Could not create _StructureWrapper,"
|
---|
197 | + " base is NULL. Current log:\n"
|
---|
198 | + GetLogMessages())
|
---|
199 | self._hive = hive
|
---|
200 | self._base = base
|
---|
201 |
|
---|
202 | # Memory management for most regfi structures is taken care of here
|
---|
203 | def __del__(self):
|
---|
204 | regfi.regfi_free_record(self._base)
|
---|
205 |
|
---|
206 | # Any attribute requests not explicitly defined in subclasses gets passed
|
---|
207 | # to the equivalent REGFI_* structure defined in structures.py
|
---|
208 | def __getattr__(self, name):
|
---|
209 | return getattr(self._base.contents, name)
|
---|
210 |
|
---|
211 | ## Test for equality
|
---|
212 | #
|
---|
213 | # Records returned by pyregfi may be compared with one another. For example:
|
---|
214 | # @code
|
---|
215 | # >>> key2 = key1.subkeys['child']
|
---|
216 | # >>> key1 == key2
|
---|
217 | # False
|
---|
218 | # >>> key1 != key2
|
---|
219 | # True
|
---|
220 | # >>> key1 == key2.get_parent()
|
---|
221 | # True
|
---|
222 | # @endcode
|
---|
223 | def __eq__(self, other):
|
---|
224 | return (type(self) == type(other)) and (self.offset == other.offset)
|
---|
225 |
|
---|
226 | def __ne__(self, other):
|
---|
227 | return (not self.__eq__(other))
|
---|
228 |
|
---|
229 |
|
---|
230 | class Key():
|
---|
231 | pass
|
---|
232 |
|
---|
233 |
|
---|
234 | class Value():
|
---|
235 | pass
|
---|
236 |
|
---|
237 |
|
---|
238 | ## Registry security record and descriptor
|
---|
239 | # XXX: Access to security descriptors not yet implemented
|
---|
240 | class Security(_StructureWrapper):
|
---|
241 | pass
|
---|
242 |
|
---|
243 | ## Abstract class for ValueList and SubkeyList
|
---|
244 | class _GenericList(object):
|
---|
245 | _hive = None
|
---|
246 | _key = None
|
---|
247 | _length = None
|
---|
248 | _current = None
|
---|
249 |
|
---|
250 | # implementation-specific functions for SubkeyList and ValueList
|
---|
251 | _fetch_num = None
|
---|
252 | _find_element = None
|
---|
253 | _get_element = None
|
---|
254 | _constructor = None
|
---|
255 |
|
---|
256 | def __init__(self, key):
|
---|
257 | self._hive = key._hive
|
---|
258 |
|
---|
259 | # Normally it's good to avoid cyclic references like this
|
---|
260 | # (key.list.key...) but in this case it makes ctypes memory
|
---|
261 | # management easier to reference the Key instead of the base
|
---|
262 | # structure. We use a weak reference in order to allow for garbage
|
---|
263 | # collection, since value/subkey lists should not be usable if their
|
---|
264 | # parent Key is freed anyway.
|
---|
265 |
|
---|
266 | # XXX: check for NULL here, throw an exception if so.
|
---|
267 | self._key = weakref.proxy(key)
|
---|
268 | self._length = self._fetch_num(key._base)
|
---|
269 |
|
---|
270 |
|
---|
271 | ## Length of list
|
---|
272 | def __len__(self):
|
---|
273 | return self._length
|
---|
274 |
|
---|
275 |
|
---|
276 | ## Retrieves a list element by name
|
---|
277 | #
|
---|
278 | # @return the first element whose name matches, or None if the element
|
---|
279 | # could not be found
|
---|
280 | def __getitem__(self, name):
|
---|
281 | index = ctypes.c_uint32()
|
---|
282 | if isinstance(name, str):
|
---|
283 | name = name.encode('utf-8')
|
---|
284 |
|
---|
285 | if name != None:
|
---|
286 | name = create_string_buffer(bytes(name))
|
---|
287 |
|
---|
288 | if self._find_element(self._hive.file, self._key._base,
|
---|
289 | name, byref(index)):
|
---|
290 | return self._constructor(self._hive,
|
---|
291 | self._get_element(self._hive.file,
|
---|
292 | self._key._base,
|
---|
293 | index))
|
---|
294 | raise KeyError('')
|
---|
295 |
|
---|
296 | def get(self, name, default):
|
---|
297 | try:
|
---|
298 | return self[name]
|
---|
299 | except KeyError:
|
---|
300 | return default
|
---|
301 |
|
---|
302 | def __iter__(self):
|
---|
303 | self._current = 0
|
---|
304 | return self
|
---|
305 |
|
---|
306 | def __next__(self):
|
---|
307 | if self._current >= self._length:
|
---|
308 | raise StopIteration('')
|
---|
309 |
|
---|
310 | elem = self._get_element(self._hive.file, self._key._base,
|
---|
311 | ctypes.c_uint32(self._current))
|
---|
312 | self._current += 1
|
---|
313 | return self._constructor(self._hive, elem)
|
---|
314 |
|
---|
315 | # For Python 2.x
|
---|
316 | next = __next__
|
---|
317 |
|
---|
318 |
|
---|
319 | ## The list of subkeys associated with a Key
|
---|
320 | #
|
---|
321 | # This attribute is both iterable:
|
---|
322 | # @code
|
---|
323 | # for k in myKey.subkeys:
|
---|
324 | # ...
|
---|
325 | # @endcode
|
---|
326 | # and accessible as a dictionary:
|
---|
327 | # @code
|
---|
328 | # mySubkey = myKey.subkeys["keyName"]
|
---|
329 | # @endcode
|
---|
330 | #
|
---|
331 | # @note SubkeyLists should never be accessed directly and only exist
|
---|
332 | # in association with a parent Key object. Do not retain references to
|
---|
333 | # SubkeyLists. Instead, access them via their parent Key at all times.
|
---|
334 | class SubkeyList(_GenericList):
|
---|
335 | _fetch_num = regfi.regfi_fetch_num_subkeys
|
---|
336 | _find_element = regfi.regfi_find_subkey
|
---|
337 | _get_element = regfi.regfi_get_subkey
|
---|
338 |
|
---|
339 |
|
---|
340 | ## The list of values associated with a Key
|
---|
341 | #
|
---|
342 | # This attribute is both iterable:
|
---|
343 | # @code
|
---|
344 | # for v in myKey.values:
|
---|
345 | # ...
|
---|
346 | # @endcode
|
---|
347 | # and accessible as a dictionary:
|
---|
348 | # @code
|
---|
349 | # myValue = myKey.values["valueName"]
|
---|
350 | # @endcode
|
---|
351 | #
|
---|
352 | # @note ValueLists should never be accessed directly and only exist
|
---|
353 | # in association with a parent Key object. Do not retain references to
|
---|
354 | # ValueLists. Instead, access them via their parent Key at all times.
|
---|
355 | class ValueList(_GenericList):
|
---|
356 | _fetch_num = regfi.regfi_fetch_num_values
|
---|
357 | _find_element = regfi.regfi_find_value
|
---|
358 | _get_element = regfi.regfi_get_value
|
---|
359 |
|
---|
360 |
|
---|
361 | ## Registry key
|
---|
362 | # These represent registry keys (@ref REGFI_NK records) and provide
|
---|
363 | # access to their subkeys, values, and other metadata.
|
---|
364 | #
|
---|
365 | # @note Value instances may provide access to more than the attributes
|
---|
366 | # documented here. However, undocumented attributes may change over time
|
---|
367 | # and are not officially supported. If you need access to an attribute
|
---|
368 | # not shown here, see pyregfi.structures.
|
---|
369 | class Key(_StructureWrapper):
|
---|
370 | ## A @ref ValueList object representing the list of Values
|
---|
371 | # stored on this Key
|
---|
372 | values = None
|
---|
373 |
|
---|
374 | ## A @ref SubkeyList object representing the list of subkeys
|
---|
375 | # stored on this Key
|
---|
376 | subkeys = None
|
---|
377 |
|
---|
378 | ## The raw Key name as an uninterpreted bytearray
|
---|
379 | name_raw = (b"...")
|
---|
380 |
|
---|
381 | ## The name of the Key as a (unicode) string
|
---|
382 | name = "..."
|
---|
383 |
|
---|
384 | ## The absolute file offset of the Key record's cell in the Hive file
|
---|
385 | offset = 0xCAFEBABE
|
---|
386 |
|
---|
387 | ## This Key's last modified time represented as the number of seconds
|
---|
388 | # since the UNIX epoch in UTC; similar to what time.time() returns
|
---|
389 | modified = 1300000000.123456
|
---|
390 |
|
---|
391 | ## The NK record's flags field
|
---|
392 | flags = 0x10110001
|
---|
393 |
|
---|
394 | def __init__(self, hive, base):
|
---|
395 | super(Key, self).__init__(hive, base)
|
---|
396 | self.values = ValueList(self)
|
---|
397 | self.subkeys = SubkeyList(self)
|
---|
398 |
|
---|
399 | def __getattr__(self, name):
|
---|
400 | if name == "name":
|
---|
401 | ret_val = super(Key, self).__getattr__(name)
|
---|
402 |
|
---|
403 | if ret_val == None:
|
---|
404 | ret_val = self.name_raw
|
---|
405 | else:
|
---|
406 | ret_val = ret_val.decode('utf-8', 'replace')
|
---|
407 |
|
---|
408 | elif name == "name_raw":
|
---|
409 | ret_val = super(Key, self).__getattr__(name)
|
---|
410 | length = super(Key, self).__getattr__('name_length')
|
---|
411 | ret_val = _buffer2bytearray(ret_val, length)
|
---|
412 |
|
---|
413 | elif name == "modified":
|
---|
414 | ret_val = regfi.regfi_nt2unix_time(byref(self._base.contents.mtime))
|
---|
415 |
|
---|
416 | else:
|
---|
417 | ret_val = super(Key, self).__getattr__(name)
|
---|
418 |
|
---|
419 | return ret_val
|
---|
420 |
|
---|
421 |
|
---|
422 | ## Retrieves the Security properties for this key
|
---|
423 | def fetch_security(self):
|
---|
424 | return Security(self._hive,
|
---|
425 | regfi.regfi_fetch_sk(self._hive.file, self._base))
|
---|
426 |
|
---|
427 |
|
---|
428 | ## Retrieves the class name for this key
|
---|
429 | #
|
---|
430 | # Class names are typically stored as UTF-16LE strings, so these are decoded
|
---|
431 | # into proper python (unicode) strings. However, if this fails, a bytearray
|
---|
432 | # is instead returned containing the raw buffer stored for the class name.
|
---|
433 | #
|
---|
434 | # @return The class name as a string or bytearray. None if a class name
|
---|
435 | # doesn't exist or an unrecoverable error occurred during retrieval.
|
---|
436 | def fetch_classname(self):
|
---|
437 | ret_val = None
|
---|
438 | cn_p = regfi.regfi_fetch_classname(self._hive.file, self._base)
|
---|
439 | if cn_p:
|
---|
440 | cn_struct = cn_p.contents
|
---|
441 | if cn_struct.interpreted:
|
---|
442 | ret_val = cn_struct.interpreted.decode('utf-8', 'replace')
|
---|
443 | else:
|
---|
444 | ret_val = _buffer2bytearray(cn_struct.raw,
|
---|
445 | cn_struct.size)
|
---|
446 | regfi.regfi_free_record(cn_p)
|
---|
447 |
|
---|
448 | return ret_val
|
---|
449 |
|
---|
450 |
|
---|
451 | ## Retrieves this key's parent key
|
---|
452 | #
|
---|
453 | # @return The parent's Key instance or None if current key is root
|
---|
454 | # (or an error occured)
|
---|
455 | def get_parent(self):
|
---|
456 | if self.is_root():
|
---|
457 | return None
|
---|
458 | parent_base = regfi.regfi_get_parentkey(self._hive.file, self._base)
|
---|
459 | if parent_base:
|
---|
460 | return Key(self._hive, parent_base)
|
---|
461 | return None
|
---|
462 |
|
---|
463 | def is_root(self):
|
---|
464 | return (self._hive.root == self)
|
---|
465 |
|
---|
466 |
|
---|
467 | ## Registry value (metadata)
|
---|
468 | #
|
---|
469 | # These represent registry values (@ref REGFI_VK records) and provide
|
---|
470 | # access to their associated data.
|
---|
471 | #
|
---|
472 | # @note Value instances may provide access to more than the attributes
|
---|
473 | # documented here. However, undocumented attributes may change over time
|
---|
474 | # and are not officially supported. If you need access to an attribute
|
---|
475 | # not shown here, see pyregfi.structures.
|
---|
476 | class Value(_StructureWrapper):
|
---|
477 | ## The raw Value name as an uninterpreted bytearray
|
---|
478 | name_raw = (b"...")
|
---|
479 |
|
---|
480 | ## The name of the Value as a (unicode) string
|
---|
481 | name = "..."
|
---|
482 |
|
---|
483 | ## The absolute file offset of the Value record's cell in the Hive file
|
---|
484 | offset = 0xCAFEBABE
|
---|
485 |
|
---|
486 | ## The length of data advertised in the VK record
|
---|
487 | data_size = 0xCAFEBABE
|
---|
488 |
|
---|
489 | ## An integer which represents the data type for this Value's data
|
---|
490 | # Typically this value is one of 12 types defined in @ref DATA_TYPES,
|
---|
491 | # but in some cases (the SAM hive) it may be used for other purposes
|
---|
492 | type = DATA_TYPES.NONE
|
---|
493 |
|
---|
494 | ## The VK record's flags field
|
---|
495 | flags = 0x10110001
|
---|
496 |
|
---|
497 | ## Retrieves the Value's data according to advertised type
|
---|
498 | #
|
---|
499 | # Data is loaded from its cell(s) and then interpreted based on the data
|
---|
500 | # type recorded in the Value. It is not uncommon for data to be stored with
|
---|
501 | # the wrong type or even with invalid types. If you have difficulty
|
---|
502 | # obtaining desired data here, use @ref fetch_raw_data().
|
---|
503 | #
|
---|
504 | # @return The interpreted representation of the data as one of several
|
---|
505 | # possible Python types, as listed below. None if any failure
|
---|
506 | # occurred during extraction or conversion.
|
---|
507 | #
|
---|
508 | # @retval string for SZ, EXPAND_SZ, and LINK
|
---|
509 | # @retval int for DWORD, DWORD_BE, and QWORD
|
---|
510 | # @retval list(string) for MULTI_SZ
|
---|
511 | # @retval bytearray for NONE, BINARY, RESOURCE_LIST,
|
---|
512 | # FULL_RESOURCE_DESCRIPTOR, and RESOURCE_REQUIREMENTS_LIST
|
---|
513 | #
|
---|
514 | def fetch_data(self):
|
---|
515 | ret_val = None
|
---|
516 | data_p = regfi.regfi_fetch_data(self._hive.file, self._base)
|
---|
517 | if not data_p:
|
---|
518 | return None
|
---|
519 | data_struct = data_p.contents
|
---|
520 |
|
---|
521 | if data_struct.interpreted_size == 0:
|
---|
522 | ret_val = None
|
---|
523 | elif data_struct.type in (DATA_TYPES.SZ, DATA_TYPES.EXPAND_SZ, DATA_TYPES.LINK):
|
---|
524 | # Unicode strings
|
---|
525 | ret_val = data_struct.interpreted.string.decode('utf-8', 'replace')
|
---|
526 | elif data_struct.type in (DATA_TYPES.DWORD, DATA_TYPES.DWORD_BE):
|
---|
527 | # 32 bit integers
|
---|
528 | ret_val = data_struct.interpreted.dword
|
---|
529 | elif data_struct.type == DATA_TYPES.QWORD:
|
---|
530 | # 64 bit integers
|
---|
531 | ret_val = data_struct.interpreted.qword
|
---|
532 | elif data_struct.type == DATA_TYPES.MULTI_SZ:
|
---|
533 | ret_val = _charss2strlist(data_struct.interpreted.multiple_string)
|
---|
534 | elif data_struct.type in (DATA_TYPES.NONE, DATA_TYPES.RESOURCE_LIST,
|
---|
535 | DATA_TYPES.FULL_RESOURCE_DESCRIPTOR,
|
---|
536 | DATA_TYPES.RESOURCE_REQUIREMENTS_LIST,
|
---|
537 | DATA_TYPES.BINARY):
|
---|
538 | ret_val = _buffer2bytearray(data_struct.interpreted.none,
|
---|
539 | data_struct.interpreted_size)
|
---|
540 |
|
---|
541 | regfi.regfi_free_record(data_p)
|
---|
542 | return ret_val
|
---|
543 |
|
---|
544 |
|
---|
545 | ## Retrieves raw representation of Value's data
|
---|
546 | #
|
---|
547 | # @return A bytearray containing the data
|
---|
548 | #
|
---|
549 | def fetch_raw_data(self):
|
---|
550 | ret_val = None
|
---|
551 | # XXX: should we load the data without interpretation instead?
|
---|
552 | data_p = regfi.regfi_fetch_data(self._hive.file, self._base)
|
---|
553 | if not data_p:
|
---|
554 | return None
|
---|
555 |
|
---|
556 | data_struct = data_p.contents
|
---|
557 | ret_val = _buffer2bytearray(data_struct.raw,
|
---|
558 | data_struct.size)
|
---|
559 | regfi.regfi_free_record(data_p)
|
---|
560 | return ret_val
|
---|
561 |
|
---|
562 |
|
---|
563 | def __getattr__(self, name):
|
---|
564 | ret_val = super(Value, self).__getattr__(name)
|
---|
565 | if name == "name":
|
---|
566 | if ret_val == None:
|
---|
567 | ret_val = self.name_raw
|
---|
568 | else:
|
---|
569 | ret_val = ret_val.decode('utf-8', 'replace')
|
---|
570 |
|
---|
571 | elif name == "name_raw":
|
---|
572 | length = super(Value, self).__getattr__('name_length')
|
---|
573 | ret_val = _buffer2bytearray(ret_val, length)
|
---|
574 |
|
---|
575 | return ret_val
|
---|
576 |
|
---|
577 |
|
---|
578 | # Avoids chicken/egg class definitions.
|
---|
579 | # Also makes for convenient code reuse in these lists' parent classes.
|
---|
580 | SubkeyList._constructor = Key
|
---|
581 | ValueList._constructor = Value
|
---|
582 |
|
---|
583 |
|
---|
584 |
|
---|
585 | ## Represents a single registry hive (file)
|
---|
586 | class Hive():
|
---|
587 | file = None
|
---|
588 | raw_file = None
|
---|
589 | _root = None
|
---|
590 |
|
---|
591 | ## The root Key of this Hive
|
---|
592 | root = None
|
---|
593 |
|
---|
594 | ## This Hives's last modified time represented as the number of seconds
|
---|
595 | # since the UNIX epoch in UTC; similar to what time.time() returns
|
---|
596 | modified = 1300000000.123456
|
---|
597 |
|
---|
598 | ## First sequence number
|
---|
599 | sequence1 = 12345678
|
---|
600 |
|
---|
601 | ## Second sequence number
|
---|
602 | sequence2 = 12345678
|
---|
603 |
|
---|
604 | ## Major version
|
---|
605 | major_version = 1
|
---|
606 |
|
---|
607 | ## Minor version
|
---|
608 | minor_version = 5
|
---|
609 |
|
---|
610 | # XXX: Possibly add a second or factory function which opens a
|
---|
611 | # hive file for you
|
---|
612 |
|
---|
613 | ## Constructor
|
---|
614 | #
|
---|
615 | # @param fh A Python file object. The constructor first looks for a valid
|
---|
616 | # fileno attribute on this object and uses it if possible.
|
---|
617 | # Otherwise, the seek and read methods are used for file
|
---|
618 | # access.
|
---|
619 | #
|
---|
620 | # @note Supplied file must be seekable
|
---|
621 | def __init__(self, fh):
|
---|
622 | try:
|
---|
623 | # The fileno method may not exist, or it may throw an exception
|
---|
624 | # when called if the file isn't backed with a descriptor.
|
---|
625 | if hasattr(fh, 'fileno'):
|
---|
626 | self.file = regfi.regfi_alloc(fh.fileno(), REGFI_ENCODING_UTF8)
|
---|
627 | return
|
---|
628 | except:
|
---|
629 | pass
|
---|
630 |
|
---|
631 | self.raw_file = structures.REGFI_RAW_FILE()
|
---|
632 | self.raw_file.fh = fh
|
---|
633 | self.raw_file.seek = seek_cb_type(self.raw_file.cb_seek)
|
---|
634 | self.raw_file.read = read_cb_type(self.raw_file.cb_read)
|
---|
635 | self.file = regfi.regfi_alloc_cb(self.raw_file, REGFI_ENCODING_UTF8)
|
---|
636 |
|
---|
637 |
|
---|
638 | def __getattr__(self, name):
|
---|
639 | if name == "root":
|
---|
640 | if self._root == None:
|
---|
641 | self._root = Key(self, regfi.regfi_get_rootkey(self.file))
|
---|
642 | return self._root
|
---|
643 |
|
---|
644 | elif name == "modified":
|
---|
645 | return regfi.regfi_nt2unix_time(byref(self._base.contents.mtime))
|
---|
646 |
|
---|
647 | return getattr(self.file.contents, name)
|
---|
648 |
|
---|
649 |
|
---|
650 | def __del__(self):
|
---|
651 | regfi.regfi_free(self.file)
|
---|
652 | if self.raw_file != None:
|
---|
653 | self.raw_file = None
|
---|
654 |
|
---|
655 |
|
---|
656 | def __iter__(self):
|
---|
657 | return HiveIterator(self)
|
---|
658 |
|
---|
659 |
|
---|
660 | ## Creates a @ref HiveIterator initialized at the specified path in
|
---|
661 | # the hive.
|
---|
662 | #
|
---|
663 | # @param path A list of Key names which represent an absolute path within
|
---|
664 | # the Hive
|
---|
665 | #
|
---|
666 | # @return A @ref HiveIterator which is positioned at the specified path.
|
---|
667 | #
|
---|
668 | # @exception Exception If the path could not be found/traversed
|
---|
669 | def subtree(self, path):
|
---|
670 | hi = HiveIterator(self)
|
---|
671 | hi.descend(path)
|
---|
672 | return hi
|
---|
673 |
|
---|
674 |
|
---|
675 | ## A special purpose iterator for registry hives
|
---|
676 | #
|
---|
677 | # Iterating over an object of this type causes all keys in a specific
|
---|
678 | # hive subtree to be returned in a depth-first manner. These iterators
|
---|
679 | # are typically created using the @ref Hive.subtree() function on a @ref Hive
|
---|
680 | # object.
|
---|
681 | #
|
---|
682 | # HiveIterators can also be used to manually traverse up and down a
|
---|
683 | # registry hive as they retain information about the current position in
|
---|
684 | # the hive, along with which iteration state for subkeys and values for
|
---|
685 | # every parent key. See the @ref up and @ref down methods for more
|
---|
686 | # information.
|
---|
687 | class HiveIterator():
|
---|
688 | _hive = None
|
---|
689 | _iter = None
|
---|
690 | _iteration_root = None
|
---|
691 |
|
---|
692 | def __init__(self, hive):
|
---|
693 | self._iter = regfi.regfi_iterator_new(hive.file, REGFI_ENCODING_UTF8)
|
---|
694 | if self._iter == None:
|
---|
695 | raise Exception("Could not create iterator. Current log:\n"
|
---|
696 | + GetLogMessages())
|
---|
697 | self._hive = hive
|
---|
698 |
|
---|
699 | def __getattr__(self, name):
|
---|
700 | return getattr(self.file.contents, name)
|
---|
701 |
|
---|
702 | def __del__(self):
|
---|
703 | regfi.regfi_iterator_free(self._iter)
|
---|
704 |
|
---|
705 | def __iter__(self):
|
---|
706 | self._iteration_root = None
|
---|
707 | return self
|
---|
708 |
|
---|
709 | def __next__(self):
|
---|
710 | if self._iteration_root == None:
|
---|
711 | self._iteration_root = self.current_key()
|
---|
712 | elif not regfi.regfi_iterator_down(self._iter):
|
---|
713 | up_ret = regfi.regfi_iterator_up(self._iter)
|
---|
714 | while (up_ret and
|
---|
715 | not regfi.regfi_iterator_next_subkey(self._iter)):
|
---|
716 | if self._iteration_root == self.current_key():
|
---|
717 | self._iteration_root = None
|
---|
718 | raise StopIteration('')
|
---|
719 | up_ret = regfi.regfi_iterator_up(self._iter)
|
---|
720 |
|
---|
721 | if not up_ret:
|
---|
722 | self._iteration_root = None
|
---|
723 | raise StopIteration('')
|
---|
724 |
|
---|
725 | # XXX: Use non-generic exception
|
---|
726 | if not regfi.regfi_iterator_down(self._iter):
|
---|
727 | raise Exception('Error traversing iterator downward.'+
|
---|
728 | ' Current log:\n'+ GetLogMessages())
|
---|
729 |
|
---|
730 | regfi.regfi_iterator_first_subkey(self._iter)
|
---|
731 | return self.current_key()
|
---|
732 |
|
---|
733 | # For Python 2.x
|
---|
734 | next = __next__
|
---|
735 |
|
---|
736 | # XXX: Should add sanity checks on some of these traversal functions
|
---|
737 | # to throw exceptions if a traversal/retrieval *should* have worked
|
---|
738 | # but failed for some reason.
|
---|
739 |
|
---|
740 | ## Descends the iterator to a subkey
|
---|
741 | #
|
---|
742 | # Descends the iterator one level to the current subkey, or a subkey
|
---|
743 | # specified by name.
|
---|
744 | #
|
---|
745 | # @param subkey_name If specified, locates specified subkey by name
|
---|
746 | # (via find_subkey()) and descends to it.
|
---|
747 | #
|
---|
748 | # @return True if successful, False otherwise
|
---|
749 | def down(self, subkey_name=None):
|
---|
750 | if subkey_name == None:
|
---|
751 | return regfi.regfi_iterator_down(self._iter)
|
---|
752 | else:
|
---|
753 | if name != None:
|
---|
754 | name = name.encode('utf-8')
|
---|
755 | return (regfi.regfi_iterator_find_subkey(self._iter, name)
|
---|
756 | and regfi.regfi_iterator_down(self._iter))
|
---|
757 |
|
---|
758 |
|
---|
759 | ## Causes the iterator to ascend to the current Key's parent
|
---|
760 | #
|
---|
761 | # @return True if successful, False otherwise
|
---|
762 | #
|
---|
763 | # @note The state of current subkeys and values at this level in the tree
|
---|
764 | # is lost as a side effect. That is, if you go up() and then back
|
---|
765 | # down() again, current_subkey() and current_value() will return
|
---|
766 | # default selections.
|
---|
767 | def up(self):
|
---|
768 | return regfi.regfi_iterator_up(self._iter)
|
---|
769 |
|
---|
770 |
|
---|
771 | ## Selects first subkey of current key
|
---|
772 | #
|
---|
773 | # @return A Key instance for the first subkey.
|
---|
774 | # None on error or if the current key has no subkeys.
|
---|
775 | def first_subkey(self):
|
---|
776 | if regfi.regfi_iterator_first_subkey(self._iter):
|
---|
777 | return self.current_subkey()
|
---|
778 | return None
|
---|
779 |
|
---|
780 |
|
---|
781 | ## Selects first value of current Key
|
---|
782 | #
|
---|
783 | # @return A Value instance for the first value.
|
---|
784 | # None on error or if the current key has no values.
|
---|
785 | def first_value(self):
|
---|
786 | if regfi.regfi_iterator_first_value(self._iter):
|
---|
787 | return self.current_value()
|
---|
788 | return None
|
---|
789 |
|
---|
790 |
|
---|
791 | ## Selects the next subkey in the current Key's list
|
---|
792 | #
|
---|
793 | # @return A Key instance for the next subkey.
|
---|
794 | # None if there are no remaining subkeys or an error occurred.
|
---|
795 | def next_subkey(self):
|
---|
796 | if regfi.regfi_iterator_next_subkey(self._iter):
|
---|
797 | return self.current_subkey()
|
---|
798 | return None
|
---|
799 |
|
---|
800 |
|
---|
801 | ## Selects the next value in the current Key's list
|
---|
802 | #
|
---|
803 | # @return A Value instance for the next value.
|
---|
804 | # None if there are no remaining values or an error occurred.
|
---|
805 | def next_value(self):
|
---|
806 | if regfi.regfi_iterator_next_value(self._iter):
|
---|
807 | return self.current_value()
|
---|
808 | return None
|
---|
809 |
|
---|
810 |
|
---|
811 | ## Selects the first subkey which has the specified name
|
---|
812 | #
|
---|
813 | # @return A Key instance for the selected key.
|
---|
814 | # None if it could not be located or an error occurred.
|
---|
815 | def find_subkey(self, name):
|
---|
816 | if name != None:
|
---|
817 | name = name.encode('utf-8')
|
---|
818 | if regfi.regfi_iterator_find_subkey(self._iter, name):
|
---|
819 | return self.current_subkey()
|
---|
820 | return None
|
---|
821 |
|
---|
822 |
|
---|
823 | ## Selects the first value which has the specified name
|
---|
824 | #
|
---|
825 | # @return A Value instance for the selected value.
|
---|
826 | # None if it could not be located or an error occurred.
|
---|
827 | def find_value(self, name):
|
---|
828 | if name != None:
|
---|
829 | name = name.encode('utf-8')
|
---|
830 | if regfi.regfi_iterator_find_value(self._iter, name):
|
---|
831 | return self.current_value()
|
---|
832 | return None
|
---|
833 |
|
---|
834 | ## Retrieves the currently selected subkey
|
---|
835 | #
|
---|
836 | # @return A Key instance of the current subkey
|
---|
837 | def current_subkey(self):
|
---|
838 | return Key(self._hive, regfi.regfi_iterator_cur_subkey(self._iter))
|
---|
839 |
|
---|
840 | ## Retrieves the currently selected value
|
---|
841 | #
|
---|
842 | # @return A Value instance of the current value
|
---|
843 | def current_value(self):
|
---|
844 | return Value(self._hive, regfi.regfi_iterator_cur_value(self._iter))
|
---|
845 |
|
---|
846 | ## Retrieves the current key
|
---|
847 | #
|
---|
848 | # @return A Key instance of the current position of the iterator
|
---|
849 | def current_key(self):
|
---|
850 | return Key(self._hive, regfi.regfi_iterator_cur_key(self._iter))
|
---|
851 |
|
---|
852 |
|
---|
853 | ## Traverse downward multiple levels
|
---|
854 | #
|
---|
855 | # This is more efficient than calling down() multiple times
|
---|
856 | #
|
---|
857 | # @param path A list of Key names which represent the path to descend
|
---|
858 | #
|
---|
859 | # @exception Exception If path could not be located
|
---|
860 | def descend(self, path):
|
---|
861 | cpath = _strlist2charss(path)
|
---|
862 |
|
---|
863 | # XXX: Use non-generic exception
|
---|
864 | if not regfi.regfi_iterator_walk_path(self._iter, cpath):
|
---|
865 | raise Exception('Could not locate path.\n'+GetLogMessages())
|
---|
866 |
|
---|
867 |
|
---|
868 | # Freeing symbols defined for the sake of documentation
|
---|
869 | del Value.name,Value.name_raw,Value.offset,Value.data_size,Value.type,Value.flags
|
---|
870 | del Key.name,Key.name_raw,Key.offset,Key.modified,Key.flags
|
---|
871 | del Hive.root,Hive.modified,Hive.sequence1,Hive.sequence2,Hive.major_version,Hive.minor_version
|
---|