-
Notifications
You must be signed in to change notification settings - Fork 634
GSoC - add Frida dynamic analysis for Android #2712
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
xukunzh
wants to merge
61
commits into
mandiant:frida-gsoc
Choose a base branch
from
xukunzh:master
base: frida-gsoc
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
61 commits
Select commit
Hold shift + click to select a range
cc06df8
add basic Android dynamic extractor framework
xukunzh 5415459
Add Frida log to capa analysis workflow
xukunzh 8ed3cd1
Implement basic Frida JSONL output and parser
xukunzh afe17ed
Merge pull request #2 from xukunzh/FridaExtractor
xukunzh 3c3fce1
Implement basic Frida JSONL output and parser
xukunzh 31fad02
Revert "Implement basic Frida JSONL output and parser"
xukunzh fda4892
Add FROMAT_ANDROID
xukunzh c843822
Merge Mike's commit suggestion
xukunzh b03c7bd
Merge Mike's commit suggestion
xukunzh 53d75ff
Integrate FridaExtractor into Capa
xukunzh 4c681df
Use Pydantic models to validate these JSON blobs
xukunzh 7886446
Add arguments handling
xukunzh 28d28f9
Change to FORMAT_APK in common.py
xukunzh 24fe942
Change to FORMAT_APK in extractor.py
xukunzh 3c1bae7
Fix a AttributeError bug
xukunzh 20839a0
Merge pull request #3 from xukunzh/FridaExtractor
xukunzh a1b8b11
Squash fix commits into one
xukunzh 191bf03
Merge branch 'master' into FridaExtractor
xukunzh c28d1e2
Update the value type in Argument model
xukunzh 25bd5c0
Merge pull request #4 from xukunzh/FridaExtractor
xukunzh 25696a9
Auto-generate Frida hooks from Capa rules
xukunzh 98391f3
Switch to use APIs JSON file
xukunzh 1da2435
Merge pull request #5 from xukunzh/FridaExtractor
xukunzh 63304d2
add Java native & static method support and update model with Pydantic
xukunzh 4a015df
Update scripts/frida/hook_builder.py
xukunzh 14a60a2
Merge pull request #6 from xukunzh/FridaExtractor
xukunzh 0752417
Add native API hooking support
xukunzh 601037c
Merge branch 'master' into FridaExtractor
xukunzh 5aeb03f
Add missing changes from last PR
xukunzh 346b0e3
Apply pre-commit formatting to existing code
xukunzh 2cba84f
Merge pull request #7 from xukunzh/FridaExtractor
xukunzh fd859d4
Add complete script generation and reorganize templates folder
xukunzh 79e72b2
Add changes from last PR's comments
xukunzh 9e32651
Update README setup and workflow
xukunzh 9f69908
Remove files from git tracking
xukunzh d22af94
Add back SELinux disable step
xukunzh 41035b2
Fix typo
xukunzh 8a3dab7
Merge pull request #8 from xukunzh/FridaExtractor
xukunzh 69e2179
Add APK hashes support to Frida extractor
xukunzh 14a2ab1
Require all fields in models
xukunzh f509479
Changed to get package_name from input
xukunzh 94cf914
Automate Frida analysis workflow with frida-compile
xukunzh e88b4f7
Change to generate .ts script for now in manual workflow
xukunzh a5e144f
Update error handling
xukunzh 69286a9
Fix a format issue with pre-commit and update gitignore
xukunzh b70d798
Delete previous JS main templete
xukunzh e4ff271
Add APK installation process
xukunzh 0211407
Add auto emulator creation
xukunzh 4e0f64c
Fix create_emulator
xukunzh d6438ab
Fix directory creation issue
xukunzh 47a4dae
Fix root access detection issue
xukunzh edbf385
Merge pull request #9 from xukunzh/FridaExtractor
xukunzh 3b4ac24
Change to exception raising and Replace print with logging
xukunzh 0edbdc2
Update frida_api.json with lastest API list
xukunzh 5db7cf6
Simplify and fix emulator setup details in setup.md
xukunzh 09915d3
Make package name optional and add aapt APK extraction
xukunzh 6bd19e5
Reorganize README and setup.md
xukunzh a38c397
Keep only automated setup in README
xukunzh cc40e39
Update capa and dependencies installation instructions
xukunzh 4de0aa7
Update CHANGELOG
xukunzh ac50435
Merge branch 'frida-gsoc' into master
xukunzh File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,141 @@ | ||
| from typing import Union, Iterator | ||
| from pathlib import Path | ||
|
|
||
| from capa.features.insn import API, Number | ||
| from capa.features.common import ( | ||
| OS, | ||
| ARCH_ARM, | ||
| ARCH_I386, | ||
| ARCH_AMD64, | ||
| FORMAT_APK, | ||
| OS_ANDROID, | ||
| ARCH_AARCH64, | ||
| Arch, | ||
| Format, | ||
| String, | ||
| Feature, | ||
| ) | ||
| from capa.features.address import NO_ADDRESS, Address, ThreadAddress, ProcessAddress, DynamicCallAddress, _NoAddress | ||
| from capa.features.extractors.frida.models import Call, FridaReport | ||
| from capa.features.extractors.base_extractor import ( | ||
| CallHandle, | ||
| SampleHashes, | ||
| ThreadHandle, | ||
| ProcessHandle, | ||
| DynamicFeatureExtractor, | ||
| ) | ||
|
|
||
|
|
||
| class FridaExtractor(DynamicFeatureExtractor): | ||
| """ | ||
| Frida dynamic analysis feature extractor for Android applications. | ||
|
|
||
| Processes JSON output from Frida instrumentation to extract behavioral features. | ||
| """ | ||
|
|
||
| def __init__(self, report: FridaReport): | ||
| super().__init__( | ||
| hashes=SampleHashes( | ||
| md5=report.hashes.md5.lower(), | ||
| sha1=report.hashes.sha1.lower(), | ||
| sha256=report.hashes.sha256.lower(), | ||
| ) | ||
| ) | ||
| self.report: FridaReport = report | ||
|
|
||
| def get_base_address(self) -> Union[_NoAddress, None]: | ||
| return NO_ADDRESS | ||
|
|
||
| def extract_global_features(self) -> Iterator[tuple[Feature, Address]]: | ||
| """Basic global features""" | ||
| yield OS(OS_ANDROID), NO_ADDRESS | ||
|
|
||
| if self.report.processes: | ||
| process = self.report.processes[0] | ||
|
|
||
| if process.arch: | ||
| arch_mapping = {"arm64": ARCH_AARCH64, "arm": ARCH_ARM, "x64": ARCH_AMD64, "ia32": ARCH_I386} | ||
| capa_arch = arch_mapping.get(process.arch, process.arch) | ||
| yield Arch(capa_arch), NO_ADDRESS | ||
|
|
||
| yield Format(FORMAT_APK), NO_ADDRESS | ||
|
|
||
| def extract_file_features(self) -> Iterator[tuple[Feature, Address]]: | ||
| """Basic file features""" | ||
| yield String(self.report.package_name), NO_ADDRESS | ||
|
|
||
| def get_processes(self) -> Iterator[ProcessHandle]: | ||
| """Get all processes from the report""" | ||
| for process in self.report.processes: | ||
| addr = ProcessAddress(pid=process.pid, ppid=0) | ||
| yield ProcessHandle(address=addr, inner=process) | ||
|
|
||
| def extract_process_features(self, ph: ProcessHandle) -> Iterator[tuple[Feature, Address]]: | ||
| # TODO: we have not identified process-specific features for Frida yet | ||
| yield from [] | ||
|
|
||
| def get_process_name(self, ph: ProcessHandle) -> str: | ||
| return ph.inner.package_name | ||
|
|
||
| def get_threads(self, ph: ProcessHandle) -> Iterator[ThreadHandle]: | ||
| """Get all threads by grouping calls by thread_id""" | ||
| thread_ids = set() | ||
| for call in ph.inner.calls: | ||
| thread_ids.add(call.thread_id) | ||
|
|
||
| for tid in thread_ids: | ||
| addr = ThreadAddress(process=ph.address, tid=tid) | ||
| yield ThreadHandle(address=addr, inner={"tid": tid}) | ||
|
|
||
| def extract_thread_features(self, ph: ProcessHandle, th: ThreadHandle) -> Iterator[tuple[Feature, Address]]: | ||
| # TODO: we have not identified thread-specific features for Frida yet | ||
| yield from [] | ||
|
|
||
| def get_calls(self, ph: ProcessHandle, th: ThreadHandle) -> Iterator[CallHandle]: | ||
| """Get all API calls in a specific thread""" | ||
| for call in ph.inner.calls: | ||
| if call.thread_id == th.address.tid: | ||
| addr = DynamicCallAddress(thread=th.address, id=call.call_id) | ||
| yield CallHandle(address=addr, inner=call) | ||
|
|
||
| def extract_call_features( | ||
| self, ph: ProcessHandle, th: ThreadHandle, ch: CallHandle | ||
| ) -> Iterator[tuple[Feature, Address]]: | ||
| """Extract features from individual API calls""" | ||
| call: Call = ch.inner | ||
|
|
||
| yield API(call.api_name), ch.address | ||
|
|
||
| if call.arguments: | ||
| for arg_obj in call.arguments: | ||
| arg_value = arg_obj.value | ||
| if isinstance(arg_value, (int, float, bool)): | ||
| yield Number(arg_value), ch.address | ||
| elif isinstance(arg_value, str): | ||
| yield String(arg_value), ch.address | ||
|
|
||
| def get_call_name(self, ph: ProcessHandle, th: ThreadHandle, ch: CallHandle) -> str: | ||
| """Format API call name and parameters""" | ||
| call: Call = ch.inner | ||
|
|
||
| parts = [] | ||
| parts.append(call.api_name) | ||
| parts.append("(") | ||
|
|
||
| if call.arguments: | ||
| args_display = [] | ||
| for arg_obj in call.arguments: | ||
| display_value = str(arg_obj.value) | ||
| # Current implementation: Display name=value, since we have arg name | ||
| args_display.append(f"{arg_obj.name}={display_value}") | ||
| parts.append(", ".join(args_display)) | ||
|
|
||
| parts.append(")") | ||
|
|
||
| return "".join(parts) | ||
|
|
||
| @classmethod | ||
| def from_jsonl_file(cls, jsonl_path: Path) -> "FridaExtractor": | ||
| """Entry point: Create an extractor from a JSONL file""" | ||
| report = FridaReport.from_jsonl_file(jsonl_path) | ||
| return cls(report) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,96 @@ | ||
| import json | ||
| from typing import List, Union | ||
|
|
||
| from pydantic import Field, BaseModel, ConfigDict | ||
|
|
||
|
|
||
| class FlexibleModel(BaseModel): | ||
| model_config = ConfigDict(extra="allow") | ||
|
|
||
|
|
||
| class Hashes(BaseModel): | ||
| md5: str | ||
| sha1: str | ||
| sha256: str | ||
|
|
||
|
|
||
| class Metadata(FlexibleModel): | ||
| process_id: int | ||
| package_name: str | ||
| arch: str | ||
| platform: str | ||
| hashes: Hashes | ||
|
|
||
|
|
||
| class Argument(FlexibleModel): | ||
| """Represents a single argument in an API call""" | ||
|
|
||
| name: str | ||
| value: Union[str, int, float, bool, None] | ||
|
|
||
|
|
||
| class Call(FlexibleModel): | ||
| """Represents a single API call captured by Frida""" | ||
|
|
||
| api_name: str # API name like "java.io.File.<init>", not sure if need to seperate 'japi' 'napi' 'jni'... | ||
| process_id: int | ||
| thread_id: int | ||
| call_id: int | ||
| # timestamp: Optional[str] = None | ||
| arguments: List[Argument] = Field(default_factory=list) | ||
| # return_value: Optional[Any] = None # Not very sure if we should use str as the return value type | ||
| # caller: Optional[str] = None | ||
|
|
||
|
|
||
| class Process(FlexibleModel): | ||
| """Process information from Frida analysis""" | ||
|
|
||
| # ppid is omitted here as Android apps are usually single-process; it will be set to 0 in extractor.py | ||
| pid: int | ||
| package_name: str | ||
| arch: str | ||
| platform: str | ||
| calls: List[Call] = Field(default_factory=list) | ||
|
|
||
|
|
||
| class FridaReport(FlexibleModel): | ||
| """Main report structure for Android analysis""" | ||
|
|
||
| # TODO: Some more file-level information may go here | ||
| package_name: str | ||
| processes: List[Process] = Field(default_factory=list) | ||
| hashes: Hashes | ||
|
|
||
| @classmethod | ||
| def from_jsonl_file(cls, jsonl_path) -> "FridaReport": | ||
| """Load from JSON Lines file""" | ||
| metadata = None | ||
| api_calls = [] | ||
|
|
||
| with open(jsonl_path, "r") as f: | ||
| content = f.read() | ||
| for line in content.splitlines(): | ||
| record = json.loads(line) | ||
|
|
||
| if "metadata" in record: | ||
| metadata = Metadata(**record["metadata"]) | ||
| elif "api" in record: | ||
| if "java_api" in record["api"]: | ||
| call = Call(**record["api"]["java_api"]) | ||
| api_calls.append(call) | ||
| elif "native_api" in record["api"]: | ||
| call = Call(**record["api"]["native_api"]) | ||
| api_calls.append(call) | ||
|
|
||
| if metadata is None: | ||
| raise ValueError("No metadata found in JSONL file") | ||
|
|
||
| process = Process( | ||
| pid=metadata.process_id, | ||
| package_name=metadata.package_name, | ||
| arch=metadata.arch, | ||
| platform=metadata.platform, | ||
| calls=api_calls, | ||
| ) | ||
|
|
||
| return cls(package_name=metadata.package_name, processes=[process], hashes=metadata.hashes) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Reading the entire file into memory with
f.read()can be inefficient for large JSONL files. It's better to iterate over the file line by line to reduce memory consumption. This change also addsencoding='utf-8'for robustness and handles empty or malformed JSON lines.