INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Constructs a CFG
def construct(start_block, vmap, exceptions): """ Constructs a CFG :param androguard.core.analysis.analysis.DVMBasicBlock start_block: The startpoint :param vmap: variable mapping :param exceptions: list of androguard.core.analysis.analysis.ExceptionAnalysis :rtype: Graph """ bfs_block...
Remove the node from the graph removes also all connections.
def remove_node(self, node): """ Remove the node from the graph, removes also all connections. :param androguard.decompiler.dad.node.Node node: the node to remove """ preds = self.reverse_edges.get(node, []) for pred in preds: self.edges[pred].remove(node) ...
Number the nodes in reverse post order. An RPO traversal visit as many predecessors of a node as possible before visiting the node itself.
def compute_rpo(self): """ Number the nodes in reverse post order. An RPO traversal visit as many predecessors of a node as possible before visiting the node itself. """ nb = len(self.nodes) + 1 for node in self.post_order(): node.num = nb - node.po ...
Yields the: class ~androguard. decompiler. dad. node. Node s of the graph in post - order i. e we visit all the children of a node before visiting the node itself.
def post_order(self): """ Yields the :class`~androguard.decompiler.dad.node.Node`s of the graph in post-order i.e we visit all the children of a node before visiting the node itself. """ def _visit(n, cnt): visited.add(n) for suc in self.all_sucs(n): ...
Writes the current graph as a PNG file
def draw(self, name, dname, draw_branches=True): """ Writes the current graph as a PNG file :param str name: filename (without .png) :param str dname: directory of the output png :param draw_branches: :return: """ from pydot import Dot, Edge impor...
Parse the AndroidManifest. xml.
def axml(input_, output, file_, resource): """ Parse the AndroidManifest.xml. Parsing is either direct or from a given APK and prints in XML format or saves to file. This tool can also be used to process any AXML encoded file, for example from the layout directory. Example: \b ...
Decode resources. arsc either directly from a given file or from an APK.
def arsc(input_, file_, output, package, locale, type_, id_, list_packages, list_locales, list_types): """ Decode resources.arsc either directly from a given file or from an APK. Example: \b $ androguard arsc app....
Create a call graph and export it into a graph format.
def cg(output, show, verbose, classname, methodname, descriptor, accessflag, no_isolated, apk): """ Create a call graph and export it into a graph format. classnames are found in the type "Lfoo/bar/bla;". Example: \b $ androguard cg ...
Decompile an APK and create Control Flow Graphs.
def decompile(input_, file_, output, format_, jar, limit, decompiler): """ Decompile an APK and create Control Flow Graphs. Example: \b $ androguard resources.arsc """ from androguard import session if file_ and input_: print("Can not give --input and positional argument! "...
Return the fingerprint ( s ) of all certificates inside an APK.
def sign(hash_, print_all_hashes, show, apk): """Return the fingerprint(s) of all certificates inside an APK.""" androsign_main(apk, hash_, print_all_hashes, show)
Return the packageName/ versionCode/ versionName per APK as JSON.
def apkid(apks): """Return the packageName/versionCode/versionName per APK as JSON.""" import json import logging logging.getLogger("androguard.axml").setLevel(logging.ERROR) results = dict() for apk in apks: results[apk] = androguard.core.bytecodes.apk.get_apkid(apk) print(json.dump...
Load a module by name and search path
def load_module(module_name, file_path): """ Load a module by name and search path Returns None if Module could not be loaded. """ if sys.version_info >= (3,5,): import importlib.util spec = importlib.util.spec_from_file_location(module_name, file_path) if not spec: ...
Helper function called by any window to display a message in status bar.
def showStatus(self, msg): """Helper function called by any window to display a message in status bar. """ log.debug(msg) self.statusBar().showMessage(msg)
User clicked Save menu. Display a Dialog to ask whwre to save.
def saveFile(self): """User clicked Save menu. Display a Dialog to ask whwre to save.""" filepath, _ = QtWidgets.QFileDialog.getSaveFileName( self, "Save File", '', "Androguard Session (*.ag)") if filepath: # Ensure .ag as file ending if not filepath.endswith...
Save androguard session.
def saveSession(self, filepath): """Save androguard session.""" try: session_module.Save(self.session, filepath) except RuntimeError as e: log.exception(e) os.remove(filepath) log.warning("Session not saved")
Setup empty Tree at startup.
def setupEmptyTree(self): """Setup empty Tree at startup. """ if hasattr(self, "tree"): del self.tree self.tree = QtWidgets.QTreeWidget(self) self.tree.header().close()
Setup empty Dock at startup.
def setupDock(self): """Setup empty Dock at startup. """ self.dock = QtWidgets.QDockWidget("Classes", self) self.dock.setWidget(self.tree) self.dock.setFeatures(QtWidgets.QDockWidget.NoDockWidgetFeatures) self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.dock)
Setup empty window supporting tabs at startup.
def setupCentral(self): """Setup empty window supporting tabs at startup. """ self.central = TabsWindow(self.bin_windows, self) self.setCentralWidget(self.central)
Main function to open a decompile source window It checks if it already opened and open that tab otherwise initialize a new window.
def openSourceWindow(self, current_class, method=None): """Main function to open a decompile source window It checks if it already opened and open that tab, otherwise, initialize a new window. """ log.debug("openSourceWindow for %s" % current_class) sourcewin = sel...
Convert a object or primitive name into androguard syntax
def name_to_androguard(n): """ Convert a object or primitive name into androguard syntax For example: byte --> B foo.bar.bla --> Lfoo/bar/bla; [int --> [I There is also a special case, where some arrays are specified differently: B[] --> [B foo.bar.bla[] --> [Lf...
Converts a line of axplorer format into androguard method signature + permission: param s:: return:
def convert_name(s): """ Converts a line of axplorer format into androguard method signature + permission :param s: :return: """ m = re.compile(r"^(.*)\.(.*)\((.*)\)(.*) :: (.*)$") res = m.search(s) if res: clname, methodname, all_args, ret, perm = res.groups() args = "...
Generate the permission mappings from a axplorer root dir into a given folder. For each API Level separate json file will be created.
def generate_mappings(axplorerdir="libraries/axplorer", outfolder="androguard/core/api_specific_resources"): """ Generate the permission mappings from a axplorer root dir into a given folder. For each API Level, separate json file will be created. :param axplorerdir: path to the axplorer dir :param...
Return the: class: DvClass with the given name
def get_class(self, class_name): """ Return the :class:`DvClass` with the given name The name is partially matched against the known class names and the first result is returned. For example, the input `foobar` will match on Lfoobar/bla/foo; :param str class_name: :retu...
Process all classes inside the machine.
def process(self): """ Process all classes inside the machine. This calls :meth:`~androgaurd.decompiler.dad.decompile.DvClass.process` on each :class:`DvClass`. """ for name, klass in self.classes.items(): logger.debug('Processing class: %s', name) if isi...
Run: meth: process and: meth: show_source after each other.
def process_and_show(self): """ Run :meth:`process` and :meth:`show_source` after each other. """ for name, klass in sorted(self.classes.items()): logger.debug('Processing class: %s', name) if not isinstance(klass, DvClass): klass = DvClass(klass, ...
Processes each class with AST enabled and returns a dictionary with all single ASTs Classnames as keys.
def get_ast(self): """ Processes each class with AST enabled and returns a dictionary with all single ASTs Classnames as keys. :return: an dictionary for all classes :rtype: dict """ ret = dict() for name, cls in sorted(self.classes.items()): ...
Disable colors from the output ( color = normal )
def disable_colors(): """ Disable colors from the output (color = normal)""" for i in CONF["COLORS"]: if isinstance(CONF["COLORS"][i], dict): for j in CONF["COLORS"][i]: CONF["COLORS"][i][j] = Color.normal else: CONF["COLORS"][i] = Color.normal
Remove colors from the output ( no escape sequences )
def remove_colors(): """ Remove colors from the output (no escape sequences)""" for i in CONF["COLORS"]: if isinstance(CONF["COLORS"][i], dict): for j in CONF["COLORS"][i]: CONF["COLORS"][i][j] = "" else: CONF["COLORS"][i] = ""
Returns a string that describes the type of file for common Android specific formats
def is_android_raw(raw): """ Returns a string that describes the type of file, for common Android specific formats """ val = None # We do not check for META-INF/MANIFEST.MF, # as you also want to analyze unsigned APKs... # AndroidManifest.xml should be in every APK. # classes.dex an...
enable log messages on stdout
def show_logging(level=logging.INFO): """ enable log messages on stdout We will catch all messages here! From all loggers... """ logger = logging.getLogger() h = logging.StreamHandler(stream=sys.stderr) h.setFormatter(logging.Formatter(fmt="[%(levelname)-8s] %(name)s: %(message)s")) l...
Recursivly delete a directory
def rrmdir(directory): """ Recursivly delete a directory :param directory: directory to remove """ for root, dirs, files in os.walk(directory, topdown=False): for name in files: os.remove(os.path.join(root, name)) for name in dirs: os.rmdir(os.path.join(root,...
turn something like #000000 into 0 0 0 or #FFFFFF into 255 255 255
def make_color_tuple(color): """ turn something like "#000000" into 0,0,0 or "#FFFFFF into "255,255,255" """ R = color[1:3] G = color[3:5] B = color[5:7] R = int(R, 16) G = int(G, 16) B = int(B, 16) return R, G, B
wrapper for interpolate_tuple that accepts colors as html ( #CCCCC and such )
def color_range(startcolor, goalcolor, steps): """ wrapper for interpolate_tuple that accepts colors as html ("#CCCCC" and such) """ start_tuple = make_color_tuple(startcolor) goal_tuple = make_color_tuple(goalcolor) return interpolate_tuple(start_tuple, goal_tuple, steps)
Load the module from the JSON files and return a dict which might be empty if the resource could not be loaded.
def load_api_specific_resource_module(resource_name, api=None): """ Load the module from the JSON files and return a dict, which might be empty if the resource could not be loaded. If no api version is given, the default one from the CONF dict is used. :param resource_name: Name of the resource to...
qp. drawLine ( self. fontWidth * ( len ( pos ) + 1 ) + 15 0 self. fontWidth * ( len ( pos ) + 1 ) + 15 50 ) qp. drawLine ( self. fontWidth * ( len ( pos + sd ) + 1 ) + 3 * 15 0 self. fontWidth * ( len ( pos + sd ) + 1 ) + 3 * 15 50 ) qp. drawLine ( self. fontWidth * ( len ( pos + sd + sq ) + 1 ) + 5 * 15 0 self. fontWi...
def draw(self): qp = QtGui.QPainter() qp.begin(self.qpix) qp.fillRect(0, 0, self.width, self.height, self.backgroundBrush) qp.setPen(self.textPen) qp.setFont(self.font) cemu = ConsoleEmulator(qp, self.height // self.fontHeight, self.width // self.fontWidth) dwo...
Updates the DU chain of the instruction located at loc such that there is no more reference to it so that we can remove it. When an instruction is found to be dead ( i. e it has no side effect and the register defined is not used ) we have to update the DU chain of all the variables that may me used by the dead instruc...
def update_chain(graph, loc, du, ud): """ Updates the DU chain of the instruction located at loc such that there is no more reference to it so that we can remove it. When an instruction is found to be dead (i.e it has no side effect, and the register defined is not used) we have to update the DU cha...
Run a dead code elimination pass. Instructions are checked to be dead. If it is the case we remove them and we update the DU & UD chains of its variables to check for further dead instructions.
def dead_code_elimination(graph, du, ud): """ Run a dead code elimination pass. Instructions are checked to be dead. If it is the case, we remove them and we update the DU & UD chains of its variables to check for further dead instructions. """ for node in graph.rpo: for i, ins in no...
Check that the path from loc1 to loc2 is clear. We have to check that there is no side effect between the two location points. We also have to check that the variable reg is not redefined along one of the possible pathes from loc1 to loc2.
def clear_path(graph, reg, loc1, loc2): """ Check that the path from loc1 to loc2 is clear. We have to check that there is no side effect between the two location points. We also have to check that the variable `reg` is not redefined along one of the possible pathes from loc1 to loc2. """ lo...
Propagate the temporary registers between instructions and remove them if necessary. We process the nodes of the graph in reverse post order. For each instruction in the node we look at the variables that it uses. For each of these variables we look where it is defined and if we can replace it with its definition. We h...
def register_propagation(graph, du, ud): """ Propagate the temporary registers between instructions and remove them if necessary. We process the nodes of the graph in reverse post order. For each instruction in the node, we look at the variables that it uses. For each of these variables we look ...
Builds the Def - Use and Use - Def ( DU/ UD ) chains of the variables of the method.
def build_def_use(graph, lparams): """ Builds the Def-Use and Use-Def (DU/UD) chains of the variables of the method. """ analysis = reach_def_analysis(graph, lparams) UD = defaultdict(list) for node in graph.rpo: for i, ins in node.get_loc_with_ins(): for var in ins.get_...
Compute the intervals of the graph Returns interval_graph: a graph of the intervals of G interv_heads: a dict of ( header node interval )
def intervals(graph): """ Compute the intervals of the graph Returns interval_graph: a graph of the intervals of G interv_heads: a dict of (header node, interval) """ interval_graph = Graph() # graph of intervals heads = [graph.entry] # list of header nodes interv_heads = {} # int...
Compute the derived sequence of the graph G The intervals of G are collapsed into nodes intervals of these nodes are built and the process is repeated iteratively until we obtain a single node ( if the graph is not irreducible )
def derived_sequence(graph): """ Compute the derived sequence of the graph G The intervals of G are collapsed into nodes, intervals of these nodes are built, and the process is repeated iteratively until we obtain a single node (if the graph is not irreducible) """ deriv_seq = [graph] de...
Return the Java source code of a whole class
def get_source_class(self, _class): """ Return the Java source code of a whole class :param _class: `ClassDefItem` object, to get the source from :return: """ if not _class.get_name() in self.classes: return "" return self.classes[_class.get_name()]
Tests if any class inside a DalvikVMObject uses ASCII Obfuscation ( e. g. UTF - 8 Chars in Classnames )
def is_ascii_obfuscation(vm): """ Tests if any class inside a DalvikVMObject uses ASCII Obfuscation (e.g. UTF-8 Chars in Classnames) :param vm: `DalvikVMObject` :return: True if ascii obfuscation otherwise False """ for classe in vm.get_classes(): if is_ascii_problem(classe.get_name...
Prints the content of this method to stdout.
def show(self): """ Prints the content of this method to stdout. This will print the method signature and the decompiled code. """ args, ret = self.method.get_descriptor()[1:].split(")") if self.code: # We patch the descriptor here and add the registers, if c...
Returns True if the method seems to be an Android API method.
def is_android_api(self): """ Returns True if the method seems to be an Android API method. This method might be not very precise unless an list of known API methods is given. :return: boolean """ if not self.is_external(): # Method must be external ...
.. deprecated:: 3. 1. 0 Use: meth: get_method instead.
def GetMethod(self, name, descriptor): """ .. deprecated:: 3.1.0 Use :meth:`get_method` instead. """ warnings.warn("deprecated, use get_method instead. This function might be removed in a later release!", DeprecationWarning) return self.get_method(name, descriptor)
Get the method by name and descriptor or create a new one if the requested method does not exists.
def get_method(self, name, descriptor): """ Get the method by name and descriptor, or create a new one if the requested method does not exists. :param name: method name :param descriptor: method descriptor, for example `'(I)V'` :return: :class:`ExternalMethod` ""...
Tries to guess if the current class is an Android API class.
def is_android_api(self): """ Tries to guess if the current class is an Android API class. This might be not very precise unless an apilist is given, with classes that are in fact known APIs. Such a list might be generated by using the android.jar files. :return: boolea...
Search for the given method name and descriptor and return a fake ( ExternalMethod ) if required.
def get_fake_method(self, name, descriptor): """ Search for the given method name and descriptor and return a fake (ExternalMethod) if required. :param name: name of the method :param descriptor: descriptor of the method, for example `'(I I I)V'` :return: :class:`Externa...
Add a Field Read to this class
def AddFXrefRead(self, method, classobj, field): """ Add a Field Read to this class :param method: :param classobj: :param field: :return: """ if field not in self._fields: self._fields[field] = FieldClassAnalysis(field) self._fields[f...
Add a Field Write to this class
def AddFXrefWrite(self, method, classobj, field): """ Add a Field Write to this class :param method: :param classobj: :param field: :return: """ if field not in self._fields: self._fields[field] = FieldClassAnalysis(field) self._fields...
Creates a crossreference to another class. XrefTo means that the current class calls another class. The current class should also be contained in the another class XrefFrom list.
def AddXrefTo(self, ref_kind, classobj, methodobj, offset): """ Creates a crossreference to another class. XrefTo means, that the current class calls another class. The current class should also be contained in the another class' XrefFrom list. :param REF_TYPE ref_kind: type of ...
Creates a crossreference from this class. XrefFrom means that the current class is called by another class.
def AddXrefFrom(self, ref_kind, classobj, methodobj, offset): """ Creates a crossreference from this class. XrefFrom means, that the current class is called by another class. :param REF_TYPE ref_kind: type of call :param classobj: :class:`ClassAnalysis` object to link :p...
Add a DalvikVMFormat to this Analysis
def add(self, vm): """ Add a DalvikVMFormat to this Analysis :param vm: :class:`dvm.DalvikVMFormat` to add to this Analysis """ self.vms.append(vm) for current_class in vm.get_classes(): self.classes[current_class.get_name()] = ClassAnalysis(current_class) ...
Create Class Method String and Field crossreferences for all classes in the Analysis.
def create_xref(self): """ Create Class, Method, String and Field crossreferences for all classes in the Analysis. If you are using multiple DEX files, this function must be called when all DEX files are added. If you call the function after every DEX file, the c...
Create the xref for current_class
def _create_xref(self, current_class): """ Create the xref for `current_class` There are four steps involved in getting the xrefs: * Xrefs for classes * for method calls * for string usage * for field manipulation All these information ...
Search for a: class: EncodedMethod in all classes in this analysis
def get_method_by_name(self, class_name, method_name, method_descriptor): """ Search for a :class:`EncodedMethod` in all classes in this analysis :param class_name: name of the class, for example 'Ljava/lang/Object;' :param method_name: name of the method, for example 'onCreate' ...
Returns the crossreferencing object for a given Method.
def get_method_analysis(self, method): """ Returns the crossreferencing object for a given Method. Beware: the similar named function :meth:`~get_method()` will return a :class:`MethodAnalysis` object, while this function returns a :class:`MethodClassAnalysis` object! This Meth...
Returns the crossreferencing object for a given method.
def get_method_analysis_by_name(self, class_name, method_name, method_descriptor): """ Returns the crossreferencing object for a given method. This function is similar to :meth:`~get_method_analysis`, with the difference that you can look up the Method by name :param class_name...
Get the FieldAnalysis for a given fieldname
def get_field_analysis(self, field): """ Get the FieldAnalysis for a given fieldname :param field: TODO :return: :class:`FieldClassAnalysis` """ class_analysis = self.get_class_analysis(field.get_class_name()) if class_analysis: return class_analysis....
Returns a list of MethodClassAnalysis objects
def get_methods(self): """ Returns a list of `MethodClassAnalysis` objects """ for c in self.classes.values(): for m in c.get_methods(): yield m
Returns a list of FieldClassAnalysis objects
def get_fields(self): """ Returns a list of `FieldClassAnalysis` objects """ for c in self.classes.values(): for f in c.get_fields(): yield f
Find classes by name using regular expression This method will return all ClassAnalysis Object that match the name of the class.
def find_classes(self, name=".*", no_external=False): """ Find classes by name, using regular expression This method will return all ClassAnalysis Object that match the name of the class. :param name: regular expression for class name (default ".*") :param no_external: R...
Find a method by name using regular expression. This method will return all MethodClassAnalysis objects which match the classname methodname descriptor and accessflags of the method.
def find_methods(self, classname=".*", methodname=".*", descriptor=".*", accessflags=".*", no_external=False): """ Find a method by name using regular expression. This method will return all MethodClassAnalysis objects, which match the classname, methodname, descriptor and ac...
Find strings by regex
def find_strings(self, string=".*"): """ Find strings by regex :param string: regular expression for the string to search for :rtype: generator of `StringAnalysis` """ for s, sa in self.strings.items(): if re.match(string, s): yield sa
find fields by regex
def find_fields(self, classname=".*", fieldname=".*", fieldtype=".*", accessflags=".*"): """ find fields by regex :param classname: regular expression of the classname :param fieldname: regular expression of the fieldname :param fieldtype: regular expression of the fieldtype ...
Generate a directed graph based on the methods found by the filters applied. The filters are the same as in: meth: ~androguard. core. analaysis. analaysis. Analysis. find_methods
def get_call_graph(self, classname=".*", methodname=".*", descriptor=".*", accessflags=".*", no_isolated=False, entry_points=[]): """ Generate a directed graph based on the methods found by the filters applied. The filters are the same as in :meth:`~androguard.core...
.. warning:: this feature is experimental and is currently not enabled by default! Use with caution!
def create_ipython_exports(self): """ .. warning:: this feature is experimental and is currently not enabled by default! Use with caution! Creates attributes for all classes, methods and fields on the Analysis object itself. This makes it easier to work with Analysis module in an iPytho...
Returns the permissions and the API method based on the API level specified. This can be used to find usage of API methods which require a permission. Should be used in combination with an: class: ~androguard. core. bytecodes. apk. APK.
def get_permissions(self, apilevel=None): """ Returns the permissions and the API method based on the API level specified. This can be used to find usage of API methods which require a permission. Should be used in combination with an :class:`~androguard.core.bytecodes.apk.APK`. ...
Find the usage of a permission inside the Analysis.
def get_permission_usage(self, permission, apilevel=None): """ Find the usage of a permission inside the Analysis. example:: from androguard.misc import AnalyzeAPK a, d, dx = AnalyzeAPK("somefile.apk") for meth in dx.get_permission_usage('android.permission....
save your session to use it later.
def Save(session, filename=None): """ save your session to use it later. Returns the filename of the written file. If not filename is given, a file named `androguard_session_<DATE>.ag` will be created in the current working directory. `<DATE>` is a timestamp with the following format: `%Y-%m-%d...
Print information to stdout about the current session. Gets all APKs all DEX files and all Analysis objects.
def show(self): """ Print information to stdout about the current session. Gets all APKs, all DEX files and all Analysis objects. """ print("APKs in Session: {}".format(len(self.analyzed_apk))) for d, a in self.analyzed_apk.items(): print("\t{}: {}".format(d, ...
Add an APK file to the Session and run analysis on it.
def addAPK(self, filename, data): """ Add an APK file to the Session and run analysis on it. :param filename: (file)name of APK file :param data: binary data of the APK file :return: a tuple of SHA256 Checksum and APK Object """ digest = hashlib.sha256(data).hexd...
Add a DEX file to the Session and run analysis.
def addDEX(self, filename, data, dx=None): """ Add a DEX file to the Session and run analysis. :param filename: the (file)name of the DEX file :param data: binary data of the dex file :param dx: an existing Analysis Object (optional) :return: A tuple of SHA256 Hash, Dalv...
Generic method to add a file to the session.
def add(self, filename, raw_data=None, dx=None): """ Generic method to add a file to the session. This is the main method to use when adding files to a Session! If an APK file is supplied, all DEX files are analyzed too. For DEX and ODEX files, only this file is analyzed (what ...
Returns all Java Classes from the DEX objects as an array of DEX files.
def get_classes(self): """ Returns all Java Classes from the DEX objects as an array of DEX files. """ for idx, digest in enumerate(self.analyzed_vms): dx = self.analyzed_vms[digest] for vm in dx.vms: filename = self.analyzed_digest[digest] ...
Returns the: class: ~androguard. core. analysis. analysis. Analysis object which contains the current_class.
def get_analysis(self, current_class): """ Returns the :class:`~androguard.core.analysis.analysis.Analysis` object which contains the `current_class`. :param current_class: The class to search for :type current_class: androguard.core.bytecodes.dvm.ClassDefItem :rtype: an...
Returns the filename of the DEX file where the class is in.
def get_filename_by_class(self, current_class): """ Returns the filename of the DEX file where the class is in. Returns the first filename this class was present. For example, if you analyzed an APK, this should return the filename of the APK and not of the DEX file. :p...
Return the SHA256 hash of the object containing the ClassDefItem
def get_digest_by_class(self, current_class): """ Return the SHA256 hash of the object containing the ClassDefItem Returns the first digest this class was present. For example, if you analyzed an APK, this should return the digest of the APK and not of the DEX file. """ ...
Yields all StringAnalysis for all unique Analysis objects
def get_strings(self): """ Yields all StringAnalysis for all unique Analysis objects """ seen = [] for digest, dx in self.analyzed_vms.items(): if dx in seen: continue seen.append(dx) yield digest, self.analyzed_digest[digest], ...
Return the total number of strings in all Analysis objects
def get_nb_strings(self): """ Return the total number of strings in all Analysis objects """ nb = 0 seen = [] for digest, dx in self.analyzed_vms.items(): if dx in seen: continue seen.append(dx) nb += len(dx.get_strings_...
Returns APK DalvikVMFormat and Analysis of a specified APK.
def get_objects_apk(self, filename=None, digest=None): """ Returns APK, DalvikVMFormat and Analysis of a specified APK. You must specify either `filename` or `digest`. It is possible to use both, but in this case only `digest` is used. example:: s = Session() ...
Yields all dex objects inclduing their Analysis objects
def get_objects_dex(self): """ Yields all dex objects inclduing their Analysis objects :returns: tuple of (sha256, DalvikVMFormat, Analysis) """ # TODO: there is no variant like get_objects_apk for digest, d in self.analyzed_dex.items(): yield digest, d, self...
Parse all the paths ( [ Lcom/ example/ myclass/ MyActivity$1 ;... ] ) and build a tree using the QTreeWidgetItem insertion method.
def fill(self): """Parse all the paths (['Lcom/example/myclass/MyActivity$1;', ...]) and build a tree using the QTreeWidgetItem insertion method.""" log.debug("Fill classes tree") for idx, filename, digest, classes in self.session.get_classes(): for c in sorted(classes, k...
try to parse additional attributes but ends up to hexdump if the scheme is unknown
def _dump_additional_attributes(additional_attributes): """ try to parse additional attributes, but ends up to hexdump if the scheme is unknown """ attributes_raw = io.BytesIO(additional_attributes) attributes_hex = binascii.hexlify(additional_attributes) if not len(additional_attributes): ret...
Print Fingerprints Issuer and Subject of an X509 Certificate.
def show_Certificate(cert, short=False): """ Print Fingerprints, Issuer and Subject of an X509 Certificate. :param cert: X509 Certificate to print :param short: Print in shortform for DN (Default: False) :type cert: :class:`asn1crypto.x509.Certificate` :type short: Boolean ...
Ensure incoming value is always the value not the resid
def ensure_final_value(packageName, arsc, value): """Ensure incoming value is always the value, not the resid androguard will sometimes return the Android "resId" aka Resource ID instead of the actual value. This checks whether the value is actually a resId, then performs the Android Resource look...
Read ( appid versionCode versionName ) from an APK
def get_apkid(apkfile): """Read (appid, versionCode, versionName) from an APK This first tries to do quick binary XML parsing to just get the values that are needed. It will fallback to full androguard parsing, which is slow, if it can't find the versionName value or versionName is set to a Androi...
Return the appname of the APK
def get_app_name(self): """ Return the appname of the APK This name is read from the AndroidManifest.xml using the application android:label. If no label exists, the android:label of the main activity is used. If there is also no main activity label, an empty string is ...
Return the first icon file name which density is not greater than max_dpi unless exact icon resolution is set in the manifest in which case return the exact file.
def get_app_icon(self, max_dpi=65536): """ Return the first icon file name, which density is not greater than max_dpi, unless exact icon resolution is set in the manifest, in which case return the exact file. This information is read from the AndroidManifest.xml From ht...
Return the filetype guessed for a buffer: param buffer: bytes: returns: str of filetype
def _get_file_magic_name(self, buffer): """ Return the filetype guessed for a buffer :param buffer: bytes :returns: str of filetype """ default = "Unknown" # Faster way, test once, return default. if self.__no_magic: return default tr...
Return the files inside the APK with their associated types ( by using python - magic )
def get_files_types(self): """ Return the files inside the APK with their associated types (by using python-magic) At the same time, the CRC32 are calculated for the files. :rtype: a dictionnary """ if self._files == {}: # Generate File Types / CRC List ...
Overwrite some probably wrong detections by mime libraries
def _patch_magic(self, buffer, orig): """ Overwrite some probably wrong detections by mime libraries :param buffer: bytes of the file to detect :param orig: guess by mime libary :returns: corrected guess """ if ("Zip" in orig) or ('(JAR)' in orig) and androconf.i...
Calculates and compares the CRC32 and returns the raw buffer.
def _get_crc32(self, filename): """ Calculates and compares the CRC32 and returns the raw buffer. The CRC32 is added to `files_crc32` dictionary, if not present. :param filename: filename inside the zipfile :rtype: bytes """ buffer = self.zip.read(filename) ...
Calculates and returns a dictionary of filenames and CRC32
def get_files_crc32(self): """ Calculates and returns a dictionary of filenames and CRC32 :returns: dict of filename: CRC32 """ if self.files_crc32 == {}: for i in self.get_files(): self._get_crc32(i) return self.files_crc32
Return the files inside the APK with their associated types and crc32
def get_files_information(self): """ Return the files inside the APK with their associated types and crc32 :rtype: str, str, int """ for k in self.get_files(): yield k, self.get_files_types()[k], self.get_files_crc32()[k]
Return the raw data of the specified filename inside the APK
def get_file(self, filename): """ Return the raw data of the specified filename inside the APK :rtype: bytes """ try: return self.zip.read(filename) except KeyError: raise FileNotPresent(filename)
Return the names of all DEX files found in the APK. This method only accounts for offical dex files i. e. all files in the root directory of the APK named classes. dex or classes [ 0 - 9 ] +. dex
def get_dex_names(self): """ Return the names of all DEX files found in the APK. This method only accounts for "offical" dex files, i.e. all files in the root directory of the APK named classes.dex or classes[0-9]+.dex :rtype: a list of str """ dexre = re.compile...
Yields all the attribute values in xml files which match with the tag name and the specific attribute
def get_all_attribute_value( self, tag_name, attribute, format_value=True, **attribute_filter ): """ Yields all the attribute values in xml files which match with the tag name and the specific attribute :param str tag_name: specify the tag name :param str attribute: specify ...