836 lines
58 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Android 애플리케이션 Pentesting
{{#include ../../banners/hacktricks-training.md}}
## Android 애플리케이션 기본
이 페이지를 먼저 읽어 **Android 보안과 Android 애플리케이션에서 가장 위험한 구성요소와 관련된 가장 중요한 부분들**을 알아두는 것을 강력히 권장합니다:
{{#ref}}
android-applications-basics.md
{{#endref}}
## ADB (Android Debug Bridge)
이는 에뮬레이터나 실기기와 같은 Android 기기에 연결하기 위해 필요한 주요 도구입니다.\
**ADB**는 컴퓨터에서 **USB** 또는 **네트워크**를 통해 기기를 제어할 수 있게 해줍니다. 이 유틸리티는 양방향 파일 **복사**, 앱의 **설치****제거**, 셸 명령의 **실행**, 데이터의 **백업**, 로그의 **읽기** 등 다양한 기능을 제공합니다.
adb 사용 방법을 배우려면 다음 [**ADB Commands**](adb-commands.md) 목록을 확인하세요.
## Smali
때때로 **애플리케이션 코드를 수정**해 **숨겨진 정보**(예: 잘 난독화된 비밀번호나 플래그)에 접근하는 것이 흥미로울 수 있습니다. 그런 경우, apk를 디컴파일하고 코드를 수정한 뒤 다시 컴파일하는 것이 유용할 수 있습니다.\
[**In this tutorial** you can **learn how to decompile and APK, modify Smali code and recompile the APK** with the new functionality](smali-changes.md). 이 방법은 이후 소개될 동적 분석 중 여러 테스트에 대한 **동적 분석 중 여러 테스트에 대한 대안**으로 매우 유용할 수 있습니다. 그러므로 **항상 이 가능성을 염두에 두세요**.
## 기타 흥미로운 팁
- [Spoofing your location in Play Store](spoofing-your-location-in-play-store.md)
- [Shizuku Privileged API (ADB-based non-root privileged access)](shizuku-privileged-api.md)
- [Exploiting Insecure In-App Update Mechanisms](insecure-in-app-update-rce.md)
- [Abusing Accessibility Services (Android RAT)](accessibility-services-abuse.md)
- **APK 다운로드**: [https://apps.evozi.com/apk-downloader/](https://apps.evozi.com/apk-downloader/), [https://apkpure.com/es/](https://apkpure.com/es/), [https://www.apkmirror.com/](https://www.apkmirror.com), [https://apkcombo.com/es-es/apk-downloader/](https://apkcombo.com/es-es/apk-downloader/), [https://github.com/kiber-io/apkd](https://github.com/kiber-io/apkd)
- 기기에서 APK 추출:
```bash
adb shell pm list packages
com.android.insecurebankv2
adb shell pm path com.android.insecurebankv2
package:/data/app/com.android.insecurebankv2-Jnf8pNgwy3QA_U5f-n_4jQ==/base.apk
adb pull /data/app/com.android.insecurebankv2-Jnf8pNgwy3QA_U5f-n_4jQ==/base.apk
```
- 모든 split 및 base APK를 [APKEditor](https://github.com/REAndroid/APKEditor)로 병합:
```bash
mkdir splits
adb shell pm path com.android.insecurebankv2 | cut -d ':' -f 2 | xargs -n1 -i adb pull {} splits
java -jar ../APKEditor.jar m -i splits/ -o merged.apk
# after merging, you will need to align and sign the apk, personally, I like to use the uberapksigner
java -jar uber-apk-signer.jar -a merged.apk --allowResign -o merged_signed
```
## 사례 연구 및 취약점
{{#ref}}
../ios-pentesting/air-keyboard-remote-input-injection.md
{{#endref}}
{{#ref}}
../../linux-hardening/privilege-escalation/android-rooting-frameworks-manager-auth-bypass-syscall-hook.md
{{#endref}}
## 정적 분석
우선, APK를 분석할 때는 **decompiler를 사용해 Java 코드를 살펴보는 것**이 중요합니다.\
다양한 사용 가능한 decompiler에 대한 정보를 확인하려면 [**여기에서 읽어보세요**](apk-decompilers.md).
### 흥미로운 정보 찾기
APK의 **strings**만 살펴봐도 **비밀번호**, **URLs** ([https://github.com/ndelphit/apkurlgrep](https://github.com/ndelphit/apkurlgrep)), **api** 키, **encryption**, **bluetooth uuids**, **토큰** 등 흥미로운 것들을 찾을 수 있습니다... 코드 실행을 위한 **backdoors**나 인증 백도어(앱에 하드코딩된 관리자 자격증명)도 확인하세요.
Firebase
**Firebase URLs**에 특히 주의하고 잘못 구성되어 있는지 확인하세요. [Firebase가 무엇이고 이를 악용하는 방법에 대한 추가 정보는 여기](../../network-services-pentesting/pentesting-web/buckets/firebase-database.md)에서 확인할 수 있습니다.
### 애플리케이션의 기본 이해 - Manifest.xml, strings.xml
애플리케이션의 **_Manifest.xml_와 **_strings.xml_ 파일을 검토하면 잠재적인 보안 취약점을 발견할 수 있습니다**. 이 파일들은 decompiler로 접근하거나 APK 파일의 확장자를 .zip으로 바꿔 압축을 풀어 확인할 수 있습니다.
Manifest.xml에서 식별되는 **취약점**에는 다음이 포함됩니다:
- **Debuggable Applications**: _Manifest.xml_ 파일에서 `debuggable="true"`로 설정된 애플리케이션은 연결을 허용하여 악용될 수 있으므로 위험합니다. 디버깅 가능한 애플리케이션을 찾고 이를 악용하는 방법에 대한 튜토리얼을 참고하세요.
- **Backup Settings**: 민감한 정보를 다루는 애플리케이션은 `android:allowBackup="false"` 속성을 명시적으로 설정하여 adb를 통한 무단 데이터 백업을 방지해야 합니다(특히 usb debugging이 활성화된 경우).
- **Network Security**: _res/xml/_의 커스텀 네트워크 보안 구성(`android:networkSecurityConfig="@xml/network_security_config"`)은 certificate pinning이나 HTTP 트래픽 설정과 같은 보안 세부사항을 지정할 수 있습니다. 예를 들어 특정 도메인에 대해 HTTP 트래픽을 허용하도록 설정할 수 있습니다.
- **Exported Activities and Services**: 매니페스트에서 노출된(exported) activity나 service를 식별하면 악용될 수 있는 컴포넌트를 드러낼 수 있습니다. 동적 테스트 중 추가 분석을 통해 이러한 컴포넌트를 어떻게 악용할 수 있는지 밝혀낼 수 있습니다.
- **Content Providers and FileProviders**: 노출된 content provider는 무단으로 데이터에 접근하거나 수정할 수 있게 할 수 있습니다. FileProviders의 구성도 면밀히 검토해야 합니다.
- **Broadcast Receivers and URL Schemes**: 이런 컴포넌트들은 악용될 가능성이 있으며, 특히 URL 스킴이 입력을 어떻게 처리하는지 주의해서 살펴봐야 합니다.
- **SDK Versions**: `minSdkVersion`, `targetSDKVersion`, 및 `maxSdkVersion` 속성은 지원되는 Android 버전을 나타내며, 오래된 취약한 Android 버전을 지원하지 않는 것이 중요함을 시사합니다.
**strings.xml** 파일에서는 API 키, 커스텀 스키마, 기타 개발자 메모 등 민감한 정보가 드러날 수 있으므로 이러한 리소스를 주의 깊게 검토해야 합니다.
### Tapjacking
**Tapjacking**은 **악의적인** **애플리케이션**이 실행되어 **피해자 애플리케이션 위에 자신을 배치하는** 공격입니다. 악성 앱이 피해자 앱을 가시적으로 가리게 되면, 악성 앱의 UI가 사용자를 속여 상호작용하도록 설계되고, 그 상호작용은 피해자 앱으로 전달됩니다.\
결과적으로 사용자는 자신이 실제로 피해자 앱에서 동작을 수행하고 있다는 사실을 **알 수 없게 됩니다**.
자세한 정보는 다음을 확인하세요:
{{#ref}}
tapjacking.md
{{#endref}}
### Task Hijacking
`launchMode`**`singleTask`로 설정되어 있고 `taskAffinity`가 정의되어 있지 않은** activity는 Task Hijacking 취약점에 노출됩니다. 이는 악성 **애플리케이션**을 설치하고 실제 애플리케이션보다 먼저 실행하면 **실제 애플리케이션의 task를 가로챌 수 있음을 의미**합니다(따라서 사용자는 자신이 실제 앱을 사용한다고 생각하면서 **악성 애플리케이션**과 상호작용하게 됩니다).
자세한 내용은 다음을 확인하세요:
{{#ref}}
android-task-hijacking.md
{{#endref}}
### Insecure data storage
Internal Storage
Android에서 내부 저장소에 **저장된** 파일은 **해당 파일을 생성한 앱만 접근할 수 있도록 설계되어 있습니다**. 이 보안 조치는 Android 운영체제에 의해 강제되며 대부분의 애플리케이션 보안 요구사항에 충분합니다. 다만 개발자가 `MODE_WORLD_READABLE``MODE_WORLD_WRITABLE` 같은 모드를 사용해 파일을 다른 애플리케이션과 공유하도록 허용하는 경우가 있습니다. 이러한 모드는 잠재적으로 다른 애플리케이션(악성 앱 포함)이 해당 파일에 접근할 수 있게 하므로 주의가 필요합니다.
1. Static Analysis:
- `MODE_WORLD_READABLE``MODE_WORLD_WRITABLE`의 사용을 **면밀히 검토**하세요. 이 모드들은 파일을 **원치 않거나 무단의 접근에 노출시킬 수 있습니다**.
2. Dynamic Analysis:
- 앱이 생성한 파일에 설정된 **권한**을 **검증**하세요. 특히 파일이 **전 세계에서 읽기 또는 쓰기가 가능한지** 확인하세요. 이는 심각한 보안 위험을 초래할 수 있으며, 설치된 어떤 애플리케이션이라도 해당 파일을 읽거나 수정할 수 있게 됩니다.
External Storage
SD Card와 같은 **external storage**의 파일을 다룰 때는 다음과 같은 점을 고려해야 합니다:
1. 접근성:
- external storage의 파일은 **전역적으로 읽기/쓰기 가능**합니다. 즉 어떤 애플리케이션이나 사용자도 이 파일들에 접근할 수 있습니다.
2. 보안 문제:
- 접근이 쉬우므로 **민감한 정보를 외부 저장소에 저장하지 않는 것이 권장**됩니다.
- 외부 저장소는 제거되거나 어떤 앱이라도 접근할 수 있어 더 안전하지 않습니다.
3. External Storage로부터의 데이터 처리:
- 외부 저장소에서 가져온 데이터에 대해 항상 **입력 검증(input validation)**을 수행하세요. 외부 저장소의 데이터는 신뢰할 수 없는 소스이기 때문에 필수적입니다.
- 외부 저장소에 실행 파일이나 class 파일을 저장하고 동적으로 로드하는 것은 강력히 권장되지 않습니다.
- 애플리케이션이 외부 저장소에서 실행 파일을 가져와야 하는 경우, 이러한 파일이 동적으로 로드되기 전에 반드시 **서명되고 암호학적으로 검증**되었는지 확인하세요. 이 단계는 애플리케이션의 보안 무결성을 유지하는 데 필수적입니다.
External storage는 `/storage/emulated/0` , `/sdcard` , `/mnt/sdcard`에서 접근할 수 있습니다.
> [!TIP]
> Android 4.4(**API 17**)부터 SD 카드에는 앱 전용 디렉터리 구조가 도입되어 **앱이 자신의 전용 디렉터리로만 접근하도록 제한**됩니다. 이는 악성 애플리케이션이 다른 앱의 파일에 읽기/쓰기 접근을 얻는 것을 방지합니다.
**평문으로 저장된 민감한 데이터**
- **Shared preferences**: Android는 각 애플리케이션이 `/data/data/<packagename>/shared_prefs/` 경로에 xml 파일을 쉽게 저장할 수 있도록 허용하며, 때때로 해당 폴더에서 평문으로 된 민감한 정보를 발견할 수 있습니다.
- **Databases**: Android는 각 애플리케이션이 `/data/data/<packagename>/databases/` 경로에 sqlite 데이터베이스를 쉽게 저장할 수 있도록 허용하며, 때때로 해당 폴더에서 평문으로 된 민감한 정보를 발견할 수 있습니다.
### Broken TLS
모든 인증서 수락(Accept All Certificates)
어떤 이유에서인지 개발자들이 호스트네임이 일치하지 않아도 모든 인증서를 수락하는 경우가 있습니다. 예를 들어 다음과 같은 코드 라인처럼:
```java
SSLSocketFactory sf = new cc(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
```
A good way to test this is to try to capture the traffic using some proxy like Burp without authorising Burp CA inside the device. Also, you can generate with Burp a certificate for a different hostname and use it.
### 취약한 암호화
**취약한 키 관리 프로세스**
일부 개발자는 민감한 데이터를 로컬 저장소에 저장하고 코드에 하드코딩되었거나 예측 가능한 키로 암호화합니다. 리버싱을 통해 공격자가 기밀 정보를 추출할 수 있으므로 이렇게 해서는 안 됩니다.
**안전하지 않거나/또는 폐기된 알고리즘 사용**
개발자는 권한 확인, 데이터 **저장** 또는 **전송**에 **deprecated algorithms**을 사용해서는 안 됩니다. 이러한 알고리즘의 예로는 RC4, MD4, MD5, SHA1 등이 있습니다. 예를 들어 비밀번호를 저장하기 위해 **hashes**를 사용하는 경우에는 salt와 함께 브루트포스에 **저항성 있는** 해시를 사용해야 합니다.
### 기타 확인사항
- 공격자의 리버스 엔지니어링 작업을 어렵게 하기 위해 **APK를 obfuscate** 하는 것이 권장됩니다.
- 앱이 민감한 경우(예: 은행 앱)는 모바일이 **rooted**인지 확인하는 자체 검사를 수행하고 그에 따라 동작해야 합니다.
- 앱이 민감한 경우(예: 은행 앱)는 **emulator** 사용 여부를 검사해야 합니다.
- 앱이 민감한 경우(예: 은행 앱)는 **실행 전에 자체 무결성을 확인하여** 수정되었는지 검사해야 합니다.
- APK를 빌드할 때 어떤 compiler/packer/obfuscator가 사용되었는지 확인하려면 [**APKiD**](https://github.com/rednaga/APKiD)를 사용하세요
### React Native Application
Read the following page to learn how to easily access javascript code of React applications:
{{#ref}}
react-native-application.md
{{#endref}}
### Xamarin Applications
Read the following page to learn how to easily access C# code of a xamarin applications:
{{#ref}}
../xamarin-apps.md
{{#endref}}
### Superpacked Applications
According to this [**blog post**](https://clearbluejar.github.io/posts/desuperpacking-meta-superpacked-apks-with-github-actions/) superpacked is a Meta algorithm that compress the content of an application into a single file. The blog talks about the possibility of creating an app that decompress these kind of apps... and a faster way which involves to **execute the application and gather the decompressed files from the filesystem.**
### 자동화된 정적 코드 분석
툴 [**mariana-trench**](https://github.com/facebook/mariana-trench)는 애플리케이션의 코드를 **스캔**하여 **취약점**을 찾아낼 수 있습니다. 이 도구는 일련의 **known sources**(사용자가 제어하는 **입력**이 어디인지 도구에 알려주는), **sinks**(악의적 입력이 피해를 줄 수 있는 **위험한 지점**을 도구에 알려주는) 및 **rules**를 포함합니다. 이러한 규칙들은 취약점을 나타내는 **sources-sinks 조합**을 지정합니다.
이 지식을 바탕으로 **mariana-trench는 코드를 검토하여 잠재적 취약점을 찾아냅니다**.
### Secrets leaked
An application may contain secrets (API keys, passwords, hidden urls, subdomains...) inside of it that you might be able to discover. You could us a tool such as [https://github.com/dwisiswant0/apkleaks](https://github.com/dwisiswant0/apkleaks)
### Bypass Biometric Authentication
{{#ref}}
bypass-biometric-authentication-android.md
{{#endref}}
### 기타 흥미로운 기능
- **코드 실행**: `Runtime.exec(), ProcessBuilder(), native code:system()`
- **SMS 전송**: `sendTextMessage, sendMultipartTestMessage`
- **Native 함수들** 선언: `public native, System.loadLibrary, System.load`
- [이 문서를 읽어 **how to reverse native functions**를 알아보세요](reversing-native-libraries.md)
- JNI를 통한 메모리 상의 native 코드 실행 (downloaded shellcode → mmap/mprotect → call):
{{#ref}}
in-memory-jni-shellcode-execution.md
{{#endref}}
### **Other tricks**
{{#ref}}
content-protocol.md
{{#endref}
---
---
## 동적 분석
> 무엇보다도 애플리케이션과 필요한 환경(Burp CA cert, Drozer 및 Frida 등)을 설치할 수 있는 환경이 필요합니다. 따라서 루팅된 기기(에뮬레이터 포함)를 사용하는 것을 강력히 권장합니다.
### 온라인 동적 분석
다음에서 **free account**를 만들 수 있습니다: [https://appetize.io/](https://appetize.io). 이 플랫폼은 APK를 **업로드**하고 **실행**할 수 있게 해주므로 APK가 어떻게 동작하는지 확인하는 데 유용합니다.
웹에서 애플리케이션의 **로그를 볼 수** 있고 **adb**로 연결할 수도 있습니다.
![](<../../images/image (831).png>)
ADB 연결 덕분에 에뮬레이터 내에서 **Drozer**와 **Frida**를 사용할 수 있습니다.
### 로컬 동적 분석
#### 에뮬레이터 사용
- [**Android Studio**](https://developer.android.com/studio) (x86 및 arm 디바이스를 생성할 수 있으며, [**this**](https://android-developers.googleblog.com/2020/03/run-arm-apps-on-android-emulator.html)에 따르면 최신 **x86** 버전은 느린 arm 에뮬레이터 없이 **ARM 라이브러리**를 지원합니다).
- 설정 방법은 다음 페이지를 참고하세요:
{{#ref}}
avd-android-virtual-device.md
{{#endref}}
- [**Genymotion**](https://www.genymotion.com/fun-zone/) **(Free version:** Personal Edition, 계정 생성 필요. _잠재적 오류를 피하려면 **VirtualBox** 포함 버전을 **다운로드**하는 것이 권장됩니다._)
- [**Nox**](https://es.bignox.com) (무료지만 Frida나 Drozer를 지원하지 않습니다).
> [!TIP]
> 새로운 에뮬레이터를 만들 때 화면이 클수록 에뮬레이터가 느려지므로 가능하면 작은 화면을 선택하세요.
Genymotion에 **google services**(예: AppStore)를 설치하려면 다음 이미지의 빨간 표시된 버튼을 클릭해야 합니다:
![](<../../images/image (277).png>)
또한 Genymotion의 **Android VM 구성**에서 **Bridge Network mode**를 선택할 수 있다는 점에 유의하세요(다른 VM에서 도구로 Android VM에 연결할 때 유용합니다).
#### 실기기 사용
디버깅 옵션을 활성화해야 하며 가능하면 **root**하는 것이 좋습니다:
1. **Settings**.
2. (FromAndroid 8.0) Select **System**.
3. Select **About phone**.
4. Press **Build number** 7 times.
5. 뒤로 가면 **Developer options**를 찾을 수 있습니다.
> 애플리케이션을 설치한 후 가장 먼저 해야 할 일은 그것을 사용해보고 무엇을 하는지, 어떻게 동작하는지 파악하여 익숙해지는 것입니다.\
> 저는 이 초기 동적 분석을 **MobSF dynamic analysis + pidcat**으로 수행할 것을 권합니다. 이렇게 하면 MobSF가 나중에 검토할 수 있는 많은 **흥미로운 데이터**를 캡처하는 동안 애플리케이션의 동작을 학습할 수 있습니다.
Magisk/Zygisk quick notes (recommended on Pixel devices)
- Magisk 앱으로 boot.img를 패치하고 fastboot로 플래시하여 systemless root를 얻으세요
- root 숨김을 위해 Zygisk + DenyList를 활성화하세요; 더 강한 숨김이 필요하면 LSPosed/Shamiko를 고려하세요
- OTA 업데이트에서 복구할 수 있도록 원본 boot.img를 보관하세요; OTA 후에는 다시 패치하세요
- 화면 미러링은 호스트에서 scrcpy를 사용하세요
### Unintended Data Leakage
**로깅**
개발자는 **debugging information**을 공개적으로 노출하지 않도록 주의해야 하며, 이는 민감한 데이터 leak로 이어질 수 있습니다. 애플리케이션 로그를 모니터링하여 민감한 정보를 식별하고 보호하기 위해 [**pidcat**](https://github.com/JakeWharton/pidcat)와 `adb logcat`을 권장합니다. **Pidcat**은 사용 편의성과 가독성 때문에 선호됩니다.
> [!WARNING]
> Android 4.0 이후 버전부터 **applications are only able to access their own logs**. 따라서 애플리케이션은 다른 앱의 로그에 접근할 수 없습니다.\
> 어쨌든 민감한 정보를 로그로 남기지 않는 것이 권장됩니다.
**복사/붙여넣기 버퍼 캐싱**
Android의 **clipboard-based** 프레임워크는 앱에서 복사·붙여넣기 기능을 가능하게 하지만, 다른 애플리케이션이 클립보드에 접근할 수 있어 민감한 데이터가 노출될 위험이 있습니다. 신용카드 정보와 같은 민감한 섹션에서는 복사/붙여넣기 기능을 비활성화하는 것이 중요합니다.
**크래시 로그**
애플리케이션이 크래시하여 로그를 저장하면, 특히 애플리케이션을 리버스엔지니어링할 수 없을 때 이러한 로그는 공격자에게 도움이 될 수 있습니다. 이 위험을 완화하려면 크래시 시 로그를 남기지 말고, 네트워크로 로그를 전송해야 하는 경우 SSL 채널로 전송되도록 보장하세요.
Pentester로서, **이 로그들을 확인해 보세요**.
**3자에게 전송되는 분석 데이터**
애플리케이션은 종종 Google Adsense와 같은 서비스를 통합하는데, 개발자의 부적절한 구현으로 인해 민감한 데이터가 의도치 않게 **leak**될 수 있습니다. 잠재적인 데이터 누수를 식별하려면 애플리케이션의 트래픽을 **가로채서** 서드파티 서비스로 전송되는 민감한 정보가 있는지 확인하는 것이 좋습니다.
### SQLite DBs
대부분의 애플리케이션은 정보를 저장하기 위해 **internal SQLite databases**를 사용합니다. 펜테스트 중에는 생성된 **데이터베이스**, **테이블****컬럼** 이름과 저장된 모든 **데이터**를 확인하세요. 민감한 정보가 발견될 수 있습니다(이는 취약점입니다).\
데이터베이스는 `/data/data/the.package.name/databases`에 위치해야 합니다. 예: `/data/data/com.mwr.example.sieve/databases`
데이터베이스가 기밀 정보를 저장하고 **암호화되어 있더라도** 애플리케이션 내부에서 **password**를 찾을 수 있다면 이는 여전히 **vulnerability**입니다.
`.tables`로 테이블을 나열하고 `.schema <table_name>`로 테이블의 컬럼을 나열하세요.
### Drozer (Exploit Activities, Content Providers and Services)
From [Drozer Docs](https://labs.mwrinfosecurity.com/assets/BlogFiles/mwri-drozer-user-guide-2015-03-23.pdf): **Drozer**는 **앱의 역할을 가정**하여 다른 앱과 상호작용할 수 있게 해줍니다. 설치된 애플리케이션이 할 수 있는 모든 작업(예: Android의 Inter-Process Communication(IPC) 메커니즘 사용 및 기본 운영체제와의 상호작용)을 수행할 수 있습니다.\
Drozer는 **exported activities, exported services 및 Content Providers를 exploit**하는 데 유용한 도구이며, 이는 다음 섹션에서 배울 수 있습니다.
### Exploiting exported Activities
[**Read this if you want to refresh what is an Android Activity.**](android-applications-basics.md#launcher-activity-and-other-activities)\
또한 액티비티의 코드는 **`onCreate`** 메서드에서 시작된다는 점을 기억하세요.
**Authorisation bypass**
Activity가 exported되어 있을 때 외부 앱에서 해당 화면을 호출할 수 있습니다. 따라서 **sensitive information**을 포함한 액티비티가 **exported**되어 있다면 인증 메커니즘을 **bypass**하여 접근할 수 있습니다.
[**Learn how to exploit exported activities with Drozer.**](drozer-tutorial/index.html#activities)
또한 adb에서 exported activity를 시작할 수 있습니다:
- PackageName is com.example.demo
- Exported ActivityName is com.example.test.MainActivity
```bash
adb shell am start -n com.example.demo/com.example.test.MainActivity
```
**참고**: MobSF는 액티비티에서 `android:launchMode`로 _**singleTask/singleInstance**_를 사용하는 것을 악성으로 감지하지만, [this](https://github.com/MobSF/Mobile-Security-Framework-MobSF/pull/750) 때문에 이는 구버전(API 버전 < 21)에서만 위험한 것으로 보입니다.
> [!TIP]
> authorisation bypass가 항상 취약점인 것은 아니며, 우회 방식과 어떤 정보가 노출되는지에 따라 달라집니다.
**민감한 정보 누출**
액티비티는 결과를 반환할 수도 있습니다. export되어 있고 보호되지 않은 액티비티가 **`setResult`** 메서드를 호출하며 **민감한 정보를 반환**하는 것을 찾으면, 민감한 정보 누출이 발생합니다.
#### Tapjacking
Tapjacking이 방지되지 않으면 export된 액티비티를 악용해 **사용자가 예기치 않은 동작을 수행하도록 만들 수 있습니다**. Tapjacking에 대한 자세한 내용은 [**Tapjacking이 무엇인지 보려면 링크를 따르세요**](#tapjacking).
### Exploiting Content Providers - Accessing and manipulating sensitive information
[**Content Provider가 무엇인지 새로 확인하고 싶다면 읽어보세요.**](android-applications-basics.md#content-provider)
Content provider는 기본적으로 **데이터를 공유**하는 데 사용됩니다. 앱에 content provider가 존재하면 거기서 **민감한 데이터를 추출**할 수 있습니다. 또한 잠재적 취약점으로 **SQL injections** **Path Traversals** 테스트해보는 것도 흥미롭습니다.
[**Drozer로 Content Providers를 악용하는 방법 배우기.**](drozer-tutorial/index.html#content-providers)
### **Exploiting Services**
[**Service가 무엇인지 다시 확인하고 싶다면 읽어보세요.**](android-applications-basics.md#services)
Service의 동작은 `onStartCommand` 메서드에서 시작된다는 점을 기억하세요.
서비스는 기본적으로 데이터를 **수신**, **처리**하고 **반환**(또는 반환하지 않음) 있습니다. 따라서 앱이 일부 서비스를 export하고 있다면 무엇을 하는지 이해하기 위해 **코드**를 **검토**하고, 기밀 정보를 추출하거나 인증 수단을 우회하기 위해 **동적으로** 테스트해보아야 합니다.
[**Drozer로 서비스 악용 방법 배우기.**](drozer-tutorial/index.html#services)
### **Exploiting Broadcast Receivers**
[**Broadcast Receiver가 무엇인지 다시 확인하고 싶다면 읽어보세요.**](android-applications-basics.md#broadcast-receivers)
Broadcast Receiver의 동작은 `onReceive` 메서드에서 시작된다는 점을 기억하세요.
브로드캐스트 리시버는 특정 유형의 메시지를 기다립니다. 리시버가 메시지를 처리하는 방식에 따라 취약할 있습니다.
[**Drozer로 Broadcast Receiver 악용 방법 배우기.**](#exploiting-broadcast-receivers)
### **Exploiting Schemes / Deep links**
MobSF 같은 도구나 [this one](https://github.com/ashleykinguk/FBLinkBuilder/blob/master/FBLinkBuilder.py) 같은 스크립트를 사용해 링크를 수동으로 찾을 있습니다.
선언된 **scheme** **adb** **브라우저** 있습니다:
```bash
adb shell am start -a android.intent.action.VIEW -d "scheme://hostname/path?param=value" [your.package.name]
```
_참고로 **패키지 이름을 생략할 수 있으며** 모바일이 해당 링크를 열 앱을 자동으로 호출합니다._
```html
<!-- Browser regular link -->
<a href="scheme://hostname/path?param=value">Click me</a>
<!-- fallback in your url you could try the intent url -->
<a href="intent://hostname#Intent;scheme=scheme;package=your.package.name;S.browser_fallback_url=http%3A%2F%2Fwww.example.com;end">with alternative</a>
```
**실행되는 코드**
앱에서 **실행될 코드**를 찾으려면 deeplink에 의해 호출되는 activity로 이동하여 함수 **`onNewIntent`** 검색하세요.
![](<../../images/image (436) (1) (1) (1).png>)
**민감한 정보**
deep link를 찾을 때마다 **URL 파라미터를 통해 민감한 데이터(예: passwords)를 수신하지 않는지** 확인하세요. 다른 애플리케이션이 **deep link를 가장해 해당 데이터를 탈취할 수 있습니다!**
**경로 내 파라미터**
You **must check also if any deep link is using a parameter inside the path** of the URL like: `https://api.example.com/v1/users/{username}` , in that case you can force a path traversal accessing something like: `example://app/users?username=../../unwanted-endpoint%3fparam=value` .\
Note that if you find the correct endpoints inside the application you may be able to cause a **Open Redirect** (if part of the path is used as domain name), **account takeover** (if you can modify users details without CSRF token and the vuln endpoint used the correct method) and any other vuln. More [info about this here](http://dphoeniixx.com/2020/12/13-2/).
**추가 예시**
An [interesting bug bounty report](https://hackerone.com/reports/855618) about links (_/.well-known/assetlinks.json_).
### 전송 계층 검사 및 검증 실패
- **Certificates are not always inspected properly** by Android applications. 이러한 애플리케이션은 경고를 무시하고 자체 서명 인증서를 수용하거나, 경우에 따라 HTTP 연결로 되돌아가는 경우가 흔합니다.
- **Negotiations during the SSL/TLS handshake are sometimes weak**, 취약한 cipher suites를 사용하기도 합니다. 이 취약점은 연결을 MITM(man-in-the-middle) 공격에 노출시켜 공격자가 데이터를 복호화할 수 있게 합니다.
- **Leakage of private information** is a risk when applications authenticate using secure channels but then communicate over non-secure channels for other transactions. 이런 접근은 세션 쿠키나 사용자 세부정보 같은 민감한 데이터를 악의적인 주체가 가로채는 것으로부터 보호하지 못합니다.
#### Certificate Verification
우리는 **certificate verification**에 중점을 둘 것입니다. 보안을 강화하려면 서버 인증서의 무결성을 검증해야 합니다. 이는 insecure TLS 구성과 암호화되지 않은 채널을 통한 민감한 데이터 전송이 심각한 위험을 초래할 수 있기 때문에 매우 중요합니다. 서버 인증서를 검증하고 취약점을 해결하는 자세한 단계는 [**this resource**](https://manifestsecurity.com/android-application-security-part-10/)에서 확인할 수 있습니다.
#### SSL Pinning
SSL Pinning은 애플리케이션이 서버의 인증서를 앱 내에 저장된 알려진 복사본과 대조하여 검증하는 보안 방법입니다. 이 방법은 MITM 공격을 방지하는 데 필수적입니다. 민감한 정보를 다루는 애플리케이션에는 SSL Pinning 구현을 강력히 권장합니다.
#### Traffic Inspection
HTTP 트래픽을 검사하려면 **프록시 도구의 인증서 설치**(예: Burp)가 필요합니다. 이 인증서를 설치하지 않으면 암호화된 트래픽을 프록시에서 볼 수 없을 수 있습니다. 커스텀 CA 인증서 설치 가이드는 [**click here**](avd-android-virtual-device.md#install-burp-certificate-on-a-virtual-machine)를 참조하세요.
**API Level 24 and above**를 타깃으로 하는 애플리케이션은 프록시의 CA 인증서를 수용하도록 Network Security Config를 수정해야 합니다. 암호화된 트래픽을 검사하려면 이 단계가 필수적입니다. Network Security Config 수정 방법은 [**refer to this tutorial**](make-apk-accept-ca-certificate.md)를 참고하세요.
만약 **Flutter**를 사용 중이라면 [**this page**](flutter.md)에 있는 지침을 따라야 합니다. 단순히 인증서를 스토어에 추가하는 것만으로는 동작하지 않을 수 있으며, Flutter는 자체 유효한 CA 목록을 사용하기 때문입니다.
#### Static detection of SSL/TLS pinning
런타임 우회를 시도하기 전에 APK에서 pinning이 적용되는 위치를 빠르게 매핑하세요. 정적 탐지는 훅/패치 계획을 세우고 올바른 코드 경로에 집중하는 데 도움이 됩니다.
Tool: SSLPinDetect
- 오픈소스 정적 분석 유틸리티로 APK를 Smali(apktool 통해)로 디컴파일하고 SSL/TLS pinning 구현의 정제된 정규식 패턴을 스캔합니다.
- 각 매치에 대해 정확한 파일 경로, 라인 번호, 코드 스니펫을 리포트합니다.
- 일반적인 프레임워크와 커스텀 코드 경로를 커버합니다: OkHttp CertificatePinner, custom javax.net.ssl.X509TrustManager.checkServerTrusted, SSLContext.init with custom TrustManagers/KeyManagers, 그리고 Network Security Config XML pins.
설치
- Prereqs: Python >= 3.8, Java on PATH, apktool
```bash
git clone https://github.com/aancw/SSLPinDetect
cd SSLPinDetect
pip install -r requirements.txt
```
사용법
```bash
# Basic
python sslpindetect.py -f app.apk -a apktool.jar
# Verbose (timings + per-match path:line + snippet)
python sslpindetect.py -a apktool_2.11.0.jar -f sample/app-release.apk -v
```
예제 패턴 규칙 (JSON)
프로프라이어터리/커스텀 pinning 스타일을 탐지하기 위해 signatures를 사용하거나 확장하세요. 자체 JSON을 로드하여 scan at scale할 수 있습니다.
```json
{
"OkHttp Certificate Pinning": [
"Lcom/squareup/okhttp/CertificatePinner;",
"Lokhttp3/CertificatePinner;",
"setCertificatePinner"
],
"TrustManager Override": [
"Ljavax/net/ssl/X509TrustManager;",
"checkServerTrusted"
]
}
```
Notes and tips
- 대형 앱을 빠르게 스캔하려면 multi-threading 및 memory-mapped I/O를 사용하세요; pre-compiled regex는 오버헤드와 false positives를 줄여줍니다.
- Pattern collection: https://github.com/aancw/smali-sslpin-patterns
- 다음으로 분류할 일반적인 탐지 대상:
- OkHttp: CertificatePinner 사용, setCertificatePinner, okhttp3/okhttp 패키지 참조
- Custom TrustManagers: javax.net.ssl.X509TrustManager, checkServerTrusted 오버라이드
- Custom SSL contexts: SSLContext.getInstance + SSLContext.init를 custom managers와 함께 사용
- Declarative pins in res/xml network security config 및 manifest 참조
- 매칭된 위치를 사용해 dynamic testing 전에 Frida hooks, static patches 또는 config 리뷰를 계획하세요.
#### SSL Pinning 우회
SSL Pinning이 구현되어 있으면 HTTPS 트래픽을 검사하기 위해 이를 우회할 필요가 있습니다. 이를 위한 여러 방법이 있습니다:
- 자동으로 **apk**를 **수정**하여 **SSLPinning**을 우회하려면 [**apk-mitm**](https://github.com/shroudedcode/apk-mitm)를 사용하세요. 이 방법의 가장 큰 장점은 SSL Pinning을 우회하는 데 root가 필요 없다는 것이지만, 애플리케이션을 삭제하고 새로 설치해야 하며 항상 동작하지는 않을 수 있습니다.
- 이 보호를 우회하기 위해 **Frida**(아래에서 설명)를 사용할 수 있습니다. Burp+Frida+Genymotion을 사용하는 가이드는 다음을 참조하세요: [https://spenkk.github.io/bugbounty/Configuring-Frida-with-Burp-and-GenyMotion-to-bypass-SSL-Pinning/](https://spenkk.github.io/bugbounty/Configuring-Frida-with-Burp-and-GenyMotion-to-bypass-SSL-Pinning/)
- [**objection**](frida-tutorial/objection-tutorial.md)를 사용해 **자동으로 SSL Pinning을 우회**하려고 시도할 수도 있습니다: `objection --gadget com.package.app explore --startup-command "android sslpinning disable"`
- **MobSF dynamic analysis**(아래 설명)를 사용해 **자동으로 SSL Pinning을 우회**해볼 수도 있습니다.
- 여전히 캡처되지 않는 트래픽이 있다고 생각되면 **iptables를 사용해 트래픽을 burp로 포워딩**해보세요. 블로그 읽기: [https://infosecwriteups.com/bypass-ssl-pinning-with-ip-forwarding-iptables-568171b52b62](https://infosecwriteups.com/bypass-ssl-pinning-with-ip-forwarding-iptables-568171b52b62)
#### 일반적인 웹 취약점 찾기
애플리케이션 내에서 일반적인 웹 취약점을 찾는 것도 중요합니다. 이러한 취약점을 식별하고 완화하는 자세한 내용은 이 요약의 범위를 벗어나지만 다른 곳에 광범위하게 설명되어 있습니다.
### Frida
[Frida](https://www.frida.re) 는 개발자, 리버스 엔지니어, 보안 연구원을 위한 동적 인스트루먼테이션 툴킷입니다.\
**실행 중인 애플리케이션에 접근해 런타임에 메서드를 후킹하여 동작을 변경하고, 값 변경·추출하거나 다른 코드를 실행할 수 있습니다.**\
Android 애플리케이션을 pentest하려면 Frida 사용법을 알아야 합니다.
- Frida 사용법 배우기: [**Frida tutorial**](frida-tutorial/index.html)
- Frida 작업용 일부 "GUI": [**https://github.com/m0bilesecurity/RMS-Runtime-Mobile-Security**](https://github.com/m0bilesecurity/RMS-Runtime-Mobile-Security)
- Ojection은 Frida 사용을 자동화하기에 좋습니다: [**https://github.com/sensepost/objection**](https://github.com/sensepost/objection) **,** [**https://github.com/dpnishant/appmon**](https://github.com/dpnishant/appmon)
- 유용한 Frida 스크립트 모음: [**https://codeshare.frida.re/**](https://codeshare.frida.re)
- ptrace 없이 Frida를 로드해 안티 디버깅/안티-frida 메커니즘을 우회해보세요: [https://erfur.github.io/blog/dev/code-injection-without-ptrace](https://erfur.github.io/blog/dev/code-injection-without-ptrace) (도구: [linjector](https://github.com/erfur/linjector-rs))
#### Anti-instrumentation & SSL pinning bypass workflow
{{#ref}}
android-anti-instrumentation-and-ssl-pinning-bypass.md
{{#endref}}
### **메모리 덤프 - Fridump**
애플리케이션이 비밀번호나 니모닉 같은 민감한 정보를 메모리에 저장하고 있지 않은지 확인하세요.
[**Fridump3**](https://github.com/rootbsd/fridump3)를 사용하면 다음과 같이 앱의 메모리를 덤프할 수 있습니다:
```bash
# With PID
python3 fridump3.py -u <PID>
# With name
frida-ps -Uai
python3 fridump3.py -u "<Name>"
```
이것은 메모리를 ./dump 폴더에 덤프하며, 그 안에서 다음과 같이 grep을 실행할 수 있습니다:
```bash
strings * | grep -E "^[a-z]+ [a-z]+ [a-z]+ [a-z]+ [a-z]+ [a-z]+ [a-z]+ [a-z]+ [a-z]+ [a-z]+ [a-z]+ [a-z]+$"
```
### **Keystore 내 민감한 데이터**
Android에서 Keystore는 민감한 데이터를 저장하기에 가장 적합한 장소이지만, 충분한 권한이 있으면 여전히 **접근할 수 있습니다**. 애플리케이션이 여기서 **sensitive data in clear text**를 저장하는 경향이 있으므로, pentests는 root user 또는 기기에 물리적으로 접근할 수 있는 사람이 이 데이터를 탈취할 수 있으므로 이를 확인해야 합니다.
앱이 Keystore에 데이터를 저장하더라도, 해당 데이터는 암호화되어야 합니다.
Keystore 내부 데이터를 접근하려면 이 Frida 스크립트를 사용할 수 있습니다: [https://github.com/WithSecureLabs/android-keystore-audit/blob/master/frida-scripts/tracer-cipher.js](https://github.com/WithSecureLabs/android-keystore-audit/blob/master/frida-scripts/tracer-cipher.js)
```bash
frida -U -f com.example.app -l frida-scripts/tracer-cipher.js
```
### **Fingerprint/Biometrics Bypass**
다음 Frida script를 사용하면 Android 애플리케이션이 특정 민감 영역을 보호하기 위해 수행할 수 있는 **bypass fingerprint authentication**을 우회할 수 있습니다:
```bash
frida --codeshare krapgras/android-biometric-bypass-update-android-11 -U -f <app.package>
```
### **백그라운드 이미지**
애플리케이션을 백그라운드로 보내면, Android는 애플리케이션의 **스냅샷**을 저장합니다. 포그라운드로 복구될 때 앱보다 먼저 이미지를 로드해 앱이 더 빨리 열린 것처럼 보이게 합니다.
하지만 이 **스냅샷**에 **민감한 정보**가 포함되어 있으면, 스냅샷에 접근할 수 있는 사람이 해당 정보를 **탈취할 수 있습니다**(접근하려면 root 권한이 필요합니다).
스냅샷은 보통 다음 경로에 저장됩니다: **`/data/system_ce/0/snapshots`**
Android는 **FLAG_SECURE 레이아웃 파라미터를 설정하여 스크린샷 캡처를 방지**하는 방법을 제공합니다. 이 플래그를 사용하면 윈도우 내용을 보안 처리하여 스크린샷에 나타나거나 보안되지 않은 디스플레이에서 표시되는 것을 방지합니다.
```bash
getWindow().setFlags(LayoutParams.FLAG_SECURE, LayoutParams.FLAG_SECURE);
```
### **Android 애플리케이션 분석기**
이 도구는 동적 분석 중 여러 도구를 관리하는 데 도움을 줄 수 있습니다: [https://github.com/NotSoSecure/android_application_analyzer](https://github.com/NotSoSecure/android_application_analyzer)
### Intent Injection
Developers often create proxy components like activities, services, and broadcast receivers that handle these Intents and pass them to methods such as `startActivity(...)` or `sendBroadcast(...)`, which can be risky.
위험은 공격자가 이러한 Intents를 잘못 유도하여 non-exported 앱 컴포넌트를 트리거하거나 민감한 content providers에 접근할 수 있게 허용하는 데 있습니다. 주목할 만한 예로 `WebView`가 URL을 `Intent.parseUri(...)``Intent` 객체로 변환한 다음 이를 실행하면서 악의적인 Intent 주입으로 이어질 수 있습니다.
### Essential Takeaways
- **Intent Injection** 은 웹의 Open Redirect 문제와 유사합니다.
- Exploits involve passing `Intent` objects as extras, which can be redirected to execute unsafe operations.
- It can expose non-exported components and content providers to attackers.
- `WebView`s URL to `Intent` conversion can facilitate unintended actions.
### Android Client Side Injections and others
아마 웹에서 이런 유형의 취약점을 알고 계실 것입니다. Android 애플리케이션에서는 다음 취약점들에 특히 주의해야 합니다:
- **SQL Injection:** When dealing with dynamic queries or Content-Providers ensure you are using parameterized queries.
- **JavaScript Injection (XSS):** Verify that JavaScript and Plugin support is disabled for any WebViews (disabled by default). [More info here](webview-attacks.md#javascript-enabled).
- **Local File Inclusion:** WebViews should have access to the file system disabled (enabled by default) - `(webview.getSettings().setAllowFileAccess(false);)`. [More info here](webview-attacks.md#javascript-enabled).
- **Eternal cookies**: 몇몇 경우 Android 애플리케이션이 세션을 종료할 때 쿠키가 무효화되지 않거나 심지어 디스크에 저장될 수 있습니다
- [**Secure Flag** in cookies](../../pentesting-web/hacking-with-cookies/index.html#cookies-flags)
---
## 자동 분석
### [MobSF](https://github.com/MobSF/Mobile-Security-Framework-MobSF)
**정적 분석**
![](<../../images/image (866).png>)
**애플리케이션의 취약점 평가**를 깔끔한 웹 기반 프런트엔드를 통해 수행합니다. 동적 분석도 수행할 수 있지만(환경을 준비해야 합니다).
```bash
docker pull opensecurity/mobile-security-framework-mobsf
docker run -it -p 8000:8000 opensecurity/mobile-security-framework-mobsf:latest
```
Notice that MobSF can analyse **Android**(apk)**, IOS**(ipa) **and Windows**(apx) applications (_Windows applications must be analyzed from a MobSF installed in a Windows host_).\
Also, if you create a **ZIP** file with the source code if an **Android** or an **IOS** app (go to the root folder of the application, select everything and create a ZIPfile), it will be able to analyse it also.
MobSF also allows you to **diff/Compare** analysis and to integrate **VirusTotal** (you will need to set your API key in _MobSF/settings.py_ and enable it: `VT_ENABLED = TRUE` `VT_API_KEY = <Your API key>` `VT_UPLOAD = TRUE`). You can also set `VT_UPLOAD` to `False`, then the **hash** will be **upload** instead of the file.
### Assisted Dynamic analysis with MobSF
**MobSF** can also be very helpful for **dynamic analysis** in **Android**, but in that case you will need to install MobSF and **genymotion** in your host (a VM or Docker won't work). _Note: You need to **start first a VM in genymotion** and **then MobSF.**_\
The **MobSF dynamic analyser** can:
- **Dump application data** (URLs, 로그, clipboard, 당신이 찍은 screenshots, "**Exported Activity Tester**"가 찍은 screenshots, emails, SQLite databases, XML files, 그리고 생성된 다른 파일들). 스크린샷을 제외한 모든 항목은 자동으로 수행되며, 스크린샷은 캡처하고 싶을 때 버튼을 눌러야 하거나 모든 exported activities의 스크린샷을 얻기 위해 "**Exported Activity Tester**"를 눌러야 합니다.
- Capture **HTTPS traffic**
- Use **Frida** to obtain **runtime** **information**
From android **versions > 5**, it will **automatically start Frida** and will set global **proxy** settings to **capture** traffic. It will only capture traffic from the tested application.
**Frida**
By default, it will also use some Frida Scripts to **bypass SSL pinning**, **root detection** and **debugger detection** and to **monitor interesting APIs**.\
MobSF can also **invoke exported activities**, grab **screenshots** of them and **save** them for the report.
To **start** the dynamic testing press the green bottom: "**Start Instrumentation**". Press the "**Frida Live Logs**" to see the logs generated by the Frida scripts and "**Live API Monitor**" to see all the invocation to hooked methods, arguments passed and returned values (this will appear after pressing "Start Instrumentation").\
MobSF also allows you to load your own **Frida scripts** (to send the results of your Friday scripts to MobSF use the function `send()`). It also has **several pre-written scripts** you can load (you can add more in `MobSF/DynamicAnalyzer/tools/frida_scripts/others/`), just **select them**, press "**Load**" and press "**Start Instrumentation**" (you will be able to see the logs of that scripts inside "**Frida Live Logs**").
![](<../../images/image (419).png>)
Moreover, you have some Auxiliary Frida functionalities:
- **Enumerate Loaded Classes**: 모든 로드된 클래스를 출력합니다
- **Capture Strings**: 애플리케이션 사용 중에 캡처된 모든 문자열을 출력합니다 (매우 noisy)
- **Capture String Comparisons**: 매우 유용할 수 있습니다. 비교되는 2개의 문자열을 **보여주며** 결과가 True인지 False인지 표시합니다.
- **Enumerate Class Methods**: 클래스 이름(예: "java.io.File")을 입력하면 해당 클래스의 모든 메서드를 출력합니다.
- **Search Class Pattern**: 패턴으로 클래스를 검색합니다
- **Trace Class Methods**: **Trace** a **whole class** (클래스의 모든 메서드의 입력과 출력을 확인). 기본적으로 MobSF는 여러 흥미로운 Android Api 메서드들을 trace 한다는 것을 기억하세요.
Once you have selected the auxiliary module you want to use you need to press "**Start Intrumentation**" and you will see all the outputs in "**Frida Live Logs**".
**Shell**
Mobsf also brings you a shell with some **adb** commands, **MobSF commands**, and common **shell** **commands** at the bottom of the dynamic analysis page. Some interesting commands:
```bash
help
shell ls
activities
exported_activities
services
receivers
```
**HTTP 도구**
HTTP 트래픽이 캡처되면 "**HTTP(S) Traffic**" 버튼에서 캡처된 트래픽의 보기 흉한 뷰를 보거나 "**Start HTTPTools**" 녹색 버튼에서 더 보기 좋은 뷰를 볼 수 있습니다. 두 번째 옵션에서는 **send** the **captured requests** to **proxies** like Burp or Owasp ZAP.\
이를 위해, _power on Burp -->_ _turn off Intercept --> in MobSB HTTPTools select the request_ --> 버튼 "**Send to Fuzzer**"를 누른 다음 --> _select the proxy address_ ([http://127.0.0.1:8080\\](http://127.0.0.1:8080)).
MobSF로 dynamic analysis를 마치면 "**Start Web API Fuzzer**"를 눌러 **fuzz http requests** 하여 취약점을 찾을 수 있습니다.
> [!TIP]
> MobSF로 dynamic analysis를 수행한 후 프록시 설정이 잘못 구성되어 GUI에서 수정할 수 없을 수 있습니다. 프록시 설정은 다음을 실행하여 수정할 수 있습니다:
>
> ```
> adb shell settings put global http_proxy :0
> ```
### Inspeckage를 이용한 Assisted Dynamic Analysis
도구는 [**Inspeckage**](https://github.com/ac-pm/Inspeckage)에서 얻을 수 있습니다.\
이 도구는 일부 **Hooks**를 사용하여 **dynamic analysis**를 수행하는 동안 애플리케이션에서 무슨 일이 일어나는지 알려줍니다.
### [Yaazhini](https://www.vegabird.com/yaazhini/)
이것은 **GUI로 static analysis를 수행하기에 훌륭한 도구**입니다
![](<../../images/image (741).png>)
### [Qark](https://github.com/linkedin/qark)
이 도구는 **security related Android application vulnerabilities**를 찾도록 설계되었으며, **source code** 또는 **packaged APKs**에서 동작합니다. 또한 이 도구는 **capable of creating a "Proof-of-Concept" deployable APK** 및 **ADB commands**를 생성하여 발견된 일부 취약점(Exposed activities, intents, tapjacking...)을 악용할 수 있습니다. Drozer와 마찬가지로 테스트 디바이스를 root할 필요는 없습니다.
```bash
pip3 install --user qark # --user is only needed if not using a virtualenv
qark --apk path/to/my.apk
qark --java path/to/parent/java/folder
qark --java path/to/specific/java/file.java
```
### [**ReverseAPK**](https://github.com/1N3/ReverseAPK.git)
- 참고하기 쉽도록 추출된 모든 파일을 표시
- APK 파일을 자동으로 Java 및 Smali 형식으로 디컴파일
- AndroidManifest.xml을 분석하여 일반적인 취약점 및 동작을 식별
- 일반적인 취약점 및 동작에 대한 정적 소스 코드 분석
- 기기 정보
-
```bash
reverse-apk relative/path/to/APP.apk
```
### [SUPER Android Analyzer](https://github.com/SUPERAndroidAnalyzer/super)
SUPER는 Windows, MacOS X 및 Linux에서 사용할 수 있는 명령줄 애플리케이션으로, 취약점을 찾기 위해 _.apk_ 파일을 분석합니다.
이는 APK의 압축을 풀고 일련의 규칙을 적용하여 해당 취약점을 탐지함으로써 동작합니다.
모든 규칙은 `rules.json` 파일에 집중되어 있으며, 각 회사나 테스터는 필요한 분석을 위해 자체 규칙을 생성할 수 있습니다.
최신 바이너리는 [download page](https://superanalyzer.rocks/download.html)에서 다운로드하세요.
```
super-analyzer {apk_file}
```
### [StaCoAn](https://github.com/vincentcox/StaCoAn)
![](<../../images/image (297).png>)
StaCoAn은 모바일 애플리케이션에 대한 [static code analysis](https://en.wikipedia.org/wiki/Static_program_analysis)을 수행하는 개발자, bugbounty hunters 및 ethical hackers를 돕는 크로스플랫폼 도구입니다.
개념은 모바일 애플리케이션 파일(.apk 또는 .ipa 파일)을 StaCoAn 애플리케이션에 드래그 앤 드롭하면 시각적이고 휴대 가능한 보고서를 생성해 준다는 것입니다. 설정과 wordlists를 조정하여 맞춤형 경험을 얻을 수 있습니다.
다운로드[ latest release](https://github.com/vincentcox/StaCoAn/releases):
```
./stacoan
```
### [AndroBugs](https://github.com/AndroBugs/AndroBugs_Framework)
AndroBugs Framework는 Android 취약점 분석 시스템으로, 개발자나 hackers가 Android 애플리케이션의 잠재적 보안 취약점을 찾는 데 도움을 줍니다.\
[Windows releases](https://github.com/AndroBugs/AndroBugs_Framework/releases)
```
python androbugs.py -f [APK file]
androbugs.exe -f [APK file]
```
### [Androwarn](https://github.com/maaaaz/androwarn)
**Androwarn**는 Android 애플리케이션이 수행할 수 있는 잠재적 악성 동작을 탐지하고 사용자에게 경고하는 것을 주요 목적으로 하는 도구입니다.
탐지는 애플리케이션의 Dalvik bytecode가 **Smali**로 표현된 것에 대해 [`androguard`](https://github.com/androguard/androguard) 라이브러리를 사용한 **static analysis**로 수행됩니다.
이 도구는 Telephony identifiers exfiltration, Audio/video flow interception, PIM data modification, Arbitrary code execution...과 같은 **"bad" 애플리케이션의 일반적인 동작**을 찾아냅니다.
```
python androwarn.py -i my_application_to_be_analyzed.apk -r html -v 3
```
### [MARA Framework](https://github.com/xtiankisutsa/MARA_Framework)
![](<../../images/image (595).png>)
**MARA**는 **M**obile **A**pplication **R**everse engineering 및 **A**nalysis 프레임워크입니다. 이 도구는 일반적으로 사용되는 모바일 애플리케이션 리버스 엔지니어링 및 분석 도구들을 하나로 모아, OWASP 모바일 보안 위협에 대비해 모바일 애플리케이션을 테스트하는 데 도움을 줍니다. 목표는 이 작업을 모바일 애플리케이션 개발자와 보안 전문가에게 더 쉽고 친숙하게 만드는 것입니다.
다음 작업을 수행할 수 있습니다:
- 다양한 도구를 사용해 Java 및 Smali 코드를 추출합니다
- 다음 도구들을 사용해 APK를 분석합니다: [smalisca](https://github.com/dorneanu/smalisca), [ClassyShark](https://github.com/google/android-classyshark), [androbugs](https://github.com/AndroBugs/AndroBugs_Framework), [androwarn](https://github.com/maaaaz/androwarn), [APKiD](https://github.com/rednaga/APKiD)
- regexps를 사용하여 APK에서 개인 정보를 추출합니다.
- Manifest를 분석합니다.
- 발견된 도메인을 다음 도구들로 분석합니다: [pyssltest](https://github.com/moheshmohan/pyssltest), [testssl](https://github.com/drwetter/testssl.sh) and [whatweb](https://github.com/urbanadventurer/WhatWeb)
- APK의 난독화를 [apk-deguard.com](http://www.apk-deguard.com) 을 통해 해제할 수 있습니다
### Koodous
악성코드 탐지에 유용: [https://koodous.com/](https://koodous.com/)
## 코드 난독화/난독화 해제
코드를 난독화하는 데 사용하는 서비스와 구성에 따라 시크릿이 난독화되거나 그렇지 않을 수 있다는 점에 유의하세요.
### [ProGuard](<https://en.wikipedia.org/wiki/ProGuard_(software)>)
From [Wikipedia](<https://en.wikipedia.org/wiki/ProGuard_(software)>): **ProGuard**는 Java 코드를 축소(shrink), 최적화(optimize) 및 난독화(obfuscate)하는 오픈 소스 명령줄 도구입니다. 바이트코드를 최적화하고 사용되지 않는 명령을 탐지 및 제거할 수 있습니다. ProGuard는 무료 소프트웨어이며 GNU General Public License 버전 2 하에 배포됩니다.
ProGuard는 Android SDK의 일부로 배포되며 애플리케이션을 릴리스 모드로 빌드할 때 실행됩니다.
### [DexGuard](https://www.guardsquare.com/dexguard)
APK 난독화 해제에 대한 단계별 가이드는 [https://blog.lexfo.fr/dexguard.html](https://blog.lexfo.fr/dexguard.html)에서 확인하세요.
(해당 가이드에서) 마지막으로 확인했을 때, Dexguard의 동작 방식은 다음과 같았습니다:
- 리소스를 InputStream으로 로드합니다;
- 결과를 FilterInputStream을 상속한 클래스에 전달하여 복호화합니다;
- 리버서의 시간을 몇 분 낭비시키기 위해 불필요한 난독화 작업을 합니다;
- 복호화된 결과를 ZipInputStream에 전달하여 DEX 파일을 얻습니다;
- 마지막으로 `loadDex` 메서드를 사용해 생성된 DEX를 Resource로 로드합니다.
### [DeGuard](http://apk-deguard.com)
**DeGuard는 Android 난독화 도구가 수행한 난독화 과정을 역전시킵니다. 이를 통해 코드 검사 및 라이브러리 예측 등 다양한 보안 분석이 가능해집니다.**
난독화된 APK를 해당 플랫폼에 업로드할 수 있습니다.
### [Deobfuscate android App]https://github.com/In3tinct/deobfuscate-android-app
이 도구는 LLM을 사용해 android 앱의 잠재적 보안 취약점을 찾고 android 앱 코드를 난독화 해제하는 도구입니다. Google의 Gemini public API를 사용합니다.
### [Simplify](https://github.com/CalebFenton/simplify)
이는 **범용 android 난독화 해제기**입니다. Simplify는 앱을 **가상으로 실행**하여 동작을 이해한 뒤, 동작은 동일하게 유지하면서 사람이 이해하기 쉽게 **코드를 최적화하려고 시도합니다**. 각 최적화 유형은 단순하고 일반적이므로 특정 난독화 기법이 무엇인지에 상관없이 적용됩니다.
### [APKiD](https://github.com/rednaga/APKiD)
APKiD는 **APK가 어떻게 만들어졌는지**에 대한 정보를 제공합니다. 많은 **컴파일러**, **패커**, **난독화 도구**, 기타 이상한 것들을 식별합니다. Android용 [_PEiD_](https://www.aldeid.com/wiki/PEiD)입니다.
### Manual
[Read this tutorial to learn some tricks on **how to reverse custom obfuscation**](manual-deobfuscation.md)
## 실습
### [Androl4b](https://github.com/sh4hin/Androl4b)
AndroL4b는 ubuntu-mate 기반의 Android 보안 가상 머신으로, 리버스 엔지니어링 및 맬웨어 분석을 위한 다양한 보안 전문가와 연구자들의 최신 프레임워크, 튜토리얼 및 실습 모음을 포함합니다.
## 참고자료
- [https://owasp.org/www-project-mobile-app-security/](https://owasp.org/www-project-mobile-app-security/)
- [https://appsecwiki.com/#/](https://appsecwiki.com/#/) 좋은 자료 모음입니다
- [https://maddiestone.github.io/AndroidAppRE/](https://maddiestone.github.io/AndroidAppRE/) Android 빠른 강좌
- [https://manifestsecurity.com/android-application-security/](https://manifestsecurity.com/android-application-security/)
- [https://github.com/Ralireza/Android-Security-Teryaagh](https://github.com/Ralireza/Android-Security-Teryaagh)
- [https://www.youtube.com/watch?v=PMKnPaGWxtg&feature=youtu.be&ab_channel=B3nacSec](https://www.youtube.com/watch?v=PMKnPaGWxtg&feature=youtu.be&ab_channel=B3nacSec)
- [SSLPinDetect: Advanced SSL Pinning Detection for Android Security Analysis](https://petruknisme.medium.com/sslpindetect-advanced-ssl-pinning-detection-for-android-security-analysis-1390e9eca097)
- [SSLPinDetect GitHub](https://github.com/aancw/SSLPinDetect)
- [smali-sslpin-patterns](https://github.com/aancw/smali-sslpin-patterns)
- [Build a Repeatable Android Bug Bounty Lab: Emulator vs Magisk, Burp, Frida, and Medusa](https://www.yeswehack.com/learn-bug-bounty/android-lab-mobile-hacking-tools)
- [CoRPhone — Android in-memory JNI execution and packaging pipeline](https://github.com/0xdevil/corphone)
{{#include ../../banners/hacktricks-training.md}}