This repository has been archived by the owner on Mar 31, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
main_gui.py
556 lines (477 loc) · 21.9 KB
/
main_gui.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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
try:
import Tkinter as tk
import ttk
from tkFileDialog import askopenfilename, askdirectory
import tkMessageBox
except ImportError:
import tkinter as tk
from tkinter import ttk
from tkinter.filedialog import askopenfilename, askdirectory
import tkinter.messagebox
from fatx.drive.drive import FatXDrive, x_signatures, x360_signatures
from fatx.analysis.metadata_analyzer import FatXAnalyzer
from fatx.analysis.file_carver import FatXCarver
import os
import sys
import threading
import time
import logging
import argparse
LOG = logging.getLogger("FATX")
class DrivePanel(ttk.Frame):
def __init__(self, master):
ttk.Frame.__init__(self, master)
self.master = master
self.drive_nodes = {} # TreeView nodes that have drives
self.partition_nodes = {} # TreeView nodes that have partitions
self.progress_bar = ttk.Progressbar(self, orient='horizontal',
mode='determinate')
self.progress_bar.pack(side=tk.BOTTOM, fill=tk.X)
self.progress_label_text = tk.StringVar()
self.progress_label = ttk.Label(self, textvariable=self.progress_label_text)
self.progress_label.pack(side=tk.BOTTOM, fill=tk.X)
self.thread = None
self.analyzer = None
self.timer0 = None
self.timer1 = None
self.pack()
tree_columns = ('filesize', 'attr', 'cdate', 'mdate', 'adate')
self.tree = ttk.Treeview(self, columns=tree_columns)
self.tree.heading('#0', text='Drive Contents')
self.tree.column('#0', minwidth=100)
self.tree.pack(side=tk.LEFT, expand=True, fill=tk.BOTH)
self.tree.bind("<ButtonRelease-3>", self.open_context_menu)
# self.tree.heading('cluster', text='Cluster')
self.tree.heading('filesize', text='File Size')
self.tree.heading('attr', text='Attributes')
self.tree.heading('cdate', text='Date Created')
self.tree.heading('mdate', text='Date Modified')
self.tree.heading('adate', text='Date Accessed')
scroll_y = tk.Scrollbar(self.tree, orient=tk.VERTICAL)
self.tree.configure(yscrollcommand=scroll_y.set)
scroll_y.config(command=self.tree.yview)
scroll_y.pack(side=tk.RIGHT, fill=tk.Y)
self.context_menu = tk.Menu(self, tearoff=0)
self.context_menu.add_command(label='Recover File System..',
command=self.recover_partition)
self.context_menu.add_command(label='Perform Orphan Analysis',
command=self.run_orphan_scanner)
self.context_menu.add_command(label='Perform Signature Analysis',
command=self.run_signature_scanner)
self.context_menu.add_separator()
self.context_menu.add_command(label='Expand Partition',
command=self.expand_all)
self.context_menu.add_command(label='Collapse Partition',
command=self.collapse_all)
def expand_all(self):
def expand_node(node):
for child in self.tree.get_children(node):
self.tree.item(child, open=True)
expand_node(child)
partition_node = self.tree.selection()[0]
self.tree.item(partition_node, open=True)
expand_node(partition_node)
def collapse_all(self):
def collapse_node(node):
for child in self.tree.get_children(node):
self.tree.item(child, open=False)
collapse_node(child)
partition_node = self.tree.selection()[0]
self.tree.item(partition_node, open=False)
collapse_node(partition_node)
def recover_progress(self):
file_name = self.thread.current_file[1]
label_text = 'Recovering: {}'.format(file_name)
self.progress_label_text.set(label_text)
self.progress_bar['value'] = self.thread.current_file[0]
if self.thread.is_alive():
self.after(100, self.recover_progress)
else:
self.progress_label_text.set('')
self.progress_bar['value'] = 0
self.timer1 = time.time()
print('Dump completed in {} seconds'.format(self.timer1 - self.timer0))
self.master.bell()
class RecoverPartition(threading.Thread):
def __init__(self, partition, directory):
threading.Thread.__init__(self)
self.partition = partition
self.directory = directory
self.current_file = (0, '')
def run(self):
for x, dirent in enumerate(self.partition.get_root()):
self.current_file = (x, dirent.file_name)
dirent.recover(self.directory)
def recover_partition(self):
if self.thread is not None and self.thread.is_alive():
tkMessageBox.showerror("Error", "Please wait for analysis to finish.")
return
# TODO: selection() returns all selected. Support this.
partition_node = self.tree.selection()[0]
partition = self.partition_nodes[partition_node]
directory = askdirectory()
if directory == '':
return
self.thread = self.RecoverPartition(partition, directory)
self.progress_bar['maximum'] = len(partition.get_root())
self.timer0 = time.time()
self.thread.start()
self.recover_progress()
def orphan_scanner_progress(self):
cluster = self.analyzer.current_block
label_text = "Cluster {}/{}".format(cluster, self.progress_bar['maximum'])
self.progress_label_text.set(label_text)
self.progress_bar['value'] = cluster
if self.thread.is_alive():
self.after(100, self.orphan_scanner_progress)
else:
# self.tree.configure(state='normal')
self.progress_label_text.set('')
self.progress_bar['value'] = 0
self.timer1 = time.time()
print('analysis completed in {} seconds.'.format(self.timer1 - self.timer0))
self.master.bell()
panel = RecoverPanel(self.master, 0)
self.master.add(panel, text='Analysis results')
orphans = self.analyzer.get_roots()
panel.add_orphans(orphans)
class OrphanScanner(threading.Thread):
def __init__(self, analyzer):
threading.Thread.__init__(self)
self.analyzer = analyzer
def run(self):
self.analyzer.perform_orphan_analysis()
self.analyzer.save_roots('data')
def run_orphan_scanner(self):
if self.thread is not None and self.thread.is_alive():
tkMessageBox.showerror("Error", "Please wait for analysis to finish.")
return
partition_node = self.tree.selection()[0]
partition = self.partition_nodes[partition_node]
self.analyzer = FatXAnalyzer(partition)
self.thread = self.OrphanScanner(self.analyzer)
self.progress_bar['maximum'] = self.analyzer.volume.max_clusters
# self.tree.state(('disabled',))
self.timer0 = time.time()
self.thread.start()
self.orphan_scanner_progress()
pass
def signature_scanner_progress(self):
cluster = self.analyzer.current_block
label_text = "Block {}/{}".format(cluster, self.progress_bar['maximum'])
self.progress_label_text.set(label_text)
self.progress_bar['value'] = cluster
if self.thread.is_alive():
self.after(100, self.signature_scanner_progress)
else:
# self.tree.configure(state='normal')
self.progress_label_text.set('')
self.progress_bar['value'] = 0
self.timer1 = time.time()
print('analysis completed in {} seconds.'.format(self.timer1 - self.timer0))
self.master.bell()
panel = RecoverPanel(self.master, 1)
self.master.add(panel, text='Analysis results')
orphans = self.analyzer.get_valid_sigs()
panel.add_entries(orphans)
class SignatureScanner(threading.Thread):
def __init__(self, analyzer, signatures, interval=0x200, length=0):
threading.Thread.__init__(self)
self.analyzer = analyzer
self.signatures = signatures
self.interval = interval
self.length = length
def run(self):
self.analyzer.perform_signature_analysis(signatures=self.signatures,
interval=self.interval,
length=self.length)
def run_signature_scanner(self):
if self.thread is not None and self.thread.is_alive():
tkMessageBox.showerror("Error", "Please wait for analysis to finish.")
return
partition_node = self.tree.selection()[0]
partition = self.partition_nodes[partition_node]
self.analyzer = FatXCarver(partition)
# TODO: this is nasty, don't do this
signatures = x360_signatures if self.analyzer.volume.endian_fmt == '>' else x_signatures
self.thread = self.SignatureScanner(self.analyzer, signatures=signatures)
self.progress_bar['maximum'] = self.analyzer.volume.length / 0x200 # TODO: analyzer.get_interval()
self.timer0 = time.time()
self.thread.start()
self.signature_scanner_progress()
pass
def open_context_menu(self, event):
item = self.tree.identify('row', event.x, event.y)
self.tree.selection_set(item)
self.tree.focus(item)
if item in self.partition_nodes:
try:
self.context_menu.tk_popup(event.x_root, event.y_root, 0)
finally:
self.context_menu.grab_release()
return
def add_drive(self, path):
# close this file upon termination
# or when drive is closed.
# file handle is needed for performing work.
infile = open(path, 'rb')
drive = FatXDrive(infile)
# insert entry for this drive
file_name = os.path.basename(path)
drive_root = self.tree.insert('', tk.END, text=file_name)
for index, partition in enumerate(drive.partitions):
partition_name = partition.name + \
' (Offset={:#x} Length={:#x})'.format(partition.offset, partition.length)
partition_root = self.tree.insert(drive_root, tk.END, text=partition_name)
try:
partition.mount()
self.populate_directory(partition_root, partition.get_root())
self.partition_nodes[partition_root] = partition
except Exception as e:
print(e)
self.drive_nodes[drive_root] = drive
@staticmethod
def format_attributes(attr):
attr_str = ''
if attr & 0x1:
attr_str += 'RO '
if attr & 0x2:
attr_str += 'HDN '
if attr & 0x4:
attr_str += 'SYS'
if attr & 0x10:
attr_str += 'DIR'
if attr & 0x20:
attr_str += 'ARC'
if attr & 0x40:
attr_str += 'DEV'
if attr & 0x80:
attr_str += 'NML'
return attr_str
def populate_directory(self, tree_root, stream):
for dirent in stream:
if dirent.is_deleted():
file_name = '[DELETED] {}'.format(dirent.file_name)
else:
file_name = dirent.file_name
if dirent.is_directory():
if len(dirent.children) == 256:
print('WARN: %s has max files' % dirent.get_full_path())
dir_root = self.tree.insert(tree_root, tk.END, text=file_name,
values=('', self.format_attributes(dirent.file_attributes),
str(dirent.creation_time),
str(dirent.last_write_time),
str(dirent.last_access_time)))
self.populate_directory(dir_root, dirent.children)
else:
self.tree.insert(tree_root, tk.END, text=file_name,
values=('{} bytes'.format(dirent.file_size),
self.format_attributes(dirent.file_attributes),
str(dirent.creation_time),
str(dirent.last_write_time),
str(dirent.last_access_time)))
class RecoverPanel(ttk.Frame):
def __init__(self, master, mode):
ttk.Frame.__init__(self, master)
self.master = master
self.mode = mode
self.pack()
# Add offset
tree_columns = ('cluster', 'filesize', 'cdate', 'mdate', 'adate')
self.tree = ttk.Treeview(self, columns=tree_columns)
self.tree.heading('#0', text='File Name')
self.tree.heading('cluster', text='Cluster')
self.tree.heading('filesize', text='File Size')
self.tree.heading('cdate', text='Date Created')
self.tree.heading('mdate', text='Date Modified')
self.tree.heading('adate', text='Date Accessed')
column_width = 170
self.tree.column('filesize', minwidth=column_width, width=column_width, stretch=False)
self.tree.column('cdate', minwidth=column_width, width=column_width, stretch=False)
self.tree.column('mdate', minwidth=column_width, width=column_width, stretch=False)
self.tree.column('adate', minwidth=column_width, width=column_width, stretch=False)
self.tree.pack(side=tk.LEFT, expand=True, fill=tk.BOTH)
self.tree.bind("<ButtonRelease-3>", self.open_context_menu)
scroll_y = tk.Scrollbar(self.tree, orient=tk.VERTICAL)
self.tree.configure(yscrollcommand=scroll_y.set)
scroll_y.config(command=self.tree.yview)
scroll_y.pack(side=tk.RIGHT, fill=tk.Y)
self.context_menu = tk.Menu(self, tearoff=0)
self.context_menu.add_command(label='Recover this node..', command=self.recover_orphan) # recover file or folder
self.context_menu.add_command(label='Recover all..', command=self.recover_all)
# self.context_menu.add_command(label='Save to database', command=self.save_database)
self.context_menu.add_separator()
self.context_menu.add_command(label='Expand all', command=self.expand_all)
self.context_menu.add_command(label='Collapse all', command=self.collapse_all)
self.orphan_nodes = {}
def recover_cluster(self, item, path):
for child_item in self.tree.get_children(item):
dirent = self.orphan_nodes[child_item]
dirent.recover(path)
def recover_all(self):
directory = askdirectory()
if directory == '':
return
if self.mode == 0:
for cluster_item in self.tree.get_children():
# create directory for this cluster
# cluster_item is same as text
cluster_path = directory + '/' + cluster_item
if not os.path.exists(cluster_path):
os.mkdir(cluster_path)
self.recover_cluster(cluster_item, cluster_path)
elif self.mode == 1:
for item in self.tree.get_children():
dirent = self.orphan_nodes[item]
dirent.recover(directory)
self.master.bell()
def recover_orphan(self):
item = self.tree.selection()[0]
dirent = self.orphan_nodes[item]
directory = askdirectory()
if directory == '':
return
if dirent is None:
# this is a cluster node
self.recover_cluster(item, directory)
else:
# this is a file or directory
dirent.recover(directory)
self.master.bell()
def expand_all(self):
def expand_node(node):
for child in self.tree.get_children(node):
self.tree.item(child, open=True)
expand_node(child)
for root in self.tree.get_children():
expand_node(root)
def collapse_all(self):
def collapse_node(node):
for child in self.tree.get_children(node):
self.tree.item(child, open=False)
collapse_node(child)
for root in self.tree.get_children():
self.tree.item(root, open=False)
def open_context_menu(self, event):
item = self.tree.identify('item', event.x, event.y)
self.tree.selection_set(item)
self.tree.focus(item)
try:
self.context_menu.tk_popup(event.x_root, event.y_root, 0)
finally:
self.context_menu.grab_release()
# we know which item it is, now grab the file info and dump
def add_children(self, children, root_node=''):
for child in children:
if child.is_directory():
if len(child.children) == 256:
print('WARN: directory %s contains max files' % child.get_full_path())
orphan_node = self.tree.insert(root_node, tk.END, text=child.file_name,
values=(child.cluster, '',
str(child.creation_time),
str(child.last_write_time),
str(child.last_access_time)))
self.add_children(child.children, orphan_node)
else:
orphan_node = self.tree.insert(root_node, tk.END, text=child.file_name,
values=(child.cluster,
'{} bytes'.format(child.file_size),
str(child.creation_time),
str(child.last_write_time),
str(child.last_access_time)))
self.orphan_nodes[orphan_node] = child
def add_orphans(self, roots):
self.tree.delete(*self.tree.get_children())
# add RootX for each of same cluster?
for root in roots:
cluster_node = 'Cluster' + str(root.cluster)
if not self.tree.exists(cluster_node):
cluster_node = self.tree.insert('', tk.END, iid=cluster_node, text=cluster_node)
self.orphan_nodes[cluster_node] = None
if root.is_directory():
root_node = self.tree.insert(cluster_node, tk.END, text=root.file_name,
values=(root.cluster,))
self.add_children(root.children, root_node)
else:
root_node = self.tree.insert(cluster_node, tk.END, text=root.file_name,
values=(root.cluster,
'{} bytes'.format(root.file_size),
str(root.creation_time),
str(root.last_write_time),
str(root.last_access_time)))
self.orphan_nodes[root_node] = root
def add_entries(self, sign_entries):
self.tree.delete(*self.tree.get_children())
for entry in sign_entries:
byte_size = '%d bytes' % entry.length
entry_node = self.tree.insert('', tk.END, text=entry.get_file_name(), values=(byte_size, ''))
self.orphan_nodes[entry_node] = entry
class MainFrame(ttk.Frame):
def __init__(self, master):
ttk.Frame.__init__(self, master, width=1080, height=720)
self.pack(expand=True, fill=tk.BOTH)
self.master = master
# style = ttk.Style()
# style.theme_use('clam')
self.menu = tk.Menu(self.master)
self.master.config(menu=self.menu)
self.file_menu = tk.Menu(self.menu, tearoff=0)
self.help_menu = tk.Menu(self.menu, tearoff=0)
self.menu.add_cascade(label='File', menu=self.file_menu)
self.menu.add_cascade(label='Help', menu=self.help_menu)
self.file_menu.add_command(label="Open..", command=self.open_image)
self.file_menu.add_command(label="Exit", command=self.master.quit)
self.help_menu.add_command(label="About..")
self.notebook = ttk.Notebook(self)
self.notebook.pack(fill=tk.BOTH, expand=True)
self.drive_tab = DrivePanel(self.notebook)
self.notebook.add(self.drive_tab, text='Drives')
def open_image(self, file_name=''):
if file_name == '':
file_name = askopenfilename()
if file_name == '':
return
self.drive_tab.add_drive(file_name)
def main():
root = tk.Tk()
frame = MainFrame(root)
# if len(sys.argv) > 1:
# frame.open_image(sys.argv[1])
root.title('FatX-Recover')
root.minsize(1200, 720)
'''
root.wm_title("FatX-Recover")
# set background color
root['bg'] = 'grey'
s = ttk.Style()
print s.theme_names()
s.theme_use('vista')
# fieldbackground = actual background
# background = background of nodes
# foreground = text color
s.configure('Treeview',
background='black',
foreground='white',
fieldbackground='black',
selectbackground='green')
s.configure('Treeview.Heading', background='grey',
foreground='white',
relief='flat')
'''
root.mainloop()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='GUI for fatx-tools.')
parser.add_argument("-v", "--verbose", help="Verbose.", action='store_true')
args = parser.parse_args()
_stream = logging.StreamHandler(sys.stdout)
_stream.setLevel(logging.INFO)
_stream.setFormatter(logging.Formatter('%(levelname).4s: %(message)s'))
if args.verbose:
_file = logging.FileHandler("log.txt", "w", "utf-8")
_file.setLevel(logging.DEBUG)
_file.setFormatter(
logging.Formatter('%(module)s::%(funcName)s::%(lineno)d %(levelname).4s %(asctime)s - %(message)s'))
LOG.setLevel(logging.DEBUG)
LOG.addHandler(_file)
LOG.addHandler(_stream)
main()