Ejemplo n.º 1
0
 def _init_arsc(self):
     ARSC_NAME = 'resources.arsc'
     try:
         with apkfile.ZipFile(self.apk_path, mode="r") as zf:
             if ARSC_NAME in zf.namelist():
                 data = zf.read(ARSC_NAME)
                 self.arsc = ARSCParser(data)
     except Exception as e:
         raise e
Ejemplo n.º 2
0
 def save_icon(self, icon_path: str):
     """
     Args:
         icon_path (str): should endwith .png
     """
     zip_icon_path = self._apk.get_app_icon()
     with apkfile.ZipFile(self._apk.apk_path) as z:
         with z.open(zip_icon_path) as f:
             with open(icon_path, 'wb') as w:
                 shutil.copyfileobj(f, w)
Ejemplo n.º 3
0
 def _init_dex_files(self):
     self.dex_files = []
     try:
         with apkfile.ZipFile(self.apk_path, 'r') as z:
             for name in z.namelist():
                 data = z.read(name)
                 if name.startswith('classes') and name.endswith('.dex') \
                         and Magic(data).get_type() == 'dex':
                     dex_file = DexFile(data)
                     self.dex_files.append(dex_file)
     except Exception as ex:
         raise ex
Ejemplo n.º 4
0
 def _init_certs(self):
     try:
         with apkfile.ZipFile(self.apk_path, mode="r") as zf:
             for name in zf.namelist():
                 if 'META-INF' in name:
                     data = zf.read(name)
                     mine = Magic(data).get_type()
                     if mine != 'txt':
                         from apkutils.cert import Certificate
                         cert = Certificate(data)
                         self.certs = cert.get()
     except Exception as e:
         raise e
Ejemplo n.º 5
0
 def _init_org_manifest(self):
     ANDROID_MANIFEST = "AndroidManifest.xml"
     try:
         with apkfile.ZipFile(self.apk_path, mode="r") as zf:
             if ANDROID_MANIFEST in zf.namelist():
                 data = zf.read(ANDROID_MANIFEST)
                 try:
                     axml = AXML(data)
                     if axml.is_valid:
                         self.org_manifest = axml.get_xml()
                 except Exception as e:
                     raise e
     except Exception as e:
         raise e
Ejemplo n.º 6
0
 def _init_certs(self, digestalgo):
     try:
         with apkfile.ZipFile(self.apk_path, mode="r") as zf:
             for name in zf.namelist():
                 if name.startswith('META-INF/') and name.endswith(
                     ('.DSA', '.RSA')):
                     data = zf.read(name)
                     mine = Magic(data).get_type()
                     if mine != 'txt':
                         from apkutils.cert import Certificate
                         cert = Certificate(data, digestalgo=digestalgo)
                         self.certs[digestalgo] = cert.get()
     except Exception as e:
         raise e
Ejemplo n.º 7
0
    def _init_org_manifest(self):
        ANDROID_MANIFEST = "AndroidManifest.xml"
        try:
            with apkfile.ZipFile(self.apk_path, mode="r") as zf:
                if ANDROID_MANIFEST in zf.namelist():
                    data = zf.read(ANDROID_MANIFEST)
                    try:
                        axml = AXML(data)
                        if axml.is_valid:
                            self.org_manifest = axml.get_xml()
                    except Exception as e:
                        raise e
        except Exception as e:
            raise e

        # fix manifest
        self.org_manifest = re.sub(r'\s:(="[\w]*?\.[\.\w]*")',
                                   r' android:name\1', self.org_manifest)
Ejemplo n.º 8
0
 def _init_app_icon(self):
     files = self.get_files()
     result = re.search(r':icon="@(.*?)"', self.get_org_manifest())
     ids = '0x' + result.groups()[0].lower()
     try:
         with apkfile.ZipFile(self.apk_path, 'r') as z:
             data = z.read('resources.arsc')
             self.arscobj = ARSCParser(data)
             self.package = self.arscobj.get_packages_names()[0]
             datas = xmltodict.parse(
                 self.arscobj.get_public_resources(self.package))
             for item in datas['resources']['public']:
                 if ids != item['@id']:
                     continue
                 for f in files:
                     name = f['name']
                     if item['@type'] in name and item['@name'] in name:
                         self.app_icon = name
     except Exception as ex:
         raise ex
Ejemplo n.º 9
0
    def _init_manifest(self):
        ANDROID_MANIFEST = "AndroidManifest.xml"
        try:
            with apkfile.ZipFile(self.apk_path, mode="r") as zf:
                if ANDROID_MANIFEST in zf.namelist():
                    data = zf.read(ANDROID_MANIFEST)
                    try:
                        axml = AXML(data)
                        if axml.is_valid:
                            self.org_manifest = axml.get_xml()
                    except Exception as e:
                        raise e

                    if self.org_manifest:
                        try:
                            self.manifest = xmltodict.parse(
                                self.org_manifest, False)['manifest']
                        except xml.parsers.expat.ExpatError as e:
                            print(self.apk_path, e)
                        except Exception as e:
                            raise e
        except Exception as e:
            raise e
Ejemplo n.º 10
0
 def _init_children(self):
     self.children = []
     try:
         with apkfile.ZipFile(self.apk_path, mode="r") as zf:
             for name in zf.namelist():
                 try:
                     data = zf.read(name)
                     mine = Magic(data).get_type()
                     info = zf.getinfo(name)
                 except Exception as ex:
                     print(name, ex)
                     continue
                 item = {}
                 item["name"] = name
                 item["type"] = mine
                 item["time"] = "%d%02d%02d%02d%02d%02d" % info.date_time
                 crc = str(hex(info.CRC)).upper()[2:]
                 crc = '0' * (8 - len(crc)) + crc
                 item["crc"] = crc
                 # item["sha1"] = ""
                 self.children.append(item)
     except Exception as e:
         raise e
def extract_feature_from_APK(path, permission_dict, file_type='manifest'):
    '''This function extract features of interest takes as 
    Input: 
        the path : String, path where the zipfiles are
        permission_dict : Dictionary; containing all the permissions
        the type : String in ['manifest','dex']
    Output:
        return a dataframe containing the requested features
    '''
    if file_type == 'manifest':

        df = pd.DataFrame(columns=sorted(
            list(permission_dict.keys())).insert(0, "id"))
    else:
        df = pd.DataFrame()

    i = 0

    for _, _, f in os.walk(path):
        for file in f:
            i = i + 1
            if i == 8:
                break

            apk_path = path+file
            try:
                with apkfile.ZipFile(apk_path, 'r') as unzip_file:
                    for name in unzip_file.namelist():
                        if file_type == 'manifest' and name.startswith('AndroidManifest') and name.endswith('.xml'):
                            try:
                                data = unzip_file.read(name)
                                axml = AXML(data).get_xml()
                                dat = xmltodict.parse(axml, False)['manifest']
                                print(name + " " + str(i))
                                features = generate_xml_features(
                                    dat, file, permission_dict)
                                print(features)
                                df = pd.concat([df, features])
                                print(name + " " + str(i))
                            except Exception as e:
                                print("manifest error", e)

                        elif file_type == 'dex' and name.startswith('classes') and name.endswith('.dex'):
                            try:
                                data = unzip_file.read(name)
                                dat = DexFile(data)
                                print(name + " " + str(i))
                                features = generate_dex_features(dat, file)

                                df = pd.concat(
                                    [df, features], ignore_index=True)

                                print(name + " " + str(i))
                            except Exception as e:
                                print("dex error", e)
                        else:
                            pass
            except Exception as e:
                print("ERROR:")
                print(e)
                pass

    return df