def run(self, ctx):
        self.ctx = ctx

        if not isinstance(self.ctx, IGraphicalClientContext):
            print ('This script must be run within a graphical client')
            return

        engctx = ctx.getEnginesContext()
        if not engctx:
            print('Back-end engines not initialized')
            return

        projects = engctx.getProjects()
        if not projects:
            print('There is no opened project')

        self.prj = projects[0]

        self.codeUnits = RuntimeProjectUtil.findUnitsByType(self.prj, ICodeUnit, False)
        if not self.codeUnits:
            return

        self.JavaSourceUnit = RuntimeProjectUtil.findUnitsByType(self.prj, IJavaSourceUnit, False)

        for unit in self.JavaSourceUnit:
            clz = unit.getClassElement()
            self.dfs(unit, clz)
            unit.notifyListeners(JebEvent(J.UnitChange))
Example #2
0
    def run(self, ctx):
        print('start deal with strings')
        self.ctx = ctx
        engctx = ctx.getEnginesContext()
        if not engctx:
            print('Back-end engines not initialized')
            return

        projects = engctx.getProjects()
        if not projects:
            print('There is no opened project')
            return
        # means this is current project
        prj = projects[0]

        self.codeunits = RuntimeProjectUtil.findUnitsByType(
            prj, ICodeUnit, False)
        for codeUnit in self.codeunits:
            self.decompileForCodeUnit(codeUnit)

        units = RuntimeProjectUtil.findUnitsByType(prj, IJavaSourceUnit, False)
        for unit in units:
            javaClass = unit.getClassElement()
            print('[+] decrypt:' + javaClass.getName())
            self.cstbuilder = unit.getFactories().getConstantFactory()
            self.processClass(javaClass)
            unit.notifyListeners(JebEvent(J.UnitChange))
        print('Done.')
    def run(self, ctx):
        self.keys = {}

        engctx = ctx.getEnginesContext()
        if not engctx:
            print('Back-end engines not initialized')
            return

        projects = engctx.getProjects()
        if not projects:
            print('There is no opened project')
            return

        project = projects[0]  # Get current project(IRuntimeProject)
        print('Decompiling code units of %s...' % project)

        self.dexunit = RuntimeProjectUtil.findUnitsByType(
            project, IDexUnit, False)[0]  # Get dex context, needs >=V2.2.1
        self.currentunit = ctx.getFocusedView().getActiveFragment().getUnit(
        )  # Get current Source Tab in Focus
        javaclass = self.currentunit.getClassElement()  # needs >V2.1.4
        curaddr = ctx.getFocusedView().getActiveFragment().getActiveAddress(
        )  # needs 2.1.4
        print('Current class: %s' % javaclass.getName())
        print('Current address: %s' % curaddr)
        self.cstbuilder = self.currentunit.getFactories().getConstantFactory(
        )  # we need a context to cstbuilder to replace strings
        self.processTargetClass(javaclass)  #Call our main function
        self.currentunit.notifyListeners(JebEvent(J.UnitChange))
Example #4
0
  def run(self, ctx):
    # retrieve the currently active UI fragment (make sure to select a Decompiled Java fragment)
    f = ctx.getFocusedFragment()

    # IJavaSourceUnit    
    unit = f.getUnit()

    # a DEX-style address: TYPENAME->METHODNAME(PARAMTYPES)RETTYPE+OFFSET
    addr = f.getActiveAddress()

    # IDexDecompilerUnit
    dexdec = unit.getParent()

    pos = addr.find('+')
    if pos >= 0: addr = addr[:pos]

    # retrieve the already decompiled IJavaMethod on caret
    _m = dexdec.getMethod(addr)

    # method body...
    _blk = _m.getBody()
    # we pick the first statement
    _stm0 = _blk.get(0)
    print('Will replace statement: "%s"' % _stm0)

    # IJavaFactories
    self.jfactory = unit.getFactories()

    # now, replace that first method statement by a call to 'new String("...")'
    if self.replaceStatement(_blk, _stm0):
      unit.notifyListeners(JebEvent(J.UnitChange))
    def run(self, ctx):
        engctx = ctx.getEnginesContext()
        if not engctx:
            print('Back-end engines not initialized')
            return

        projects = engctx.getProjects()
        if not projects:
            print('There is no opened project')
            return

        prj = projects[0]
        print('Decompiling code units of %s...' % prj)

        self.codeUnit = RuntimeProjectUtil.findUnitsByType(
            prj, ICodeUnit, False)[0]
        print(self.codeUnit)

        # the encryption keys could be determined by analyzing the decryption method
        self.targetClass = 'MainActivity'
        self.keys = [409, 62, -8]

        # enumerate the decompiled classes, find and process the target class
        units = RuntimeProjectUtil.findUnitsByType(prj, IJavaSourceUnit, False)
        for unit in units:
            javaClass = unit.getClassElement()
            if javaClass.getName().find(self.targetClass) >= 0:
                self.cstbuilder = unit.getFactories().getConstantFactory()
                if self.processClass(javaClass):
                    # let client code know about those changes
                    unit.notifyListeners(JebEvent(J.UnitChange))
                break
Example #6
0
 def processDex(self, dex):
     # replace DEX strings
     cnt = 0
     for s in dex.getStrings():
         if s.getValue().startswith('text/html'):
             s.setValue('foobar')
             cnt += 1
             print('String replaced')
     if cnt > 0:
         dex.notifyListeners(JebEvent(J.UnitChange))
Example #7
0
    def run(self, ctx):
        prj = ctx.getMainProject()

        unit = prj.findUnits(IJavaSourceUnit).get(0)

        self.replcnt = 0
        self.cstbuilder = unit.getFactories().getConstantFactory()
        self.checkElement(None, unit.getClassElement())

        unit.notifyListeners(JebEvent(J.UnitChange))
        print('Replaced %d strings' % self.replcnt)
Example #8
0
    def run(self, ctx):
        engctx = ctx.getEnginesContext()
        if not engctx:
            print('Back-end engines not initialized')
            return

        projects = engctx.getProjects()
        if not projects:
            print('There is no opened project')
            return

        # get the first unit available
        units = RuntimeProjectUtil.findUnitsByType(projects[0], None, False)
        if not units:
            print('No unit available')
            return

        unit = units[0]
        print('Unit: %s' % unit)

        # retrieve the formatter, which is a producer of unit representations
        formatter = unit.getFormatter()

        # create a table document
        columnLabels = Arrays.asList('Key', 'Value', 'Comment')
        rows = ArrayList()
        rows.add(
            TableRow(Arrays.asList(Cell('foo'), Cell('bar'), Cell('none'))))
        rows.add(
            TableRow(
                Arrays.asList(Cell('type'), Cell('integer'), Cell('unset'))))
        extraDoc = StaticTableDocument(columnLabels, rows)
        extraPres0 = UnitRepresentationAdapter(101, 'Demo Table', False,
                                               extraDoc)

        # create a tree document
        columnLabels = Arrays.asList('Key', 'Value')
        root = KVNode('foo', 'bar')
        roots = Arrays.asList(root)
        root.addChild(KVNode('quantified', 'self'))
        root.addChild(KVNode('galaxy', 'milky way'))
        node = KVNode('black hole', '42')
        node.setClassId(ItemClassIdentifiers.INFO_DANGEROUS)
        root.addChild(node)
        extraDoc = StaticTreeDocument(roots, columnLabels, -1)
        extraPres1 = UnitRepresentationAdapter(102, 'Demo Tree', False,
                                               extraDoc)

        # add the newly created presentations to our unit, and notify clients
        # the second argument indicates that the presentation should be persisted when saving the project
        formatter.addPresentation(extraPres0, True)
        formatter.addPresentation(extraPres1, True)
        unit.notifyListeners(JebEvent(J.UnitChange))
 def process(self, dex):
     cnt = 0
     for c in dex.getClasses():
         name = c.getName()
         idx = c.getSourceStringIndex()
         if idx >= 0:
             debugName = dex.getString(idx).getValue()
             #print(debugName)
             if debugName:
                 debugName = debugName.replace('.java', '')
                 if debugName != name and c.setName(debugName):
                     print('Renamed class %s to %s' % (name, debugName))
                     cnt += 1
     if cnt > 0:
         dex.notifyListeners(JebEvent(J.UnitChange))
Example #10
0
    def run(self, ctx):
        prj = ctx.getMainProject()
        print('Decompiling code units of %s...' % prj)

        # first code unit
        self.codeUnit = prj.findUnit(ICodeUnit)
        print('Code unit: %s' % self.codeUnit)

        # the encryption keys could be determined by analyzing the decryption method
        self.targetClass = 'MainActivity'
        self.keys = [409, 62, -8]

        # enumerate the decompiled classes, find and process the target class
        for unit in prj.findUnits(IJavaSourceUnit):
            javaClass = unit.getClassElement()
            if javaClass.getName().find(self.targetClass) >= 0:
                self.cstbuilder = unit.getFactories().getConstantFactory()
                if self.processClass(javaClass):
                    # let client code know about those changes
                    unit.notifyListeners(JebEvent(J.UnitChange))
                break
Example #11
0
 def replace(self, father, elem, statement, javaClass, unit):
     for argument in elem.getArguments():
         if isinstance(argument, IJavaNewArray):
             encbytes = []
             decbytes = []
             for v in argument.getInitialValues():
                 # retrieve the encoded values
                 encbytes.append(v.getByte())
             if len(encbytes) > 0:
                 decbytes = self.decodeBytes(encbytes)
                 id = ''
                 if isinstance(statement.getLeft(), IJavaArrayElt):
                     id = str(statement.getLeft().getIndex())
                 if isinstance(statement.getLeft(), IJavaStaticField):
                     id = str(statement.getLeft().getField().getSignature())
                 print "Class: %s Id: %s Value: %s" % (
                     javaClass.getName(), id, ''.join(map(chr, decbytes)))
                 father.replaceSubElement(
                     elem,
                     self.cstbuilder.createString(''.join(map(
                         chr, decbytes))))
                 unit.notifyListeners(JebEvent(J.UnitChange))
Example #12
0
    def run(self, ctx):
        engctx = ctx.getEnginesContext()
        if not engctx:
            print('Back-end engines not initialized')
            return

        projects = engctx.getProjects()
        if not projects:
            print('There is no opened project')
            return

        # get the first unit available
        units = RuntimeProjectUtil.findUnitsByType(projects[0], None, False)
        if not units:
            print('No unit available')
            return

        unit = units[0]
        print('Unit: %s' % unit)

        # retrieve the formatter, which is a producer of unit representations
        formatter = unit.getFormatter()

        # create an extra document (text document), wrap it in a representtion
        lines = ArrayList()
        lines.add(
            Line(
                'There are two hard problems in computer science: cache invalidation, naming things, and off-by-one errors.'
            ))
        lines.add(Line('   - Phil Karlton (and others)'))
        extraDoc = StaticTextDocument(lines)
        extraPres = UnitRepresentationAdapter(100, 'Quotes', False, extraDoc)

        # add the newly created representation to our unit, and notify clients
        # the second argument indicates that the presentation should be persisted when saving the project
        formatter.addPresentation(extraPres, True)
        unit.notifyListeners(JebEvent(J.UnitChange))
Example #13
0
    def find_allatori(self, unit, father, element):
        if isinstance(element, IJavaCall) and element.getMethod().getName(
        ) == 'ALLATORIxDEMO':
            # get the obfuscated string
            try:
                obfuscated_string = self.prepare_string(
                    element.getArguments()[0].getString())
                print "Processing obfuscated string: ", obfuscated_string
            except AttributeError:
                print "Not a call to ALLATORIxDEMO"
                return

            # the de-obfuscation routine is configured by two integers x1 and x2
            # those values are different for each routine
            # we ask the end-user what values to use
            x1, x2 = self.get_args(obfuscated_string)

            # de-obfuscate
            deobfuscated_string = self.deobfuscate(obfuscated_string, x1, x2)

            # if de-obfuscation was successful, we ask end-user if we should replace in the code or not
            if deobfuscated_string is not None:
                print "De-obfuscated string: ", deobfuscated_string
                answer = self.ctx.displayQuestionBox(
                    deobfuscated_string, 'Shall we replace? (y/n)[n]', 'n')
                if answer == 'y':
                    father.replaceSubElement(
                        element,
                        self.cstbuilder.createString(deobfuscated_string))
                    unit.notifyListeners(JebEvent(J.UnitChange))
        else:
            if isinstance(element, IJavaAssignment):
                self.find_allatori(unit, element, element.getRight())
            else:
                for sub in element.getSubElements():
                    self.find_allatori(unit, element, sub)
Example #14
0
    def run(self, ctx):
        self.documentName = 'Comments Table'
        engctx = ctx.getEnginesContext()
        if not engctx:
            print('Back-end engines not initialized')
            return

        projects = engctx.getProjects()
        if not projects:
            print('There is no opened project')
            return

        prj = projects[0]
        print('Decompiling code units of %s...' % prj)

        units = RuntimeProjectUtil.findUnitsByType(prj, None, False)

        if not units:
            print('No unit exists')
            return

        targetUnit = units[0]  # Get the top-level unit
        formatter = targetUnit.getFormatter()  # Get the formatter of the unit

        # Set table column names
        columnLabels = Arrays.asList('Unit Name', 'Address', 'Comment')

        # Add comments to the arraylist rows
        self.rows = ArrayList()
        for unit in units:
            self.addCommentsToDoc(unit)

        # Create the table doc
        tableDoc = StaticTableDocument(columnLabels, self.rows)

        # Delete the old table doc and add the new table doc to presentations
        newId = 2  # Set the initial table doc Id (Do not use 1! 1 is default number used by "source")
        for i, document in enumerate(
                formatter.getPresentations()):  # Find the old table doc
            if (self.documentName == document.getLabel()):
                newId = document.getId(
                ) + 1  # Adding 1 to the old table doc Id as the Id of the new doc (avoid the collision)
                formatter.removePresentation(
                    i)  # Delete the old table doc from presentations
                break
        adapter = UnitRepresentationAdapter(newId, self.documentName, False,
                                            tableDoc)  # Get the new adapter
        formatter.addPresentation(
            adapter, True)  # Add the new table doc to presentations

        # Jump to the table doc fragment in the top-level unit
        views = ctx.getViews(
            targetUnit)  # Get all views of target unit(top-level unit)
        if not views:
            ctx.displayMessageBox('Warning', 'Please open the top-level unit',
                                  None, None)  # Show the value directly
            return

        targetView = views.get(0)

        fragments = targetView.getFragments(
        )  # Get all fragments of target view
        if not fragments:
            ctx.displayMessageBox('Warning', 'No fragment exists', None, None)
            return

        targetFragment = targetView.getFragments().get(
            fragments.size() - 1)  # Get the table doc just created
        # targetView.setActiveFragment(targetFragment)
        ctx.openView(targetUnit)  # Open target Unit(top-level unit)
        targetUnit.notifyListeners(JebEvent(J.UnitChange))