Repository navigation
Development
git clone https://github.com/sam-mg/lu77U-MobileSec.git
cd lu77U-MobileSec
python -m venv .venv && source .venv/bin/activate
pip install -e ".[claude]"
./scripts/install_hooks.sh # commit-msg and pre-push hooks, once per clone
python -m lu77U_MobileSec -V # or: lu77U-MobileSec -V
python -m lu77U_MobileSec and the console script both land in cli.main:main.
Test APKs live in etc/APKs/ (DIVA is the usual target, since it has a wide spread of deliberate flaws). Design notes and diagrams are in etc/Documents/.
The dependency direction is one-way:
cli → web → services → engine (detection, analyzers, dynamic_analysis, report_generator)
↑
ai, config, utils
AnalysisService is the only place the full pipeline is sequenced. Engine modules take a verbose flag and optional progress and is_cancelled callbacks, and never import anything from web/. Keeping that direction is what allowed the terminal UI to be replaced by a web UI without touching the engine.
Five conventions worth preserving:
-
verbose_print(msg, verbose)everywhere, rather than a logger. A sink registered at app startup routes those lines to the right scan's WebSocket using acontextvar, so call sites need no plumbing. Any code running on its own thread must start fromcontextvars.copy_context()or its log lines vanish. -
ScanCancelledis re-raised through every intermediateexcept Exception. Best-effort error handling must not swallow cancellation. - Best-effort enhancements return
Noneand log, rather than raising. The code graph, call graph, checkpointing, dynamic verification and report generation all follow this: a failure degrades the scan instead of failing it. - Nothing in
web/checkpoint.pymay raise into a scan. A bad checkpoint means "start over", never "fail". - Scoring arithmetic lives only in
utils/scoring.py. Three copies once existed and disagreed.
- Subclass
BaseAIProviderinai/. Implementanalyze,list_models,validate_credentials, anddefault_model. Overridesupports_visionif the model accepts images. -
analyzemust return{"response": str}or{"error": str}and must not raise for provider-side failures. - Map the
schemaargument onto the provider's structured-output mechanism. Where the API needs an object at the top level, wrap the array undervulnerabilities, as the OpenAI and Claude providers do. - Register the class in
PROVIDER_CLASSES(ai/provider_factory.py), add the name touser_settings.PROVIDERS, a config block inDEFAULT_SETTINGS, a display name and default model inai/registry.py, and a branch intools_checker/ollama_checker.check_ai_provider_configuredif readiness differs from "has an API key". - Keep credentials out of URLs. Anything in a request URL reappears in httpx exception text, which is logged and returned.
- Subclass
BaseFrameworkDetectorinframework_detector/, implementdetect(input_path)returning{"framework", "confidence", "indicators"}orNone. - Append an instance to the list in
HybridFrameworkDetector.__init__. - For a pure file-signature detector, add entries to
TECH_DETECTION_MAPinconfig/constants.pyinstead; the zip-entry detector picks them up with no new class. - Decide whether the framework gets deep analysis. If it does, see "Adding a framework analyzer" below; if not, it just needs to not be in
analyzers/registry.py, and belongs inAnalysisService.UNSUPPORTED_FRAMEWORKSfor the verbose-log wording.
This is the bigger version of the above: giving a detected-but-currently-unsupported framework the same static-analysis depth the five supported ones already get. Follow the shape they share:
-
Profile. Add a
SourceProfileinanalyzers/agent/profiles.py: the source extensions, noise fragments (vendor/framework paths to filter), generated-file stems, and what file (if any) should stand in as the agent's first-turn orientation context. -
Decompiler/extractor wrapper. A module under
decompiler/followingblutter_runner.py's shape: resolve the tool path fresh fromuser_settingson every call (so a Settings change takes effect without a restart), run it as an argv list (nevershell=True), and judge success by output artifacts rather than return code. -
Settings + readiness. A
<tool>_pathkey inuser_settings.DEFAULT_SETTINGSwith a getter/setter pair, atools_checker/<tool>_checker.pymirroringjadx_checker.py, and a<tool>_configuredentry intools_checker/analysis_checker.get_analysis_status(), but not folded intoready_for_analysisunless the framework should be able to block every other scan on the machine (JADX is the only tool that currently does). Add the field toSettingsUpdate,settings_service.get_settings/update_settings, and the frontend'sAnalysisStatus/Settingstypes plus aPathFieldinSettings.tsx. -
Code graph. A
build_<framework>_graph(source_root, verbose) -> Optional[CodeGraph]function reusing the existingCodeNode/CodeGraphcontainers fromanalyzers/agent/code_graph.pyunmodified; only how nodes get built differs. ReturnNoneon any parse failure or when nothing is recoverable; the agent loop falls back to the flat file tree automatically. -
Analyzer class. Subclass
BaseAnalyzer(analyzers/base.py): implementpreflight()(checks the tool is configured) andanalyze()(decompile/extract, build the graph, callself.run_agent(source_root, code_graph), thenself.enrich_vulnerabilities(vulnerabilities, source_root)). Overrideframework_label,profile, andsource_prefixes()if the model might cite paths under a subdirectory the way JADX'ssources/resourcessplit does. -
Prompt + skill. Add a
<framework>_agent_systemprompt id toconfig/prompts.py(PROMPT_IDS,_AGENT_SYSTEM_BY_PROFILE, labels, help, default text) and a bundled skill file, registered inskills_loader.CORE_SKILLSunder the profile's key. For the prompt'sSCORING SEVERITYblock, call the shared_cvss_scoring(av, scope, cia_and_example)helper rather than writing the six CVSS bullets out again: the AC/PR/UI bullets are identical across every framework prompt and are supplied by the helper itself; only the attack-vector example, scope question, and closing worked example need to be framework-specific. -
Scanners. Add the profile key to
analyzers/sast/runner._BY_PROFILE.manifestandsecretswork for any framework; the rest need decompiled Java. Omitting the key falls back to those two rather than to nothing. -
Register it. One line in
analyzers/registry.py's_REGISTRYmapping the detected framework name(s) to a lazy-import factory for the new class, and remove the name fromAnalysisService.UNSUPPORTED_FRAMEWORKSif it is listed there.
tests/test_registry.py::TestEveryProfileIsFullyWired enforces steps 1 and 6 together: every analyzer's profile key must resolve to a real agent prompt over 500 characters and a core skill whose file exists. It exists because a half-wired framework silently falls back to the Java/Kotlin prompt and looks like it works.
Nothing in AnalysisService, the agent loop, the region fan-out, validation, or code-context enrichment needs to change. That is the point of the shared BaseAnalyzer/SourceProfile machinery. See Static analysis for how the existing frameworks' versions of steps 2-6 work, as worked examples; Xamarin is the most recent and the closest to a template.
- Add the method to
AgentTools(phase 1) orVerifyTools(phase 2). Resolve any path through the existing sandbox helper; do not build paths from model input by hand. - Add the action name to the relevant
NEXT_ACTION_SCHEMAenum and describe its arguments in the schema. - Add a dispatch branch in the loop, plus
_describe_request/_describe_responseentries so the transcript reads sensibly. Decide whether results are cacheable: in phase 2, read-only calls belong in_dedup_key; side-effecting ones must not be cached. A tool that navigates the call graph goes throughAgentTools._method_or_errorso an unresolvable name returns a usable error instead of an exception. - Document the action in every framework's system prompt this loop drives.
config/prompts.pyhelp text warns users not to remove action names from an override, so both must stay in step.
web/checkpoint.py records pipeline stages in order (STAGES = ("decompiled", "sast_done", "agents_done")). To make a new stage resumable:
- Append its name to
STAGES, after the stages it depends on. -
cp.mark("<stage>", **facts)when the stage finishes, with whatever is cheap to store and expensive to recompute. -
cp.reached("<stage>")/cp.get(key)at the top of the stage, to skip it and reuse those facts. - Emit a progress message saying the stage was reused, so the log distinguishes a resumed scan from a fast one.
Per-region agent state is separate (agent-<region>.json), one file per worker, so region threads write with no shared lock. Region keys must stay stable across runs, and partition_graph is deterministic for exactly this reason, down to the node-key tiebreak in _seed_rank.
Drop a markdown file into lu77U_MobileSec/skills/ to bundle it, or upload it with POST /api/settings/skills to install it into <config dir>/skills/ for the current user. Either way it is keyed by filename stem, and a user file shadows a bundled one of the same name. Four ways to have it loaded:
| Route | Where |
|---|---|
| Core skill for a framework | skills_loader.CORE_SKILLS |
| Region guidance for a sink family | An AttackSurface.skills tuple in analyzers/agent/surfaces.py, resolved by guidance_for_families
|
| A keyword rule as the agent works |
_contextual_skills in analyzers/agent/agent_loop.py
|
| Always |
_ALWAYS_LOADED in analyzers/agent/agent_loop.py, and the report turn |
tests/test_skills.py asserts that every bundled skill is reachable by at least one of those and that every name referenced resolves to a real file. Both checks exist because load_skills silently drops names it cannot resolve, so a typo costs the agent its guidance with no error anywhere. Add the new skill's stem to the OWN tuple in that file as well — the content rules (no third-party attribution, no external repository link, no iOS material) are parametrized over OWN, so a skill left out of it ships unchecked.
Write skills rather than importing them. If you take material from another project it needs a source and licence header in the file plus a NOTICE at the repository root. test_skills.py currently asserts that no bundled skill or shipped source carries an attribution, that none points at an external repository, and that no NOTICE exists. Adding one is a deliberate decision that has to update those tests too.
Skills are prompt text, so keep them short and specific. Everything loaded is re-sent on every turn of the loop.
See Web UI for structure and the known build gap. The build output goes to lu77U_MobileSec/web/static, which is what MANIFEST.in ships; the frontend source is pruned from the distribution.
pip install -e ".[dev]"
python -m pytest # the suite on its own
./scripts/preflight.sh # commit messages, the commenting standard, the suite, CodeQL and a clean-install check, i.e. what the push gate runs
tests/ covers the parts where a silent regression would be expensive and the behaviour is checkable without a device or a model. A feature or fix is not finished until something would fail if it regressed, and a new rule or check needs tests for the rule itself.
Repository standard
| File | Covers |
|---|---|
test_comment_style.py |
Each rule of the commenting standard pinned against a crafted file, so a rule that stops firing is caught rather than silently passing everything; plus the shipped package and the checker itself passing, vendored trees being skipped, and the exit codes and JSON output the hook and CI read |
test_commit_message.py |
The commit message format: a subject alone or a subject and single-line - items pass; a wrapped item, a paragraph, a blank line between items, a wrapped subject, a nested item, trailing whitespace, an empty item and an empty message each reported with its line; git's comment lines and the scissors ignored in a message file; a range naming only the broken commit; merge commits and commits GitHub made skipped; the pre-push lines for new, deleted and unknown refs; CONTRIBUTING.md's example passing; and the commit-msg hook, pre-push, preflight and CI each still running the check |
test_codeql_scan.py |
The CodeQL gate following the latest CodeQL release with no version hardcoded, query packs unpinned so they move with the CLI, and Python extracted with the project's own interpreter |
Engine core
| File | Covers |
|---|---|
test_cvss.py |
Base scores against FIRST's published vectors, severity bands, prefix and metric-order tolerance, an unparseable vector meaning "no score" rather than zero, a partial vector completed only when it states an attack vector and an impact, and the parser scoring the completed vector |
test_utils.py |
Verbose-log redaction, URL and truncation helpers, and find_tool finding a tool beside the interpreter when its venv is not on PATH
|
test_metadata.py |
Name, version, description, author and homepage matching pyproject.toml everywhere (including the rendered report HTML and /api/version), that skills/ and rules/ are declared as package data, and that Semgrep and mitmproxy are optional extras rather than dependencies, reported in the readiness status, with an install hint when the HTTPS check finds mitmproxy missing |
test_favicon.py |
The favicon on every page the tool serves or writes: inlined artwork matching the shipped file, both HTML entry points and both report builders referencing it, the built static directory containing what they link to |
test_web_paths.py |
Static-file resolution against traversal and symlinks, scan-id validation, upload filename sanitising |
test_scan_logs.py |
Per-scan log persistence: complete when verbose, and nothing written when not |
Agent engine
| File | Covers |
|---|---|
test_agent_parsing.py |
Thinking-token stripping (including the lone </think> case), balanced-object extraction, report coercion, salvage of malformed findings |
test_agent_loop.py |
Turn budget, the opt-in max_steps cap forcing a final report, cancellation interrupting a never-reporting model, the add_finding accumulator surviving an empty forced report, the coverage note appearing only once compaction has dropped turns, and a failed turn costing a step rather than the region (two tolerated, an unavailable provider never retried) |
test_agent_budget.py |
The step, wall-clock and review-request ceilings, throttle credit back to the deadline, and the stop_reason a region reports when it stops |
test_agent_tools.py |
The phase-1 sandbox, the paged reader and its continuation, search filtering, source inventory |
test_ghidra.py |
The optional Ghidra integration: every install layout resolving to analyzeHeadless, the JNI function-table layout behind the annotations, nothing from the APK reaching the command line, results and failures cached, a timed-out run leaving no JVM behind, JNI entry points first in the paged view, native citation repair |
test_profiles.py |
AgentTools under each SourceProfile: noise filtering, generated-file exclusion, orientation-file resolution; the Java/Kotlin default reproducing pre-refactor behaviour exactly |
test_fanout.py |
Region partitioning and the four threading hazards: per-thread context copies, one progress event per region inside the band, a child ScanCancelled reaching the parent, collision-free provider log paths, a failing region not costing the others |
test_sast_first.py |
SAST running before the agent on Java/Kotlin and its output becoming the per-region worklist: lead construction, ranking, routing and rendering |
test_source_resolution.py |
resolve_source_path against a tree of same-basename twins: refusing rather than guessing, and using the claimed construct to disambiguate |
test_agent_failure_paths.py |
Failure paths across the agent engine: a failing checkpoint or malformed resume state logging rather than losing the region, an androguard class with no access flags surviving the code graph, the shared vendor-prefix/sink-family tables staying identity-equal across modules with no import cycle, a BaseException in a fan-out worker still escaping, and SQL-provenance/vendor-tagging/manifest-read failures degrading to a log line |
Code graphs and decompilers
| File | Covers |
|---|---|
test_apk_payload.py |
Bundle discovery, Hermes magic-byte sniffing, native-library extraction, Cordova assets/www extraction including zip-slip refusal |
test_code_graph_prefetch.py |
analyze_apk_for_code_graph as a separable half, so androguard can run on its own thread while JADX decompiles |
test_code_graph_js_bridge.py |
@JavascriptInterface flagging in the Java/Kotlin graph, without androguard or a real APK |
test_flutter_graph.py |
Per-asm-file nodes, sink/role detection, object-pool secret recovery, None on nothing recoverable |
test_flutter_recovery.py |
Debug-build Dart source read exactly and safely from kernel_blob.bin, Blutter output parsing, app/package/SDK classification, the Dart-to-Java channel map, the framework kept out of the graph, the overview, the analyzer's choice between build modes, and a value cited from pp.txt/objs.txt traced to the app code that loads it (directly, through a const object, or through a pool list; a value the model cut short completed first) |
test_rn_graph.py |
Both JS shapes: module directory (vendor filtering, refs, sinks) and single-file Hermes output (function splitting, safe fallback) |
test_rn_recovery.py |
Splitting a plain Metro bundle, the whitespace-only formatter, the app/framework classification (including the case that once picked the app as the framework), hermes-decomp's extraction, native-module discovery and spec merging, the overview's leads and bound, the module-tree graph, the format-aware preflight, the long-line cap, and imported libraries (WebView, crypto-js) leaving the app region while a re-export the app imports stays |
test_cordova_graph.py |
DOM-XSS/bridge/network sinks, runtime + vendor noise filtering, <script src>/require refs, secrets, entry-page role, None on noise only |
test_xamarin.py |
XALZ LZ4 round-trips including an overlapping match, AssemblyStore parsing and its refusal of implausible headers, MAUI's blob-disguised-as-.so, UTF-16 string mining, the C# graph |
test_external_runners.py |
The Blutter/hermes-decomp/react-native-decompiler wrappers: exact argv, artifact-based success, every failure mode returning None rather than raising |
test_native_loading.py |
Tying a bundled native library to the app code that loads it: the arm64-v8a copy preferred, System.loadLibrary and dart:ffi literals, libraries and runtimes ignored, the overview section |
test_file_review.py |
The file review after the agents: which files are reviewed and in what order (lead files, entry points, the rest; plugin Java and native-library paths handled), native libraries first with the native skill, numbering, the Blutter digest (literals, calls, const objects and lists, integer arrays and their shift or XOR decodings, XOR, closures, returns and handlers), packing and splitting, provenance tags and citation pinning, manifest citations counting as read, failures, the request budget, cancellation, and the base analyzer adding the pass's findings without losing the agent's |
test_ollama_models.py |
The Ollama model chooser: the live cloud catalogue fetched without a credential, the capability filter, pulled models leading under their cloud names and retired ones dropped, an unreachable catalogue giving an empty list, the default being a name the cloud API accepts, and a fresh install with no settings file actually landing on that default |
test_registry.py |
Framework name → analyzer dispatch, the shared BaseAnalyzer contract across all five, preflight() degrading cleanly, and that every profile is fully wired to a prompt and a core skill |
Scanners, validation and chains
| File | Covers |
|---|---|
test_sast_extractors.py |
Every deterministic scanner against real files: manifest tri-state export rules, the WebView taint and SQL regexes that once failed silently, secret classification and downgrades, SDK fingerprinting, bundled libraries and framework embeddings skipped by tls and injection, the tool's own overviews skipped by secrets, the crypto-misuse, platform-misuse and OAuth rules each firing on the risky shape and quiet when its guard is present (including the Flutter loader and deep-copy shapes real apps tripped), test-only builds and broad FileProvider paths, the launcher-only and browsable deep-link activities, plugin-code findings capped at Low, credentials written to preferences, SQLite, temp files and external storage, input compared against a hardcoded secret, a typed URL loaded into a WebView, the FLAG_SECURE note, the React Native and Dart script rules (whole-word sensitive names, storage, logging, SQL, keys, cleartext, dynamic code, WebView settings, hash checks, pinning and fail-open pinning), one scanner raising costing only its own findings; user-CA trust filed as NETWORK-05, a Bundle or a null value not counted as stored preferences, a private network address as a note, text-field input into a SQL write graded Low while a read stays High, and command execution and class loading graded by their input (constant commands skipped, a runtime command a lead until external input appears, class loading with a signature or digest check a lead); an empty key array the file fills (nextBytes, a stream read, a copy, an element write) not reported as a constant key; custom permissions graded by level (normal Medium, dangerous Low); a component guarded by a permission nobody declares reported as unguarded; SQL judged by its riskiest operand, constants-only statements skipped, a selection clause read when it opens with a column name, and a method parameter traced to its callers |
test_patterns.py |
The shared secret/endpoint table: specific-before-generic ordering, per-pattern severity, the endpoint classifier |
test_validation.py |
The gates, the weak-class table against the titles the extractors actually emit, a JavaScript-bridge claim supported by each framework's bridge API (Java, React Native, Flutter), the review pass carrying the attacker-model, mitigation and specific-fact rules, that nothing is ever removed, that the judge can only weaken a finding and cannot collapse a standalone class with CHAIN_REQUIRED, the class ceilings matching the skill table, the cleartext request and development-host gates, provider key shapes, source-file names not counting as API claims, the local-authorization class hints, the hardcoded-check/secret merge and storage-API subjects in dedupe, chain matching and confirmation, and the HTML/JSON rendering of both; user-CA trust held as a chain step and a model's NETWORK-01 for it re-filed, the SQL cap leaving storage findings alone, a written data file's name not counting as an API claim, and the location pass across the rule engine, the agents and the file review (one secret seen as a key, a secret and its seeded row on a shared literal, one preferences save cited at two writes, a component and its intent action, an Intent-extra gate filed two ways on one line, while two different secrets and two different classes stay apart); a cached verdict reused only for the same APK; a title cut at an ellipsis read without its cut word; a scanner finding surviving its fact_key group; a merged finding keeping its strongest device verdict; the protected-broadcast, clipboard-literal and explicit-PendingIntent gates; and the review rules on receivers, signature guards, mutable PendingIntents and File(dir, name)
|
test_evidence_hop.py |
The claim vocabulary one step from a citation: the enclosing method, called helpers resolved by package or nested class, a declared field's uses, a cited resource value's readers; statements not taken for definitions; the claim gate accepting what the reached code supports and still refuting what it does not |
test_chain_determinism.py |
Deterministic chain pairings, candidate ranking by severity, and rejection logging; user-CA trust never pairing with missing pinning as a TLS bypass |
test_chain_annotation.py |
Cross-referencing findings with no model: chain-table pairings kept as related_findings, same-file grouping, and never as a severity claim |
test_skills.py |
Every bundled skill resolving, being reachable by at least one route, the signals that load the OAuth, deep-link, deep-link endpoint, business-logic, storage/crypto and IPC skills, the deep-link surface preloading the endpoint method, carrying no third-party attribution, external repository link or iOS material, no NOTICE file being needed, and the chain table using no code the catalogue does not define |
Providers and reporting
| File | Covers |
|---|---|
test_provider_resilience.py |
What a scan does when the provider stops answering: error classification, the circuit opening once, and no repeated rediscovery of a dead quota |
test_provider_limits.py |
num_predict bounding runaway generation, a truncated reply retried with the cap doubled up to the ceiling, thinking-token accounting, and the concurrency gate, and the thinking allowance added to a caller's cap |
test_cli_provider.py |
The subscription-CLI providers: the prompt on standard input, array schemas wrapped and unwrapped, error classification and the circuit, one call in flight |
test_custom_provider_schema.py |
Structured output on the OpenAI-compatible provider and its one-time downgrade for endpoints that lack it |
test_quota_resume.py |
Pausing on a provider outage and continuing afterwards: the continuable flag, continuing with more turns and the earlier findings kept, a finished region replayed for free, the shared definition of an exhausted quota; a region resumed with steps spent keeping its place when the host is down, which failures mean an unreachable host, an unreachable provider counted as an outage with quota taking precedence, and the provider's marker clearing on the next success |
test_credentials_pool.py |
Multiple keys per provider: storage, rotation on a fatal error, index removal, reveal, and key labels (stored with their key, an unlabelled pool kept in the old format, older entries read with no label, a stored key labelled by re-adding it or by position, labels surviving a removal, normalising and refusing unsafe labels, and the label endpoints), none of it touching the real keychain |
test_report_integrity.py |
Report fields that were silently wrong: pass-through and arithmetic checks over the exporter and serializer, the limitation reaching the dashboard's view, and the downloaded report's notices (coverage read from the analyzer details, reduced coverage, a failed analysis named instead of "nothing found", an unconfigured decompiler named instead of "under development") |
test_job_ownership.py |
A queued scan recording its owner before it runs, another live server's queued scan left alone at startup, an abandoned queued scan made resumable, an abandoned running scan with no checkpoint still failed, a scan whose status changed while it waited not run, and an earlier error cleared when a scan starts, and a scan whose provider was unreachable paused for a short retry and picked up by auto-resume |
test_demo_data.py |
The static demo's settings snapshot carrying every field the live endpoint returns, configured tools having paths, and the model the published scans ran on; the published Ghera scans being the scored ones, named by their repository path, each vulnerable app beside its fixed one, published uncurated, and listed after the showcase apps |
test_ghera_benchmark.py |
scripts/ghera_benchmark.py: the answer key covering the 60 lean benchmarks with real classes and working patterns, a candidate needing both its class and its wording, a review overriding the match only with a reason, and a resumed run adopting scans in flight |
test_demo_accuracy.py |
The wording, citations and reasons a reader sees on a finding, each case a published one: device evidence split per finding, report-style titles and their fallback (no dangling pronoun, no scanner title long enough to be cut), cap notes only where a cap lowered something, inventory notes not told their claim cannot be checked, an annotation the finding is about being a valid citation, a comparison against a literal re-filed from CRYPTO-02 to AUTH-04, the backup chain over plaintext credentials, and manifest findings placed on their lines (the backup note on the application element, the minSdkVersion note on minSdkVersion) and worded for the declared target; titles lowered from Title Case, scanner findings carrying their class's labels, exported components under M8, the app's own framework left out of the SDK inventory, repeated scanner titles naming what differs, a full private address, a bare offset named as a hook point; device verdicts only for evidence that names a device action, and an early stop quoting the tool's error |
test_review_pass.py |
The review, title and chain passes once their answers are read: fenced and id-keyed answers parsed, model text kept whole up to the field bound, the review floor (a downgrade it stops leaves the verdict and says why; a downgrade never reaches Informational), "could not be confirmed" not added to Informational notes, batch ids and renamed titles in reasons, the Blutter disassembly note, a chain never weak-classed, chains folded per entry with their references repointed, the AUTH-03/AUTH-04 pair merging from one pass, and numbered-list device evidence split by the findings each item names |
test_dart_snapshot.py |
The fallback for a Flutter build Blutter cannot disassemble: libapp.so strings extracted and filtered (framework names, curve constants and package URIs out; endpoints, SQL, channels, digests and sensitive words in), the slice chosen, the analyzer continuing for an x86_64-only APK and a Blutter failure with a stated limitation while a missing Blutter or a missing libapp.so still fail, and the graph and overview built over the strings |
test_metadata_parity.py |
Agent and SAST findings carrying the same metadata (a CWE on both, a CVSS vector on both), so no consumer filter silently loses half the scan |
test_parsing_and_detection_fixes.py |
Parser and detector defects that lost or mislabelled information with no exception and no log line |
test_analysis_service.py |
Phase 2 orchestration: runtime findings merging, the session running without static findings, progress remapping, failures degrading rather than raising, the package name passed to every install; and a failed analysis logged with its reason while a limitation reaches the stored analyzer results |
test_adb_manager.py |
Installing the APK under test: an identical installed build (same version and SHA-256) reused, anything else installed (missing, other version, rebuilt APK, split install, unprovable hash, unusable path), the package-verifier retry, verification disabled only for that retry and the prior settings always restored; an APK built for none of the device's ABIs refused with that reason before any install |
test_verify_tools.py |
The phase-2 adb allowlist: prefix stripping, package scoping, traversal and unknown-verb refusals; && chains run in order with each part checked, pipes and redirection refused; content reaching only the app's own providers; on a root adb shell, am and content sent as uid 2000; a UI dump listing only the app's own elements with their tap points; a Frida action's trigger held to the same allowlist and run between the script's load and unload |
test_verifier_triage.py |
The device triage answer read under the schema's key, under another name when it is the only list, and every finding verified when neither; a finding limited to an older Android set aside on a newer device; the agent shown the device's version and the most severe findings first; configuration findings never taking device steps; a refutation recorded with its evidence, graded Informational and shown in the report; the proof review setting aside a rejected proof with its reason, keeping every verdict when its answer cannot be read, and reading an echoed label in any form (P0, [P0], 0) |
test_dynamic_session.py |
A working HTTPS interception check recorded as an environment result, not as a finding about the app; the UI explorer stopping its uiautomator2 server when it is done, so a later UI dump is not blocked |
test_provider_config_paths.py |
Provider and config edge cases: Ollama with no retries configured returning an error instead of hanging, a keychain delete failure warning while a PasswordDeleteError stays silent, the one-time fallback warning printing once, a configured output directory being used and an empty one falling back to the default, and a custom endpoint's model listing falling back to the configured model on failure |
test_web_dynamic_failure_paths.py |
Web server and dynamic-analysis failure paths: killing an orphaned mitmdump process, the firewall helper script's permissions, a failed startup reconciliation or checkpoint write logging rather than being lost, one failing dashboard log subscriber not costing the others, a failed frida-server stop surfacing in both the log and the result, and KeyboardInterrupt/SystemExit in the analysis thread re-raising instead of being recorded as an ordinary error |
test_detector_and_report_fixes.py |
The comprehensive PDF generator failing to import raising a clear error instead of crashing in its own fallback, a multi-DEX app's class list no longer duplicated once per DEX file, Kony and Unity directory detection actually finding a project, and every public name validation.taxonomy exports staying importable |
test_cordova_dvhma.py, test_flutter_dvfa.py
|
End-to-end against real vulnerable-app APKs (below). Both skip when the APK isn't present |
Device work, provider calls, keychain access, and JADX/Blutter/hermes-decomp/react-native-decompiler/ilspycmd/Ghidra are all stubbed; nothing in the suite touches the network, a device, an external tool binary, a live quota, the OS keychain, or the user's settings file. Anything involving a real device, model, or external tool still needs a manual scan:
lu77U-MobileSec -V # scan etc/APKs/DIVA.apk and read the verbose log
test_cordova_dvhma.py and test_flutter_dvfa.py run against real deliberately-vulnerable apps cloned under etc/vulnerable-apps/ (gitignored, so present locally but not in CI; the tests skip when the APK is absent). tests/fixtures.py locates them.
-
Cordova, DVHMA (logicalhacking/DVHMA): ships prebuilt Cordova APKs under
releases/; used directly, no build. -
Flutter, DVFA (Schmiemandev/dvfa): a release APK is downloaded from the repo's GitHub Releases to
flutter-dvfa-schmieman/build/app/outputs/flutter-apk/app-release.apk. Building from source instead needs the Flutter SDK, JDK 21 (Gradle does not run on JDK 26), and a valid Android NDK, thenflutter build apk --release. The AOTlibapp.soBlutter needs exists only in a release/profile build, never a debug one.
Two lab apps written for this project live beside the third-party fixtures under etc/vulnerable-apps/ (gitignored), each one release APK with an ANSWER_KEY.md the scanner never sees:
-
lu77u-flutter-lab/- PocketVault, Flutter 3.38.7 (Dart 3.10.7), arm64-v8a. 18 issues combining DVFA, the brnpl Flutter reverse-engineering labs and dvfa-sebsnyk, plus adart:ffiC library with a stack overflow and a hardcoded key. -
lu77u-rn-lab/- StreamBox, React Native 0.81.6 (Hermes 96), arm64-v8a. 15 issues combining all five DVRN issues with React Native versions of the labs, plus a JNI C library reachable from the WebView bridge.
Rescan them after a pipeline change and score the result against the answer key. Their values must never be copied into a skill or prompt. They are benchmarks only and are not in the UI demo, which shows only apps a reader can download. Building them needs a JDK 17-21 for Gradle (Android Studio's bundled JDK 25 is too new for Gradle 8.14) and, for the Flutter one, a Flutter SDK whose Dart version Blutter has been built for.
Every model call in a scan is nondeterministic, so two scans of one of these apps with the same model will not match word for word; score the findings against the answer key rather than diffing reports. See Troubleshooting.
flutter-re-labs-brnpl-all/ builds all nine levels of brnpl's Flutter Reverse Engineering Labs into one release APK (releases/all-release.apk), so one scan covers the whole lab; this one is in the demo. Each level's upstream main.dart is copied unchanged as lib/chall<N>.dart and imported under a prefix, a launcher opens each level's HomePage (chall7's entry runs its integrity check first, as its own main() did), and the upstream chall7 MainActivity carries chall5's RootBeer root-check channel too. Its README lists the differences from the separate upstream APKs; one is that root_jailbreak_sniffer pins NDK 29, so the root Gradle file builds it with the installed NDK 28.2 instead.
scripts/ghera_benchmark.py scans Ghera's 60 lean benchmarks through a running dashboard and scores the scans against scripts/ghera_answer_key.json; Benchmarks has the latest results, how they are scored and the commands to rerun them. After a change that could move detection, rerun it and publish only the new results: score rewrites scripts/ghera_results.json, and build_demo_data.py replaces the demo's Ghera scans with the ones that file names. Like the lab apps' answer keys, the Ghera key is for scoring only and must never be copied into a skill, a prompt or a scanner rule. A miss is fixed by a rule that holds for any app, checked against the benchmark's fixed app, which must stay clean.
.github/workflows/python-publish.yml runs on a published GitHub release: it builds an sdist and wheel with python -m build, checks them with twine check, and publishes to PyPI through trusted publishing (id-token: write, environment pypi). No manual upload step.
Before tagging:
- Bump
versioninpyproject.toml. That is the only place to edit; see Project identity. - Run
./scripts/preflight.sh: the same five checks the push gate and CI run. - Rebuild the frontend with
./scripts/build_frontend.shif the UI changed, and commitweb/static/, since that is what ships. The script also syncspackage.json's version frompyproject.toml.
Name, version, description, author and homepage live in pyproject.toml and nowhere else. _metadata.py resolves them once at import:
- From the checkout's
pyproject.tomlwhen one sits directly above the package. An editable install's recorded metadata goes stale the moment the version is bumped, so the file on disk wins. - Otherwise from the installed distribution's metadata, which is the only source available inside a wheel. The distribution is located through
packages_distributions()rather than by naming it, so even the lookup carries no literal.
Everything downstream imports from there:
| Consumer | Uses |
|---|---|
lu77U_MobileSec.__version__, __title__, __author__, __email__
|
All five values |
config/settings.py (APP_NAME, APP_VERSION, …, SOCIAL_LINKS) |
All five values |
config/paths.py |
Name, for the config, cache and default output directories |
config/credentials.py |
Name, as the keyring service |
web/store.py |
Name, as the scan-folder prefix |
web/app.py, web/server.py, web/routes/system.py
|
Name and version |
cli/parser.py |
Name, version, and the description as the first line of -h
|
dynamic_analysis/frida_manager.py, mitmproxy_manager.py
|
Name, for the cache directory, User-Agent and firewall prompt |
report_generator/*, utils/output_manager.py
|
Name, version and homepage in report titles, footers, page furniture and filenames |
frontend/vite.config.js |
Reads pyproject.toml at build time and injects __APP_NAME__, __APP_VERSION__, __APP_HOMEPAGE__, plus %APP_NAME% in index.html
|
The rest of [project] describes the package to an index and an installer:
-
Description: one sentence on what the tool is, shown by
-hand in the JSON export; no trailing period, since-hadds one. -
Classifiers:
Development Status :: 4 - Betawhile the version is 0.x and the result format and grading still change between releases;Environment :: Web EnvironmentandFramework :: FastAPI, since the tool is a local web dashboard started from a command rather than a console program; Python 3.12 to 3.14; macOS, Linux and Windows. -
URLs:
Homepage(the one the code and the reports use),Documentation(this wiki),Repository,Issues,Demo(the UI demo) andFunding. -
License: an SPDX expression with
license-files, which needs setuptools 77 or later, hencerequires = ["setuptools>=77"]. -
Data files:
[tool.setuptools.package-data]andMANIFEST.inboth list the skills, the semgrep rules, the Ghidra export script and the built dashboard, so a wheel and an install from the source archive ship the same files.
Renaming the project or changing its URL is therefore a one-line edit. Note that the name is also the keyring service and the config-directory name, so a rename orphans previously stored keys and settings.
tests/test_metadata.py asserts each of those consumers still matches pyproject.toml, including the rendered HTML report.
Every .py file in lu77U_MobileSec/, tests/ and scripts/ follows one commenting standard, and it is enforced mechanically rather than in review. CONTRIBUTING.md is the contributor-facing statement of it and CLAUDE.md is the same rules written for AI assistants; both are authoritative, this section is the summary.
- Line 1 is exactly
#!/usr/bin/env python3, and the module docstring is the next statement on line 2. -
Zero
#comments past line 1 — not# noqa, not# pragma: no cover, not a banner. Everything goes in a triple-double-quoted docstring; the single-quoted form is rejected. - Every module, class, function and method is documented, including nested functions and ones defined under an
ifor atry. - Docstrings are sectioned from a fixed vocabulary (
Purpose,Parameters,Returns,Raises,Side effects,Security considerations,Implementation notes, and the rest). APurpose:is always required; anything returning or yielding a value needsReturns:. -
One line per section. A section body is a single line however long it runs — not hard-wrapped, not split into paragraphs. The exceptions are
Parameters:/Raises:/Attributes:, which take one entry per line, andUsage:/Examples:, which keep their line breaks because they hold runnable commands. - Every parameter is documented and nothing that is not a parameter. The
self/clsexemption is narrow: the leading positional argument only, on a method defined directly in a class body only, and never on a@staticmethod. A parameter that merely happens to be namedcls— which parametrized tests over analyzer classes have — still needs documenting. - Files end with exactly one newline terminator. No trailing blank line, and do not strip the terminator either.
- Never put a credential in a docstring, and never leave a second bare string literal under one: only the first is the docstring, so a second renders as a duplicated block that no other rule looks at.
Comments still explain why, not what. Several non-obvious decisions (daemon threads, the Frida 16.x pin, tail-truncating the transcript, the lone </think> case) are documented at the site that depends on them; keep that habit when changing them. Module and class docstrings carry the design rationale, and this wiki summarizes it rather than replacing it.
A docstring describing parameters a function does not have is worse than no docstring, and the checker rejects it.
Commit messages are a one-line subject and, when more is needed, a blank line and a flat list with one - item per line. An item is a single line however long it runs: never hard-wrapped, and never a paragraph or any other block. scripts/check_commit_message.py enforces it: the commit-msg hook refuses a bad message at commit time, and the push gate and CI check every commit a push sends. Merge commits are skipped, since git writes their message, and so are commits GitHub itself made (web edits, merges on github.com), which exist on the remote before anything could refuse them. This wiki has no hooks of its own, so its commits are checked by hand before a push: python ../scripts/check_commit_message.py --range origin/master..HEAD from wiki/.
Contributions: fork, branch, run ./scripts/preflight.sh, open a pull request. Issues and security reports both go to the GitHub issue tracker.
Five checks run before a push is allowed, and all five must pass:
python scripts/check_commit_message.py --unpushed # the commit message format, for every commit not yet pushed
python scripts/check_comment_style.py # the commenting standard, over 250 files
python -m pytest # the whole suite
./scripts/codeql_scan.sh # CodeQL, every finding-producing suite, zero tolerance
./scripts/verify_install.sh # a fresh venv, pip install -e ., -v and -V both actually work
./scripts/preflight.sh # runs all five
scripts/check_comment_style.py is stdlib-only and self-hosting — it satisfies the standard it enforces, which a test asserts. It reports one violation per rule with a file, a symbol and a rule name; --json gives a machine-readable form for editor integration.
scripts/codeql_scan.sh keeps its CodeQL CLI at the latest release (each run checks GitHub's latest release and installs it when the cached CLI is older, so a local run and CI, which installs fresh, run the same queries), extracts Python with the project's interpreter (the active virtualenv, else .venv) because a different python3 on PATH once hid an unused import that CI reported, builds a fresh CodeQL database for Python, JavaScript and the GitHub Actions workflows from a clean copy of the tracked (and untracked-but-not-gitignored) tree, then runs security-and-quality, security-experimental and code-quality-extended for the two code languages and actions-all for the workflows — every suite CodeQL ships that produces actual findings rather than metrics or model-generator output, which is why the LGTM-family suites are deliberately left out (see the script's own header for exactly why). Any result fails the gate. The CodeQL CLI and its query packs are close to 2GB, so the script installs its own copy on first run into ~/.codeql-lu77u and CodeQL's default pack cache ~/.codeql/packages, both outside the repo and both persisted across runs; CI caches the same two paths with actions/cache so it isn't redownloaded on every job. There is deliberately no suppression mechanism — CodeQL's usual inline lgtm[rule-id] comment would itself be a # comment, which rule 3 bans, so a finding is fixed or the code is restructured, and nothing is ever dropped from the suites, even where its stock form cannot be satisfied by application code. js/untrusted-data-to-external-api-more-sources is the one case here: its own documentation calls it a manual-audit query with no code-level sanitizer, and direct testing against this repo's real validation (a TypeScript type guard on a fetched array, extracting only primitive fields into a new object, a JSON round trip) confirmed none of it clears the taint, because the query's Sanitizer extension point has zero implementations in the shipped library. The documentation's own recommended fix is to extend its safe-API classes rather than sanitize application code, so scripts/codeql/lu77u-js-models/ is a small local query pack that does exactly that: a real, narrow model addition marking exactly the two packages this codebase's fetch-into-hook pattern hits (react, react-router-dom) as not being external security boundaries for this concern, since fetch() is the actual external call and is already covered as a source everywhere else. scripts/codeql/javascript-suite.qls runs that re-modelled copy under the exact same rule id in place of the stock one, so the check still runs against every file and would still catch a real external-API sink — a database driver, a shell, a raw HTTP client — and so do its heuristic siblings, which real validation in this codebase already satisfies unmodified.
scripts/verify_install.sh is the slowest gate by a wide margin, because it deliberately reuses nothing: a brand-new venv, pip install -e . from cold pulling every dependency straight from PyPI, then the two flags a first-time user would try. -v/--version has to print the exact version pyproject.toml declares, catching packaging metadata that drifted from the source of truth. -V/--verbose starts the real web dashboard and — unlike almost every other CLI's -v — never exits on its own, since -v is version and -V is verbose here, a deliberate, documented inversion of the usual Unix convention (see cli/parser.py); the script starts it with the real, undocumented --port/--no-browser flags meant for exactly this kind of embedding, watches for a clean startup with no traceback, then stops it. The dashboard is started with HOME pointed at a throwaway directory, because the settings location and the default output folder both derive from it, and a server started against the real ones reconciles the real scan folder at startup.
Enable the hook once per clone:
./scripts/install_hooks.sh # sets core.hooksPath to .githooks, enabling commit-msg and pre-push
The hooks live at .githooks/pre-push and .githooks/commit-msg and are versioned rather than kept in .git/hooks, so one config setting points every clone at them. git push --no-verify bypasses them, which is exactly why .github/workflows/ci.yml runs the identical five scripts — a bypassed push fails there instead.
Two rules of engagement when a check fails:
- Never weaken a rule or a test to make it pass. Fix the code.
- When the checker and the code disagree, work out which is actually wrong before changing either. The checker has been wrong before: it once exempted every argument named
clsrather than only a method's receiver, which reported correct docstrings as documenting a non-parameter.
lu77U-MobileSec · Live demo · Benchmarks · Report an issue · Documents version 0.1.5
Start
Results
How a scan works
Reference
Help and contributing