Пример #1
0
def permissions_map():
    groupcols = ['group', 'group_package', 'group_label', 'group_description']
    pcols = [
        'permission',
        'package',
        'label',
        'description',
        'protectionLevel']
    sp = simpleparse(open('Pixel2.permissions', 'r').read())
    df = pd.DataFrame(columns=groupcols + pcols)
    record = {}
    ungrouped_d = dict.fromkeys(groupcols, 'ungrouped')
    for group in sp[1]:
        record['group'] = group.split(':')[1]
        if record['group'] == '':
            for permission in sp[1][group]:
                record['permission'] = permission.split(':')[1]
                for permission_attr in sp[1][group][permission]:
                    label, val = permission_attr.split(':')
                    record[label.replace('+ ', '')] = val
                df.loc[df.shape[0]] = {**record, **ungrouped_d}
        else:
            for group_attr in sp[1][group]:
                if isinstance(group_attr, str):
                    label, val = group_attr.split(':')
                    record['group_' + label.replace('+ ', '')] = val
                else:
                    for permission in group_attr:
                        record['permission'] = permission.split(':')[1]
                        for permission_attr in group_attr[permission]:
                            label, val = permission_attr.split(':')
                            record[label.replace('+ ', '')] = val
                        df.loc[df.shape[0]] = record
    df.to_csv('static_data/android_permissions.csv')
    return df
Пример #2
0
 def _parse(lines):
     try:
         if service in custom_parse_services:
             return AndroidDump.custom_parse(service, lines)
         else:
             return simpleparse('\n'.join(join_lines))
     except Exception as ex:
         print("Could not parse for {} service={}. Exception={}"\
               .format(fname, service, ex))
         return lines
Пример #3
0
def permissions_used(appid):
    # FIXME: add check on all permissions, too.
    #cmd = '{cli} shell dumpsys package {app}'
    #app_permissions = catch_err(run_command(cmd, app=appid))
    #print(app_permissions)

    # switch to top method after tests
    package_dump = open(DUMPPKG, 'r').read()
    #print(package_dump)
    sp = simpleparse(package_dump)
    try:
        pkg = [v for k, v in sp['Packages:'].items() if appid in k][0]
    except IndexError as e:
        print(e)
        print('Didn\'t parse correctly. Not sure why.')
        exit(0)

    #print(pkg['install permissions:'])
    install_perms = [
        k.split(':')[0] for k, v in pkg['install permissions:'].items()
    ]
    requested_perms = pkg['requested permissions:']
    install_date = pkg['firstInstallTime']

    all_perms = list(set(requested_perms) | set(install_perms))

    # need to get
    # requested permissions:
    # install permissions:
    # runtime permissions:

    #cmd = '{cli} shell appops get {app}'
    #recently_used = catch_err(run_command(cmd, app=appid))
    #recently_used = recently_used.split("\n")
    #for perm in recently_used:
    #    print(perm.split(";"))
    return all_perms
Пример #4
0
def package_info(dumpf, appid):
    # FIXME: add check on all permissions, too.
    # need to get
    # requested permissions:
    # install permissions:
    # runtime permissions:
    cmd = "sed -n -e '/Package \[{appid}\]/,/Package \[/p' {dumpf}"\
        .format(appid=appid, dumpf=dumpf.replace('.json', '.txt'))
    print(cmd)
    # TODO: Need to udpate it once the catch_err function is fixed.
    package_dump = run_command(cmd).stdout.read().decode()

    # cmd = '{cli} shell dumpsys usagestats {app} | grep "App Standby States:" -A 1'\
    #     .format(cli=config.ADB_PATH, app=appid)
    # now = datetime.datetime.now()
    #usage_stats = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)\
    #        .stdout.read().decode('utf-8')#.strip()

    '''
     App Standby States:
        package=net.cybrook.trackview u=0 bucket=10 reason=u-mb used=+4m41s645ms usedScr=+2m19s198ms lastPred=+19d0h27m2s920ms activeLeft=+55m18s355ms wsLeft=-30d6h13m15s667ms lastJob=-24855d3h14m7s432ms idle=n

        totalElapsedTime=+305d6h7m59s376ms
        totalScreenOnTime=+67d8h56m19s585ms
    '''

    '''
    # switch to top method after tests
    package_dump = open(DUMPPKG, 'r').read()
    #print(package_dump)
    '''
    try:
        sp = simpleparse(package_dump)
    except AttributeError as e:
        print(package_dump)
        return []

    try:
        # FIXME: TypeError: list indices must be integers or slices, not str
        # FIXME: don't rely on rsonlite to parse correctly? Seems to miss the
        # Packages:.  for now, using sed to filter out potential hazards in
        # parsing output.
        if isinstance(sp, list):
            sp = sp[0]
        _, pkg = sp.popitem()
        if isinstance(pkg, list):
            pkg = pkg[0]
    except IndexError as e:
        print(e)
        print('Didn\'t parse correctly. Not sure why.')
        return [], {}
    print("pkg={}".format(json.dumps(pkg, indent=2)))
    install_perms = [k.split(':')[0] for k, v in
                     pkg.get('install permissions:', {}).items()]
    requested_perms = pkg.get('requested permissions:', [])

    #usage_stats = filter(None, usage_stats.split('\n')[1].split(' '))
    #usage_stats = dict(item.split('=') for item in usage_stats)
    # print(usage_stats)
    pkg_info = {}
    pkg_info['firstInstallTime'] = pkg.get('firstInstallTime', '')
    pkg_info['lastUpdateTime'] = pkg.get('lastUpdateTime', '')
    pkg_info['versionCode'] = pkg.get('versionCode', '')
    pkg_info['versionName'] = pkg.get('versionName', '')
    #pkg_info['used'] = now - _parse_time(usage_stats['used'])
    #pkg_info['usedScr'] = now - _parse_time(usage_stats['usedScr'])

    #('User 0:  installed', 'true hidden=false stopped=false notLaunched=false enabled=0\nlastDisabledCaller: com.android.vending\ngids=[3003]\nruntime permissions:')
    #inst_det_key = [v for k,v in pkg.items() if 'User 0:' in k][0]
    #install_details = dict(item.split('=') for item in inst_det_key.strip().split(' ')[1:])
    #install_details = {k:bool(strtobool(install_details[k])) for k in install_details}
    # print(install_details)

    all_perms = list(set(requested_perms) | set(install_perms))

    return all_perms, pkg_info