Beispiel #1
0
class Open(Script):
  def __init__(self):
    Script.__init__(self, "open")
    self.loader = loader.loader()
    self.cm = ConfigManager.Get()
    self.vtreeprinter = VariantTreePrinter()
    self.lmodules = self.loader.modules
    self.taskmanager = TaskManager()

  def start(self, args):
    node = args["file"].value()
    self.open(node)

  def open(self, node):
    try:
      mod = node.compatibleModules()[0]
      conf = self.cm.configByName(mod)
      argsnode = conf.argumentsByFlags(typeId.Node|Argument.Required)
      if len(argsnode) == 1:
        argnode = argsnode[0]
        margs = {argnode.name(): node}
        args = conf.generate(margs)
        self.taskmanager.add(mod, args, ["thread", "gui"], True)
      else:
        print "There are more than 1 file to provides"
      print  "applying module " + mod + " on " + node.absolute()
    except IndexError:
      typeattr = node.attributesByName("type")
      if typeattr.type() == typeId.List:
        res = self.vtreeprinter.fillList(1, typeattr.value())
        print  "No module registered to handle following types " + res
Beispiel #2
0
class BATCH(Script):
    def __init__(self):
        Script.__init__(self, "batch")
        self.tm = TaskManager()
        self.DEBUG = False
        self.VERBOSITY = 0
        self.lp = LineParser(self.DEBUG, self.VERBOSITY - 1)
        self.cm = ConfigManager.Get()

    def start(self, args):
        ic = InteractiveConsole()
        path = args["path"].value().path
        print "executing batch script " + path
        file = open(path)
        for line in file.xreadlines():
            if line[0] == "#":
                continue
            elif line[0] == "!":
                cmds = self.lp.makeCommands(line[1:])
                for cmd in cmds:
                    exec_type = ["console"]
                    config = self.cm.configByName(cmd[0])
                    args = config.generate(cmd[1])
                    proc = self.tm.add(cmd[0], args, exec_type)
                    proc.event.wait()
            else:
                ic.push(line)
        ic.resetbuffer()
        file.close()
        return
Beispiel #3
0
class BATCH(Script):
  def __init__(self):
    Script.__init__(self, "batch")
    self.tm = TaskManager()
    self.DEBUG = False
    self.VERBOSITY = 0
    self.lp = LineParser(self.DEBUG, self.VERBOSITY -1)
    self.cm = ConfigManager.Get()
 
  def start(self, args):
    ic = InteractiveConsole()
    path = args["path"].value().path
    print "executing batch script " + path 
    file = open(path) 
    for line in file.xreadlines():
	if line[0] == "#":
	   continue
        elif line[0] == "!":
	  cmds = self.lp.makeCommands(line[1:])
	  for cmd in cmds:
	    exec_type = ["console"]
	    config = self.cm.configByName(cmd[0])
	    args  = config.generate(cmd[1])
	    proc = self.tm.add(cmd[0], args, exec_type)
	    proc.event.wait()
	else:
	   ic.push(line) 
    ic.resetbuffer()
    file.close()
    return
Beispiel #4
0
class CarverUi(Script):
    def __init__(self):
        Script.__init__(self, "carverui")
        self.tm = TaskManager()

    def start(self, args):
        if args.has_key("start-offset"):
            startoff = args["start-offset"].value()
        else:
            startoff = 0
        if args.has_key("block-aligned"):
            aligned = True
        else:
            aligned = False
        patterns = VList()
        for mimetype in filetypes.keys():
            if mimetype in args:
                vsubtypes = args[mimetype].value()
                for subtype in filetypes[mimetype].keys():
                    if subtype in vsubtypes:
                        pattern = VMap()
                        descr = filetypes[mimetype][subtype]
                        for p in descr:
                            header = VMap()
                            header["needle"] = Variant(p[0], typeId.String)
                            header["size"] = Variant(len(p[0]), typeId.UInt32)

                            footer = VMap()
                            footer["needle"] = Variant(p[1], typeId.String)
                            footer["size"] = Variant(len(p[1]), typeId.UInt32)

                            pattern["filetype"] = Variant(
                                subtype, typeId.String)
                            pattern["header"] = Variant(header)
                            pattern["footer"] = Variant(footer)
                            pattern["window"] = Variant(
                                int(p[2]), typeId.UInt32)
                            if aligned:
                                pattern["aligned"] = Variant(True, typeId.Bool)
                            else:
                                pattern["aligned"] = Variant(
                                    False, typeId.Bool)
                            patterns.append(pattern)
        margs = VMap()
        margs["patterns"] = Variant(patterns)
        margs["file"] = args["file"]
        margs["start-offset"] = Variant(startoff, typeId.UInt64)
        proc = self.tm.add("carver", margs, ["console"])
        if proc:
            proc.event.wait()

    def c_display(self):
        pass
Beispiel #5
0
    def execModule(name, type, nameArg, listNode):
        tm = TaskManager()
        configs = ConfigManager.Get()
        mconf = configs.configByName(str(name))
        arg = mconf.argumentByName(nameArg)
        if isinstance(listNode, Node):
            args = mconf.generate({arg.name(): listNode})
            tm.add(str(name), args, ["thread", "gui"])
	else:
            if arg.inputType() == Argument.List:
                args = mconf.generate({arg.name(): listNode})
                tm.add(str(name), args, ["thread", "gui"])
            else:
                for i in listNode:
                    args = mconf.generate({arg.name(): i})
                    tm.add(str(name), args, ["thread", "gui"])
Beispiel #6
0
 def execModule(name, type, nameArg, listNode):
     tm = TaskManager()
     configs = ConfigManager.Get()
     mconf = configs.configByName(str(name))
     arg = mconf.argumentByName(nameArg)
     if isinstance(listNode, Node):
         args = mconf.generate({arg.name(): listNode})
         tm.add(str(name), args, ["thread", "gui"])
     else:
         if arg.inputType() == Argument.List:
             args = mconf.generate({arg.name(): listNode})
             tm.add(str(name), args, ["thread", "gui"])
         else:
             for i in listNode:
                 args = mconf.generate({arg.name(): i})
                 tm.add(str(name), args, ["thread", "gui"])
Beispiel #7
0
class BATCH(Script):
    def __init__(self):
        Script.__init__(self, "batch")
        self.tm = TaskManager()
        self.DEBUG = False
        self.VERBOSITY = 0
        self.lp = LineParser(self.DEBUG, self.VERBOSITY - 1)
        self.cm = ConfigManager.Get()

    def start(self, args):
        path = args["path"].value().path
        print "executing batch script " + path
        ib = InteractiveBatch(path)
        ifile = open(path)
        ifeed = False
        err = None
        for line in ifile.xreadlines():
            lstrip = line.strip()
            if lstrip.startswith("!"):
                if ifeed:
                    ifeed = ib.lpush("")
                cmds = self.lp.makeCommands(line[1:])
                for cmd in cmds:
                    exec_type = ["console"]
                    config = self.cm.configByName(cmd[0])
                    args = config.generate(cmd[1])
                    proc = self.tm.add(cmd[0], args, exec_type)
                    proc.event.wait()
            else:
                try:
                    ifeed = ib.lpush(line)
                except RuntimeError:
                    ifeed = False
                    break
            ib.lcount += 1
        ib.end()
        ifile.close()
        return
Beispiel #8
0
class Dialog(QObject):
    def __init__(self, parent):
        QObject.__init__(self)
        self.parent = parent
        self.vfs = vfs.vfs()
        self.taskmanager = TaskManager()
        self.loader = loader.loader()

    def preferences(self):
        """Open a preferences dialog"""

        pref = Preferences(self.parent)
        ret = pref.exec_()
        if ret:
            pass

    def addDevices(self):
        """Open a device list dialog"""
        dev = DevicesDialog(self.parent)
        if dev.exec_():
            self.addDevicesCreateProcess(dev)
        del dev

    def addDevicesCreateProcess(self, dev):
        if dev.selectedDevice:
            args = {}
            args["path"] = str(dev.selectedDevice.blockDevice())
            args["parent"] = self.vfs.getnode("/Local devices")
            args["size"] = long(dev.selectedDevice.size())
            exec_type = ["thread", "gui"]
            try:
                if os.name == "nt":
                    args["name"] = str(dev.selectedDevice.model())
                conf = self.loader.get_conf(str("devices"))
                genargs = conf.generate(args)
                self.taskmanager.add("devices", genargs, exec_type)
            except RuntimeError:
                err_type, err_value, err_traceback = sys.exc_info()
                err_trace = traceback.format_tb(err_traceback)
                err_typeval = traceback.format_exception_only(
                    err_type, err_value)
                terr = QString()
                detailerr = QString()
                for err in err_trace:
                    detailerr.append(err)
                    for errw in err_typeval:
                        terr.append(errw)
                        detailerr.append(err)
                self.messageBox(terr, detailerr)

    def addFiles(self):
        """ Open a Dialog for select a file and add in VFS """
        edialog = evidenceDialog(self.parent)
        ir = edialog.exec_()
        if ir > 0:
            self.addFilesCreateProcess(edialog)

    def addFilesCreateProcess(self, edialog):
        args = {}
        paths = edialog.manager.get("local")
        if edialog.rawcheck.isChecked():
            module = "local"
            args["path"] = paths
            args["parent"] = self.vfs.getnode('/Logical files')
        elif edialog.ewfcheck.isChecked():
            module = "ewf"
            args["files"] = paths
            args["parent"] = self.vfs.getnode('/Logical files')
        else:
            module = "aff"
            args["path"] = paths
            args["parent"] = self.vfs.getnode('/Logical files')
        self.conf = self.loader.get_conf(str(module))
        try:
            genargs = self.conf.generate(args)
            self.taskmanager.add(str(module), genargs, ["thread", "gui"])
        except RuntimeError:
            err_type, err_value, err_traceback = sys.exc_info()
            err_trace = traceback.format_tb(err_traceback)
            err_typeval = traceback.format_exception_only(err_type, err_value)
            terr = QString()
            detailerr = QString()
            for err in err_trace:
                detailerr.append(err)
                for errw in err_typeval:
                    terr.append(errw)
                    detailerr.append(err)
            self.messageBox(terr, detailerr)

    def messageBox(self, coretxt, detail):
        msg = QMessageBox()
        msg.setWindowTitle(self.tr("Error in configuration"))
        msg.setText(self.tr("An error was detected in the configuration"))
        msg.setInformativeText(coretxt)
        msg.setIcon(QMessageBox.Critical)
        msg.setDetailedText(detail)
        msg.setStandardButtons(QMessageBox.Ok)
        ret = msg.exec_()

    def loadDriver(self):
        sFileName = QFileDialog.getOpenFileName(
            self.parent, self.parent.actionLoadModule.toolTip(),
            os.path.expanduser('~'), "Modules(*.py)")
        if (sFileName):
            self.loader.do_load(str(sFileName.toUtf8()))

    def about(self):
        """ Open a About Dialog """
        about = About()
        about.exec_()

    def manager(self):
        """ Open module browser dialog """
        module = browserDialog(self.parent)
        ir = module.exec_()
        if ir > 0:
            module.browser.execute()
Beispiel #9
0
class CarvingProcess(QWidget, EventHandler):
    def __init__(self, selector, vnode):
        QWidget.__init__(self)
        EventHandler.__init__(self)
        self.vnode = vnode.value()
        self.filesize = self.vnode.size()
        self.tm = TaskManager()
        self.selector = selector
        self.setLayout(QVBoxLayout())
        self.factor = 1
        self.parsetime = 0
        self.time = time.time()
        self.starttime = time.time()
        self.createStartOffset()
        self.createButtons()
        self.createStateInfo()

    def createStartOffset(self):
        self.offsetLayout = QHBoxLayout()
        self.offsetSpinBox = QFFSpinBox(self)
        self.offsetSpinBox.setMinimum(0)
        self.offsetSpinBox.setMaximum(self.filesize)
        self.offsetLabel = QLabel("start offset:")
        self.offsetLayout.addWidget(self.offsetLabel)
        self.offsetLayout.addWidget(self.offsetSpinBox)
        self.layout().addLayout(self.offsetLayout)

    def createButtons(self):
        self.startButton = QPushButton("Start")
        self.stopButton = QPushButton("Stop")
        self.stopButton.setEnabled(False)
        self.connect(self.stopButton, SIGNAL("clicked()"), self.stopCarving)
        self.connect(self.startButton, SIGNAL("clicked()"), self.startCarving)
        self.connect(self, SIGNAL("ended"), self.carvingEnded)
        self.buttonLayout = QHBoxLayout()
        self.buttonLayout.addWidget(self.startButton)
        self.buttonLayout.addWidget(self.stopButton)
        self.layout().addLayout(self.buttonLayout)

    def createStateInfo(self):
        self.stateLayout = QVBoxLayout()

        self.overallLayout = QHBoxLayout()
        self.currentLabel = QLabel("Overall progress :")
        self.currentProgress = QProgressBar()
        self.overallLayout.addWidget(self.currentLabel)
        self.overallLayout.addWidget(self.currentProgress)
        self.stateLayout.addLayout(self.overallLayout)

        self.elapsedLabel = QLabel("elapsed time:    00d00h00m00s")
        self.stateLayout.addWidget(self.elapsedLabel)
        self.estimatedLabel = QLabel("estimated time: 00d00h00m00s")
        self.stateLayout.addWidget(self.estimatedLabel)
        self.totalLabel = QLabel("total headers found: 0")
        self.stateLayout.addWidget(self.totalLabel)
        self.stateLayout.setEnabled(False)
        self.layout().addLayout(self.stateLayout)

    def createContext(self, selected):
        lpatterns = VList()
        for filetype in selected.iterkeys():
            patterns = selected[filetype][0]
            aligned = selected[filetype][1]
            for pattern in patterns:
                vpattern = VMap()
                vpattern["filetype"] = Variant(filetype, typeId.String)

                header = VMap()
                header["needle"] = Variant(pattern[0], typeId.String)
                header["size"] = Variant(len(pattern[0]), typeId.UInt32)

                footer = VMap()
                footer["needle"] = Variant(pattern[1], typeId.String)
                footer["size"] = Variant(len(pattern[1]), typeId.UInt32)

                vpattern["header"] = Variant(header)
                vpattern["footer"] = Variant(footer)
                vpattern["window"] = Variant(int(pattern[2]), typeId.UInt32)
                vpattern["aligned"] = Variant(aligned, typeId.Bool)
                lpatterns.append(vpattern)
        return lpatterns

    def startCarving(self):
        selected = self.selector.selectedItems()
        if len(selected):
            try:
                f = self.vnode.open()
                f.close()
            except:
                mbox = QMessageBox(
                    QMessageBox.Warning, self.tr("Carver bad input"),
                    self.
                    tr("The provided input file seems to be a directory. Please, apply the module on a file"
                       ), QMessageBox.Ok, self)
                mbox.exec_()
                return
            patterns = self.createContext(selected)
            args = VMap()
            args["patterns"] = Variant(patterns)
            args["file"] = Variant(self.vnode)
            args["start-offset"] = Variant(self.offsetSpinBox.value(),
                                           typeId.UInt64)
            factor = round(float(self.filesize) / 2147483647)
            self.startButton.setEnabled(False)
            self.stopButton.setEnabled(True)
            self.stopButton.setDown(False)
            if factor == 0:
                factor = 1
            proc = self.tm.add("carver", args, ["gui", "thread"])
            if proc:
                self.doJob(self.filesize, factor, self.offsetSpinBox.value())
                self.stateLayout.setEnabled(True)
                self.connection(proc.inst)
                proc.inst.connection(self)
                #self.connect(self, SIGNAL("stateInfo(QString)"), self.setStateInfo)
        else:
            mbox = QMessageBox(
                QMessageBox.Warning, self.tr("Carver no items selected"),
                self.
                tr("No items have been provided to know what to look for. Please chose types you want to search."
                   ), QMessageBox.Ok, self)
            mbox.exec_()
            return

    def carvingEnded(self, res):
        #results = str(res).split("\n")
        #print results
        #for item in results:
        #    begidx = item.find(":")
        #    self.res.add_const(str(item[:begidx]), str(item[begidx+1:] + "\n"))
        self.startButton.setEnabled(True)
        self.stopButton.setEnabled(False)
        self.stateLayout.setEnabled(False)

    def stopCarving(self):
        self.killJob()
        self.stopButton.setDown(True)

    def strtime(self, day, hour, min, sec):
        day = str(day)
        hour = str(hour)
        min = str(min)
        sec = str(sec)
        res = "0" * (2 - len(day)) + day + "d" + "0" * (
            2 - len(hour)) + hour + "h" + "0" * (
                2 - len(min)) + min + "m" + "0" * (2 - len(sec)) + sec + "s"
        return res

    def timesec2str(self, timesec):
        day = hour = min = sec = 0
        if timesec > 3600 * 24:
            day = timesec / (3600 * 24)
            timesec = timesec % (3600 * 24)
        if timesec > 3600:
            hour = timesec / 3600
            timesec = timesec % 3600
        if timesec > 60:
            min = timesec / 60
            timesec = timesec % 60
        sec = timesec
        res = self.strtime(int(day), int(hour), int(min), int(sec))
        return res

    def Event(self, e):
        if e.type == Carver.Position:
            self.emit(SIGNAL("updatePosition"), e)
        elif e.type == Carver.Matches:
            self.emit(SIGNAL("updateMatches"), e)
        elif e.type == Carver.EndOfProcessing:
            self.emit(SIGNAL("ended"), "")

    def updatePosition(self, e):
        ref = time.time() - self.time
        self.time = time.time()
        if not str(ref).startswith("0.0"):
            ref *= self.parsetime
            res = self.timesec2str(ref)
            self.estimatedLabel.setText("estimated time: " + res)
        res = self.timesec2str(time.time() - self.starttime)
        self.elapsedLabel.setText("elapsed time:    " + res)
        i = int(e.value.value() / self.factor)
        if i > 2147483647:
            i = 2147483647
        self.emit(SIGNAL("valueChanged(int)"), i)
        info = self.currentProgress.text() + " - " + self.totalLabel.text()
        self.emit(SIGNAL("stateInfo(QString)"), info)

    def updateMatches(self, e):
        self.totalLabel.setText("total headers found: " + str(e.value))

    def doJob(self, filesize, factor, start):
        self.factor = factor
        self.parsetime = filesize / (10 * 1204 * 1024)
        self.elapsedLabel.setText("elapsed time:    00d00h00m00s")
        self.estimatedLabel.setText("estimated time: 00d00h00m00s")
        self.totalLabel.setText("total headers found: 0")
        maxrange = int(filesize / self.factor)
        if maxrange > 2147483647:
            maxrange = 2147483647
        self.currentProgress.setRange(0, maxrange)
        self.currentProgress.setValue(0)
        self.connect(self, SIGNAL("valueChanged(int)"),
                     self.currentProgress.setValue)
        self.time = time.time()
        self.starttime = time.time()
        self.connect(self, SIGNAL("updateMatches"), self.updateMatches)
        self.connect(self, SIGNAL("updatePosition"), self.updatePosition)

    def killJob(self):
        e = event()
        e.thisown = False
        e.type = Carver.Stop
        self.notify(e)
Beispiel #10
0
class ApplyModule(QDialog, Ui_applyModule):
    def __init__(self, mainWindow):
        QDialog.__init__(self, mainWindow)
        Ui_applyModule.__init__(self)
        self.setupUi(self)
        self.labActivate.setVisible(False)
        self.labType.setVisible(False)
        self.labDescription.setVisible(False)
        self.connect(self.buttonBox, SIGNAL("accepted()"), self.validateModule)
        self.__mainWindow = mainWindow
        self.loader = loader.loader()
        self.vfs = vfs()
        self.valueArgs = {}
        self.translation()

    def initAllInformations(self, nameModule, typeModule, nodesSelected):
        self.__nodesSelected = nodesSelected
        self.nameModule = nameModule

        try:
            self.module = self.loader.modules[str(nameModule)]
        except KeyError:
            self.module = None
        if self.module and self.module.icon:
            p = QPixmap(self.module.icon)
            p.scaled(64, 64, Qt.KeepAspectRatio)
            self.modulepix.setPixmap(p)
        else:
            p = self.modulepix.pixmap().scaled(64, 64, Qt.KeepAspectRatio)
            self.modulepix.setPixmap(p)

        title = self.windowTitle() + ' ' + str(nameModule)
        self.setWindowTitle(title)
        self.nameModuleField.setText(nameModule)
        self.typeModuleField.setText(typeModule)

        if not nodesSelected:
            self.__nodesSelected = []

        self.conf = self.loader.get_conf(str(nameModule))
        try:
            self.textEdit.setText(self.conf.description)
        except TypeError:
            self.textEdit.setText(self.conf.description())
        args = self.conf.arguments()
        self.createArgShape(args)

    def createArgShape(self, args):
        self.connect(
            self.listargs,
            SIGNAL("currentItemChanged(QListWidgetItem*,QListWidgetItem*)"),
            self.argChanged)
        for arg in args:
            self.createArgument(arg)

        if len(self.listargs):
            self.listargs.item(0).setSelected(True)
        self.argsLayout.setStretchFactor(0, 1)
        self.argsLayout.setStretchFactor(1, 3)

    def createArgument(self, arg):
        warg = QWidget()
        vlayout = QVBoxLayout()
        vlayout.setSpacing(5)
        vlayout.setMargin(0)
        winfo = QWidget()
        infolayout = QFormLayout()
        infolayout.setMargin(0)
        requirement = arg.requirementType()
        # Generate argument's widget
        warguments = self.getWidgetFromType(arg)

        if arg.requirementType() in (Argument.Optional, Argument.Empty):
            checkBox = checkBoxWidget(self, winfo, warguments,
                                      self.labActivate.text())
            vlayout.addWidget(checkBox, 0)
        if arg.type() in [
                typeId.Int16, typeId.UInt16, typeId.Int32, typeId.UInt32,
                typeId.Int64, typeId.UInt64
        ]:
            typeinfo = self.tr("Number")
        elif arg.type() in [typeId.String, typeId.CArray]:
            typeinfo = self.tr("String")
        elif arg.type() in [typeId.Bool]:
            typeinfo = self.tr("Boolean")
        elif arg.type() in [typeId.Path]:
            typeinfo = self.tr("File or folder stored on the local system")
        elif arg.type() in [typeId.Node]:
            typeinfo = self.tr("Node from the virtual filesystem")
        else:
            typeinfo = None
        if typeinfo is not None:
            self.labType.setText(self.tr("Input type:"))
            infolayout.addRow(self.labType.text(), QLabel(typeinfo))
        tedit = QTextEdit(str(arg.description()))
        tedit.setReadOnly(True)
        infolayout.addRow(tedit)
        winfo.setLayout(infolayout)
        vlayout.addWidget(winfo, 1)
        if warguments:
            vlayout.addWidget(warguments, 2)
            self.valueArgs[arg.name()] = warguments
        else:
            self.valueArgs[arg.name()] = winfo
        warg.setLayout(vlayout)
        self.stackedargs.addWidget(warg)
        argitem = QListWidgetItem(str(arg.name()), self.listargs)

    def getWidgetFromType(self, arg):
        warguments = layoutManager()
        inputype = arg.inputType()
        predefs = arg.parameters()
        ptype = arg.parametersType()
        if ptype == Parameter.Editable:
            editable = True
        else:
            editable = False
        if inputype == Argument.Single:
            if arg.type() == typeId.Node:
                warguments.addSingleNode(arg.name(), predefs,
                                         self.__nodesSelected, editable)
            elif arg.type() == typeId.Path:
                warguments.addSinglePath(arg.name(), predefs, editable)
            else:
                warguments.addSingleArgument(arg.name(), predefs, arg.type(),
                                             editable)
        elif inputype == Argument.List:
            if arg.type() == typeId.Node:
                warguments.addNodeList(arg.name(), predefs,
                                       self.__nodesSelected)
            elif arg.type() == typeId.Path:
                warguments.addPathList(arg.name(), predefs)
            else:
                warguments.addListArgument(arg.name(), arg.type(), predefs,
                                           editable)
        else:
            # Argument.Empty (typically, bool arguments)
            return None
        return warguments

    def validateModule(self):
        # get values
        args = {}
        try:
            for argname, lmanager in self.valueArgs.iteritems():
                if lmanager.isEnabled():
                    arg = self.conf.argumentByName(argname)
                    if arg.inputType() == Argument.Empty:
                        params = True
                    else:
                        params = lmanager.get(argname)
                    args[argname] = params
            genargs = self.conf.generate(args)
            self.taskmanager = TaskManager()
            self.taskmanager.add(str(self.nameModule), genargs,
                                 ["thread", "gui"])
            self.accept()
        except RuntimeError:
            err_type, err_value, err_traceback = sys.exc_info()
            err_trace = traceback.format_tb(err_traceback)
            err_typeval = traceback.format_exception_only(err_type, err_value)
            terr = QString()
            detailerr = QString()
            for err in err_trace:
                detailerr.append(err)
            for errw in err_typeval:
                terr.append(errw)
                detailerr.append(err)
            self.messageBox(terr, detailerr)
        return

    def openApplyModule(self,
                        nameModule=None,
                        typeModule=None,
                        nodesSelected=None):
        self.initAllInformations(nameModule, typeModule, nodesSelected)
        self.exec_()

    def argChanged(self, curitem, previtem):
        self.stackedargs.setCurrentIndex(self.listargs.row(curitem))

    def messageBox(self, coretxt, detail):
        msg = QMessageBox(self)
        msg.setWindowTitle(self.configureError)
        msg.setText(self.configureErrorMsg)
        msg.setInformativeText(coretxt)
        msg.setIcon(QMessageBox.Critical)
        msg.setDetailedText(detail)
        msg.setStandardButtons(QMessageBox.Ok)
        ret = msg.exec_()

    def translation(self):
        self.configureError = self.tr("Configuration error")
        self.configureErrorMsg = self.tr(
            "An error was detected in the configuration")

    def changeEvent(self, event):
        """ Search for a language change event

        This event have to call retranslateUi to change interface language on
        the fly.
        """
        if event.type() == QEvent.LanguageChange:
            self.retranslateUi(self)
            title = self.windowTitle() + ' ' + self.nameModule
            self.setWindowTitle(title)
            self.translation()
        else:
            QDialog.changeEvent(self, event)
Beispiel #11
0
class ApplyModule(QDialog, Ui_applyModule):
    def __init__(self,  mainWindow):
        QDialog.__init__(self, mainWindow)
        Ui_applyModule.__init__(self)
        self.setupUi(self)
        self.labActivate.setVisible(False)
        self.labType.setVisible(False)
        self.labDescription.setVisible(False)
        self.connect(self.buttonBox,SIGNAL("accepted()"), self.validateModule)
        self.__mainWindow = mainWindow
        self.loader = loader.loader()
        self.vfs = vfs()
        self.valueArgs = {}
        self.translation()
    
    def initAllInformations(self, nameModule, typeModule, nodesSelected):
        self.__nodesSelected = nodesSelected
        self.nameModule = nameModule
        try: 
	  self.module = self.loader.modules[str(nameModule)]
        except KeyError:
	   self.module = None
        if self.module and self.module.icon:
          p = QPixmap(self.module.icon)
          p.scaled(64, 64, Qt.KeepAspectRatio)
	  self.modulepix.setPixmap(p)
        else:
          p = self.modulepix.pixmap().scaled(64,64, Qt.KeepAspectRatio)
          self.modulepix.setPixmap(p)
	   

        title = self.windowTitle() + ' ' + str(nameModule)
        self.setWindowTitle(title)
        self.nameModuleField.setText(nameModule)
        self.typeModuleField.setText(typeModule)

        if not nodesSelected:
            self.__nodesSelected = []

        self.conf = self.loader.get_conf(str(nameModule))
        try:
            self.textEdit.setText(self.conf.description)
        except TypeError:
            self.textEdit.setText(self.conf.description())
        args = self.conf.arguments()
        self.createArgShape(args)
    
    def createArgShape(self, args):
        self.connect(self.listargs, SIGNAL("currentItemChanged(QListWidgetItem*,QListWidgetItem*)"), self.argChanged)
        for arg in args:
            self.createArgument(arg)

	if len(self.listargs):
          self.listargs.item(0).setSelected(True)
        self.argsLayout.setStretchFactor(0, 1)
        self.argsLayout.setStretchFactor(1, 3)

    def createArgument(self, arg):
        warg = QWidget()
        vlayout = QVBoxLayout()
        vlayout.setSpacing(5)
        vlayout.setMargin(0)
        winfo = QWidget()
        infolayout = QFormLayout()
        infolayout.setMargin(0)
        requirement = arg.requirementType()
        # Generate argument's widget
        warguments = self.getWidgetFromType(arg)

        if arg.requirementType() in (Argument.Optional, Argument.Empty):
            checkBox =  checkBoxWidget(self, winfo, warguments, self.labActivate.text())
            vlayout.addWidget(checkBox, 0)

        infolayout.addRow(self.labType.text(), QLabel(str(typeId.Get().typeToName(arg.type()))))
        tedit = QTextEdit(str(arg.description()))
        tedit.setReadOnly(True)
        infolayout.addRow(tedit)
        winfo.setLayout(infolayout)
        vlayout.addWidget(winfo, 1)
        if warguments:
            vlayout.addWidget(warguments, 2)        
            self.valueArgs[arg.name()] = warguments
        else:
            self.valueArgs[arg.name()] = winfo
        warg.setLayout(vlayout)
        self.stackedargs.addWidget(warg)
        argitem = QListWidgetItem(str(arg.name()), self.listargs)

    def getWidgetFromType(self, arg):
        warguments = layoutManager()
        inputype = arg.inputType()
        predefs = arg.parameters()
        ptype = arg.parametersType()
        if ptype == Parameter.Editable:
            editable = True
        else:
            editable = False
        if inputype == Argument.Single:
            if arg.type() in (typeId.Node, typeId.Path):
                warguments.addPath(arg.name(), arg.type(), predefs, self.__nodesSelected, editable)
            else:
                warguments.addSingleArgument(arg.name(), predefs, arg.type(), editable)
        elif inputype == Argument.List:
            if arg.type() in (typeId.Node, typeId.Path):
                warguments.addPathList(arg.name(), arg.type(), predefs, self.__nodesSelected)
            else:
                warguments.addListArgument(arg.name(), arg.type(), predefs, editable)
        else:
            # Argument.Empty (typically, bool arguments)
            return None
        return warguments

    def validateModule(self):
        # get values
        args = {}
        try :
            for argname, lmanager in self.valueArgs.iteritems():
                if lmanager.isEnabled():
                    arg = self.conf.argumentByName(argname)
                    if arg.type() == typeId.Node and arg.inputType() == Argument.List:
                        plist = lmanager.get(argname)
                        params = []
                        for param in plist:
                            params.append(self.vfs.getnode(param))
                    elif arg.type() == typeId.Node and arg.inputType() == Argument.Single:
                        params = self.vfs.getnode(lmanager.get(argname))
                    elif arg.inputType() == Argument.Empty:
                        params = True
                    else:                        
                        params = lmanager.get(argname)
                    args[argname] = params
            genargs = self.conf.generate(args)
            self.taskmanager = TaskManager()
            self.taskmanager.add(str(self.nameModule), genargs, ["thread", "gui"])
            self.accept()
        except RuntimeError:
            err_type, err_value, err_traceback = sys.exc_info()
            err_trace =  traceback.format_tb(err_traceback)
            err_typeval = traceback.format_exception_only(err_type, err_value)
            terr = QString()
            detailerr = QString()
            for err in err_trace:
                detailerr.append(err)
            for errw in err_typeval:
                terr.append(errw)
                detailerr.append(err)
            self.messageBox(terr, detailerr)
        return

    def openApplyModule(self, nameModule = None, typeModule = None, nodesSelected = None):
        self.initAllInformations(nameModule, typeModule, nodesSelected)
        self.exec_()

    def argChanged(self, curitem, previtem):
        self.stackedargs.setCurrentIndex(self.listargs.row(curitem))

    def messageBox(self, coretxt, detail):
        msg = QMessageBox(self)
        msg.setWindowTitle(self.configureError)
        msg.setText(self.configureErrorMsg)
        msg.setInformativeText(coretxt)
        msg.setIcon(QMessageBox.Critical)
        msg.setDetailedText(detail)
        msg.setStandardButtons(QMessageBox.Ok)
        ret = msg.exec_()

    def translation(self):
        self.configureError = self.tr("Configuration error")
        self.configureErrorMsg = self.tr("An error was detected in the configuration")

    def changeEvent(self, event):
        """ Search for a language change event

        This event have to call retranslateUi to change interface language on
        the fly.
        """
        if event.type() == QEvent.LanguageChange:
            self.retranslateUi(self)
            title = self.windowTitle() + ' ' + self.nameModule
            self.setWindowTitle(title)
            self.translation()
        else:
            QDialog.changeEvent(self, event)
Beispiel #12
0
class ReportUI(UI):
    def __init__(self, arguments):
        UI.__init__(self, arguments)
        self.taskManager = TaskManager()
        self.reportManager = ReportManager()
        self.registryManager = ModuleProcessusManager().get("winreg")
        self.evtxManager = ModuleProcessusManager().get("evtx")
        self.sqliteManager = ModuleProcessusManager().get('SqliteDB')
        self.root = vfs().getnode("/")

    def configureProcessing(self):
        self.taskManager.addPostProcessingModules(PROCESSING_MODULES)
        self.taskManager.addPostProcessingAnalyses(PROCESSING_ANALYSES)
        self.taskManager.addAnalyseDependencies()

    def launchProcessing(self):
        proc = self.taskManager.add("local", {"path": self.dumpPath},
                                    "console")
        proc.event.wait()
        self.taskManager.join()

    def launch(self):
        self.startTime = time.time()

        self.dumpPath = sys.argv[1]
        self.reportPath = sys.argv[2]

        #PROCESSING
        self.configureProcessing()
        self.launchProcessing()

        self.searchTaggedNode()
        self.addProcessingTime()

        self.reportManager.setExportPath(self.reportPath)
        self.reportManager.export(exportContent=True)

        #SHOW EXECUTION TIME
    def addProcessingTime(self):
        totalTime = time.time() - self.startTime
        if totalTime > 60:
            totalTime = str(totalTime / 60) + " minutes"
        else:
            totalTime = str(totalTime) + " secondes"

        page = self.reportManager.createPage("MyAnalysis", "Stats")
        page.addText("Processing time ", totalTime)
        self.reportManager.addPage(page)

    def searchTaggedNode(self):
        f = Filter("")
        f.compile('tags in ["malware", "suspicious"]')
        f.process(self.root)
        malwareNodes = f.matchedNodes()
        if len(malwareNodes
               ) != 0:  #if get some results we add it to the report
            page = self.reportManager.createPage("MyAnalysis", "Files")
            page.addNodeList("Malware", malwareNodes)
            self.reportManager.addPage(page)

    def searchRegistryKeys(self):
        regKeys = self.registryManager.getKeys(
            {'HKLM\Software\Microsoft\Windows NT\CurrentVersion': ['*']}, root)
        table = []
        for key in regKeys:
            for value in key.values():
                data = value.data()
                if type(data) != bytearray:
                    table.append((
                        value.name,
                        data,
                        key.hive.absolute(),
                    ))

        registryPage = iself.reportManager.createPage("MyAnalysis", "Registry")
        registryPage.addTable("Current version",
                              ["name", "value", "hive path"], table)
        self.reportManager.addPage(registryPage)

    def searchSQL(self):
        cookiePage = reportManager.createPage("MyAnalysis", "Cookies")
        for db, node in sqliteManager.databases.iteritems():
            sqltables = db.execute("SELECT * FROM cookies").fetchall()
            table = []
            for row in sqltables:
                table.append((row[1], ))
            if len(table):
                cookiePage.addTable(node.absolute(), ["site"], table)
        reportManager.addPage(cookiePage)

    def searchEVTX(self):
        events = self.evtxManager.getXmlById({"id": [4624]}, "/")
        table = []
        for event in events:
            try:
                etime = event.findall(".//TimeCreated")[0].attrib["SystemTime"]
                user = event.findall(
                    ".//Data[@Name='SubjectUserName']")[0].text
                domain = event.findall(
                    ".//Data[@Name='SubjectDomainName']")[0].text
                table.append((
                    etime,
                    user,
                    domain,
                ))
            except:
                pass

        #NODES COUNT AND STATS (type of files etc ?)
        #save to reload ? :)
        eventPage = self.reportManager.createPage("MyAnalysis", "Event")
        eventPage.addTable("Login", ["time", "user", "domain"], table)
        self.reportManager.addPage(eventPage)