Skip to content

Commit

Permalink
linting fixes for Python files
Browse files Browse the repository at this point in the history
  • Loading branch information
Rahul Chatterjee committed Dec 9, 2024
1 parent d1555ef commit ce4f36d
Show file tree
Hide file tree
Showing 37 changed files with 1,549 additions and 1,100 deletions.
29 changes: 16 additions & 13 deletions config.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import logging
import logging.handlers as handlers


def setup_logger():
"""
Set up a logger with a rotating file handler.
Expand All @@ -20,13 +21,14 @@ def setup_logger():
logging.Logger: The configured logger object.
"""
handler = handlers.RotatingFileHandler(
'logs/app.log', maxBytes=100000,
backupCount=30)
"logs/app.log", maxBytes=100000, backupCount=30
)
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logger.addHandler(handler)
return logger


DEV_SUPPRTED = ["android", "ios"] # 'windows', 'mobileos', later
THIS_DIR = Path(__file__).absolute().parent

Expand Down Expand Up @@ -76,25 +78,27 @@ def setup_logger():
# there are a couple of sources of truth that may disagree with their "path
# relavitity". Needless to say, FIXME
SQL_DB_PATH = f"sqlite:///{str(THIS_DIR / 'data/fieldstudy.db')}"
#SQL_DB_CONSULT_PATH = 'sqlite:///data/consultnotes.db' + ("~test" if TEST else "")
# SQL_DB_CONSULT_PATH = 'sqlite:///data/consultnotes.db' + ("~test" if TEST else "")


def set_test_mode(test):
"""
Sets the test mode to the given value and returns the new values of APP_FLAGS_FILE and SQL_DB_PATH.
"""
app_flags_file, sql_db_path = APP_FLAGS_FILE, SQL_DB_PATH
if test:
if not app_flags_file.endswith('~test'):
if not app_flags_file.endswith("~test"):
app_flags_file = APP_FLAGS_FILE + "~test"
if not sql_db_path.endswith('~test'):
if not sql_db_path.endswith("~test"):
sql_db_path = sql_db_path + "~test"
else:
if app_flags_file.endswith('~test'):
app_flags_file = app_flags_file.replace("~test", '')
if sql_db_path.endswith('~test'):
sql_db_path = sql_db_path.replace("~test", '')
if app_flags_file.endswith("~test"):
app_flags_file = app_flags_file.replace("~test", "")
if sql_db_path.endswith("~test"):
sql_db_path = sql_db_path.replace("~test", "")
return app_flags_file, sql_db_path


APP_FLAGS_FILE, SQL_DB_PATH = set_test_mode(TEST)


Expand All @@ -108,9 +112,7 @@ def set_test_mode(test):
else (
"linux"
if platform.startswith("linux")
else "win32"
if platform == "win32"
else None
else "win32" if platform == "win32" else None
)
)

Expand Down Expand Up @@ -148,8 +150,9 @@ def open_or_create_random_key(fpath, keylen=32):
Returns:
bytes: The contents of the file as bytes.
"""

def create():
with fpath.open('wb') as f:
with fpath.open("wb") as f:
f.write(secrets.token_bytes(keylen))

if not fpath.exists():
Expand Down
79 changes: 42 additions & 37 deletions phone_scanner/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,11 @@ def devices(self):

def get_system_apps(self, serialno, from_device: bool) -> list:
pass

def get_apps(self, serialno: str, from_dump: bool) -> list:
pass

def get_offstore_apps(self, serialno:str, from_dump: bool) -> list:
def get_offstore_apps(self, serialno: str, from_dump: bool) -> list:
return []

def get_app_titles(self, serialno):
Expand Down Expand Up @@ -107,19 +107,19 @@ def app_details(self, serialno, appid) -> tuple[dict, dict]:

info = ddump.info(appid)

config.logging.info('BEGIN APP INFO')
config.logging.info("BEGIN APP INFO")
config.logging.info("info={}".format(info))
config.logging.info('END APP INFO')
config.logging.info("END APP INFO")
# FIXME: sloppy iOS hack but should fix later, just add these to DF
# directly.
if self.device_type == "ios":
# TODO: add extra info about iOS? Like idevicediagnostics
# ioregentry AppleARMPMUCharger or IOPMPowerSource or
# AppleSmartBattery.
d['permissions'] = pd.Series(info.get('permissions',''), dtype=object)
d['title'] = pd.Series(info.get('title',''))
del info['permissions']
d = d.fillna('').to_dict(orient='index').get(0, {})
d["permissions"] = pd.Series(info.get("permissions", ""), dtype=object)
d["title"] = pd.Series(info.get("title", ""))
del info["permissions"]
d = d.fillna("").to_dict(orient="index").get(0, {})
return d, info
except KeyError as ex:
print(">>> Exception:::", ex, file=sys.stderr)
Expand All @@ -137,18 +137,22 @@ def find_spyapps(self, serialno, from_dump=True):
[], columns=["title", "flags", "score", "class_", "html_flags"]
)
r = blocklist.app_title_and_flag(
pd.DataFrame({'appId': installed_apps}),
pd.DataFrame({"appId": installed_apps}),
offstore_apps=self.get_offstore_apps(serialno, from_dump=from_dump),
system_apps=self.get_system_apps(serialno, from_dump=from_dump)
system_apps=self.get_system_apps(serialno, from_dump=from_dump),
)
r["title"] = r.title.fillna("")
if self.device_type == "android":
td = pd.read_sql(
'select appid as appId, title from apps where appid in (?{})'.format(
', ?'*(len(installed_apps)-1)
), self.app_info_conn, params=(installed_apps), index_col='appId')
td.index.rename('appId', inplace=True)
elif self.device_type == 'ios':
"select appid as appId, title from apps where appid in (?{})".format(
", ?" * (len(installed_apps) - 1)
),
self.app_info_conn,
params=(installed_apps),
index_col="appId",
)
td.index.rename("appId", inplace=True)
elif self.device_type == "ios":
td = self.get_app_titles(serialno)

r.set_index("appId", inplace=True)
Expand Down Expand Up @@ -244,11 +248,11 @@ def _get_apps_from_dump(self, serialno):
app_and_codes = self.dump_d.apps()
return [a for a, c in app_and_codes]

def get_apps(self, serialno: str, from_dump: bool=True) -> list:
def get_apps(self, serialno: str, from_dump: bool = True) -> list:
print(f"Getting Android apps: {serialno} from_dump={from_dump}")
hmac_serial = config.hmac_serial(serialno)
if (not from_dump):
installed_apps = self._get_apps_from_device(serialno, '-u')
if not from_dump:
installed_apps = self._get_apps_from_device(serialno, "-u")
if installed_apps:
q = run_command(
"bash scripts/android_scan.sh scan {ser} {hmac_serial}",
Expand All @@ -264,8 +268,8 @@ def get_apps(self, serialno: str, from_dump: bool=True) -> list:
return installed_apps

def get_system_apps(self, serialno, from_dump=False) -> list:
if (not from_dump):
apps = self._get_apps_from_device(serialno, '-s')
if not from_dump:
apps = self._get_apps_from_device(serialno, "-s")
else:
apps = [] # TODO: fix this later, not sure how to get from dump
return apps
Expand Down Expand Up @@ -400,11 +404,11 @@ def app_details(self, serialno, appid) -> tuple[dict, dict]:
axis=1,
)
# print("hf_recent['label']=", hf_recent['label'].tolist())
#print(~hf_recent['timestamp'].str.contains('unknown'))
non_hf_recent.drop('appId', axis=1, inplace=True)
# print(~hf_recent['timestamp'].str.contains('unknown'))
non_hf_recent.drop("appId", axis=1, inplace=True)
print(d)
d['permissions'] = hf_recent['label'].tolist()
d['non_hf_permissions_html'] = non_hf_recent.to_html()
d["permissions"] = hf_recent["label"].tolist()
d["non_hf_permissions_html"] = non_hf_recent.to_html()
print("App info dict:", d)

# hf_recent['label'] = hf_recent['label'].map(str) + " (last used by app: "+\
Expand All @@ -420,21 +424,23 @@ def isrooted(self, serial):
"""
# FIXME: load these from a private database instead. from OWASP,
# https://sushi2k.gitbooks.io/the-owasp-mobile-security-testing-guide/content/0x05j-Testing-Resiliency-Against-Reverse-Engineering.html

root_pkgs_check_str = "\\|".join([
"com.noshufou.android.su",
"com.thirdparty.superuser",
"eu.chainfire.supersu",
"com.koushikdutta.superuser",
"com.zachspong.temprootremovejb",
"com.ramdroid.appquarantine",
])

root_pkgs_check_str = "\\|".join(
[
"com.noshufou.android.su",
"com.thirdparty.superuser",
"eu.chainfire.supersu",
"com.koushikdutta.superuser",
"com.zachspong.temprootremovejb",
"com.ramdroid.appquarantine",
]
)
print(root_pkgs_check_str)
root_checks = {
"su binary": ("command -v su", "0"),
"oem unlock": ("getprop ro.boot.flash.locked", "0"),
"oem unlock": ("getprop ro.boot.flash.locked", "0"),
"frida server": ("ps -A | grep frida", "0"),
"root_pkgs": (f"pm list packages | grep {root_pkgs_check_str}", "0")
"root_pkgs": (f"pm list packages | grep {root_pkgs_check_str}", "0"),
}
for k, v in root_checks.items():
cmd = "{cli} -s {serial} shell '{v[0]}'"
Expand All @@ -444,7 +450,6 @@ def isrooted(self, serial):
return (False, "The device is probably not rooted.")



class IosScan(AppScan):
"""
Run `bash scripts/setup.sh to get libimobiledevice dependencies`
Expand Down Expand Up @@ -508,7 +513,7 @@ def get_apps(self, serialno: str, from_dump: bool) -> list:
print("iOS INFO DUMPED.")
return self.installed_apps

def get_system_apps(self, serialno:str, from_dump: bool) -> list:
def get_system_apps(self, serialno: str, from_dump: bool) -> list:
if self.parse_dump:
return self.parse_dump.system_apps()
else:
Expand Down
Loading

0 comments on commit ce4f36d

Please sign in to comment.