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 project = projects[0] # Get current project(IRuntimeProject) print('Decompiling code units of %s...' % project) self.codeUnit = RuntimeProjectUtil.findUnitsByType(project, ICodeUnit, False)[0] # Get the current codeUnit(ICodeUnit) # enumerate the decompiled classes, find and process the target class units = RuntimeProjectUtil.findUnitsByType(project, IJavaSourceUnit, False) targetClass = "" # Taget class targetClassMain = "" # Main taget class for unit in units: javaClass = unit.getClassElement() # Get a reference to the Java class defined in this unit if javaClass.getName() == self.TARGET_CLASS_NAME: # If the current class is the target class, store the target class targetClass = javaClass if javaClass.getName() == self.TARGET_CLASS_NAME_MAIN: # If the current class is the main target class, store the main target class targetClassMain = javaClass self.cstbuilder = unit.getFactories().getConstantFactory() self.processTargetClass(targetClass) if self.dic: self.processMainTargetClass(targetClassMain) # If dic is not empty, which means some variables are called by other class(main target class), we should run substitStr() method
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() self.processClass(javaClass) break
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));
def run(self, ctx): 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 prj = projects[0] print('Decompiling code units of %s...' % prj) units = RuntimeProjectUtil.findUnitsByType(prj, IJavaSourceUnit, False) for unit in units: self.processSourceTree(unit.getClassElement()) doc = self.getTextDocument(unit) javaCode, formattedMarks = self.formatTextDocument(doc) print(javaCode) if(formattedMarks): print('=> Marks:') print(formattedMarks) print('Done.')
def jumpToTargetFile(self, prj, ctx): unitFilter = UnitFilterByName(self.name + '.xml') unit = RuntimeProjectUtil.filterUnits(prj, unitFilter).get(0) if unit: ctx.openView(unit) return print("*** Cannot find target file ***")
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))
def run(self, ctx): if not isinstance(ctx, IGraphicalClientContext): print('This script must be run within a graphical client') return # show which unit view is currently focused v = ctx.getFocusedView() # needs 2.1.4 print('Focused view: %s' % v) # enumerate all unit views (views representing units) and fragments within those views print('Views and fragments:') views = ctx.getViews() for view in views: print('- %s' % view.getLabel()) fragments = view.getFragments() for fragment in fragments: print(' - %s' % view.getFragmentLabel(fragment)) # focus test if len(views) >= 2: print('Focusing the second Unit view (if any)') views[1].setFocus() # opening the first certificate unit we find (in an APK, there should be one) engctx = ctx.getEnginesContext() projects = engctx.getProjects() unitFilter = UnitFilter('cert') units = RuntimeProjectUtil.filterUnits(projects[0], unitFilter) if units: ctx.openView(units.get(0))
def run(self, ctx): self.ctx = ctx engctx = ctx.getEnginesContext() if not engctx: print('Back-end engines not initialized') return prj = engctx.getProject(0) if not prj: print('There is no opened project') return codeUnits = RuntimeProjectUtil.findUnitsByType(prj, ICodeUnit, False) if not codeUnits: return dex = codeUnits[0] # ---- SAMPLE --- Replace this by your own method name targetMethod = 'Lcom/pnfsoftware/raasta/AppHelp;->onCreate(Landroid/os/Bundle;)V' javaMethod = self.getDecompiledMethod(dex, targetMethod) if not javaMethod: print('The method was not found or was not decompiled') return print('Java Method: %s (%s)' % (javaMethod, javaMethod.getName()))
def run(self, ctx): self.ctx = ctx argv = ctx.getArguments() if len(argv) < 2: print('Provide an input file and the output folder') return self.inputFile = argv[0] self.outputDir = argv[1] print('Decompiling ' + self.inputFile + '...') engctx = ctx.getEnginesContext() if not engctx: print('Back-end engines not initialized') return # Create a project project = engctx.loadProject('PlaceholderProjectName') if not project: print('Failed to open a new project') return # Add the input file as a project artifact artifact = Artifact('PlaceholderArtifactName',FileInput(File(self.inputFile))) project.processArtifact(artifact) # Decompile code units codeUnits = RuntimeProjectUtil.findUnitsByType(project, ICodeUnit, False) for codeUnit in codeUnits: self.decompileForCodeUnit(codeUnit)
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 native code unit available units = RuntimeProjectUtil.findUnitsByType(projects[0], INativeCodeUnit, False) if not units: print('No unit available') return unit = units[0] print('Unit: %s' % unit) ''' create the following type: // Size: 10, Padding: 1, Alignment: 1 struct MyStruct1 { int a; unsigned char[3][2] b; }; ''' typeman = unit.getTypeManager() tInt = typeman.getType('int') tS1 = typeman.createStructure('MyStruct1') typeman.addStructureField(tS1, 'a', tInt) typeman.addStructureField(tS1, 'b', TypeUtil.buildArrayType(typeman, 'unsigned char', 2, 3))
def run(self, ctx): # retrieve JEB's engines from the provided IClientContext engctx = ctx.getEnginesContext() if not engctx: print('Back-end engines not initialized') return # retrieve the current project (must exist) projects = engctx.getProjects() if projects: project = projects[0] else: argv = ctx.getArguments() if len(argv) < 1: print('No project found, please provide an input contract file') return self.inputFile = argv[0] print('Processing ' + self.inputFile + '...') # create a project project = engctx.loadProject('Project') # load and process the artifact artifact = Artifact('Artifact', FileInput(File(self.inputFile))) project.processArtifact(artifact) project = engctx.getProjects()[0] # retrieve the primary code unit (must be the result of an EVM contract analysis) units = RuntimeProjectUtil.findUnitsByType(project, INativeCodeUnit, False) if not units: print('No native code unit found') return unit = units[0] print('Native code unit: %s' % unit) # GlobalAnalysis is assumed to be on (default) decomp = DecompilerHelper.getDecompiler(unit) if not decomp: print('No decompiler unit found') return # retrieve a handle on the method we wish to examine method = unit.getInternalMethods().get(0)#('sub_1001929') src = decomp.decompile(method.getName(True)) if not src: print('Routine was not decompiled') return print(src) decompTargets = src.getDecompilationTargets() print(decompTargets) decompTarget = decompTargets.get(0) ircfg = decompTarget.getContext().getCfg() # CFG object reference, see package com.pnfsoftware.jeb.core.units.code.asm.cfg print("+++ IR-CFG for %s +++" % method) print(ircfg.formatSimple())
def getTargetDoc(self, prj, targetXML): units = RuntimeProjectUtil.findUnitsByType(prj, IXmlUnit, False) for unit in units: if not unit.isProcessed(): unit.process() if unit.getName() == targetXML: doc = unit.getDocument() return doc return None
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] prjname = prj.getName() prgdir = ctx.getProgramDirectory() datafile = os.path.join(prgdir, 'codedata.txt') data = {} if os.path.exists(datafile): with open(datafile, 'r') as f: try: data = json.load(f) except: pass print('Current data:', data) d = data.get(prjname, None) if not d: print('Nothing to reload') return units = RuntimeProjectUtil.findUnitsByType(prj, ICodeUnit, False) if not units: print('No code unit available') return for unit in units: if not unit.isProcessed(): continue a = d.get(unit.getName(), None) if a: renamed_classes = a['renamed_classes'] renamed_fields = a['renamed_fields'] renamed_methods = a['renamed_methods'] comments = a['comments'] for sig, name in renamed_classes.items(): unit.getClass(sig).setName(name) for sig, name in renamed_fields.items(): unit.getField(sig).setName(name) for sig, name in renamed_methods.items(): unit.getMethod(sig).setName(name) # note: comments are applied last since `addr` can be a refactored one here for addr, comment in comments.items(): unit.setComment(addr, comment) print('Basic refactoring data was applied')
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] prjname = prj.getName() prgdir = ctx.getProgramDirectory() bpfile = os.path.join(prgdir, 'breakpoints.txt') with open(bpfile, 'r+') as f: try: bpdict = json.load(f) except: bpdict = {} #print('Current breakpoints file:', bpdict) d = bpdict.get(prjname, None) if not d: print('Nothing to reload') return # get the first code unit available (code units re interactive units) units = RuntimeProjectUtil.findUnitsByType(prj, IDebuggerUnit, False) if not units: print('No unit available') return cnt = 0 for dbg in units: a = d.get(dbg.getName(), None) if a: print(a) for entry in a: address = entry['address'] enabled = entry['enabled'] #print('- Debugger: %s (for %s): %s (%s)' % (dbg.getName(), dbg.getPotentialDebuggees(), address, 'enabled' if enabled else 'disabled')) bp = dbg.getBreakpoint(address, None) if not bp: # do not overwrite an already-set breakpoint bp = dbg.setBreakpoint(address, None) if bp: if not enabled: bp.setEnabled(False) cnt += 1 else: print('Cannot restore breakpoint at address: %s' % address) print('Breakpoints reloaded: %d.' % cnt)
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 code unit available (code units re interactive units) units = RuntimeProjectUtil.findUnitsByType(projects[0], ICodeUnit, False) if not units: print('No unit available') return unit = units[0] print('Unit: %s' % unit) # the metadata manager is optional (a unit may choose to not provide one) mm = unit.getMetadataManager() if not mm: print('The unit does not have a metadata manager') return # assume the code unit has classes (pick the second one) c = unit.getClasses()[1] targetAddress = c.getAddress() g = mm.getGroupByName('custom') if not g: print('Creating new metadata group (type: RGB) ...') g = MetadataGroup('custom', MetadataGroupType.RGB) mm.addGroup(g) print('Done') print('Adding a piece of metadata at address "%s" ...' % targetAddress) g.setData(targetAddress, 0x00FF30) print('Done') print('If the unit has a text document representation with a an Overview bar, do a Refresh to visualize the metadata') print('Listing all metadata for this unit (if possible) ...') for g1 in mm.getGroups(): print('- Group %s (type: %s)' % (g1.getName(), g1.getType())) alldata = g1.getAllData() if alldata == None: print('(This group manager does not allow metadata enumeration)') else: for k in alldata: print(' - at "%s" -> %s' % (k, alldata[k]))
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] prjname = prj.getName() prgdir = ctx.getProgramDirectory() bpfile = os.path.join(prgdir, 'breakpoints.txt') with open(bpfile, 'r+') as f: try: bpdict = json.load(f) except: bpdict = {} #print('Current breakpoints file:', bpdict) units = RuntimeProjectUtil.findUnitsByType(prj, IDebuggerUnit, False) if not units: print('No unit available') return d = {} cnt = 0 for dbg in units: # may be null for a detached debugger bplist = dbg.getBreakpoints() if bplist: a = [] for bp in bplist: address = bp.getAddress() enabled = bp.isEnabled() #print('- Debugger: %s (for %s): %s (%s)' % (dbg.getName(), dbg.getPotentialDebuggees(), address, 'enabled' if enabled else 'disabled')) a.append({'address': address, 'enabled': enabled}) cnt += 1 d[dbg.getName()] = a bpdict[prjname] = d with open(bpfile, 'w') as f: try: json.dump(bpdict, f, indent=True) except Exception as e: print('ERROR: Cannot save to breakpoints file: %s' % e) print('Breakpoints saved: %d.' % cnt)
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 project = projects[0] # Get current project(IRuntimeProject) print('Decompiling code units of %s...' % project) self.codeUnit = RuntimeProjectUtil.findUnitsByType(project, ICodeUnit, False)[0] # Get the current codeUnit(ICodeUnit) # RuntimeProjectUtil: A collection of utility methods to navigate and act on JEB2 projects. # findUnitsByType: Find all units of a project that are of the specified type # ICodeUnit: Code units are inherently interactive, in order to provide facility for code refactoring, modification... # enumerate the decompiled classes, find and process the target class units = RuntimeProjectUtil.findUnitsByType(project, IJavaSourceUnit, False) # IJavaSourceUnit: Definition of a source unit representing a Java class in the form of an Abstract Syntax Tree for unit in units: javaClass = unit.getClassElement() # Get a reference to the Java class defined in this unit # IJavaClass: Java AST interface to represent a Java class. Class elements contain other classes (inner classes), fields, and methods if javaClass.getName() == self.TARGET_CLASS_NAME: # If the current class is the target class self.cstbuilder = unit.getFactories().getConstantFactory() # getFactories: A collection of Java AST element factories # IJavaFactories: A collection of Java AST element factories(methods) # IJavaConstantFactory(self.cstbuilder): Builder for Java AST constants self.processClass(javaClass) # Process the target class break
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 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 if not isinstance(ctx, IGraphicalClientContext): print('This script must be run within a graphical client') return prj = projects[0] fragment = ctx.getFocusedView().getActiveFragment() if type(fragment.getUnit()) is IXmlUnit: print('Select the Manifest XML view') return aname = fragment.getActiveItemAsText() if not aname: print('Select the activity name') return # activity name is relative to the package name if aname.startswith('.'): # unit is the Manifest, of type IXmlUnit; we can retrieve the XML document # note: an alternate way would be to retrieve the top-level IApkUnit, and use getPackageName() pname = fragment.getUnit().getDocument().getElementsByTagName("manifest").item(0).getAttribute("package") #print('Package name: %s' % pname) aname = pname + aname print('Activity name: %s' % aname) addr = 'L' + aname.replace('.', '/') + ';' print('Target address: %s' % addr) unit = RuntimeProjectUtil.findUnitsByType(prj, IDexUnit, False).get(0) if not unit: print('The DEX unit was not found') return ctx.openView(unit) # this code assumes that the active fragment is the disassembly (it may not be; strong script should focus the assembly fragment) ctx.getFocusedView().getActiveFragment().setActiveAddress(addr)
def run(self): ctx = 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] units = RuntimeProjectUtil.findUnitsByType(prj, IDexUnit, False) for unit in units: classes = unit.getClasses() if classes: for clazz in classes: # print(clazz.getName(True), clazz) sourceIndex = clazz.getSourceStringIndex() clazzAddress = clazz.getAddress() if sourceIndex == -1: # print('without have source field', clazz.getName(True)) continue sourceStr = str(unit.getString(sourceIndex)) if '.java' in sourceStr: sourceStr = sourceStr[:-5] if '$' in clazzAddress: oldName = clazzAddress.split('/')[-1].split('$') oldName.pop(0) oldName.insert(0, sourceStr) sourceStr = '$'.join(oldName) sourceStr = sourceStr[:-1] # print(clazz.getName(True), sourceIndex, sourceStr, clazz) if clazz.getName(True) != sourceStr: self.comment_class(unit, clazz, clazz.getName( True)) # Backup origin clazz name to comment self.rename_class(unit, clazz, sourceStr, True) # Rename to source name
def getComponentClasses(self, component, exported=None): ClassAppendix = { Helper.COMPONENT_ACTIVITY: "Activity", Helper.COMPONENT_SERVICE: "Service", Helper.COMPONENT_PROVIDER: "Provider", Helper.COMPONENT_RECEIVER: "Receiver" } assert component in ClassAppendix self.codeUnit = RuntimeProjectUtil.findUnitsByType( self.prj, ICodeUnit, False)[0] classes = self.codeUnit.getClasses() ret = [] for cls in classes: name = cls.getName(True) if component == Helper.COMPONENT_ALL: if not re.match(r'.*(Activity|Service|Provider|Receiver)$', name): continue else: # get component type pass elif not name.endswith(ClassAppendix[component]): continue else: compname = ClassAppendix[component].lower() if not self.checkManifest(compname, cls): continue if exported == None: ret.append(cls) elif exported == True: if self.isComponentExported(compname, cls): ret.append(cls) elif not self.isComponentExported(compname, cls): ret.append(cls) return ret
def run(self): ctx = self.ctx # print self.dec("Y\\\\@W[\\\u001CQ\\LWVF\u0016S[FQ]V\u001C|wtwlw") self.decr_method = "Lcom/xshield/aa;->E(Ljava/lang/String;)Ljava/lang/String;" engctx = ctx.getEnginesContext() if not engctx: print('Back-end engines not initialized') projects = engctx.getProjects() if not projects: print('There is no opened project') project = projects[0] # Get current project(IRuntimeProject) #获取所有的java类 units = RuntimeProjectUtil.findUnitsByType(project, IJavaSourceUnit, False) print('+++++++++++BEGIN++++++++++++++') for unit in units: cstbuilder = unit.getFactories().getConstantFactory() class_ = unit.getClassElement() # 遍历每个类的方法 for method in class_.getMethods(): # print class_.getName(), " ", method.getName() body = method.getBody() # 遍历方法中的每行语句 for i in range(body.size()): part = body.get(i) print "class ", class_.getName(), ", ", method.getName( ), ", part ", part # 如果是赋值语句,取右操作数 ''' if isinstance(part, IJavaAssignment): right = part.getRight() if isinstance(right, IJavaCall): # 如果右操作数是函数调用且调用了解密函数 self.renameElementIfNeed(part, cstbuilder, right) else: ''' self.searchMatchFun(part, part, cstbuilder) # self.onceRun(part, part, cstbuilder) print('-----------END--------------')
def run(self, ctx): self.ctx = ctx # customize this self.outputDir = ctx.getBaseDirectory() engctx = ctx.getEnginesContext() if not engctx: print('Back-end engines not initialized') return prj = engctx.getProject(0) if not prj: print('There is no opened project') return codeUnits = RuntimeProjectUtil.findUnitsByType(prj, IDexUnit, False) for codeUnit in codeUnits: self.processDex(codeUnit)
def run(self, ctx): print(sys.path) 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] units = RuntimeProjectUtil.findUnitsByType(prj, IDexUnit, False) for unit in units: classes = unit.getClasses() print('Classes in unit %s in %d' % (unit.getName(), len(classes)))
def run(self, ctx): prj = ctx.getMainProject() assert prj, 'Need a project' prjname = prj.getName() prgdir = ctx.getProgramDirectory() bpfile = os.path.join(prgdir, 'breakpoints.txt') with open(bpfile, 'r+') as f: try: bpdict = json.load(f) except: bpdict = {} #print('Current breakpoints file:', bpdict) units = RuntimeProjectUtil.findUnitsByType(prj, IDebuggerUnit, False) if not units: print('No unit available') return d = {} cnt = 0 for dbg in units: # may be null for a detached debugger bplist = dbg.getBreakpoints() if bplist: a = [] for bp in bplist: address = bp.getAddress() enabled = bp.isEnabled() #print('- Debugger: %s (for %s): %s (%s)' % (dbg.getName(), dbg.getPotentialDebuggees(), address, 'enabled' if enabled else 'disabled')) a.append({'address': address, 'enabled': enabled}) cnt += 1 d[dbg.getName()] = a bpdict[prjname] = d with open(bpfile, 'w') as f: try: json.dump(bpdict, f, indent=True) except Exception as e: print('ERROR: Cannot save to breakpoints file: %s' % e) print('Breakpoints saved: %d.' % cnt)
def run(self, ctx): prj = ctx.getMainProject() assert prj, 'Need a project' bmstr = prj.getData(BookmarkSet.BMKEY) if not bmstr: ctx.displayMessageBox('Bookmarks', 'No recorded boolmarks yet!', IconType.INFORMATION, None) return bm = json.loads(bmstr) log('Current bookmarks (%d): %s' % (len(bm), bm)) headers = ['Timestamp', 'Full Unit Path', 'Name', 'Fragment', 'Address', 'Comment'] rows = [] for uid, labelmap in bm.items(): for label, addrmap in labelmap.items(): for addr, e in addrmap.items(): unitpath, unitname, comment, ts = e # note we're appended uid, but it won't be displayed (per the header's spec above, which specifies 6 columns - not 7) rows.append([datetime.datetime.fromtimestamp(ts).ctime(), unitpath, unitname, label, addr, comment, uid]) index = ctx.displayList('Bookmarks', 'List of currently set bookmarks in the active project', headers, rows) if index < 0: return sel = rows[index] uid, label, addr = int(sel[6]), sel[3], sel[4] log('Selected: uid=%d,fragment=%s,addr=%s' % (uid, label, addr)) unit = RuntimeProjectUtil.findUnitByUid(prj, uid) if not unit: print('Unit with uid=%d was not found in the project or no longer exists!' % uid) return if not ctx.openView(unit): print('Could not open view for unit!') else: f = ctx.findFragment(unit, label, True) if not f: print('Fragment "%s" not found!' % label) elif addr: f.setActiveAddress(addr)
def run(self, ctx): prj = ctx.getMainProject() assert prj, 'Need a project' if not isinstance(ctx, IGraphicalClientContext): print('This script must be run within a graphical client') return fragment = ctx.getFocusedView().getActiveFragment() if type(fragment.getUnit()) is IXmlUnit: print('Select the Manifest XML view') return # make sure that the fragment has the focus, els the item would not be considered active aname = fragment.getActiveItemAsText() if not aname: print('Select the activity name') return # activity name is relative to the package name if aname.startswith('.'): # unit is the Manifest, of type IXmlUnit; we can retrieve the XML document # note: an alternate way would be to retrieve the top-level IApkUnit, and use getPackageName() dom = fragment.getUnit().getDocument() pname = dom.getElementsByTagName("manifest").item(0).getAttribute( "package") #print('Package name: %s' % pname) aname = pname + aname print('Activity name: %s' % aname) addr = 'L' + aname.replace('.', '/') + ';' print('Target address: %s' % addr) unit = RuntimeProjectUtil.findUnitsByType(prj, IDexUnit, False).get(0) if not unit: print('The DEX unit was not found') return ctx.openView(unit) # this code assumes that the active fragment is the disassembly (it may not be; strong script should focus the assembly fragment) ctx.getFocusedView().getActiveFragment().setActiveAddress(addr)
def run(self, ctx): 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 prj = projects[0] units = RuntimeProjectUtil.findUnitsByType(prj, IDexUnit, False) for uint in units: imp = FindImp(uint) clzes = uint.getClasses() for clz in clzes: imp.FindJsInterface(clz)
def run(self, ctx): assert isinstance(ctx, IGraphicalClientContext) class_name = ctx.displayQuestionBox("Get class methods", "What is the class?", "") if not class_name or not class_name.strip(): return filter_text = ctx.displayQuestionBox( "Get class methods", "The method Should contain", "").strip() or "" try: unit = RuntimeProjectUtil.findUnitsByType( ctx.getEnginesContext().getProjects()[0], IDexUnit, False)[0] assert isinstance(unit, IDexUnit) for method in unit.getMethods(): assert isinstance(method, IDexMethod) if method.getSignature().startswith( class_name) and filter_text in method.getSignature(): print method.getSignature() except: traceback.print_exc(file=sys.stdout)
def findMethodByItemId(self, mtdSig, itemId): self.codeUnit = RuntimeProjectUtil.findUnitsByType( self.prj, ICodeUnit, False) if not self.codeUnit: return None for unit in self.codeUnit: classes = unit.getClasses() if not classes: continue for c in classes: cAddr = c.getAddress() if not cAddr: continue if mtdSig.find(cAddr) == 0: mtdlist = c.getMethods() if not mtdlist: continue for m in mtdlist: if self.isInitMethod and m.getAddress() == mtdSig: return c, m elif itemId == self.calcItemVal(m.getItemId()): return c, m return None
def run(self): ctx = 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] units = RuntimeProjectUtil.findUnitsByType(prj, IDexUnit, False) for unit in units: classes = unit.getClasses() if classes: for clazz in classes: sourceIndex = clazz.getSourceStringIndex() clazzAddress = clazz.getAddress() if sourceIndex == -1 or '$' in clazzAddress: # Do not rename inner class continue sourceStr = str(unit.getString(sourceIndex)) if '.java' in sourceStr: sourceStr = sourceStr[:-5] if clazz.getName(True) != sourceStr: self.rename(unit, clazz, sourceStr, 'class') # Rename class fields = clazz.getFields() if fields: for field in fields: nameIndex = field.getNameIndex() if nameIndex == -1: continue classType = field.getFieldType().getAddress() if '___' in classType: name = field.getName(True) if len(name ) <= 3: # 这里的判断是为了区分有意义的变量名和无意义的变量名 classType = ((re.compile(r'[a-zA-Z]+') ).findall(classType))[1] self.rename(unit, field, classType, 'field') # Rename field
def run(self, ctx): self.ctx = ctx # customize this self.outputDir = DexCluster.OUTDIR 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 codeUnit = RuntimeProjectUtil.findUnitsByType(projects[0], ICodeUnit, False)[0] print('Clustering: %s' % codeUnit) self.clusterUnit(codeUnit, DexCluster.TARGETP) print('Done.')
def run(self): # customize this self.outputDir = self.ctx.getBaseDirectory() engctx = self.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) codeUnits = RuntimeProjectUtil.findUnitsByType(prj, ICodeUnit, False) for codeUnit in codeUnits: self.decompileForCodeUnit(codeUnit)
def run(self, ctx): engctx = ctx.getEnginesContext() if not engctx: print('Back-end engines not initialized') return prj = engctx.getProject(0) if not prj: print('There is no opened project') return codeUnits = RuntimeProjectUtil.findUnitsByType(prj, ICodeUnit, False) if not codeUnits: return self.dex = codeUnits[0] self.jeb = ctx # ui = j.getUI() # rename obfuscated class names self.rename_classes()
def run(self): ctx = 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] # units = RuntimeProjectUtil.getAllUnits(prj) # for unit in units: # print(unit.getName()) units = RuntimeProjectUtil.findUnitsByType(prj, IJavaSourceUnit, False) for unit in units: self.displayASTTree(unit.getClassElement())
def run(self): print('Deobscure class start ...') units = RuntimeProjectUtil.findUnitsByType(self.project, IDexUnit, False) for i, unit in enumerate(units): print('Process %s(%s/%s)' % (unit, i + 1, units.size())) classes = unit.getClasses() if not classes: continue rep = {} for clz in classes: if not clz.getName(): # Anonymous inner class continue adr = str(clz.getAddress()) if '$' in adr: # Inner class continue sidx = clz.getSourceStringIndex() if sidx == -1: # Not keep SourceFile attributes continue sname = str(unit.getString(sidx)) ignored = ('ProGuard', "SourceFile") if sname in ignored: # -renamesourcefileattribute SourceFile continue if sname.endswith('.java'): sname = sname[:-5] elif sname.endswith('.kt'): sname = sname[:-3] key = adr[:adr.rfind('/') + 1] + sname cname = rep.get(key, 0) rep[key] = cname + 1 if self.isKeeped(sname, clz): # There is no need to rename continue if cname > 0: sname += '$$$' + str(cname) ret = self.commentClass(unit, clz, adr) and self.renameClass( unit, clz, sname) print('%s -> %s %s' % (adr, sname, ret)) print('Done')
def get_unit(ctx, unit_type): """ Retrieves a specific unit """ 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 code unit available (code units re interactive units) units = RuntimeProjectUtil.findUnitsByType(projects[0], unit_type, False) if not units: print "No unit available" return unit = units[0] return unit
def run(self, ctx): 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 prj = projects[0] print('Decompiling code units of %s...' % prj) units = RuntimeProjectUtil.findUnitsByType(prj, IJavaSourceUnit, False) for unit in units: #self.decompileForCodeUnit(codeUnit) #print(unit.getJavaClass()) self.displayTree(unit.getClassElement()) print('Done.')
def run(self, ctx): engctx = ctx.getEnginesContext() if not engctx: print('Back-end engines not initialized') return prj = engctx.getProject(0) if not prj: print('There is no opened project') return codeUnits = RuntimeProjectUtil.findUnitsByType(prj, ICodeUnit, False) if not codeUnits: return self.unit = codeUnits[0] self.ctx = ctx # rename obfuscated names classes = self.unit.getClasses() for cls in classes: self.deobfuscate(cls, RenameObfuscatedMethodAndField.METHOD) self.deobfuscate(cls, RenameObfuscatedMethodAndField.FIELD)
def run(self, ctx): self.ctx = ctx argv = ctx.getArguments() if len(argv) < 2: print('Provide an input file and the output folder') return self.inputFile = argv[0] self.outputDir = argv[1] print('Decompiling ' + self.inputFile + '...') engctx = ctx.getEnginesContext() if not engctx: print('Back-end engines not initialized') return # Create a project project = engctx.loadProject('PlaceholderProjectName') if not project: print('Failed to open a new project') return # Add the input file as a project artifact artifact = Artifact('PlaceholderArtifactName', FileInput(File(self.inputFile))) project.processArtifact(artifact) # Decompile code units codeUnits = RuntimeProjectUtil.findUnitsByType(project, ICodeUnit, False) for codeUnit in codeUnits: if isinstance(codeUnit, IDexUnit): self.decompileForCodeUnit(codeUnit)
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))
def run(self): ctx = 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] global pkg pkg = self.GetPackage(prj) units = RuntimeProjectUtil.findUnitsByType(prj, IDexUnit, False) for unit in units: classes = unit.getClasses() if classes: for clazz in classes: sourceIndex = clazz.getSourceStringIndex() clazzAddress = clazz.getAddress() if pkg in clazzAddress: if sourceIndex == -1 or '$' in clazzAddress:# Do not rename inner class # print('without have source field', clazz.getName(True)) continue sourceStr = str(unit.getString(sourceIndex)) if '.java' in sourceStr: sourceStr = sourceStr[:-5] # print(clazz.getName(True), sourceIndex, sourceStr, clazz) if clazz.getName(True) != sourceStr: self.comment_class(unit, clazz, clazz.getName(True)) # Backup origin clazz name to comment self.rename_class(unit, clazz, sourceStr, True) # Rename to source name
def run(self, ctx): # retrieve JEB's engines from the provided IClientContext engctx = ctx.getEnginesContext() if not engctx: print('Back-end engines not initialized') return # retrieve the current project (must exist) projects = engctx.getProjects() if projects: project = projects[0] else: argv = ctx.getArguments() if len(argv) < 1: print('No project found, please provide an input contract file') return self.inputFile = argv[0] print('Processing ' + self.inputFile + '...') if not self.inputFile.endswith('.evm-bytecode'): print('Warning: it is recommended your contract file has the evm-bytecode extension in order to guarantee processing by the EVM modules') # create a project project = engctx.loadProject('EVMProject') # load and process the artifact artifact = Artifact('EVMArtifact', FileInput(File(self.inputFile))) project.processArtifact(artifact) project = engctx.getProjects()[0] # retrieve the primary code unit (must be the result of an EVM contract analysis) units = RuntimeProjectUtil.findUnitsByType(project, INativeCodeUnit, False) if not units: print('No native code unit found') return unit = units[0] print('EVM unit: %s' % unit) # GlobalAnalysis is assumed to be on: the contract is already decompiled # we retrieve a handle on the EVM decompiler ... decomp = DecompilerHelper.getDecompiler(unit) if not decomp: print('No decompiler unit found') return # ... and retrieve a handle on the decompiled contract's INativeSourceUnit src = decomp.decompile("DecompiledContract") print(src) #targets = src.getDecompilationTargets() #print(targets) # let's get the contract's AST astDecompClass = src.getRootElement() # the commented line below will output the entire decompiled source code #print(astDecompClass) # here, we walk the AST tree and print the type of each element in the tree print("*** AST of contract") self.displayASTTree(astDecompClass) # now, let's retrieve the individual methods implemented in the contract methods = unit.getInternalMethods() for method in methods: # retrieve the INativeSourceUnit of the method r = decomp.decompileMethod(method) print("*** AST for method: %s" % method.getName(True)) self.displayASTTree(r.getRootElement()) # list of INativeDecompilationTarget for a decompiled method decompTargets = r.getDecompilationTargets() if decompTargets: # get the first (generally, only) target object decompTarget = decompTargets.get(0) # an INativeDecompilationTarget object aggregates many useful objects resulting from the decompilation of a method # here, we retrieve the most refined CFG of the Intermediate Representation for the method ircfg = decompTarget.getContext().getCfg() # CFG object reference, see package com.pnfsoftware.jeb.core.units.code.asm.cfg print("++++ IR-CFG for method: %s" % method.getName(True)) print(ircfg.formatSimple()) # end of demo, we have enough with one method, uncomment to print out the AST and IR of all methods break
def run(self, ctx): 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 self.prj = projects[0] if not isinstance(self.ctx, IGraphicalClientContext): print('This script must be run within a graphical client') return self.focusFragment = ctx.getFocusedFragment() self.focusUnit = self.focusFragment.getUnit() # JavaSourceUnit self.activeItem = self.focusFragment.getActiveItem() self.activeItemVal = self.calcItemVal(self.activeItem.getItemId()) self.codeUnit = RuntimeProjectUtil.findUnitsByType( self.prj, ICodeUnit, False) if not isinstance(self.focusUnit, IJavaSourceUnit): print('This script must be run within IJavaSourceUnit') return if not self.focusFragment: print("You Should pick one method name before run this script.") return viewMethodSig = self.focusFragment.getActiveAddress() self.isInitMethod = "<init>" in viewMethodSig and self.activeItem.toString( ).find('cid=CLASS_NAME') != 0 clz, mtd = self.findMethodByItemId(viewMethodSig, self.activeItemVal) if not mtd: print('Could not find method: %s' % viewMethodSig) return assert isinstance(mtd, ICodeMethod) paramList = [] for x in mtd.getParameterTypes(): if ";" in str(x.getAddress()): argType = self.getRealClassSig(x.getImplementingClass()) else: argType = x.getAddress() paramList.append(argType) currentClassName = clz.getName() currentClassPath = clz.getAddress()[1:-1].replace('/', '.') realClassName = self.getItemOriginalName(clz) realClassSig = self.getRealClassSig(clz) realClassPath = realClassSig[1:-1].replace('/', '.') currentMethodName = mtd.getName() commentMethodName = self.methodNameTransform(currentMethodName, False) realMethodName = self.getItemOriginalName(mtd) print(FMT_OBJ_CLZ.format(class_path=realClassPath)) print( FMT_OBJ_MTD.format( class_path=realClassPath, method_name=self.methodNameTransform(realMethodName))) print( FMT_CLZ.format(class_name=currentClassName, class_path=realClassPath)) print( FMT_SIGNOTE.format(original_method_sig=realClassPath + self.methodNameTransform(realMethodName), mnemonic_method_sig=viewMethodSig)) print( FMT_MTD.format( class_name=currentClassName, method_name=self.methodNameTransform(realMethodName), custom_name=commentMethodName, param_list=','.join([self.toFrida(x) for x in paramList]), ))
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))
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 try: self.current_unit = ctx.getFocusedView().getActiveFragment( ).getUnit() # Get current Source Tab in Focus # java_class = self.current_unit.getClassElement() # needs >V2.1.4 current_addr = ctx.getFocusedView().getActiveFragment( ).getActiveAddress() # needs 2.1.4 if "(" in current_addr: current_addr = current_addr.split("+")[0] print("current function: " + current_addr) m = FridaCodeGenerator.get_decompiled_method( self.dexunit, current_addr) method_name = m.get_name() class_name = FridaCodeGenerator.to_canonical_name( m.get_class_name()) return_type = FridaCodeGenerator.to_canonical_name( str(m.get_return_type())) if method_name == "<clinit>": return args = [] for item in range(len(m.get_parameters())): # print(item.getIdentifier().getName()) args.append(str("arg_%d" % item)) types = [ FridaCodeGenerator.to_canonical_name(param) for param in m.get_parameters() ] simple_class_name = class_name.split('.')[-1].replace("$", "_") if method_name == "<init>": method_name = "$init" type_code = generate_type_code(types) args_code = generate_args_code(args) log_code = generate_log_code(types, return_type, method_name, simple_class_name, args) hook_code = hook_template.format( simple_class_name=simple_class_name, full_class_name=class_name, method_name=method_name, types=type_code, args=args_code, log_code=log_code) print(hook_code) if not isinstance(ctx, IGraphicalClientContext): print('This script must be run within a graphical client') return file_name = 'hook_{class_name}.js'.format( class_name=simple_class_name) file_path = os.path.join(os.environ['HOME'], file_name) value = ctx.displayQuestionBox( 'Input', 'Enter the hook script save path(Save to directory {file_path} by default)' .format(file_path=file_path), file_path) # print(value) # with open(value) if value: file_path = value try: with open(file_path, "w+") as f: f.write(hook_code) f.flush() ctx.displayMessageBox( 'Information', 'Frida script save to \n{}'.format(file_path), IconType.INFORMATION, ButtonGroupType.OK) except Exception as e: print(e) else: print( "Place the cursor in the function you want to generate the Frida code, then run the script" ) except Exception as e: print(e) print( "Place the cursor in the function you want to generate the Frida code, then run the script" )
def run(self): ctx = 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] self.codeUnit = RuntimeProjectUtil.findUnitsByType(prj, ICodeUnit, False) self.curIdx = 0 bcUnits = [] for unit in self.codeUnit: classes = unit.getClasses() if classes and unit.getName().lower() == "bytecode": bcUnits.append(unit) targetUnit = bcUnits[0] units = RuntimeProjectUtil.findUnitsByType(prj, IJavaSourceUnit, False) self.targetUnit = targetUnit # print(targetUnit.getClass(javaclz.getSupertype().getSignature())) # this is a single classes.dex item fuckingClasses = [] cnt = 0 for clz in targetUnit.getClasses(): # the name maybe renamed # print(clz.getSignature(False))#False is for original Name if isFuckingName(clz.getName(False)): determinedName = self.tryDetermineGoodName(clz) if determinedName is None: determinedName = genNameFromIdx(cnt) else: determinedName = genNameFromIdx(cnt) + determinedName.split('/')[-1][:-1] self.commenceRename(clz.getSignature(False), determinedName, 0) print("cnt is " + str(cnt) + "determined name is " + str(determinedName)) cnt += 1 # rename all fields cnt = 0 for field in targetUnit.getFields(): if isFuckingName(field.getName(False)): # get field type(renamed Type) fieldType = field.getFieldType().getName(True) newName = genNameFromIdx(cnt) + fieldType self.commenceRename(field.getAddress(), newName, 1) print("cnt is " + str(cnt) + "determined name is " + str(newName)) cnt += 1 # rename all functions cnt = 0 for mtd in targetUnit.getMethods(): if isFuckingName(mtd.getName(False)): print(mtd.getName(False)) # get method arguments # new mtd name is paramTypeJoin newName = genNameFromIdx(cnt) + ''.join(map(lambda x: x.getName(True), mtd.getParameterTypes())) self.commenceRename(mtd.getAddress(), newName, 2) print("cnt is " + str(cnt) + "determined name is " + str(newName)) cnt += 1
def run(self, ctx): 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 self.prj = projects[0] if not isinstance(self.ctx, IGraphicalClientContext): print('This script must be run within a graphical client') return assert isinstance(ctx, IGraphicalClientContext) self.focusFragment = ctx.getFocusedFragment() self.focusUnit = self.focusFragment.getUnit() # JavaSourceUnit self.dexunits = RuntimeProjectUtil.findUnitsByType( self.prj, IDexUnit, False) if not self.focusFragment: print("You Should pick one method name before run this script.") return activeAddress = self.focusFragment.getActiveAddress( AddressConversionPrecision.FINE) activeItem = self.focusFragment.getActiveItem() activeItemText = self.focusFragment.getActiveItemAsText() dunit, mtd = get_mtd_by_addr(self.dexunits, activeAddress) self.xrefs_set = set() self.result = [] print("Cross-references Tree of: " + activeAddress) self.dfs(dunit, mtd, 0) print("\n") headers = ['Depth', 'Address'] index = ctx.displayList('Cross-references Tree of: ', activeAddress, headers, self.result) if index < 0: return sel = self.result[index] depth, addr, unit_id = int(sel[0]), sel[1], int(sel[2]) addr = addr[depth * PI:] unit = RuntimeProjectUtil.findUnitByUid(self.prj, unit_id) if not unit: print( 'Unit with uid=%d was not found in the project or no longer exists!' % unit_id) return if not ctx.openView(unit): print('Could not open view for unit!') else: f = ctx.findFragment(unit, "Disassembly", True) if not f: print('Fragment Disassembly not found!') elif addr: f.setActiveAddress(addr)
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] prjname = prj.getName() prgdir = ctx.getProgramDirectory() datafile = os.path.join(prgdir, 'codedata.txt') data = {} if os.path.exists(datafile): with open(datafile, 'r') as f: try: data = json.load(f) except: pass #print('Current data:', data) units = RuntimeProjectUtil.findUnitsByType(prj, ICodeUnit, False) if not units: print('No code unit available') return d = {} for unit in units: if not unit.isProcessed(): continue a = {} d[unit.getName()] = a a['renamed_classes'] = {} a['renamed_fields'] = {} a['renamed_methods'] = {} a['comments'] = {} for c in unit.getClasses(): name0 = c.getName(False) name1 = c.getName(True) if name0 != name1: a['renamed_classes'][c.getSignature(False)] = name1 for f in unit.getFields(): name0 = f.getName(False) name1 = f.getName(True) if name0 != name1: a['renamed_fields'][f.getSignature(False)] = name1 for m in unit.getMethods(): name0 = m.getName(False) name1 = m.getName(True) if name0 != name1: a['renamed_methods'][m.getSignature(False)] = name1 for addr, comment in unit.getComments().items(): a['comments'][addr] = comment data[prjname] = d with open(datafile, 'w') as f: try: json.dump(data, f, indent=True) except Exception as e: print('ERROR: Cannot save to file: %s' % e) print('Basic refactoring data recorded to file: %s' % datafile)
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 = ctx.getMainProject() self.iiunit = self.prj.findUnit(IInteractiveUnit) self.dexunits = RuntimeProjectUtil.findUnitsByType(self.prj, IDexUnit, False) defaultValue = '5' caption = 'Search Java Methods' message = Template input = ctx.displayQuestionBox(caption, message, defaultValue) if input == None: return try: chosen = int(input) except Exception as e: chosen = 1 global custom_regex_pattern custom_regex_pattern = re.compile("JavascriptInterface") if chosen == 2: crp_caption = "Search Java methods by name pattern." elif chosen == 4: crp_caption = "Search Java methods by annotation pattern." if chosen in [2, 4]: message = "custom_regex_pattern = re.compile(input)" input = ctx.displayQuestionBox(crp_caption, message, "") if not input: return custom_regex_pattern = re.compile(input) print("Start search Java methods in dex . . .") rows = [] print(len(self.dexunits)) for unit in self.dexunits: assert isinstance(unit, IDexUnit) # print("unit") # for debug potential crash if unit.getName() != "Bytecode": continue for clazz in unit.getClasses(): assert isinstance(clazz, IDexClass) sourceIndex = clazz.getSourceStringIndex() clazzAddress = clazz.getAddress() #if "" != clazzAddress: continue DexAnnotationsDirectory = clazz.getAnnotationsDirectory() if chosen in [1, 2]: for mtd in clazz.getMethods(): assert isinstance(mtd, IDexMethod) flag = mtd.getGenericFlags() mtdname = mtd.getName() if chosen == 1 and flag & ICodeItem.FLAG_NATIVE or chosen == 2 and regex_pattern_search(mtdname, custom_regex_pattern): row = [mtd.getSignature(), clazz.getName(), mtd.getName(), unit.getUid()] rows.append(row) elif chosen in [3, 4] and DexAnnotationsDirectory: for DexAnnotationForMethod in DexAnnotationsDirectory.getMethodsAnnotations(): assert isinstance(DexAnnotationForMethod, IDexAnnotationForMethod) mtdidx = DexAnnotationForMethod.getMethodIndex() mtd = unit.getMethod(mtdidx) for DexAnnotationItem in DexAnnotationForMethod.getAnnotationItemSet(): assert isinstance(DexAnnotationItem, IDexAnnotationItem) typeidx = DexAnnotationItem.getAnnotation().getTypeIndex() typename = unit.getType(typeidx).getName() if regex_pattern_search(typename, custom_regex_pattern): row = [mtd.getSignature(), clazz.getName(), mtd.getName(), unit.getUid()] rows.append(row) elif chosen == 5: for mtd in clazz.getMethods(): assert isinstance(mtd, IDexMethod) mtdsig = mtd.getSignature() for sm_name, sm_address_suffix in Sensitive_dict.items(): print(sm_address_suffix) if mtdsig.endswith(sm_address_suffix): row = [mtd.getSignature(), clazz.getName(), mtd.getName(), unit.getUid()] rows.append(row) break out = list(set([x[0] for x in rows])) out.sort() for x in out: print(x) total = len(out) print("Search %d Java methods out." % total) headers = ['Address', 'Class', 'Method'] index = ctx.displayList('Display Java methods search result', None, headers, rows) if index < 0: return sel = rows[index] addr, unit_id = sel[0], int(sel[3]) unit = RuntimeProjectUtil.findUnitByUid(self.prj, unit_id) if not unit: print('Unit with uid=%d was not found in the project or no longer exists!' % unit_id) return if not ctx.openView(unit): print('Could not open view for unit!') else: f = ctx.findFragment(unit, "Disassembly", True) if not f: print('Fragment Disassembly not found!') elif addr: f.setActiveAddress(addr)
def run(self): ctx = 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] units = RuntimeProjectUtil.findUnitsByType(prj, IDexUnit, False) # dict save {sourceStr, {parent_pkg_path, [unit, classs]} dic = {} for unit in units: classes = unit.getClasses() if classes: for clazz in classes: # print(clazz.getName(True), clazz) sourceIndex = clazz.getSourceStringIndex() clazzAddress = clazz.getAddress() # flag = clazz.getGenericFlags() if sourceIndex == -1 or '$' in clazzAddress: # Do not rename inner class # print('without have source field', clazz.getName(True)) continue sourceStr = str(unit.getString(sourceIndex)) if '.java' in sourceStr: sourceStr = sourceStr[:-5] else: # @rf.w 20210120 continue # print(clazz.getName(True), sourceIndex, sourceStr, clazz) if clazz.getName(True) != sourceStr: # @rf.w 20210122 index = 1 source_format = sourceStr + '_{0}' source_key = sourceStr parent_pkg_name = self.get_parent_pkg_name( clazz.getSignature()) if source_key not in dic.keys(): dic[source_key] = {} dic[source_key][parent_pkg_name] = [unit, clazz] #print('ADD %s => %s(%s)' % (clazz.getSignature(), source_key, (parent_pkg_name +"/" + source_key))) continue else: while source_key in dic.keys(): inner_dic = dic[source_key] if parent_pkg_name in inner_dic.keys(): #print('found repeated: %s' % (parent_pkg_name +"/" + source_key), clazz) source_key = source_format.format( str(index)) index += 1 continue else: inner_dic[parent_pkg_name] = [unit, clazz] break dic[source_key] = {} dic[source_key][parent_pkg_name] = [unit, clazz] #print('ADD %s => %s(%s)' % (clazz.getSignature(), source_key, (parent_pkg_name +"/" + source_key))) for key in dic.keys(): inner_dic = dic[key] for inner_key in inner_dic.keys(): array = inner_dic[inner_key] unit = array[0] clazz = array[1] print("RENAME %s <= %s!" % (key, clazz.getAddress())) self.comment_class( unit, clazz, clazz.getName(True)) # Backup origin clazz name to comment self.rename_class(unit, clazz, key, True) # Rename to source name