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 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 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): 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))
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.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 if not isinstance(ctx, IGraphicalClientContext): print('This script must be run within a graphical client') return prj = projects[0] self.codeUnit = RuntimeProjectUtil.findUnitsByType( prj, ICodeUnit, False)[0] self.units = RuntimeProjectUtil.findUnitsByType( prj, IJavaSourceUnit, False) for unit in self.units: javaClass = unit.getClassElement() print "Processing class: ", javaClass.getName() self.cstbuilder = unit.getFactories().getConstantFactory() self.process_class(unit, javaClass)
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
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): 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): 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): 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 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 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 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): if not isinstance(self.ctx, IGraphicalClientContext): print ('This script must be run within a graphical client') return assert isinstance(ctx, IGraphicalClientContext) # for print(type(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] self.focusFragment = ctx.getFocusedFragment() self.focusUnit = self.focusFragment.getUnit() # JavaSourceUnit if not isinstance(self.focusUnit, IJavaSourceUnit): print ('This script must be run within IJavaSourceUnit') return self.JavaSourceUnit = RuntimeProjectUtil.findUnitsByType(self.prj, IJavaSourceUnit, False) for unit in self.JavaSourceUnit: ccllzz = unit.getClassElement() print(ccllzz) ### print(ccllzz.getSubElements()) self.dfs(unit, ccllzz)
def run(self, ctx): assert isinstance(ctx, IGraphicalClientContext) class_name = ctx.displayQuestionBox( "Phenotype helper", "What is the class name for the phenotype flag builder?", "") if not class_name or not class_name.strip(): return elif not class_name.startswith("L"): class_name = "L" + class_name.replace(".", "/") + ";" print "Class name not in dex format, trying:", class_name try: unit = RuntimeProjectUtil.findUnitsByType( ctx.enginesContext.projects[0], IDexUnit, False)[0] assert isinstance(unit, IDexUnit) init_methods = Phenotype.detect_init_methods(unit, class_name) if not init_methods: return print "Found", len(init_methods), "flag initialization methods" fields = Phenotype.detect_fields(unit, init_methods) print "Found", len(fields), "flag fields" first_getters = Phenotype.detect_first_getters(unit, fields) print "Found", len(first_getters), "getters" secondary_getters = Phenotype.detect_second_getters( unit, first_getters) print "Found", len(secondary_getters), "secondary getters" except: traceback.print_exc(file=sys.stdout)
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): 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 #ctx.executeAsync("Running deobscure class ...", AsyncTask(ctx, self)) 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: cls = unit.getClass('Lcom/jingdong/aura/wrapper/AuraInitializer;') if cls != None: print('getClassTypeIndex -> %d' % cls.getClassTypeIndex()) for m in cls.getMethods(): if m.getName(False) == 'update': # print(m.getSignature(True), m.getAddress(), m.getAddress()) refs = DataReference( DataReferenceNode(m.getItemId(), m.getAddress())) self.findMethodXRef(units, m.getItemId(), m.getAddress(), refs) print(refs.getNodes()) print(refs.getLeafNodes()) lines = [] for leaf in refs.getLeafNodes(): lines.extend(refs.getLineToRoot(XrefLine(leaf))) print(lines)
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 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.Dexunits = RuntimeProjectUtil.findUnitsByType( self.prj, IDexUnit, False) for unit in self.Dexunits: assert isinstance(unit, IDexUnit) global Conflict_clzname_pool, Possible_Logger, Possible_Clzname Possible_Logger = Counter() Conflict_clzname_pool = Counter() for clz in unit.getClasses(): assert isinstance(clz, IDexClass) clzSig = clz.getSignature() sourceIndex = clz.getSourceStringIndex() clazzAddress = clz.getAddress() if sourceIndex == -1 or '$' in clazzAddress: # Do not rename inner class self.guess_classname_from_logcat_tag(unit, clz) continue sourceStr = str(unit.getString(sourceIndex)) if not sourceStr.strip() or sourceStr.lower( ) == "proguard" or sourceStr.lower() == "sourcefile": self.guess_classname_from_logcat_tag(unit, clz) continue x = sourceStr.rfind(".") if x > 0: sourceStr = sourceStr[:x] # .java .kt sourceStr = sourceStr.replace(".", "_").replace("-", "_") if clz.getName(True) != sourceStr: self.comment_class(unit, clz, clz.getName( True)) # Backup origin clazz name to comment self.rename_class(unit, clz, sourceStr) # Rename to source name # Todo: # 1. Need check name conflict. # 2. Since source string is unreliable either, need extra judgement. print(u"\nPossible logger class: ") for x, t in Possible_Logger.most_common(20): print("{:<8d}".format(t) + x)
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 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): # self.ctx = ctx #ctx.executeAsync("Running deobscure class ...", AsyncTask(ctx, self)) 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) dexClasses = {} externalClasses = {} def getSimpleClass(item): address = item.getAddress() if item.isInternal(): return dexClasses[address] else: if not externalClasses.has_key(address): externalClasses[address] = SimpleClass(address) return externalClasses[address] for unit in units: classes = unit.getClasses() print('start parse class') for cls in classes: dexClasses[cls.getAddress()] = SimpleClass(cls.getAddress()) print('start parse superType and interfaces') for key, sClass in dexClasses.items(): cls = unit.getClass(key) supers = cls.getSupertypes() if supers != None and len(supers) > 0: sClass.superType = getSimpleClass(supers[0]) intrefaces = cls.getImplementedInterfaces() if intrefaces != None and len(intrefaces) > 0: for interface in intrefaces: sClass.interfaces.append(getSimpleClass(interface)) fields = cls.getFields() if fields != None and len(fields) > 0: for field in fields: sClass.fields.append( getSimpleClass(field.getClassType())) for key, sClass in dexClasses.items(): print(sClass) self.dump(dexClasses)
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() 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] print('Decompiling code units of %s...' % prj) self.codeUnit = RuntimeProjectUtil.findUnitsByType( prj, ICodeUnit, False)[0] self.units = RuntimeProjectUtil.findUnitsByType( prj, IJavaSourceUnit, False) self.parse()
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 GetPackage(self,prj): apk = RuntimeProjectUtil.findUnitsByType(prj, IApkUnit, False)[0] apkpkg = apk.getPackageName() print('Start from %s ------------------' %apkpkg) apkpkgname = apkpkg.split('.') pkgname = "" if len(apkpkgname)>2: pkgname = apkpkgname[0]+'/'+apkpkgname[1]+'/'+apkpkgname[2] else: pkgname = apkpkgname[0]+'/'+apkpkgname[1] return pkgname
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): self.context = ctx.getEnginesContext() if not self.context: return self.units = RuntimeProjectUtil.findUnitsByType( self.context.getProjects()[0], IJavaSourceUnit, False) if self.units: for unit in self.units: clazz = unit.getClassElement() if clazz: self.extractAnnotation(clazz)
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 JEB 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): prj = ctx.getMainProject() assert prj, 'Need a project' dbg = prj.findUnit(IDalvikDebuggerUnit) assert dbg, 'Need a dalvik debugger' dexlist = RuntimeProjectUtil.findUnitsByType(prj, IDexUnit, False) for dex in dexlist: if dbg.registerDebuggee(dex): print('Added to debuggees list: %s', UnitUtil.buildFullyQualifiedUnitPath(dex))
def run(self, ctx): prj = ctx.getMainProject() dbg = prj.findUnit(IDalvikDebuggerUnit) if not dbg: print('Cannot find the Dalvik debugger') return dexlist = RuntimeProjectUtil.findUnitsByType(prj, IDexUnit, False) for dex in dexlist: if dbg.registerDebuggee(dex): print('Added to debuggees list: %s', UnitUtil.buildFullyQualifiedUnitPath(dex))
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 # 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 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): project = ctx.getEnginesContext().getProjects()[ 0] # Get current project(IRuntimeProject) 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().getName() current_addr = ctx.getFocusedView().getActiveFragment( ).getActiveAddress() m = FridaCodeGenerator.get_decompiled_method( self.dexunit, current_addr, java_class) method_name = m.get_name() class_name = FridaCodeGenerator.to_canonical_name( m.get_class_orig_name()) return_type = FridaCodeGenerator.to_canonical_name( str(m.get_return_type())) if method_name == '<clinit>': raise Exception('Class initializer') args_code = ', '.join( [arg_format(i) for i in range(len(m.get_parameters()))]) if method_name == '<init>': method_name = '$init' types = [ FridaCodeGenerator.to_canonical_name(param) for param in m.get_parameters() ] # TODO get original type class names type_code = ', '.join(["'{0}'".format(t) for t in types]) body_code = generate_body_code(types, return_type, method_name, m.get_orig_name(), m.get_class_name()) hook = "Java.use('{class_name}').{method}.overload({sig}).implementation = function({args}) {{{body}}}".format( class_name=class_name, method=m.get_orig_name() if method_name != '$init' else method_name, sig=type_code, args=args_code, body=body_code) print(hook) # copy to system's clipboard Popen(['xclip', '-sel', 'c', '-i'], stdin=PIPE).communicate(input=(hook.encode())) except Exception as e: print(e) ctx.displayMessageBox( None, 'Place the cursor in the function you want to generate the Frida code', None, None)
def run(self, ctx): self.context = ctx.getEnginesContext() if not self.context: return # Assuming a single classes.dex unit = RuntimeProjectUtil.findUnitsByType( self.context.getProjects()[0], IDexUnit, False)[0] classez = unit.getClasses() for c in classez: if c: methods = c.getMethods() if methods: for m in methods: self.extractNativeMethods(m)
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) self.DexDecompilerUnits = RuntimeProjectUtil.findUnitsByType( self.prj, IDexDecompilerUnit, False) self.focusFragment = ctx.getFocusedFragment() self.focusUnit = self.focusFragment.getUnit() if not isinstance(self.focusUnit, IJavaSourceUnit): print('This script must be run within IJavaSourceUnit') return clz = self.focusUnit.getClassElement() self.dfs(self.focusUnit, clz)
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 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): 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): 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): # 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): 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, 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 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): # 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.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): 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)