Blame view

digger.py 7.4 KB
1
2
#! /usr/bin/env python3
3
4
5
6
7
8
import sys

sys.path.append('modules')
sys.path.append('vars')
sys.path.append('logger')
9
import time
10
11
12
13
14
import locale
from dialog import Dialog
import glob
import os
import subprocess as sp
Imanol-Mikel Barba Sabariego authored
15
import tomb
16
import traceback
17
18
19
import logger
from consolelogger import ConsoleLogger
from filelogger import FileLogger
20
from hashlib import sha256
root authored
21
import bonetypes
22
import xml.etree.ElementTree
root authored
23
import binascii
24
25
26
27
28
29
30
31
32
33
34

def getModules():
    choiceList = []
    modules = []
    for filename in glob.glob('./modules/*.py'):
        modules.append(os.path.splitext(os.path.basename(filename))[0])
    modules.remove('__init__')

    for modname in modules:
        try:
            module = __import__(modname)
35
            instance = module.getInstance()
36
37
38
39
40
            choiceList.append((instance.name,instance.description,False))
            del instance
            del module
            sys.modules.pop(modname)
        except Exception as e:
Imanol-Mikel Barba Sabariego authored
41
            logger.msgLog("Exception raised while importing " + modname + ": " + str(e),"digger",logger.TYPE_ERROR)
42
43
44
    return choiceList

def prepareModule(moduleName):
45
46
47
48
49
    try:
        module = __import__(moduleName).getInstance()
        module.getVars()
        return module
    except Exception as e:
50
51
        raise
52
53
54
55
56
57
58
59
def sha256sum(file):
    f = open(file, 'rb')
    result = sha256(f.read()).hexdigest()
    f.close()
    return result

def bagAndTag():
    tombPath = tomb.getPath()
60
    if os.path.isfile(tombPath + "MANIFEST.XML"):
root authored
61
62
        etree = xml.etree.ElementTree.parse(tombPath + "MANIFEST.XML")
        xmlroot = etree.getroot()
63
    else:
root authored
64
65
66
67
68
69
        xmlroot = xml.etree.ElementTree.Element("Manifest")
        newElem = xml.etree.ElementTree.Element("Case")
        newElem.text = tomb.__getTomb__()
        xmlroot.insert(0,newElem)
        xmlroot.insert(1,xml.etree.ElementTree.Element("EvidenceList"))
        etree = xml.etree.ElementTree.ElementTree(xmlroot)
70
71
72
    boneList = []
73
74
75
76
    for root, dirnames, filenames in os.walk(tombPath):
        for dir in dirnames:
            for subroot, subdirnames, subfilenames in os.walk(tombPath + dir):
                for filename in subfilenames:
root authored
77
                    boneList.append({"path" : subroot + "/" + filename, "type": bonetypes.definitions[dir]})
78
79
80

    d.gauge_start(title="Hashing all collected artifacts...",width=60,height=10)
    boneCount = 0
root authored
81
    evidenceList = xmlroot.find("EvidenceList")
82
    for bone in boneList:
root authored
83
84
        relpath = bone["path"][len(tombPath):]
        if evidenceList.find("./Evidence[@path='" + relpath + "']") != None:
85
            continue
root authored
86
87
        hash = sha256sum(bone["path"])
        date = str(int(os.path.getmtime(bone["path"])*1000))
root authored
88
        evidenceList.insert(len(evidenceList),xml.etree.ElementTree.Element("Evidence", hash=hash,path=relpath,type=bone["type"],date=date))
root authored
89
        d.gauge_update(text=bone["path"],percent=int(boneCount*100/len(boneList)),update_text=True)
90
91
92
        boneCount += 1
    d.gauge_update(text="Complete!",percent=100,update_text=True)
    time.sleep(1)
root authored
93
    etree.write(tombPath + "MANIFEST.XML")
94
95
96

def finish(allSuccessful):
    bagAndTag()
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
    msg = ""
    if(allSuccessful):
        msg = "All modules finished execution"
    else:
        msg = "Some or all modules failed execution. Please check the logs."

    code, tag = d.menu(msg, choices=[("Poweroff", "Shutdown the computer"),
                                     ("Reboot", "Reboot the computer"),
                                     ("Restart", "Run Gravedigger again")])
    if (code == d.OK):
        if tag == "Poweroff":
            sp.call("poweroff", shell=True)
        elif tag == "Reboot":
            sp.call("reboot", shell=True)
112
    logger.msgLog("Finished excavation of tomb: " + tomb.getPath(),"digger",logger.TYPE_INFO)
113
114
115
    exit(0)

def showContinueDialog(d,msg):
116
117
118
119
120
121
    code, tag = d.menu(msg + "\n\nDo you want to retry module configuration or continue execution without the module?",
                       choices=[("retry", "Retry configuration"),
                                ("continue", "Continue without module")])
    if code != d.OK:
        return "abort"
    return tag
122
123
124
125
126
127

if __name__ == "__main__":
    locale.setlocale(locale.LC_ALL, '')
    d = Dialog(dialog="dialog",autowidgetsize=True)
    d.set_background_title("Gravedigger")
    code,value = d.inputbox("Input computer's name")
Imanol-Mikel Barba Sabariego authored
128
    if code == d.OK:
129
130
131
        tomb._MACHINE_NAME= value
        logger.logSystems.append(ConsoleLogger())
        logger.logSystems.append(FileLogger(tomb.getPath() + "log.txt"))
132
        logger.msgLog("Beginning excavation of tomb: " + tomb.getPath(),"digger",logger.TYPE_INFO)
Imanol-Mikel Barba Sabariego authored
133
        moduleList = getModules()
134
135
136
137
138
139
        d.set_background_title("Gravedigger - " + value)
        code, tags = d.checklist("Select modules to execute",
                             choices=moduleList + [("all","Execute all modules",False)],
                             title="Module selection")
        if code == d.OK:
            runlist = []
Imanol-Mikel Barba Sabariego authored
140
            if "all" in tags:
141
                logger.msgLog("Selected modules: " + repr(moduleList), "digger", logger.TYPE_INFO)
Imanol-Mikel Barba Sabariego authored
142
                for module in moduleList:
143
144
145
146
147
148
149
150
                    while True:
                        try:
                            mod = prepareModule(module[0])
                            runlist.append(mod)
                            break
                        except Exception as e:
                            msg = "Exception raised while preparing module \"" + module[0] + "\": " + str(e)
                            logger.msgLog(msg, module[0], logger.TYPE_ERROR)
root authored
151
                            logger.msgLog(traceback.format_exc(), module[0],  logger.TYPE_ERROR)
152
153
                            ans = showContinueDialog(d,msg)
                            if ans == "abort":
154
                                finish(False)
155
                            elif ans == "continue":
Imanol-Mikel Barba Sabariego authored
156
                                logger.msgLog("Skipping module " + module[0], "digger", logger.TYPE_INFO)
157
                                break
Imanol-Mikel Barba Sabariego authored
158
            else:
159
                logger.msgLog("Selected modules: " + repr(tags), "digger", logger.TYPE_INFO)
Imanol-Mikel Barba Sabariego authored
160
                for tag in tags:
161
162
163
164
165
166
167
168
                    while True:
                        try:
                            mod = prepareModule(tag)
                            runlist.append(mod)
                            break
                        except Exception as e:
                            msg = "Exception raised while preparing module \"" + tag + "\": " + str(e)
                            logger.msgLog(msg,tag,logger.TYPE_ERROR)
root authored
169
                            logger.msgLog(traceback.format_exc(), tag, logger.TYPE_ERROR)
170
171
                            ans = showContinueDialog(d, msg)
                            if ans == "abort":
172
                                finish(False)
173
174
175
                            elif ans == "continue":
                                logger.msgLog("Skipping module " + tag, "digger", logger.TYPE_INFO)
                                break
176
Imanol-Mikel Barba Sabariego authored
177
178
            sp.call('clear', shell=True)
            for module in runlist:
179
                logger.msgLog("Running " + module.name + "...", "digger", logger.TYPE_INFO)
Imanol-Mikel Barba Sabariego authored
180
                try:
Imanol-Mikel Barba Sabariego authored
181
182
                    #Battle routine, set!
                    module.execute()
Imanol-Mikel Barba Sabariego authored
183
                except Exception as e:
184
                    logger.msgLog("Exception raised while running \"" + module.name + "\": " + str(e), module.name, logger.TYPE_ERROR)
root authored
185
                    logger.msgLog(traceback.format_exc(), module.name, logger.TYPE_ERROR)
186
Imanol-Mikel Barba Sabariego authored
187
188
            finish(True)