Пример #1
0
    def analyse_local_apks(self, list_of_apks, playstore_api, download_folder_path, return_function):
        list_apks_to_update = []
        package_bunch = []
        for position, filename in enumerate(list_of_apks):
            filepath = os.path.join(download_folder_path, filename)
            a = APK(filepath)
            packagename = a.package
            package_bunch.append(packagename)

        # BulkDetails requires only one HTTP request
        # Get APK info from store
        details = playstore_api.bulkDetails(package_bunch)
        for detail, packagename, filename in zip(details, package_bunch, list_of_apks):
            logging(self, "Analyzing %s" % packagename)
            # Getting Apk infos
            filepath = os.path.join(download_folder_path, filename)
            a = APK(filepath)
            apk_version_code = a.version_code
            store_version_code = detail['versionCode']

            # Compare
            if apk_version_code != "" and int(apk_version_code) < int(store_version_code) and int(
                    store_version_code) != 0:
                # Add to the download list
                list_apks_to_update.append([packagename, filename, int(apk_version_code), int(store_version_code)])

        return_function(list_apks_to_update)
Пример #2
0
        def install_or_upgrade(adb, apk_path, service_name):
            installed_version_code = adb.get_package_version(service_name)
            apk_version_code = APK(apk_path).version_code

            if installed_version_code is None or int(apk_version_code) > int(
                    installed_version_code):
                self.install()
Пример #3
0
    def analyse_local_apks(self, list_of_apks, download_folder):
        """
        Analyse apks in the list list_of_apks
        to check for updates and download updates
        in the download_folder folder.
        """
        list_apks_to_update = []
        package_bunch = []
        version_codes = []
        for filename in list_of_apks:
            filepath = os.path.join(download_folder, filename)
            logger.info("Analyzing %s", filepath)
            apk = APK(filepath)
            packagename = apk.package
            package_bunch.append(packagename)
            version_codes.append(util.vcode(apk.version_code))

        # BulkDetails requires only one HTTP request
        # Get APK info from store
        details = self.api.bulkDetails(package_bunch)
        for detail, packagename, filename, apk_version_code in zip(
                details, package_bunch, list_of_apks, version_codes):
            store_version_code = detail['versionCode']

            # Compare
            if apk_version_code < store_version_code:
                # Add to the download list
                list_apks_to_update.append([
                    packagename, filename, apk_version_code, store_version_code
                ])

        return list_apks_to_update
Пример #4
0
def extract_package_id(file):
    try:
        if file.endswith('.aab'):
            print('Cannot display application package ID for aab files')
            return None

        version_info = extract_version_info(file)
        if 'androidManifest' in version_info:
            apk = APK(file)
            return apk.package
        elif 'iosXmlPlist' in version_info:
            data = version_info['iosXmlPlist']
            plist = plistlib.loads(base64.b64decode(data))
            LOGGER.info('Extracted XML plist: %s', repr(plist))
            return plist['ApplicationProperties']['CFBundleIdentifier']
        elif 'iosBinaryPlist' in version_info:
            data = version_info['iosBinaryPlist']
            plist = plistlib.loads(base64.b64decode(data))
            LOGGER.info('Extracted binary plist: %s', repr(plist))
            return plist['CFBundleIdentifier'].replace('"', '')
        else:
            raise Exception('Unsupported file type')

    except Exception as e:
        print('Failed to extract application package ID')
        LOGGER.warning('extract package id failed: %s', repr(e))
        sys.exit(1)
Пример #5
0
 def __init__(self, path):
     self.path = path
     self.apk = APK(self.path)
     # temporarty hack for ella os.path.basename(path) => path[51:-21]
     self.name = path[51:-21]
     self.package = self.apk.package
     self.activity = self.apk.get_main_activity()
Пример #6
0
def main(filename):
    filename = os.path.expanduser(filename)
    apk = APK(filename)

    click.echo('APK: {}'.format(filename))
    click.echo('App name: {}'.format(apk.application))
    click.echo('Package: {}'.format(apk.package))
    click.echo('Version name: {}'.format(apk.version_name))
    click.echo('Version code: {}'.format(apk.version_code))
Пример #7
0
 def clean_file(self):
     file = self.files['file']
     try:
         apk = APK(file.file.name)
         version_name = apk.get_androidversion_name()
         if self.Meta.model.objects.filter(name=version_name).exists():
             self.add_error('file', _('This is not a new version!'))
         self.cleaned_data['name'] = version_name
     except Exception as e:
         self.add_error('file', str(e))
     return file
def main(apk_file):
    apk = APK(apk_file)
    print(apk.application)
    print(apk.package)
    print(apk.version_name)
    folder = extract_apk(apk_file)
    create_android_json(folder, apk.application, apk.package, apk.version_name)
    rename_files(folder)
    rearrange_directory(folder)
    decompile_rpyc_files(folder)
    print("All done :-)")
Пример #9
0
def main(filename):
    filename = os.path.expanduser(filename)
    apk = APK(filename)

    click.echo('APK: {}'.format(filename))
    click.echo('App name: {}'.format(apk.application))
    click.echo('Package: {}'.format(apk.packagename))
    click.echo('Version name: {}'.format(apk.version_name))
    click.echo('Version code: {}'.format(apk.version_code))
    click.echo('Is it Signed: {}'.format(apk.signed))
    click.echo('Is it Signed with v1 Signatures: {}'.format(apk.signed_v1))
    click.echo('Is it Signed with v2 Signatures: {}'.format(apk.signed_v2))
    click.echo('Is it Signed with v3 Signatures: {}'.format(apk.signed_v3))
Пример #10
0
def dexmd5():
    from pyaxmlparser import APK
    import base64
    import zipfile
    import hashlib
    print("Running dexmd5")
    try:
        zipFile = zipfile.ZipFile(apk, 'r')
        classesDexFile = zipFile.read('classes.dex')
        hash = hashlib.md5()
        hash.update(classesDexFile)
        versi = APK(apk).version_name
        MD5 = base64.b64encode(hash.digest()).decode("utf-8")
    except:
        pass
    return versi, MD5
Пример #11
0
def gather_apk_information(apk_file_path):
    try:
        apk = APK(apk_file_path)
        return {
            'error':
            False,
            'package':
            apk.package,
            'version_name':
            apk.version_name,
            'version_code':
            apk.version_code,
            'is_jodel_signature':
            True if apk.package == 'com.tellm.android.app' else False
        }
    except:
        return {'error': True, 'message': 'Failed verifying APK file!'}
Пример #12
0
	def analyse_local_apks(self, list_of_apks, download_folder):
		"""
		Analyse apks in the list list_of_apks
		to check for updates and download updates
		in the download_folder folder.
		"""
		list_apks_to_update = []
		package_bunch = []
		version_codes = []
		unavail_items = []
		UNAVAIL = "This app is not available in the Play Store"
		for filename in list_of_apks:
			filepath = os.path.join(download_folder, filename)
			logger.info("Analyzing %s", filepath)
			apk = APK(filepath)
			packagename = apk.package
			package_bunch.append(packagename)
			version_codes.append(util.vcode(apk.version_code))

		# BulkDetails requires only one HTTP request
		# Get APK info from store
		details = self.api.bulkDetails(package_bunch)
		for detail, packagename, filename, apk_version_code in zip(details,
																   package_bunch,
																   list_of_apks,
																   version_codes):
			# this app is not in the play store
			if not detail:
				unavail_items.append(((packagename, filename), UNAVAIL))
				continue
			store_version_code = detail['versionCode']

			# Compare
			if apk_version_code < store_version_code:
				# Add to the download list
				list_apks_to_update.append([packagename,
											filename,
											apk_version_code,
											store_version_code])

		if self.logging_enable:
			self.write_logfiles(None, None, [item[0][0] for item in unavail_items])
		self.print_failed(unavail_items)

		return list_apks_to_update
Пример #13
0
def apk_applier(
    list_apk: List[Path],
    function: Callable[[APK], Any],
):
    """Higher order function that applies the `callable` function to every element of `list_apk`"""
    local_dict = {}
    for apk_path in list_apk:
        try:
            apk = APK(str(apk_path), raw=False)
            log.info(f"Applying function {function} to {apk.filename}")
            local_dict[apk_path.name] = function(apk)
        except BrokenAPKError as e:
            log.warning(
                f"{apk_path} is not a valid APK , skipping file because of {e.__cause__}"
            )
            continue
    with open(Path(BASE_DIR + '/cache.json'), 'w') as output:
        output.write(json.dumps(local_dict))
Пример #14
0
def check_apk(key: str, bucket_name: str):
    """
    Script that encapsulates the various checks for the presence of the
    safetynet attestation API

    Args:
        key: the key name that identifies the object in the s3 bucket
        bucket_name: the name of the s3 bucket that the key belongs to

    """
    apk_name = key.split("-")[0]

    try:
        s3_client = create_s3_client(config)
        apk_object = s3_client.get_object(Bucket=bucket_name, Key=key)
    except ClientError as e:
        logging.error(e)
        return

    logging.info("Checking {}".format(apk_name))
    session = scoped_session(session_factory)

    apk_bytes = apk_object['Body'].read()
    apk_detail = session.query(ApkDetail).get(key)
    if not apk_detail:
        try:
            parsed_apk = APK(apk_bytes, raw=True)
            # a, d, dx = AnalyzeAPK(apk_bytes, raw=True)
            apk_detail = check_for_properties_file(apk_bytes, parsed_apk, key)

            apk_detail = check_manifest_file(parsed_apk, apk_detail)

            apk_detail.dex_file = check_class_files(apk_bytes)

            add_apk_detail(session, app_name=apk_detail.app_name,
                           app_version=apk_detail.app_version, s3_key=key,
                           safetynet_version=apk_detail.safetynet_version,
                           has_properties_file=apk_detail.has_properties_file,
                           attestation_in_manifest=apk_detail.attestation_in_manifest,
                           dex_file=apk_detail.dex_file)
        except Exception as e:
            logging.error("There was an error processing the file:" + str(e))
    else:
        logging.warning("{} has already been checked".format(apk_name))
Пример #15
0
def get_library(list_apk: List[Path]) -> ApkLibrary:
    if not list_apk:
        print('No apk files found ')
        return {}
    library = {}
    total = len(list_apk)
    counter = 0
    for apk_path in list_apk:
        apk = APK(str(apk_path))
        try:
            meta = get_meta_from_apk(apk)
        except Exception as e:
            log.error(e)
            continue
        if apk.package not in library:
            library[apk.package] = [meta]
        else:
            library[apk.package].append(meta)
        counter += 1
        print(f'{counter / total * 100}%')
    return library
Пример #16
0
def get_details_from_apk(apk, downloadPath, service):
    if apk is not None:
        filepath = os.path.join(downloadPath, apk)
        try:
            a = APK(filepath)
        except Exception as e:
            print(e)
            return None
        print('Fetching details for %s' % a.package)
        try:
            details = service.details(a.package)
            details['filename'] = apk
            details['versionCode'] = int(a.version_code)
        except RequestError as e:
            print('Cannot fetch information for %s' % a.package)
            print('Extracting basic information from package...')
            return {'docId': a.package,
                    'filename': apk,
                    'versionCode': int(a.version_code),
                    'title': a.application}
        print('Added %s to cache' % details['docId'])
    return details
Пример #17
0
def main():
    parser = argparse.ArgumentParser(description="Extract StringCare secrets from an Android APK.")
    parser.add_argument("-r", "--resign", action="store_true", help="Resign and save xml file")
    parser.add_argument("-o", "--other", action="store_true", help="Include a list of other secrets")
    parser.add_argument("apk", help="Path to the apk", type=str)
    parser.add_argument("replaced", help="Path to the replaced values", type=str, nargs='?')
    args = parser.parse_args()

    logging.getLogger("pyaxmlparser.core").setLevel(logging.ERROR)
    apk = APK(args.apk)
    logging.getLogger("pyaxmlparser.core").setLevel(logging.NOTSET)
    certificate_files = [f for f in apk.files if f.startswith('META-INF/') and f.endswith('.RSA')]

    decrypt_keys = get_decrypt_keys(apk, certificate_files)
    decrypt_ciphers = [AESCipher(key) for key in decrypt_keys]

    encrypt_cipher = None
    if args.resign:
        def get_key_from_android_debug_keystore(keystore_path: str, keystore_pass: str = 'android') -> str:
            ks = jks.KeyStore.load(keystore_path, keystore_pass)
            cert_bytes = ks.entries['androiddebugkey'].cert_chain[0][1]
            public_cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1, cert_bytes)
            sha1hash = public_cert.digest('sha1').decode()
            return sha1hash

        keystore_path = str(Path.home().joinpath('.android', 'debug.keystore'))
        sha1hash = get_key_from_android_debug_keystore(keystore_path)
        encrypt_key = generate_key(sha1hash)
        encrypt_cipher = AESCipher(encrypt_key)

    replaced_map = {}
    if args.replaced is not None:
        with open(args.replaced, 'rb') as f:
            replaced_map = json.load(f)

    valmap = extract_secrets(apk, decrypt_ciphers, encrypt_cipher, replaced_map, args.other)
    print(json.dumps(valmap, indent=4, sort_keys=True))
Пример #18
0
def read_apk(path):
	apk = APK(path)

	return apk
Пример #19
0
def open_apk(path):
    apk = APK(path)
    yield apk
            for chunk in r.iter_content(chunk_size=1024):
                if chunk:
                    file.write(chunk)


if len(sys.argv) > 1:
    search(" ".join(sys.argv[1:]))
    if len(APPS) > 0:
        print('Downloading {}.apk ...'.format(APPS[00][2].split('/')[-1]))
        download(APPS[00][2])
        print('Download completed!')
        apk_file = format(APPS[00][2].split('/')[-1]) + '.apk'

        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            apk = APK(apk_file)
            # print(apk.package)
            # print(apk.version_name)
            apk_version_name = apk.version_name
            # print(apk.version_code)
            apk_version_code = apk.version_code
            # print(apk.icon_info)
            # print(apk.icon_data)
            apk_name = apk.application
            # print('Apk Name : '+apk_name)
            print(apk_name + ' ' + apk_version_name + '_' + apk_version_code +
                  '.apk')
            # os.rename(apk_file, apk_name+' '+apk_version_name+'_'+apk_version_code+'.apk')
            copyfile(
                apk_file, apk_name + ' ' + apk_version_name + '_' +
                apk_version_code + '.apk')
Пример #21
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from pyaxmlparser import APK

info = APK('./driver-envrelease-release-1.3.0.apk')
print(info.version_name)
print(info.version_code)
Пример #22
0
from pyaxmlparser import APK

apk = APK('USBDebug 1.0_1.apk')
print(apk.package)
print(apk.version_name)
print(apk.version_code)
print(apk.icon_info)
print(apk.icon_data)
print(apk.application)
Пример #23
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from pyaxmlparser import APK

a = APK(
    "/Users/Xiaobo/Workspace_ARD/minitest/core/resources/poco/pocoservice-debug.apk"
)
print(a.xml)
print(a.axml)
print(a.version_name)
print(a.get_target_sdk_version)
print(a.get_main_activity())
print(a.apk)
Пример #24
0
from pyaxmlparser import APK
import sys
import base64
import zipfile
import hashlib

if len(sys.argv) < 2:
    print("Usage: python dexMD5.py <WhatsApp.apk>")
    exit()
else:
    apkFile = sys.argv[1]
    apk = APK(apkFile)
try:
    zipFile = zipfile.ZipFile(apkFile,'r')
    classesDexFile = zipFile.read('classes.dex')
    hash = hashlib.md5()
    hash.update(classesDexFile)

    # print(apk.version_name)
    with open('version.txt', 'w') as f:
        f.write(apk.version_name)

    # print(base64.b64encode(hash.digest()).decode("utf-8"));
    with open('md5.txt', 'w') as f:
        f.write(base64.b64encode(hash.digest()).decode("utf-8"))
except Exception as e:
    print(sys.argv[1] + " not found.")
Пример #25
0
 def get_details_from_apk(details):
     filepath = os.path.join(self.download_path,
                             details['docId'] + '.apk')
     a = APK(filepath)
     details['versionCode'] = int(a.version_code)
     return details
Пример #26
0
 def apk_info(self):
     return APK(self.file)
Пример #27
0
import warnings

from pyaxmlparser import APK

file = '/home/chillar/projects/android/apps/adbd-Insecure-v2.00.apk'

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    apk = APK(file)
    print(apk.package)
Пример #28
0
def get_apkinfo(filepath):
    from pyaxmlparser import APK
    if filepath is not None:
        apk = APK(filepath)
        return apk
Пример #29
0
	repair_container()
	result = {}
	apk_package = ""
	apk_full_path = filels[index]
	# frida_server_kill_process()
	# time.sleep(1)
	# frida_server_start_process()
	try:
		# fetch apk file
		print ("Install application: "+apk_full_path)
		
		filename = getLogdir(apk_full_path,dir)
		# install apk
		print(check_output("adb install "+apk_full_path+"|exit", shell=True,timeout=10).decode())
		# get package name
		apk = APK(apk_full_path)
		package_name = apk.packagename
		print (index)
		print (filename)
		print (package_name)
	except Exception as e:
		f=open("runlog.txt","a+").write("Error in file: "+filename+"\n")
		exit

	docker_id = '192.168.0.36'
	launchable_activity = utils.get_launchable_activity_from_aapt(
        apk_full_path)
	run_apk_res = utils.run_apk(docker_id, package_name, launchable_activity)

    # get all pid of the app while it runs
	pids = utils.get_app_pid(docker_id,package_name)