-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathshellbags.py
executable file
·292 lines (253 loc) · 10.4 KB
/
shellbags.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
291
292
#!/usr/bin/python
# This file is part of shellbags.py
#
# Copyright 2011 Will Ballenthin <[email protected]>
# while at Mandiant <http://www.mandiant.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re
import sys
import csv
import logging
import datetime
import argparse
import calendar
from Registry import Registry
from BinaryParser import OverrunBufferException
from ShellItems import SHITEMLIST
g_logger = logging.getLogger("shellbags")
def date_safe(d):
"""
From a Python datetime object, return a corresponding Unix timestamp
or the epoch timestamp if the datetime object doesn't make sense
Arguments:
- `d`: A Python datetime object
Throws:
"""
try:
return int(calendar.timegm(d.timetuple()))
except (ValueError, OverflowError):
return int(calendar.timegm(datetime.datetime(1970, 1, 1, 0, 0, 0).timetuple()))
def date_safe_str(d):
try:
return d.strftime("%m/%d/%Y %H:%M:%S")
except:
return "01/01/1970 00:00:00"
################ CLASS DEFINITIONS #############v
class ShellbagException(Exception):
"""
Base Exception class for shellbag parsing.
"""
def __init__(self, value):
"""
Constructor.
Arguments:
- `value`: A string description.
"""
super(ShellbagException, self).__init__()
self._value = value
def __str__(self):
return str(unicode(self))
def __unicode__(self):
return u"Shellbag Exception: %s" % (self._value)
################ PROGRAM FUNCTIONS #############
def get_shellbags(shell_key):
"""
Given a python-registry RegistryKey object, look for and return a
list of shellbag items. A shellbag item is a dict with the keys
(mtime, atime, crtime, path).
Arguments:
- `shell_key`: A python-registry Registry object.
Throws:
"""
shellbags = []
bagmru_key = shell_key.subkey("BagMRU")
bags_key = shell_key.subkey("Bags")
def shellbag_rec(key, bag_prefix, path_prefix):
"""
Function to recursively parse the BagMRU Registry key structure.
Arguments:
`key`: The current 'BagsMRU' key to recurse into.
`bag_prefix`: A string containing the current subkey path of
the relevant 'Bags' key. It will look something like '1\\2\\3\\4'.
`path_prefix` A string containing the current human-readable,
file system path so far constructed.
Throws:
"""
try:
# First, consider the current key, and extract shellbag items
slot = key.value("NodeSlot").value()
for bag in bags_key.subkey(str(slot)).subkeys():
for value in [value for value in bag.values() if
"ItemPos" in value.name()]:
buf = value.value()
block = SHITEMLIST(buf, 0x0, False)
offset = 0x10
while True:
offset += 0x8
size = block.unpack_word(offset)
if size == 0:
break
elif size < 0x15:
pass
else:
item = block.get_item(offset)
shellbags.append({
"path": path_prefix + "\\" + item.name(),
"mtime": item.m_date(),
"atime": item.a_date(),
"crtime": item.cr_date(),
"source": bag.path() + " @ " + hex(item.offset()),
"regsource": bag.path() + "\\" + value.name(),
"klwt": key.timestamp()
})
offset += size
except Registry.RegistryValueNotFoundException:
g_logger.warning("Registry.RegistryValueNotFoundException")
pass
except Registry.RegistryKeyNotFoundException:
g_logger.warning("Registry.RegistryKeyNotFoundException")
pass
except:
g_logger.warning("Unexpected error %s" % sys.exc_info()[0])
# Next, recurse into each BagMRU key
for value in [value for value in key.values()
if re.match("\d+", value.name())]:
path = ""
try: # TODO(wb): removeme
l = SHITEMLIST(value.value(), 0, False)
for item in l.items():
# assume there is only one entry in the value, or take the last
# as the path component
path = path_prefix + "\\" + item.name()
shellbags.append({
"path": path,
"mtime": item.m_date(),
"atime": item.a_date(),
"crtime": item.cr_date(),
"source": key.path() + " @ " + hex(item.offset()),
"regsource": key.path() + "\\" + value.name(),
"klwt": key.timestamp()
})
except OverrunBufferException:
print key.path()
print value.name()
raise
shellbag_rec(key.subkey(value.name()),
bag_prefix + "\\" + value.name(),
path)
shellbag_rec(bagmru_key, "", "")
return shellbags
def get_all_shellbags(reg):
"""
Given a python-registry Registry object, look for and return a
list of shellbag items. A shellbag item is a dict with the keys
(mtime, atime, crtime, path).
Arguments:
- `reg`: A python-registry Registry object.
Throws:
"""
shellbags = []
paths = [
# xp
"Software\\Microsoft\\Windows\\Shell",
"Software\\Microsoft\\Windows\\ShellNoRoam",
# win7
"Local Settings\\Software\\Microsoft\\Windows\\ShellNoRoam",
"Local Settings\\Software\\Microsoft\\Windows\\Shell",
]
for path in paths:
try:
shell_key = reg.open(path)
new = get_shellbags(shell_key)
shellbags.extend(new)
except Registry.RegistryKeyNotFoundException:
pass
except Exception:
g_logger.exception("Unhandled exception while parsing %s" % path)
return shellbags
def print_shellbag_csv(shellbags, regfile):
stdoutWriter = csv.writer(sys.stdout)
stdoutWriter.writerow(["Key Last Write Time", "Hive",
"Modification Date", "Accessed Date",
"Creation Date", "Path", "Key"])
for shellbag in shellbags:
modified = date_safe_str(shellbag["mtime"])
accessed = date_safe_str(shellbag["atime"])
created = date_safe_str(shellbag["crtime"])
keymod = date_safe_str(shellbag["klwt"])
try:
stdoutWriter.writerow([keymod, regfile, modified,
accessed, created,
shellbag["path"], shellbag["regsource"]])
except:
stdoutWriter.writerow([keymod, regfile, modified,
accessed, created, "Unprintable Shellbag",
shellbag["regsource"]])
def print_shellbag_bodyfile(m, a, cr, path, fail_note=None):
"""
Given the MAC timestamps and a path, print a Bodyfile v3 string entry
formatted with the data. We print instead of returning so we can handle
cases where the implicit string encoding conversion takes place as
things are written to STDOUT.
Arguments:
- `m`: A Python datetime object representing the modified date.
- `a`: A Python datetime object representing the accessed date.
- `cr`: A Python datetime object representing the created date.
- `path`: A string with the entry path.
- `fail_note`: An alternate path to print if an encoding error
is encountered.
Throws:
"""
modified = date_safe(m)
accessed = date_safe(a)
created = date_safe(cr)
changed = int(calendar.timegm(datetime.datetime.min.timetuple()))
try:
print u"0|%s (Shellbag)|0|0|0|0|0|%s|%s|%s|%s" % \
(path, modified, accessed, changed, created)
except UnicodeDecodeError:
print u"0|%s (Shellbag)|0|0|0|0|0|%s|%s|%s|%s" % \
(fail_note, modified, accessed, changed, created)
except UnicodeEncodeError:
print u"0|%s (Shellbag)|0|0|0|0|0|%s|%s|%s|%s" % \
(fail_note, modified, accessed, changed, created)
################ MAIN #############
def main(argv=None):
if argv is None:
argv = sys.argv
parser = argparse.ArgumentParser(description="Parse Shellbag entries from a Windows Registry.")
parser.add_argument("-v", action="store_true", dest="vverbose",
help="Print debugging information while parsing")
parser.add_argument("file", nargs="+",
help="Windows Registry hive file(s)")
parser.add_argument("-o", choices=["csv", "bodyfile"],
dest="fmt", default="bodyfile",
help="Output format: csv or bodyfile; default is bodyfile")
args = parser.parse_args(argv[1:])
for f in args.file:
registry = Registry.Registry(f)
parsed_shellbags = get_all_shellbags(registry)
if args.fmt == "csv":
print_shellbag_csv(parsed_shellbags, f)
elif args.fmt == "bodyfile":
for shellbag in parsed_shellbags:
print_shellbag_bodyfile(shellbag["mtime"],
shellbag["atime"],
shellbag["crtime"],
shellbag["path"],
fail_note="Failed to parse entry name from: " + shellbag["source"])
else:
print "Error: Unsupported output format"
if __name__ == "__main__":
main(argv=sys.argv)