Пример #1
0
    def fill(self):
        '''Parse all the paths (['Lcom/example/myclass/MyActivity$1;', ...])
           and build a tree using the QTreeWidgetItem insertion method.'''
        androconf.debug("Fill classes tree")

        for idx, filename, digest, classes in self.session.get_classes():
            for c in sorted(classes, key=lambda c: c.name):
                sig = Signature(c)
                path_node = self.root_path_node

                # Namespaces
                for path in sig.class_path:
                    if path not in path_node[0]:
                        path_node[0][path] = ({}, QtGui.QTreeWidgetItem(path_node[1]))
                        path_node[0][path][1].setText(0, path)
                    path_node = path_node[0][path]
                # Class
                path_node[0][path] = ({}, QtGui.QTreeWidgetItem(path_node[1]))

                class_name = sig.class_name

                if idx > 0:
                    class_name += "@%d" % idx

                c.current_title = class_name
                self._reverse_cache[path_node[0][path][1]] = (c,
                                                              filename,
                                                              digest)


                path_node[0][path][1].setText(0, class_name)
Пример #2
0
    def fill(self):
        '''Parse all the paths (['Lcom/example/myclass/MyActivity$1;', ...])
           and build a tree using the QTreeWidgetItem insertion method.'''
        androconf.debug("Fill classes tree")

        for idx, filename, digest, classes in self.session.get_classes():
            for c in sorted(classes, key=lambda c: c.name):
                sig = Signature(c)
                path_node = self.root_path_node

                # Namespaces
                for path in sig.class_path:
                    if path not in path_node[0]:
                        path_node[0][path] = ({},
                                              QtGui.QTreeWidgetItem(
                                                  path_node[1]))
                        path_node[0][path][1].setText(0, path)
                    path_node = path_node[0][path]
                # Class
                path_node[0][path] = ({}, QtGui.QTreeWidgetItem(path_node[1]))

                class_name = sig.class_name

                if idx > 0:
                    class_name += "@%d" % idx

                c.current_title = class_name
                self._reverse_cache[path_node[0][path][1]] = (c, filename,
                                                              digest)

                path_node[0][path][1].setText(0, class_name)
Пример #3
0
    def __init__(self,
                 parent=None,
                 win=None,
                 current_class=None,
                 current_title=None,
                 current_filename=None,
                 current_digest=None,
                 session=None):
        super(SourceWindow, self).__init__(parent)
        androconf.debug("New source tab for: %s" % current_class)

        self.mainwin = win
        self.session = session
        self.current_class = current_class
        self.current_title = current_title
        self.current_filename = current_filename
        self.current_digest = current_digest

        self.title = current_title

        self.setReadOnly(True)

        self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.CustomContextMenuHandler)

        self.cursorPositionChanged.connect(self.cursor_position_changed)
Пример #4
0
def BuildCFG(inputFile, outputFile):

    androconf.debug("DalvikVMFormat ...")

    #    print sys.argv
    #    print "hahahahahahahahah"

    d = None
    #    if raw == False:
    #        d = DalvikVMFormat(open(filename, "rb").read())
    #    else:
    #        d = DalvikVMFormat(filename)

    androconf.debug("APK ...")
    a = APK(inputFile, False)
    #    d, dx = AnalyzeDex(a.get_dex(), raw=True, decompiler=decompiler)
    newFile = a.get_dex()
    d = DalvikVMFormat(newFile)
    x = uVMAnalysis(d)
    fd = open(outputFile, "w")

    for method in d.get_methods():
        g = x.get_method(method)

        if method.get_code() == None:
            continue

#        print method.get_class_name(), method.get_name(), method.get_descriptor()

        fd.write(method.get_class_name() + " " + method.get_name() + " " +
                 method.get_descriptor() + " " +
                 str(method.code.get_registers_size() - 1) + "\n")

        idx = 0
        for i in g.get_basic_blocks().get():
            #            print "\t %s %x %x" % (i.name, i.start, i.end), '[ NEXT = ', ', '.join( "%x-%x-%s" % (j[0], j[1], j[2].get_name()) for j in i.get_next() ), ']', '[ PREV = ', ', '.join( j[2].get_name() for j in i.get_prev() ), ']'
            fd.write("\t" + i.name + " " + str(hex(i.start)) + " " +
                     str(hex(i.end)))
            fd.write("[ NEXT = ")

            for j in i.get_next():
                fd.write(
                    str(hex(j[0])) + "-" + str(hex(j[1])) + "-" +
                    j[2].get_name() + " ")
            fd.write(" ]")
            fd.write(" [ PREV = " + ', '.join(j[2].get_name()
                                              for j in i.get_prev()))
            fd.write("] \n")

            for ins in i.get_instructions():
                #               print "\t\t %x" % idx, ins.get_name(), ins.get_output()
                fd.write("\t\t" + str(hex(idx)) + " " + ins.get_name() + " " +
                         ins.get_output() + "\n")
                idx += ins.get_length()


#            print ""
    fd.close()

    return d
Пример #5
0
    def reload_java_sources(self):
        '''Reload completely the sources by asking Androguard
           to decompile it again. Useful when:
            - an element has been renamed to propagate the info
            - the current tab is changed because we do not know what user
              did since then, so we need to propagate previous changes as well
        '''

        androconf.debug("Getting sources for %s" % self.path)
        lines = self.class_item.get_source_ext()

        filename = os.path.join(self.ospath, self.osfile)
        androconf.debug("Writing file: %s" % filename)
        with open(filename, 'wb') as fd:
            for section, L in lines:
                for t in L:
    #                if t[0] in BINDINGS_NAMES:
    #                    self.binding[cursor.position()] = t
                    fd.write(t[1])

        #TODO: delete doc when tab is closed? not deleted by "self" :(
        if hasattr(self, "doc"):
            del self.doc
        self.doc = SourceDocument(parent=self, lines=lines)
        self.setDocument(self.doc)

        #No need to save hightlighter. highlighBlock will automatically be called
        #because we passed the QTextDocument to QSyntaxHighlighter constructor
        Highlighter(self.doc)
Пример #6
0
 def getMeSourceWindowIfExists(self, current_class):
     '''Helper for openSourceWindow'''
     for idx in range(self.central.count()):
         if current_class.get_name() == self.central.tabToolTip(idx):
             androconf.debug("Tab %s already opened at: %d" % (current_class.get_name(), idx))
             return self.central.widget(idx)
     return None
Пример #7
0
    def setupHelpMenu(self):
        androconf.debug("Setup Help Menu")

        self.helpMenu = self.menuBar().addMenu("&Help")

        self.helpMenu.addAction("&About", self.about)
        self.helpMenu.addAction("About &Qt", QtWidgets.qApp.aboutQt)
Пример #8
0
def AnalyzeJAR(filename, raw=False):
    androconf.debug("JAR ...")
    a = JAR(filename, raw)

    d = AnalyzeClasses(a.get_classes())

    return a, d
Пример #9
0
def RunDecompiler(d, dx, decompiler):
    """
        Run the decompiler on a specific analysis

        :param d: the DalvikVMFormat object
        :type d: :class:`DalvikVMFormat` object
        :param dx: the analysis of the format
        :type dx: :class:`VMAnalysis` object 
        :param decompiler: the type of decompiler to use ("dad", "dex2jad", "ded")
        :type decompiler: string
    """
    if decompiler != None:
        androconf.debug("Decompiler ...")
        decompiler = decompiler.lower()
        if decompiler == "dex2jad":
            d.set_decompiler(
                DecompilerDex2Jad(d, androconf.CONF["PATH_DEX2JAR"],
                                  androconf.CONF["BIN_DEX2JAR"],
                                  androconf.CONF["PATH_JAD"],
                                  androconf.CONF["BIN_JAD"],
                                  androconf.CONF["TMP_DIRECTORY"]))
        elif decompiler == "ded":
            d.set_decompiler(
                DecompilerDed(d, androconf.CONF["PATH_DED"],
                              androconf.CONF["BIN_DED"],
                              androconf.CONF["TMP_DIRECTORY"]))
        elif decompiler == "dad":
            d.set_decompiler(DecompilerDAD(d, dx))
        else:
            print "Unknown decompiler, use DAD decompiler by default"
            d.set_decompiler(DecompilerDAD(d, dx))
Пример #10
0
    def actionGoto(self):
        cursor = self.textCursor()
        start = cursor.selectionStart()
        end = cursor.selectionEnd()
        selection = cursor.selectedText()
        androconf.debug("Goto asked for '%s' (%d, %d)" % (selection, start, end))

        if start not in self.doc.binding.keys():
            self.mainwin.showStatus("Goto not available. No info for: '%s'." % selection)
            return

        t = self.doc.binding[start]
        if t[0] == 'NAME_METHOD_INVOKE':
            class_, method_ = t[2].split(' -> ')
            if class_ == 'this':
                class_ = self.path
            else:
                class_ = classdot2class(class_)
        else:
            self.mainwin.showStatus("Goto not available. Info ok: '%s' but object not supported." % selection)
            return

        androconf.debug("Found corresponding method: %s -> %s in source file: %s" % (class_, method_, self.path))

        if not self.mainwin.doesClassExist(class_):
            self.mainwin.showStatus("Goto not available. Class: %s not in database." % class_)
            return

        self.mainwin.openSourceWindow(class_, method=method_)
Пример #11
0
def RunDecompiler(d, dx, decompiler, session=None):
    """
        Run the decompiler on a specific analysis

        :param d: the DalvikVMFormat object
        :type d: :class:`DalvikVMFormat` object
        :param dx: the analysis of the format
        :type dx: :class:`VMAnalysis` object
        :param decompiler: the type of decompiler to use ("dad", "dex2jad", "ded")
        :type decompiler: string
    """
    if decompiler != None:
        androconf.debug("Decompiler ...")
        decompiler = decompiler.lower()
        if decompiler == "dex2jad":
            d.set_decompiler(DecompilerDex2Jad(
                d, androconf.CONF["PATH_DEX2JAR"], androconf.CONF["BIN_DEX2JAR"
                              ], androconf.CONF["PATH_JAD"],
                androconf.CONF["BIN_JAD"], androconf.CONF["TMP_DIRECTORY"]))
        elif decompiler == "dex2fernflower":
            d.set_decompiler(DecompilerDex2Fernflower(
                d, androconf.CONF["PATH_DEX2JAR"], androconf.CONF[
                    "BIN_DEX2JAR"
                ], androconf.CONF["PATH_FERNFLOWER"], androconf.CONF[
                    "BIN_FERNFLOWER"
                ], androconf.CONF["OPTIONS_FERNFLOWER"
                                 ], androconf.CONF["TMP_DIRECTORY"]))
        elif decompiler == "ded":
            d.set_decompiler(DecompilerDed(d, androconf.CONF["PATH_DED"],
                                           androconf.CONF["BIN_DED"],
                                           androconf.CONF["TMP_DIRECTORY"]))
        else:
            d.set_decompiler(DecompilerDAD(d, dx))
Пример #12
0
def AnalyzeAPK(filename, raw=False, decompiler="dad"):
    """
        Analyze an android application and setup all stuff for a more quickly analysis !

        :param filename: the filename of the android application or a buffer which represents the application
        :type filename: string
        :param raw: True is you would like to use a buffer (optional)
        :type raw: boolean
        :param decompiler: ded, dex2jad, dad (optional)
        :type decompiler: string

        :rtype: return the :class:`APK`, :class:`DalvikVMFormat`, and :class:`VMAnalysis` objects
    """
    androconf.debug("APK ...")
    a = APK(filename, raw)
    d1, dx1 = AnalyzeDex(a.get_dex(), raw=True, decompiler=decompiler)
    # print "Hello Kevin"
    n = 1
    file2 = a.get_dex2()
    if file2.strip() != '':
        # print "OK,get_dex2..."
        n = 2
        d2, dx2 = AnalyzeDex(a.get_dex2(), raw=True, decompiler=decompiler)
        d = [d1, d2]
        dx = [dx1, dx2, n]
    else:
        d2 = ''
        dx2 = ''
        d = [d1, d2]
        dx = [dx1, dx2, n]
    return a, d, dx
Пример #13
0
    def reload_java_sources(self):
        '''Reload completely the sources by asking Androguard
           to decompile it again. Useful when:
            - an element has been renamed to propagate the info
            - the current tab is changed because we do not know what user
              did since then, so we need to propagate previous changes as well
        '''

        androconf.debug("Getting sources for %s" % self.path)
        lines = self.class_item.get_source_ext()

        filename = os.path.join(self.ospath, self.osfile)
        androconf.debug("Writing file: %s" % filename)
        with open(filename, 'wb') as fd:
            for section, L in lines:
                for t in L:
                    #                if t[0] in BINDINGS_NAMES:
                    #                    self.binding[cursor.position()] = t
                    fd.write(t[1])

        #TODO: delete doc when tab is closed? not deleted by "self" :(
        if hasattr(self, "doc"):
            del self.doc
        self.doc = SourceDocument(parent=self, lines=lines)
        self.setDocument(self.doc)

        #No need to save hightlighter. highlighBlock will automatically be called
        #because we passed the QTextDocument to QSyntaxHighlighter constructor
        Highlighter(self.doc)
Пример #14
0
def AnalyzeJAR(filename, raw=False):
    androconf.debug("JAR ...")
    a = JAR(filename, raw)

    d = AnalyzeClasses(a.get_classes())

    return a, d
Пример #15
0
def RunDecompiler(d, dx, decompiler, session=None):
    """
        Run the decompiler on a specific analysis
        :param d: the DalvikVMFormat object
        :type d: :class:`DalvikVMFormat` object
        :param dx: the analysis of the format
        :type dx: :class:`VMAnalysis` object
        :param decompiler: the type of decompiler to use ("dad", "dex2jad", "ded")
        :type decompiler: string
    """
    if decompiler != None:
        androconf.debug("Decompiler ...")
        decompiler = decompiler.lower()
        if decompiler == "dex2jad":
            d.set_decompiler(
                DecompilerDex2Jad(d, androconf.CONF["PATH_DEX2JAR"],
                                  androconf.CONF["BIN_DEX2JAR"],
                                  androconf.CONF["PATH_JAD"],
                                  androconf.CONF["BIN_JAD"],
                                  androconf.CONF["TMP_DIRECTORY"]))
        elif decompiler == "dex2fernflower":
            d.set_decompiler(
                DecompilerDex2Fernflower(d, androconf.CONF["PATH_DEX2JAR"],
                                         androconf.CONF["BIN_DEX2JAR"],
                                         androconf.CONF["PATH_FERNFLOWER"],
                                         androconf.CONF["BIN_FERNFLOWER"],
                                         androconf.CONF["OPTIONS_FERNFLOWER"],
                                         androconf.CONF["TMP_DIRECTORY"]))
        elif decompiler == "ded":
            d.set_decompiler(
                DecompilerDed(d, androconf.CONF["PATH_DED"],
                              androconf.CONF["BIN_DED"],
                              androconf.CONF["TMP_DIRECTORY"]))
        else:
            d.set_decompiler(DecompilerDAD(d, dx))
Пример #16
0
    def reload_java_sources(self):
        """Reload completely the sources by asking Androguard
           to decompile it again. Useful when:
            - an element has been renamed to propagate the info
            - the current tab is changed because we do not know what user
              did since then, so we need to propagate previous changes as well
        """

        androconf.debug("Getting sources for %s" % self.current_class)

        lines = []
        lines.append(
            (
                "COMMENTS",
                [("COMMENT", "/*\n * filename:%s\n * digest:%s\n */\n" % (self.current_filename, self.current_digest))],
            )
        )
        lines.extend(self.current_class.get_source_ext())

        # TODO: delete doc when tab is closed? not deleted by "self" :(
        if hasattr(self, "doc"):
            del self.doc
        self.doc = SourceDocument(parent=self, lines=lines)
        self.setDocument(self.doc)

        # No need to save hightlighter. highlighBlock will automatically be called
        # because we passed the QTextDocument to QSyntaxHighlighter constructor
        if PYGMENTS:
            PygmentsHighlighter(self.doc, lexer=JavaLexer())
        else:
            androconf.debug("Pygments is not present !")
Пример #17
0
    def __init__(
        self,
        parent=None,
        win=None,
        current_class=None,
        current_title=None,
        current_filename=None,
        current_digest=None,
        session=None,
    ):
        super(SourceWindow, self).__init__(parent)
        androconf.debug("New source tab for: %s" % current_class)

        self.mainwin = win
        self.session = session
        self.current_class = current_class
        self.current_title = current_title
        self.current_filename = current_filename
        self.current_digest = current_digest

        self.title = current_title

        self.setReadOnly(True)

        self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.CustomContextMenuHandler)

        self.cursorPositionChanged.connect(self.cursor_position_changed)
Пример #18
0
    def openSourceWindow(self, current_class, method=None):
        """Main function to open a decompile source window
           It checks if it already opened and open that tab,
           otherwise, initialize a new window.
        """
        androconf.debug("openSourceWindow for %s" % current_class)

        sourcewin = self.getMeOpenedWindowIfExists(current_class.current_title + "(S)")
        if not sourcewin:
            current_filename = self.session.get_filename_by_class(current_class)
            current_digest = self.session.get_digest_by_class(current_class)

            sourcewin = SourceWindow(
                win=self,
                current_class=current_class,
                current_title=current_class.current_title + "(S)",
                current_filename=current_filename,
                current_digest=current_digest,
                session=self.session,
            )
            sourcewin.reload_java_sources()
            self.central.addTab(sourcewin, sourcewin.title)
            self.central.setTabToolTip(self.central.indexOf(sourcewin), sourcewin.title)

        if method:
            sourcewin.browse_to_method(method)

        self.central.setCurrentWidget(sourcewin)
Пример #19
0
    def setupHelpMenu(self):
        androconf.debug("Setup Help Menu")

        self.helpMenu = self.menuBar().addMenu("&Help")

        self.helpMenu.addAction("&About", self.about)
        self.helpMenu.addAction("About &Qt", QtWidgets.qApp.aboutQt)
Пример #20
0
    def openSourceWindow(self, current_class, method=None):
        '''Main function to open a decompile source window
           It checks if it already opened and open that tab,
           otherwise, initialize a new window.
        '''
        androconf.debug("openSourceWindow for %s" % current_class)

        sourcewin = self.getMeOpenedWindowIfExists(
            current_class.current_title + "(S)")
        if not sourcewin:
            current_filename = self.session.get_filename_by_class(
                current_class)
            current_digest = self.session.get_digest_by_class(current_class)

            sourcewin = SourceWindow(
                win=self,
                current_class=current_class,
                current_title=current_class.current_title + "(S)",
                current_filename=current_filename,
                current_digest=current_digest,
                session=self.session)
            sourcewin.reload_java_sources()
            self.central.addTab(sourcewin, sourcewin.title)
            self.central.setTabToolTip(self.central.indexOf(sourcewin),
                                       sourcewin.title)

        if method:
            sourcewin.browse_to_method(method)

        self.central.setCurrentWidget(sourcewin)
Пример #21
0
    def reload_java_sources(self):
        '''Reload completely the sources by asking Androguard
           to decompile it again. Useful when:
            - an element has been renamed to propagate the info
            - the current tab is changed because we do not know what user
              did since then, so we need to propagate previous changes as well
        '''

        androconf.debug("Getting sources for %s" % self.current_class)

        lines = []
        lines.append(("COMMENTS",
                      [("COMMENT", "/*\n * filename:%s\n * digest:%s\n */\n" %
                        (self.current_filename, self.current_digest))]))
        lines.extend(self.current_class.get_source_ext())

        #TODO: delete doc when tab is closed? not deleted by "self" :(
        if hasattr(self, "doc"):
            del self.doc
        self.doc = SourceDocument(parent=self, lines=lines)
        self.setDocument(self.doc)

        #No need to save hightlighter. highlighBlock will automatically be called
        #because we passed the QTextDocument to QSyntaxHighlighter constructor
        if PYGMENTS:
            PygmentsHighlighter(self.doc, lexer=JavaLexer())
        else:
            androconf.debug("Pygments is not present !")
Пример #22
0
    def reload_java_sources(self):
        """Reload completely the sources by asking Androguard
           to decompile it again. Useful when:
            - an element has been renamed to propagate the info
            - the current tab is changed because we do not know what user
              did since then, so we need to propagate previous changes as well
        """

        androconf.debug("Getting sources for %s" % self.current_class)

        lines = [("COMMENTS", [("COMMENT", "// filename:%s\n// digest:%s\n\n" %
                                (self.current_filename, self.current_digest))])
                 ]

        method_info_buff = ""
        for method in self.current_class.get_methods():
            method_info_buff += "// " + str(method) + "\n"

        lines.append(("COMMENTS", [("COMMENT", method_info_buff + "\n\n")]))

        lines.extend(self.current_class.get_source_ext())

        # TODO: delete doc when tab is closed? not deleted by "self" :(
        if hasattr(self, "doc"):
            del self.doc
        self.doc = SourceDocument(parent=self, lines=lines)
        self.setDocument(self.doc)

        # No need to save hightlighter. highlighBlock will automatically be called
        # because we passed the QTextDocument to QSyntaxHighlighter constructor
        MyHighlighter(self.doc, lexer=JavaLexer())
Пример #23
0
 def getMeOpenedWindowIfExists(self, name):
     for idx in range(self.central.count()):
         if name == self.central.tabToolTip(idx):
             androconf.debug("Tab %s already opened at: %d" %
                             (name, idx))
             return self.central.widget(idx)
     return None
Пример #24
0
 def _runPlugin(self, filepath):
     androconf.debug("RUN plugin from %s" % filepath)
     module_name = os.path.splitext(os.path.basename(filepath))[0]
     f, filename, description = imp.find_module(module_name, [os.path.dirname(filepath)])
     print f, filename, description
     mod = imp.load_module(module_name, f, filename, description)
     mod.PluginEntry(self.session)
Пример #25
0
    def actionGoto(self):
        cursor = self.textCursor()
        start = cursor.selectionStart()
        end = cursor.selectionEnd()
        selection = cursor.selectedText()
        androconf.debug("Goto asked for '%s' (%d, %d)" % (selection, start, end))

        if start not in self.doc.binding.keys():
            self.mainwin.showStatus("Goto not available. No info for: '%s'." % selection)
            return

        t = self.doc.binding[start]
        if t[0] == 'NAME_METHOD_INVOKE':
            class_, method_ = t[2].split(' -> ')
            if class_ == 'this':
                class_ = self.path
            else:
                class_ = classdot2class(class_)
        else:
            self.mainwin.showStatus("Goto not available. Info ok: '%s' but object not supported." % selection)
            return

        androconf.debug("Found corresponding method: %s -> %s in source file: %s" % (class_, method_, self.path))

        if not self.mainwin.doesClassExist(class_):
            self.mainwin.showStatus("Goto not available. Class: %s not in database." % class_)
            return

        self.mainwin.openSourceWindow(class_, method=method_)
Пример #26
0
 def _runPlugin(self, filepath):
     androconf.debug("RUN plugin from %s" % filepath)
     module_name = os.path.splitext(os.path.basename(filepath))[0]
     f, filename, description = imp.find_module(module_name,
                                                [os.path.dirname(filepath)])
     print f, filename, description
     mod = imp.load_module(module_name, f, filename, description)
     mod.PluginEntry(self.session)
Пример #27
0
    def openApkWindow(self):
        androconf.debug("openApkWindow for %s" % self.session.analyzed_apk)
        bin_window = binWidget(self, ApkModel(self.session.get_objects_apk(self.fileLoadingThread.file_path)[0]), "APK")
        bin_window.activateWindow()
        self.central.addTab(bin_window, bin_window.title)
        self.central.setCurrentWidget(bin_window)

        self.bin_windows[bin_window.title] = bin_window
Пример #28
0
    def setupFileMenu(self):
        androconf.debug("Setup File Menu")
        self.fileMenu = self.menuBar().addMenu("&File")

        self.fileMenu.addAction("&Open...", self.openFile, "Ctrl+O")
        self.fileMenu.addAction("&Add...", self.addFile, "Ctrl+A")
        self.fileMenu.addAction("&Save...", self.saveFile, "Ctrl+S")
        self.fileMenu.addAction("E&xit", self.close, "Ctrl+Q")
Пример #29
0
 def getMeSourceWindowIfExists(self, current_class):
     '''Helper for openSourceWindow'''
     for idx in range(self.central.count()):
         if current_class.get_name() == self.central.tabToolTip(idx):
             androconf.debug("Tab %s already opened at: %d" %
                             (current_class.get_name(), idx))
             return self.central.widget(idx)
     return None
Пример #30
0
    def setupFileMenu(self):
        androconf.debug("Setup File Menu")
        self.fileMenu = self.menuBar().addMenu("&File")

        self.fileMenu.addAction("&Open...", self.openFile, "Ctrl+O")
        self.fileMenu.addAction("&Add...", self.addFile, "Ctrl+A")
        self.fileMenu.addAction("&Save...", self.saveFile, "Ctrl+S")
        self.fileMenu.addAction("E&xit", self.close, "Ctrl+Q")
Пример #31
0
    def openApkWindow(self):
        androconf.debug("openApkWindow for %s" % self.session.analyzed_apk)
        bin_window = binWidget(self, ApkModel(self.session.get_objects_apk(self.fileLoadingThread.file_path)[0]), "APK")
        bin_window.activateWindow()
        self.central.addTab(bin_window, bin_window.title)
        self.central.setCurrentWidget(bin_window)

        self.bin_windows[bin_window.title] = bin_window
Пример #32
0
    def runAnalysis(self, d):
        androconf.debug("VMAnalysis ...")
        dx = newVMAnalysis(d)
        dx.create_xref()

        d.set_decompiler(DecompilerDAD(d, dx))
        d.set_vmanalysis(dx)

        return dx
Пример #33
0
 def addAPK(self, filename, data):
     digest = hashlib.sha256(data).hexdigest()
     androconf.debug("add APK:%s" % digest)
     apk = APK(data, True)
     self.analyzed_apk[digest] = [apk]
     self.analyzed_files[filename].append(digest)
     self.analyzed_digest[digest] = filename
     androconf.debug("added APK:%s" % digest)
     return (digest, apk)
Пример #34
0
    def cursor_position_changed(self):
        '''Used to detect when cursor change position and to auto select word
           underneath it'''

        cur = self.textCursor()
        if len(cur.selectedText()) == 0:
            cur.select(QtGui.QTextCursor.SelectionType.WordUnderCursor)
            self.setTextCursor(cur)
            androconf.debug("cursor: %s" % cur.selectedText())
Пример #35
0
    def cursor_position_changed(self):
        '''Used to detect when cursor change position and to auto select word
           underneath it'''

        cur = self.textCursor()
        if len(cur.selectedText()) == 0:
            cur.select(QtGui.QTextCursor.SelectionType.WordUnderCursor)
            self.setTextCursor(cur)
            androconf.debug("cursor: %s" % cur.selectedText())
Пример #36
0
 def load_androguard_session(self):
     if not self.apk_path.endswith('.apk'):
         print "Not loading session. APK not supported"
         return False
     if os.path.isfile(self.session_path):
         androconf.debug("Loading previous session")
         self.a, self.d, self.x = load_session(self.session_path)
         return True
     return False
Пример #37
0
 def addAPK(self, filename, data):
     digest = hashlib.sha256(data).hexdigest()
     androconf.debug("add APK:%s" % digest)
     apk = APK(data, True)
     self.analyzed_apk[digest] = [apk]
     self.analyzed_files[filename].append(digest)
     self.analyzed_digest[digest] = filename
     androconf.debug("added APK:%s" % digest)
     return (digest, apk)
Пример #38
0
 def load_androguard_session(self):
     if not self.apk_path.endswith('.apk'):
         print "Not loading session. APK not supported"
         return False
     if os.path.isfile(self.session_path):
         androconf.debug("Loading previous session")
         self.a, self.d, self.x = load_session(self.session_path)
         return True
     return False
Пример #39
0
    def diff_ins(self, di) :
        self.di = di

        off_add = {}
        off_rm = {}
        for i in self.di.add_ins :
            off_add[ i[0] ] = i

        for i in self.di.remove_ins :
            off_rm[ i[0] ] = i

        nb = 0
        for i in self.bb1.ins :
            ok = False
            if nb in off_add :
                debug("%d ADD %s %s" % (nb, off_add[ nb ][2].get_name(), off_add[ nb ][2].get_output()))
                self.ins.append( off_add[ nb ][2] )
                setattr( off_add[ nb ][2], "diff_tag", DIFF_INS_TAG["ADD"] )
                del off_add[ nb ]

            if nb in off_rm :
                debug("%d RM %s %s" % (nb, off_rm[ nb ][2].get_name(), off_rm[ nb ][2].get_output()))
                self.ins.append( off_rm[ nb ][2] )
                setattr( off_rm[ nb ][2], "diff_tag", DIFF_INS_TAG["REMOVE"] )
                del off_rm[ nb ]
                ok = True

            if ok == False :
                self.ins.append( i )
                debug("%d %s %s" % (nb, i.get_name(), i.get_output()))
                setattr( i, "diff_tag", DIFF_INS_TAG["ORIG"] )

            nb += 1

        #print nb, off_add, off_rm

        nbmax = nb
        if off_add != {} :
            nbmax = sorted(off_add)[-1]
        if off_rm != {} :
            nbmax = max(nbmax, sorted(off_rm)[-1])

        while nb <= nbmax :
            if nb in off_add :
                debug("%d ADD %s %s" % (nb, off_add[ nb ][2].get_name(), off_add[ nb ][2].get_output()))
                self.ins.append( off_add[ nb ][2] )
                setattr( off_add[ nb ][2], "diff_tag", DIFF_INS_TAG["ADD"] )
                del off_add[ nb ]

            if nb in off_rm :
                debug("%d RM %s %s" % (nb, off_rm[ nb ][2].get_name(), off_rm[ nb ][2].get_output()))
                self.ins.append( off_rm[ nb ][2] )
                setattr( off_rm[ nb ][2], "diff_tag", DIFF_INS_TAG["REMOVE"] )
                del off_rm[ nb ]

            nb += 1
Пример #40
0
    def diff_ins(self, di):
        self.di = di

        off_add = {}
        off_rm = {}
        for i in self.di.add_ins:
            off_add[ i[0] ] = i

        for i in self.di.remove_ins:
            off_rm[ i[0] ] = i

        nb = 0
        for i in self.bb1.ins:
            ok = False
            if nb in off_add:
                debug("%d ADD %s %s" % (nb, off_add[ nb ][2].get_name(), off_add[ nb ][2].get_output()))
                self.ins.append( off_add[ nb ][2] )
                setattr( off_add[ nb ][2], "diff_tag", DIFF_INS_TAG["ADD"] )
                del off_add[ nb ]

            if nb in off_rm:
                debug("%d RM %s %s" % (nb, off_rm[ nb ][2].get_name(), off_rm[ nb ][2].get_output()))
                self.ins.append( off_rm[ nb ][2] )
                setattr( off_rm[ nb ][2], "diff_tag", DIFF_INS_TAG["REMOVE"] )
                del off_rm[ nb ]
                ok = True

            if ok == False:
                self.ins.append( i )
                debug("%d %s %s" % (nb, i.get_name(), i.get_output()))
                setattr( i, "diff_tag", DIFF_INS_TAG["ORIG"] )

            nb += 1

        #print nb, off_add, off_rm

        nbmax = nb
        if off_add != {}:
            nbmax = sorted(off_add)[-1]
        if off_rm != {}:
            nbmax = max(nbmax, sorted(off_rm)[-1])

        while nb <= nbmax:
            if nb in off_add:
                debug("%d ADD %s %s" % (nb, off_add[ nb ][2].get_name(), off_add[ nb ][2].get_output()))
                self.ins.append( off_add[ nb ][2] )
                setattr( off_add[ nb ][2], "diff_tag", DIFF_INS_TAG["ADD"] )
                del off_add[ nb ]

            if nb in off_rm:
                debug("%d RM %s %s" % (nb, off_rm[ nb ][2].get_name(), off_rm[ nb ][2].get_output()))
                self.ins.append( off_rm[ nb ][2] )
                setattr( off_rm[ nb ][2], "diff_tag", DIFF_INS_TAG["REMOVE"] )
                del off_rm[ nb ]

            nb += 1
Пример #41
0
    def setupViewMenu(self):
        androconf.debug("Setup View Menu")

        self.viewMenu = self.menuBar().addMenu("&View")

        self.viewMenu.addAction("&Strings...", self.openStringsWindow)
        self.viewMenu.addAction("&Methods...", self.openMethodsWindow)
        self.viewMenu.addAction("&API...", self.openAPIWindow)
        self.viewMenu.addAction("&APK...", self.openApkWindow)
        self.viewMenu.addAction("&Resources...", self.openResourcesWindow)
Пример #42
0
    def runAnalysis(self, d, dx=None):
        androconf.debug("VMAnalysis ...")
        if dx == None:
            dx = NewVmAnalysis(d)
        else:
            dx.add(d)

        dx.explicit_icfg()

        return dx
Пример #43
0
    def actionInfo(self):
        cursor = self.textCursor()
        start = cursor.selectionStart()
        end = cursor.selectionEnd()
        androconf.debug("actionInfo asked for (%d, %d)" % (start, end))

        if start in self.doc.binding.keys():
            self.mainwin.showStatus('%s at position: (%d, %d)' % (str(self.doc.binding[start]), start, end))
        else:
            self.mainwin.showStatus("No info available.")
Пример #44
0
    def runAnalysis(self, d, dx=None):
        androconf.debug("VMAnalysis ...")
        if dx == None:
            dx = NewVmAnalysis(d)
        else:
            dx.add(d)

        dx.explicit_icfg()

        return dx
Пример #45
0
    def itemDoubleClickedHandler(self, item, column):
        androconf.debug("item %s has been double clicked at column %s" %
                        (str(item), str(column)))
        if item.childCount() != 0:
            self.mainwin.showStatus("Sources not available.")
            return

        current_class, current_filename, current_digest = self._reverse_cache[
            item]
        self.mainwin.openBinWindow(current_class)
Пример #46
0
    def itemDoubleClickedHandler(self, item, column):
        '''Signal sent by PySide when a tree element is clicked'''

        androconf.debug("item %s has been double clicked at column %s" % (str(item), str(column)))
        if item.childCount() != 0:
            self.mainwin.showStatus("Sources not available. %s is not a class" % path)
            return

        current_class, current_filename, current_digest = self._reverse_cache[item]
        self.mainwin.openSourceWindow(current_class)
Пример #47
0
    def itemDoubleClickedHandler(self, item, column):
        '''Signal sent by PySide when a tree element is clicked'''

        androconf.debug("item %s has been double clicked at column %s" % (str(item), str(column)))
        if item.childCount() != 0:
            self.mainwin.showStatus("Sources not available. %s is not a class" % path)
            return

        current_class, current_filename, current_digest = self._reverse_cache[item]
        self.mainwin.openSourceWindow(current_class)
Пример #48
0
    def actionInfo(self):
        cursor = self.textCursor()
        start = cursor.selectionStart()
        end = cursor.selectionEnd()
        androconf.debug("actionInfo asked for (%d, %d)" % (start, end))

        if start in self.doc.binding.keys():
            self.mainwin.showStatus('%s at position: (%d, %d)' % (str(self.doc.binding[start]), start, end))
        else:
            self.mainwin.showStatus("No info available.")
Пример #49
0
    def setupViewMenu(self):
        androconf.debug("Setup View Menu")

        self.viewMenu = self.menuBar().addMenu("&View")

        self.viewMenu.addAction("&Strings...", self.openStringsWindow)
        self.viewMenu.addAction("&Methods...", self.openMethodsWindow)
        self.viewMenu.addAction("&API...", self.openAPIWindow)
        self.viewMenu.addAction("&APK...", self.openApkWindow)
        self.viewMenu.addAction("&Resources...", self.openResourcesWindow)
Пример #50
0
    def itemDoubleClickedHandler(self, item, column):
        androconf.debug("item %s has been double clicked at column %s" %
                        (str(item), str(column)))
        if item.childCount() != 0:
            self.mainwin.showStatus("Sources not available.")
            return

        current_class, current_filename, current_digest = self._reverse_cache[
            item
        ]
        self.mainwin.openBinWindow(current_class)
Пример #51
0
def filter_sort_meth_basic( j, x, value ):
    z = sorted(iter(x.items()), key=lambda k_v1: (k_v1[1],k_v1[0]))

    if get_debug():
        for i in z:
            debug("\t %s %f" %(i[0].get_info(), i[1]))

    if z[:1][0][1] > value:
        return []

    return z[:1]
Пример #52
0
def filter_sort_meth_string(j, x, value):
    z = sorted(x.iteritems(), key=lambda (k, v): (v, k))

    if get_debug():
        for i in z:
            debug("\t %s %f" % (i[0].get_info(), i[1]))

    if z[:1][0][1] > value:
        return []

    return z[:1]
Пример #53
0
    def set_childs(self, abb):
        childs = []
        for c in self.bb.childs:
            if c[2].name in abb:
                debug("SET %s %s " % (c[2], abb[c[2].name]))
                childs.append((c[0], c[1], abb[c[2].name]))
            else:
                debug("SET ORIG %s" % str(c))
                childs.append(c)

        self.childs = childs
Пример #54
0
    def set_childs(self, abb) :
        childs = []
        for c in self.bb.childs :
            if c[2].name in abb :
                debug("SET %s %s " % (c[2], abb[ c[2].name ]))
                childs.append( (c[0], c[1], abb[ c[2].name ]) )
            else :
                debug("SET ORIG %s" % str(c))
                childs.append( c )

        self.childs = childs
Пример #55
0
def filter_sort_meth_basic( j, x, value ) :
    z = sorted(x.iteritems(), key=lambda (k,v): (v,k))

    if get_debug() :
        for i in z :
            debug("\t %s %f" %(i[0].get_info(), i[1]))

    if z[:1][0][1] > value :
        return []

    return z[:1]
Пример #56
0
    def get_xrefs_list(cls, class_item, method=None):
        '''Static method called before creating a XrefDialog
           to check if there are xrefs to display
            method (optional): method of the class we are looking xref from
        '''
        androconf.debug("Getting XREF for %s" % class_item)

        item = class_item
        if method:
            item = method

        return XrefDialog.get_xrefs_list_from_element(item)
Пример #57
0
 def run(self):
     if self.apk_path is not None:
         try:
             if not self.load_androguard_session():
                 self.a, self.d, self.x = AnalyzeAPK(self.apk_path,
                         decompiler="dad")
             self.emit(QtCore.SIGNAL("loadedApk(bool)"), True)
         except Exception as e:
             androconf.debug(e)
             self.emit(QtCore.SIGNAL("loadedApk(bool)"), False)
     else:
         self.emit(QtCore.SIGNAL("loadedApk(bool)"), False)
Пример #58
0
def BuildCFG(inputFile, outputFile ) :

    androconf.debug("DalvikVMFormat ...")

#    print sys.argv
#    print "hahahahahahahahah"

    
    d = None
#    if raw == False:
#        d = DalvikVMFormat(open(filename, "rb").read())
#    else:
#        d = DalvikVMFormat(filename)

    androconf.debug("APK ...")
    a = APK(inputFile, False)
#    d, dx = AnalyzeDex(a.get_dex(), raw=True, decompiler=decompiler)
    newFile = a.get_dex()
    d = DalvikVMFormat(newFile)
    x = uVMAnalysis(d)
    fd = open(outputFile, "w")

    for method in d.get_methods():
        g = x.get_method(method)

        if method.get_code() == None:
            continue

#        print method.get_class_name(), method.get_name(), method.get_descriptor()

        fd.write(method.get_class_name() + " " + method.get_name() + " " + method.get_descriptor() + " " + str(method.code.get_registers_size()-1) + "\n")

        idx = 0
        for i in g.get_basic_blocks().get(): 
#            print "\t %s %x %x" % (i.name, i.start, i.end), '[ NEXT = ', ', '.join( "%x-%x-%s" % (j[0], j[1], j[2].get_name()) for j in i.get_next() ), ']', '[ PREV = ', ', '.join( j[2].get_name() for j in i.get_prev() ), ']' 
            fd.write("\t" + i.name + " " + str(hex(i.start)) + " " + str(hex(i.end)))
            fd.write("[ NEXT = ")

            for j in i.get_next():
                fd.write(str(hex(j[0])) + "-" + str(hex(j[1])) + "-" + j[2].get_name() + " ")
            fd.write(" ]")
            fd.write(" [ PREV = " + ', '.join(j[2].get_name() for j in i.get_prev() ))
            fd.write("] \n") 
           
            for ins in i.get_instructions():
 #               print "\t\t %x" % idx, ins.get_name(), ins.get_output()
                fd.write("\t\t" + str(hex(idx)) + " " + ins.get_name() + " " + ins.get_output() + "\n")
                idx += ins.get_length()

#            print ""  
    fd.close()
  
    return d