Android 애플리케이션 Pentesting

Reading time: 35 minutes

tip

AWS 해킹 배우기 및 연습하기:HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 배우기 및 연습하기: HackTricks Training GCP Red Team Expert (GRTE) Azure 해킹 배우기 및 연습하기: HackTricks Training Azure Red Team Expert (AzRTE)

HackTricks 지원하기

Android 애플리케이션 기본

이 페이지를 먼저 읽어 Android 보안과 Android 애플리케이션에서 가장 위험한 구성 요소와 관련된 가장 중요한 부분을 아는 것을 강력히 권장합니다:

Android Applications Basics

ADB (Android Debug Bridge)

This is the main tool you need to connect to an android device (emulated or physical).
ADB를 사용하면 컴퓨터에서 USB 또는 Network을 통해 장치를 제어할 수 있습니다. 이 유틸리티는 파일을 양방향으로 복사하고, 앱의 설치제거, shell 명령의 실행, 데이터의 백업, 로그의 읽기 등 여러 기능을 제공합니다.

Take a look to the following list of ADB Commands to learn how to use adb.

Smali

Sometimes it is interesting to modify the application code to access hidden information (maybe well obfuscated passwords or flags). Then, it could be interesting to decompile the apk, modify the code and recompile it.
In this tutorial you can learn how to decompile and APK, modify Smali code and recompile the APK with the new functionality. 이는 향후 진행될 dynamic analysis 중 여러 테스트에 대한 대안으로 매우 유용할 수 있습니다. 따라서 이 가능성을 항상 염두에 두세요.

Other interesting tricks

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
  • 모든 splits 및 base apks를 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

사례 연구 및 취약점

Air Keyboard Remote Input Injection

Android Rooting Frameworks Manager Auth Bypass Syscall Hook

Static Analysis

First of all, for analysing an APK you should take a look to the to the Java code using a decompiler.
Please, read here to find information about different available decompilers.

Looking for interesting Info

Just taking a look to the strings of the APK you can search for passwords, URLs (https://github.com/ndelphit/apkurlgrep), api keys, encryption, bluetooth uuids, tokens and anything interesting... look even for code execution backdoors or authentication backdoors (hardcoded admin credentials to the app).

Firebase

Pay special attention to firebase URLs and check if it is bad configured. More information about whats is FIrebase and how to exploit it here.

Basic understanding of the application - Manifest.xml, strings.xml

The examination of an application's Manifest.xml and strings.xml files can reveal potential security vulnerabilities. These files can be accessed using decompilers or by renaming the APK file extension to .zip and then unzipping it.

Vulnerabilities identified from the Manifest.xml include:

  • Debuggable Applications: Applications set as debuggable (debuggable="true") in the Manifest.xml file pose a risk as they allow connections that can lead to exploitation. For further understanding on how to exploit debuggable applications, refer to a tutorial on finding and exploiting debuggable applications on a device.
  • Backup Settings: The android:allowBackup="false" attribute should be explicitly set for applications dealing with sensitive information to prevent unauthorized data backups via adb, especially when usb debugging is enabled.
  • Network Security: Custom network security configurations (android:networkSecurityConfig="@xml/network_security_config") in res/xml/ can specify security details like certificate pins and HTTP traffic settings. An example is allowing HTTP traffic for specific domains.
  • Exported Activities and Services: Identifying exported activities and services in the manifest can highlight components that might be misused. Further analysis during dynamic testing can reveal how to exploit these components.
  • Content Providers and FileProviders: Exposed content providers could allow unauthorized access or modification of data. The configuration of FileProviders should also be scrutinized.
  • Broadcast Receivers and URL Schemes: These components could be leveraged for exploitation, with particular attention to how URL schemes are managed for input vulnerabilities.
  • SDK Versions: The minSdkVersion, targetSDKVersion, and maxSdkVersion attributes indicate the supported Android versions, highlighting the importance of not supporting outdated, vulnerable Android versions for security reasons.

From the strings.xml file, sensitive information such as API keys, custom schemas, and other developer notes can be discovered, underscoring the need for careful review of these resources.

Tapjacking

Tapjacking is an attack where a malicious application is launched and positions itself on top of a victim application. Once it visibly obscures the victim app, its user interface is designed in such a way as to trick the user to interact with it, while it is passing the interaction along to the victim app.
In effect, it is blinding the user from knowing they are actually performing actions on the victim app.

Find more information in:

Tapjacking

Task Hijacking

An activity with the launchMode set to singleTask without any taskAffinity defined is vulnerable to task Hijacking. This means, that an application can be installed and if launched before the real application it could hijack the task of the real application (so the user will be interacting with the malicious application thinking he is using the real one).

More info in:

Android Task Hijacking

Insecure data storage

Internal Storage

In Android, files stored in internal storage are designed to be accessible exclusively by the app that created them. This security measure is enforced by the Android operating system and is generally adequate for the security needs of most applications. However, developers sometimes utilize modes such as MODE_WORLD_READABLE and MODE_WORLD_WRITABLE to allow files to be shared between different applications. Yet, these modes do not restrict access to these files by other applications, including potentially malicious ones.

  1. Static Analysis:
  • Ensure that the use of MODE_WORLD_READABLE and MODE_WORLD_WRITABLE is carefully scrutinized. These modes can potentially expose files to unintended or unauthorized access.
  1. Dynamic Analysis:
  • Verify the permissions set on files created by the app. Specifically, check if any files are set to be readable or writable worldwide. This can pose a significant security risk, as it would allow any application installed on the device, regardless of its origin or intent, to read or modify these files.

External Storage

When dealing with files on external storage, such as SD Cards, certain precautions should be taken:

  1. Accessibility:
  • Files on external storage are globally readable and writable. This means any application or user can access these files.
  1. Security Concerns:
  • Given the ease of access, it's advised not to store sensitive information on external storage.
  • External storage can be removed or accessed by any application, making it less secure.
  1. Handling Data from External Storage:
  • Always perform input validation on data retrieved from external storage. This is crucial because the data is from an untrusted source.
  • Storing executables or class files on external storage for dynamic loading is strongly discouraged.
  • If your application must retrieve executable files from external storage, ensure these files are signed and cryptographically verified before they are dynamically loaded. This step is vital for maintaining the security integrity of your application.

External storage can be accessed in /storage/emulated/0 , /sdcard , /mnt/sdcard

tip

Starting with Android 4.4 (API 17), the SD card has a directory structure which limits access from an app to the directory which is specifically for that app. This prevents malicious application from gaining read or write access to another app's files.

Sensitive data stored in clear-text

  • Shared preferences: Android allow to each application to easily save xml files in the path /data/data/<packagename>/shared_prefs/ and sometimes it's possible to find sensitive information in clear-text in that folder.
  • Databases: Android allow to each application to easily save sqlite databases in the path /data/data/<packagename>/databases/ and sometimes it's possible to find sensitive information in clear-text in that folder.

Broken TLS

Accept All Certificates

For some reason sometimes developers accept all the certificates even if for example the hostname does not match with lines of code like the following one:

java
SSLSocketFactory sf = new cc(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

좋은 테스트 방법은 Burp 같은 프록시를 사용하여 트래픽을 캡처해보되, 디바이스 내부에 Burp CA를 인증하지 않는 것입니다. 또한 Burp로 다른 hostname에 대한 certificate를 생성해 사용해 볼 수도 있습니다.

취약한 암호화

부적절한 키 관리 프로세스

일부 개발자는 민감한 데이터를 로컬 스토리지에 저장하고 코드에 하드코딩되었거나 예측 가능한 키로 암호화합니다. 이는 리버싱을 통해 공격자가 기밀 정보를 추출할 수 있으므로 해서는 안 됩니다.

안전하지 않거나/또는 폐기된 알고리즘의 사용

개발자는 권한 확인, 데이터의 저장 또는 전송에 폐기된 알고리즘을 사용해서는 안 됩니다. 예로 RC4, MD4, MD5, SHA1 등이 있습니다. 예를 들어 비밀번호 저장에 해시를 사용할 경우, salt와 함께 브루트포스에 저항하는 해시 함수를 사용해야 합니다.

기타 확인 사항

  • 역공학 작업을 어렵게 하기 위해 APK를 난독화하는 것을 권장합니다.
  • 앱이 민감한 성격(예: bank apps)이라면 디바이스가 루팅(rooted) 되었는지 자체적으로 검사하고 그에 따라 동작해야 합니다.
  • 앱이 민감한 성격(예: bank apps)이라면 에뮬레이터가 사용되는지 검사해야 합니다.
  • 앱이 민감한 성격(예: bank apps)이라면 실행 전에 스스로의 무결성(integrity)을 검사하여 수정되었는지 확인해야 합니다.
  • APKiD를 사용하여 어떤 compiler/packer/obfuscator가 APK 빌드에 사용되었는지 확인하세요

React Native Application

React 애플리케이션의 javascript 코드를 쉽게 접근하는 방법은 다음 페이지를 참고하세요:

React Native Application

Xamarin Applications

Xamarin 애플리케이션의 C# 코드에 쉽게 접근하는 방법은 다음 페이지를 참고하세요:

Xamarin Apps

Superpacked Applications

blog post에 따르면 superpacked는 애플리케이션의 내용을 단일 파일로 압축하는 Meta 알고리즘입니다. 블로그는 이러한 앱을 압축 해제하는 앱을 만드는 가능성에 대해 이야기하며... 파일 시스템에서 압축 해제된 파일을 수집하기 위해 애플리케이션을 실행하여 수집하는 더 빠른 방법을 언급합니다.

Automated Static Code Analysis

도구 mariana-trench는 애플리케이션의 코드스캔하여 취약점(vulnerabilities) 을 찾을 수 있습니다. 이 도구는 known sources(도구에 입력사용자에 의해 제어되는 위치를 알려주는 것), sinks(악의적 입력이 피해를 줄 수 있는 위험한 위치) 및 rules의 집합을 포함합니다. 이러한 규칙은 취약점을 나타내는 sources-sinks 조합을 지정합니다.

이 지식을 바탕으로 mariana-trench는 코드를 검토하고 가능한 취약점을 찾아냅니다.

Secrets leaked

애플리케이션에는 API 키, 비밀번호, 숨겨진 URL, 서브도메인 등과 같은 secrets가 포함되어 있을 수 있으며, 이를 발견할 수 있습니다. 다음과 같은 도구를 사용할 수 있습니다: https://github.com/dwisiswant0/apkleaks

Bypass Biometric Authentication

Bypass Biometric Authentication (Android)

기타 흥미로운 함수

  • Code execution: Runtime.exec(), ProcessBuilder(), native code:system()
  • Send SMSs: sendTextMessage, sendMultipartTestMessage
  • Native functions declared as native: public native, System.loadLibrary, System.load
  • 리버스 네이티브 함수를 배우려면 여기 읽기
  • JNI를 통한 메모리 내 네이티브 코드 실행(다운로드된 shellcode → mmap/mprotect → 호출):

In Memory Jni Shellcode Execution

기타 트릭

content:// protocol



Dynamic Analysis

우선 애플리케이션을 설치하고 필요한 환경(Burp CA cert, Drozer and Frida 등)을 구성할 수 있는 환경이 필요합니다. 따라서 루팅된 디바이스(에뮬레이터든 실제든)가 강력히 권장됩니다.

Online Dynamic analysis

다음에서 무료 계정을 만들 수 있습니다: https://appetize.io/. 이 플랫폼은 APK를 업로드하고 실행할 수 있게 해주므로, APK가 어떻게 동작하는지 확인하는 데 유용합니다.

웹에서 애플리케이션의 로그를 확인하고 adb로 연결할 수도 있습니다.

ADB 연결 덕분에 에뮬레이터 내부에서 DrozerFrida를 사용할 수 있습니다.

Local Dynamic Analysis

Using an emulator

  • Android Studio (x86 및 arm 디바이스를 생성할 수 있으며, this 최신 x86 버전들은 느린 arm 에뮬레이터 없이도 ARM 라이브러리를 지원합니다).
  • 설정 방법은 다음 페이지를 참고하세요:

AVD - Android Virtual Device

  • Genymotion (무료 버전: Personal Edition, 계정 생성 필요. 잠재적 오류를 피하기 위해 VirtualBox 포함 버전을 다운로드하는 것을 권장합니다.)
  • Nox (무료, 다만 Frida나 Drozer는 지원하지 않습니다).

tip

어떤 플랫폼에서 새 에뮬레이터를 만들 때 화면이 클수록 에뮬레이터가 느려집니다. 가능하면 작은 화면을 선택하세요.

Genymotion에 google services(예: AppStore)를 설치하려면 다음 이미지의 빨간 표시 버튼을 클릭해야 합니다:

또한 Genymotion의 Android VM 설정에서 Bridge Network mode를 선택할 수 있다는 점을 유의하세요(다른 VM에서 도구로 Android VM에 접속할 경우 유용합니다).

Use a physical device

디버깅 옵션을 활성화해야 하며, 가능하면 루트(root) 권한을 얻는 것이 좋습니다:

  1. Settings.
  2. (FromAndroid 8.0) System 선택.
  3. About phone 선택.
  4. Build number를 7번 누르기.
  5. 뒤로 가면 Developer options가 나타납니다.

애플리케이션을 설치한 후 가장 먼저 해야 할 일은 앱을 실행해보고 무엇을 하는지, 어떻게 동작하는지 파악하여 익숙해지는 것입니다.
초기 동적 분석은 MobSF dynamic analysis + pidcat를 사용하여 수행할 것을 권장합니다. 이렇게 하면 MobSF가 나중에 검토할 수 있는 많은 흥미로운 데이터를 캡처하는 동안 애플리케이션의 동작을 배울 수 있습니다.

Magisk/Zygisk 간단 노트 (Pixel 기기 권장)

  • Magisk 앱으로 boot.img를 패치하고 fastboot로 플래시하여 systemless root 획득
  • Zygisk + DenyList 활성화로 루트 숨기기; 더 강력한 숨김이 필요하면 LSPosed/Shamiko 고려
  • OTA 업데이트에서 복구할 수 있도록 원본 boot.img 보관; OTA 후 재패치 필요
  • 화면 미러링은 호스트에서 scrcpy 사용

의도치 않은 데이터 leak

로깅

개발자는 디버깅 정보를 공개적으로 노출하는 것을 주의해야 하며, 이는 민감한 데이터의 leak로 이어질 수 있습니다. 애플리케이션 로그를 모니터링하여 민감한 정보를 식별하고 보호하기 위해 pidcatadb logcat 도구를 권장합니다. Pidcat은 사용의 용이성과 가독성 때문에 선호됩니다.

warning

Android 4.0 이후 버전들부터 애플리케이션은 자신의 로그만 접근할 수 있습니다. 따라서 다른 앱의 로그에는 접근할 수 없습니다.
어쨌든 민감한 정보를 로그에 남기지 않는 것이 여전히 권장됩니다.

복사/붙여넣기 버퍼 캐싱

Android의 클립보드 기반 프레임워크는 앱 간 복사-붙여넣기 기능을 가능하게 하지만, 다른 애플리케이션이 클립보드에 접근할 수 있어 민감한 데이터를 노출할 위험이 있습니다. 신용카드 정보와 같은 민감한 섹션에 대해서는 복사/붙여넣기 기능을 비활성화하는 것이 중요합니다.

크래시 로그

애플리케이션이 크래시하고 로그를 저장하는 경우, 이러한 로그는 특히 애플리케이션을 리버스할 수 없을 때 공격자에게 도움이 될 수 있습니다. 이 위험을 완화하려면 크래시 시 로그를 남기지 말고, 네트워크로 로그를 전송해야 한다면 반드시 SSL 채널을 통해 전송하세요.

As pentester, 이러한 로그들을 확인해 보세요.

서드파티로 전송되는 Analytics 데이터

애플리케이션은 종종 Google Adsense와 같은 서비스를 통합하는데, 잘못된 구현으로 인해 민감한 데이터가 제3자에게 leak될 수 있습니다. 잠재적 데이터 leak를 식별하려면 애플리케이션의 트래픽을 가로채고 제3자 서비스로 전송되는 민감한 정보가 있는지 확인하는 것이 좋습니다.

SQLite DBs

대부분의 애플리케이션은 정보를 저장하기 위해 내부 SQLite 데이터베이스를 사용합니다. 펜테스트 동안 생성된 데이터베이스, 테이블컬럼 이름, 저장된 모든 데이터를 살펴보세요. 민감한 정보를 찾을 수 있으며 이는 취약점이 될 수 있습니다.
데이터베이스는 /data/data/the.package.name/databases에 위치해야 하며 예: /data/data/com.mwr.example.sieve/databases

데이터베이스가 기밀 정보를 저장하고 있고 암호화되어 있더라도비밀번호를 애플리케이션 내부에서 찾을 수 있다면 여전히 취약점입니다.

.tables로 테이블을 나열하고 .schema <table_name>으로 테이블의 컬럼을 나열하세요.

Drozer (Exploit Activities, Content Providers and Services)

From Drozer Docs: Drozer를 사용하면 Android 앱의 역할을 맡아 다른 앱과 상호작용할 수 있습니다. 설치된 애플리케이션이 할 수 있는 모든 것을 수행할 수 있으며, Android의 Inter-Process Communication (IPC) 메커니즘을 이용하고 기저 운영체제와 상호작용할 수 있습니다. .
Drozer는 수출된(exported) activities, exported services 및 Content Providers를 공격(exploit) 하는 데 유용한 도구입니다. 다음 섹션에서 학습하게 될 것입니다.

Exploiting exported Activities

Android Activity가 무엇인지 복습하고 싶다면 이 글을 읽으세요.
또한 Activity의 코드는 onCreate 메서드에서 시작된다는 것을 기억하세요.

Authorisation bypass

Activity가 exported 상태일 때 외부 앱에서 해당 화면을 호출할 수 있습니다. 따라서 민감한 정보를 포함하는 Activity가 exported 되어 있다면 인증을 우회하여 접근할 수 있습니다.

Drozer로 exported 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

NOTE: MobSF는 activity에서 android:launchMode로 _singleTask/singleInstance_를 사용하는 것을 악성으로 탐지합니다, 그러나 this 때문에, 이는 구버전(API versions < 21)에서만 위험한 것으로 보입니다.

tip

authorisation bypass가 항상 vulnerability인 것은 아니며, bypass가 어떻게 동작하는지와 어떤 정보가 노출되는지에 따라 달라집니다.

Sensitive information leakage

Activities는 결과를 반환할 수도 있습니다. exported되고 unprotected한 activity가 setResult 메서드를 호출하며 민감한 정보를 반환하는 것을 찾으면, sensitive information leakage가 발생합니다.

Tapjacking

Tapjacking이 방지되지 않으면, exported된 activity를 악용해 사용자에게 예기치 않은 동작을 수행하게 만들 수 있습니다. 자세한 내용은 what is Tapjacking follow the link를 참조하세요.

Exploiting Content Providers - 민감한 정보 접근 및 조작

Read this if you want to refresh what is a Content Provider.
Content providers는 기본적으로 데이터를 공유하기 위해 사용됩니다. 앱에 사용 가능한 content providers가 있으면 그들로부터 민감한 데이터를 추출할 수 있을지도 모릅니다. 또한 취약할 수 있으므로 가능한 SQL injectionsPath Traversals도 테스트하는 것이 흥미롭습니다.

Learn how to exploit Content Providers with Drozer.

Exploiting Services

Read this if you want to refresh what is a Service.
Service의 동작은 onStartCommand 메서드에서 시작된다는 점을 기억하세요.

Service는 기본적으로 데이터를 수신하고, 처리하며(또는 그렇지 않을 수 있고) 응답을 반환할 수 있는 것입니다. 따라서 애플리케이션이 일부 서비스를 export하고 있다면 무엇을 하는지 이해하기 위해 코드를 확인하고, 기밀 정보를 추출하거나 인증 우회 등 목적으로 동적으로 테스트해야 합니다.
Learn how to exploit Services with Drozer.

Exploiting Broadcast Receivers

Read this if you want to refresh what is a Broadcast Receiver.
Broadcast Receiver의 동작은 onReceive 메서드에서 시작된다는 점을 기억하세요.

Broadcast receiver는 특정 유형의 메시지를 기다립니다. 리시버가 메시지를 처리하는 방식에 따라 취약할 수 있습니다.
Learn how to exploit Broadcast Receivers with Drozer.

MobSF 같은 도구나 this one 같은 스크립트를 사용해 deep links를 수동으로 찾아볼 수 있습니다.
선언된 schemeadb나 브라우저로 열 수 있습니다:

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 를 검색하세요.

민감한 정보

deep link를 찾을 때마다 URL parameters를 통해 비밀번호 같은 민감한 데이터를 수신하지 않는지 확인해야 합니다. 그렇지 않으면 다른 어떤 애플리케이션이라도 해당 deep link를 가장해 그 데이터를 탈취할 수 있습니다!

Parameters in path

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 등을 유발할 수 있으며 다른 여러 취약점이 발생할 수 있습니다. 자세한 내용은 info about this here를 참조하세요.

More examples

An interesting bug bounty report about links (/.well-known/assetlinks.json).

전송 계층 검사 및 검증 실패

  • Certificates가 항상 제대로 검사되는 것은 아닙니다. Android 애플리케이션이 경고를 무시하고 self-signed certificates를 수용하거나, 경우에 따라 HTTP 연결로 되돌아가는 경우가 흔합니다.
  • SSL/TLS 핸드셰이크 중 협상이 약한 경우가 있습니다, 취약한 cipher suites를 사용하는 경우가 있어 연결이 man-in-the-middle (MITM) 공격에 노출되어 공격자가 데이터를 복호화할 수 있습니다.
  • Leakage of private information 은 애플리케이션이 일부는 보안 채널로 인증하고 다른 트랜잭션은 비암호화 채널로 통신할 때 위험합니다. 이러한 접근 방식은 세션 쿠키나 사용자 정보와 같은 민감한 데이터를 악의적인 제3자가 가로채는 것으로부터 보호하지 못합니다.

인증서 검증

우리는 certificate verification 에 중점을 둘 것입니다. 서버 인증서의 무결성을 검증하는 것은 보안을 강화하는 데 필수적입니다. 불안전한 TLS 구성과 민감한 데이터의 비암호화 채널 전송은 심각한 위험을 초래할 수 있습니다. 서버 인증서를 검증하고 취약점을 해결하는 방법에 대한 자세한 단계는 this resource를 참고하세요.

SSL Pinning

SSL Pinning은 애플리케이션이 서버의 인증서를 애플리케이션 내부에 저장된 알려진 복사본과 대조하여 검증하는 보안 수단입니다. 이 방법은 MITM 공격을 방지하는 데 필수적입니다. 민감한 정보를 다루는 애플리케이션에는 SSL Pinning의 구현을 강력히 권장합니다.

트래픽 검사

HTTP 트래픽을 검사하려면 프록시 도구의 인증서(예: Burp)를 설치해야 합니다. 이 인증서를 설치하지 않으면 암호화된 트래픽이 프록시를 통해 보이지 않을 수 있습니다. 커스텀 CA 인증서 설치 가이드는 click here를 참고하세요.

API Level 24 and above 를 대상으로 하는 애플리케이션은 프록시의 CA 인증서를 수락하도록 Network Security Config 수정을 필요로 합니다. 이 단계는 암호화된 트래픽을 검사하는 데 중요합니다. Network Security Config를 수정하는 방법은 refer to this tutorial를 참조하세요.

If Flutter 를 사용하는 경우 this page의 지침을 따라야 합니다. 단순히 인증서를 스토어에 추가하는 것만으로는 작동하지 않으며, Flutter는 자체적인 유효한 CA 목록을 가지고 있기 때문입니다.

Static detection of SSL/TLS pinning

런타임 우회 시도를 하기 전에 APK에서 핀닝이 강제되는 위치를 빠르게 매핑하세요. 정적 탐지는 훅/패치 계획을 세우고 올바른 코드 경로에 집중하는 데 도움이 됩니다.

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.

Install

  • 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) signatures를 사용하거나 확장하여 독점/커스텀 pinning 스타일을 탐지하세요. 자신의 JSON을 로드하여 대규모로 스캔할 수 있습니다.

json
{
"OkHttp Certificate Pinning": [
"Lcom/squareup/okhttp/CertificatePinner;",
"Lokhttp3/CertificatePinner;",
"setCertificatePinner"
],
"TrustManager Override": [
"Ljavax/net/ssl/X509TrustManager;",
"checkServerTrusted"
]
}

Notes and tips

  • 대규모 앱을 멀티스레딩 및 memory-mapped I/O로 빠르게 스캔; 미리 컴파일된 regex는 오버헤드와 false positives를 줄입니다.
  • Pattern collection: https://github.com/aancw/smali-sslpin-patterns
  • 다음으로 확인할 일반적인 탐지 대상:
  • OkHttp: CertificatePinner usage, setCertificatePinner, okhttp3/okhttp package references
  • Custom TrustManagers: javax.net.ssl.X509TrustManager, checkServerTrusted overrides
  • Custom SSL contexts: SSLContext.getInstance + SSLContext.init with custom managers
  • res/xml의 network security config 및 manifest 참조에 선언된 pins
  • 일치한 위치를 사용해 Frida hooks, static patches 또는 구성 검토를 동적 테스트 전에 계획하세요.

SSL Pinning 우회

애플리케이션에 SSL Pinning이 구현되어 있으면 HTTPS 트래픽을 조사하기 위해 이를 우회해야 합니다. 이를 위한 다양한 방법이 있습니다:

  • 자동으로 apk수정하여 SSLPinning우회하려면 apk-mitm을 사용하세요. 이 옵션의 가장 큰 장점은 SSL Pinning을 우회하는 데 root가 필요 없다는 점이지만, 애플리케이션을 삭제하고 새로 설치해야 하며 항상 작동하지는 않습니다.
  • 이 보호를 우회하려면 Frida(아래에서 설명)를 사용할 수 있습니다. Burp+Frida+Genymotion을 사용하는 가이드는 다음을 참고하세요: https://spenkk.github.io/bugbounty/Configuring-Frida-with-Burp-and-GenyMotion-to-bypass-SSL-Pinning/
  • objection를 사용해 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

일반적인 웹 취약점 검색

애플리케이션 내에서 일반적인 웹 취약점을 찾아보는 것도 중요합니다. 이러한 취약점을 식별하고 완화하는 자세한 정보는 이 요약의 범위를 벗어나지만 다른 곳에 광범위하게 다루어져 있습니다.

Frida

Frida 는 개발자, 리버스 엔지니어, 보안 연구원을 위한 동적 계측 도구입니다.
실행 중인 애플리케이션에 접근해 런타임에 메서드를 훅하여 동작을 변경하고, 값을 변경하거나 추출하고, 다른 코드를 실행할 수 있습니다.
Android 애플리케이션을 pentest하려면 Frida 사용법을 알아야 합니다.

Anti-instrumentation & SSL pinning bypass workflow

Android Anti Instrumentation And Ssl Pinning Bypass

메모리 덤프 - Fridump

애플리케이션이 비밀번호나 니모닉처럼 저장해서는 안 되는 민감한 정보를 메모리에 저장하고 있는지 확인하세요.

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가 민감한 데이터를 저장하기에 가장 적합한 장소이지만, 충분한 권한이 있으면 여전히 접근할 수 있습니다. 애플리케이션은 종종 여기에 민감한 데이터를 clear text로 저장하는 경향이 있으므로, pentests는 root user로 이를 확인해야 합니다. 기기에 물리적으로 접근할 수 있는 사람이 이 데이터를 탈취할 수 있습니다.

앱이 keystore에 데이터를 저장하더라도, 그 데이터는 암호화되어야 합니다.

keystore 내부의 데이터에 접근하려면 다음 Frida script를 사용할 수 있습니다: 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 스크립트를 사용하면 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 Application Analyzer

이 도구는 dynamic analysis 동안 여러 도구를 관리하는 데 도움이 될 수 있습니다: https://github.com/NotSoSecure/android_application_analyzer

Intent Injection

개발자들은 종종 activities, services, broadcast receivers와 같은 프록시 컴포넌트를 만들어 이러한 Intents를 처리하고 startActivity(...) 또는 sendBroadcast(...) 같은 메서드로 전달합니다. 이는 위험할 수 있습니다.

위험은 공격자가 이러한 Intents를 오용하여 non-exported 앱 컴포넌트를 호출하거나 민감한 content providers에 접근하도록 허용하는 데 있습니다. 대표적인 예로 WebView 컴포넌트가 URL을 Intent.parseUri(...)로 Intent 객체로 변환한 뒤 실행하여 잠재적으로 악의적인 Intent injections로 이어질 수 있습니다.

Essential Takeaways

  • Intent Injection은 웹의 Open Redirect 문제와 유사합니다.
  • 익스플로잇은 Intent 객체를 extras로 전달하여 리디렉션 시켜 안전하지 않은 동작을 실행하도록 하는 것을 포함합니다.
  • 이것은 non-exported 컴포넌트 및 content providers를 공격자에게 노출시킬 수 있습니다.
  • WebView의 URL → Intent 변환은 의도치 않은 동작을 유발할 수 있습니다.

Android Client Side Injections and others

이러한 종류의 취약점은 웹에서 익숙할 것입니다. Android 애플리케이션에서는 특히 주의해야 합니다:

  • SQL Injection: 동적 쿼리나 Content-Providers를 다룰 때는 파라미터화된 쿼리를 사용하고 있는지 확인하세요.
  • JavaScript Injection (XSS): 모든 WebView에서 JavaScript 및 Plugin 지원이 비활성화되어 있는지 확인하세요(기본적으로 비활성화됨). More info here.
  • Local File Inclusion: WebViews는 파일 시스템에 대한 접근이 비활성화되어야 합니다(기본적으로 활성화됨) - (webview.getSettings().setAllowFileAccess(false);). More info here.
  • Eternal cookies: 여러 경우에 Android 애플리케이션이 세션을 종료할 때 쿠키가 취소되지 않거나 심지어 디스크에 저장될 수 있습니다
  • Secure Flag in cookies

Automatic Analysis

MobSF

정적 분석

깔끔한 웹 기반 프런트엔드를 통해 애플리케이션의 취약점 평가를 수행할 수 있습니다. dynamic analysis도 수행할 수 있지만 환경을 준비해야 합니다.

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).
또한 Android 또는 IOS 앱의 소스 코드를 포함한 ZIP 파일(애플리케이션 루트 폴더로 이동하여 전체를 선택하고 ZIPfile을 생성)을 제공하면 그것도 분석할 수 있습니다.

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.

MobSF를 이용한 보조적 동적 분석

MobSFAndroid에서의 dynamic analysis에도 매우 유용하지만, 이 경우 호스트에 MobSF와 genymotion을 설치해야 합니다(가상 머신이나 Docker는 작동하지 않습니다). 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 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").

또한, 다음과 같은 보조 Frida 기능들이 있습니다:

  • Enumerate Loaded Classes: 로드된 모든 클래스를 출력합니다.
  • Capture Strings: 애플리케이션 사용 중 캡처된 모든 문자열을 출력합니다(매우 노이즈가 큼).
  • Capture String Comparisons: 매우 유용할 수 있습니다. 비교되는 두 문자열을 보여주고 결과가 True인지 False인지 표시합니다.
  • Enumerate Class Methods: 클래스 이름(예: "java.io.File")을 입력하면 해당 클래스의 모든 메서드를 출력합니다.
  • Search Class Pattern: 패턴으로 클래스를 검색합니다.
  • Trace Class Methods: 전체 클래스를 Trace합니다(해당 클래스의 모든 메서드 입력과 출력을 확인). 기본적으로 MobSF는 여러 흥미로운 Android Api 메서드를 추적한다는 점을 기억하세요.

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는 dynamic analysis 페이지 하단에 몇 가지 adb 명령, MobSF commands, 그리고 일반적인 shell commands가 포함된 셸을 제공합니다. 흥미로운 몇 가지 명령:

bash
help
shell ls
activities
exported_activities
services
receivers

HTTP tools

HTTP 트래픽이 캡처되면 "HTTP(S) Traffic" 버튼(하단)에서 거친 뷰를 보거나 "Start HTTPTools" 녹색 버튼에서 더 보기 좋은 뷰를 볼 수 있습니다. 두 번째 옵션에서는 캡처된 요청을 Burp 또는 Owasp ZAP 같은 proxiessend할 수 있습니다.
그렇게 하려면 power on Burp --> turn off Intercept --> in MobSB HTTPTools select the request --> 버튼 "Send to Fuzzer"을 누른 다음 --> 프록시 주소를 선택 (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로 보조된 Dynamic Analysis

도구는 Inspeckage에서 받을 수 있습니다.
이 도구는 일부 Hooks를 사용하여 dynamic analysis를 수행하는 동안 애플리케이션에서 무슨 일이 일어나는지 알려줍니다.

Yaazhini

GUI로 static analysis를 수행하기에 훌륭한 도구입니다.

Qark

이 도구는 소스 코드 또는 packaged APKs에서 여러 보안 관련 Android application 취약점을 찾도록 설계되었습니다. 또한 이 도구는 "Proof-of-Concept" 배포 가능한 APKADB commands를 생성할 수 있어 발견된 일부 취약점(Exposed activities, intents, tapjacking...)을 악용할 수 있습니다. Drozer와 마찬가지로 테스트 기기를 루팅할 필요는 없습니다.

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

  • 참조하기 쉽도록 모든 추출된 파일을 표시
  • APK 파일을 자동으로 Java 및 Smali 형식으로 디컴파일
  • AndroidManifest.xml을 분석하여 일반적인 취약점 및 동작 파악
  • 일반적인 취약점 및 동작에 대한 정적 소스 코드 분석
  • 장치 정보
  • 그 외
bash
reverse-apk relative/path/to/APP.apk

SUPER Android Analyzer

SUPER는 Windows, MacOS X 및 Linux에서 사용할 수 있는 명령줄 애플리케이션으로, 취약점을 찾기 위해 .apk 파일을 분석합니다. 이 도구는 APK를 압축 해제한 후 일련의 규칙을 적용하여 이러한 취약점을 탐지합니다.

모든 규칙은 rules.json 파일에 집중되어 있으며, 각 회사나 테스터는 필요에 따라 자체 규칙을 만들어 분석할 수 있습니다.

최신 바이너리는 download page에서 다운로드하세요.

super-analyzer {apk_file}

StaCoAn

StaCoAn은 모바일 애플리케이션에서 static code analysis를 수행하는 개발자, bugbounty hunters 및 ethical hackers를 지원하는 crossplatform 도구입니다.

컨셉은 모바일 애플리케이션 파일(.apk 또는 .ipa 파일)을 StaCoAn 애플리케이션으로 드래그 앤 드롭하면 시각적이고 휴대 가능한 리포트를 생성해 주는 것입니다. 설정과 wordlists를 조정하여 맞춤형 경험을 얻을 수 있습니다.

다운로드 latest release:

./stacoan

AndroBugs

AndroBugs Framework는 개발자나 hackers가 Android 애플리케이션에서 잠재적인 보안 취약점을 찾는 데 도움을 주는 취약점 분석 시스템입니다.
Windows releases

python androbugs.py -f [APK file]
androbugs.exe -f [APK file]

Androwarn

Androwarn은 Android 애플리케이션이 일으킬 수 있는 잠재적 악성 행위를 탐지하고 사용자에게 경고하는 것을 주요 목적으로 하는 도구입니다.

탐지는 애플리케이션의 Dalvik bytecode(표현은 Smali)에 대한 static analysisandroguard 라이브러리를 사용하여 수행됩니다.

이 도구는 common behavior of "bad" applications(예: Telephony identifiers exfiltration, Audio/video flow interception, PIM data modification, Arbitrary code execution...)을 찾아냅니다.

python androwarn.py -i my_application_to_be_analyzed.apk -r html -v 3

MARA Framework

MARA is a Mobile Application Reverse engineering and Analysis Framework. 이 도구는 일반적으로 사용되는 모바일 애플리케이션 리버스 엔지니어링 및 분석 도구들을 모아, OWASP mobile security 위협에 대해 모바일 애플리케이션을 테스트하는 데 도움을 줍니다. 목표는 모바일 애플리케이션 개발자와 보안 전문가가 이 작업을 더 쉽고 친숙하게 수행할 수 있도록 하는 것입니다.

It is able to:

  • Java 및 Smali 코드를 다양한 도구로 추출
  • APK를 다음 도구들로 분석: smalisca, ClassyShark, androbugs, androwarn, APKiD
  • 정규표현식(regexps)을 사용해 APK에서 private information 추출
  • Manifest 분석
  • 발견된 도메인을 다음으로 분석: pyssltest, testsslwhatweb
  • [apk-deguard.com]을 통해 APK deobfuscate

Koodous

malware를 탐지하는 데 유용: https://koodous.com/

Obfuscating/Deobfuscating code

참고: 코드를 obfuscate하는 데 사용하는 서비스와 설정에 따라 Secrets는 obfuscated된 상태로 남을 수도 있고 그렇지 않을 수도 있습니다.

ProGuard

From Wikipedia: ProGuard는 Java 코드를 shrink, optimize 및 obfuscate하는 오픈 소스 command-line 도구입니다. bytecode를 최적화하고 사용되지 않는 명령을 감지하여 제거할 수 있습니다. ProGuard는 자유 소프트웨어이며 GNU General Public License, version 2에 따라 배포됩니다.

ProGuard는 Android SDK의 일부로 배포되며 release 모드로 애플리케이션을 빌드할 때 실행됩니다.

DexGuard

apk를 deobfuscate하는 단계별 가이드는 https://blog.lexfo.fr/dexguard.html에서 확인하세요.

(해당 가이드 발췌) 마지막으로 확인했을 때, Dexguard의 동작 방식은 다음과 같았습니다:

  • 리소스를 InputStream으로 로드;
  • 결과를 FilterInputStream을 상속한 클래스에 전달해 복호화;
  • 리버서의 시간을 몇 분 낭비시키기 위한 무의미한 obfuscation 수행;
  • 복호화된 결과를 ZipInputStream에 전달하여 DEX 파일 획득;
  • 마지막으로 결과 DEX를 loadDex 메서드를 사용해 Resource로 로드.

DeGuard

DeGuard는 Android obfuscation 도구들이 수행한 obfuscation 과정을 역전(reverse)시킵니다. 이를 통해 코드 검사(code inspection)와 라이브러리 예측(predicting libraries) 등 다양한 security analyses가 가능해집니다.

obfuscated된 APK를 플랫폼에 업로드할 수 있습니다.

[Deobfuscate android App]https://github.com/In3tinct/deobfuscate-android-app

LLM 도구로, android apps에서 잠재적인 security vulnerabilities를 찾고 android app 코드를 deobfuscate합니다. Google의 Gemini public API를 사용합니다.

Simplify

generic android deobfuscator입니다. Simplify는 앱을 virtually execute하여 동작을 이해한 후, 동작은 동일하지만 사람이 이해하기 쉽게 코드를 optimize하려고 시도합니다. 각 최적화 타입은 단순하고 generic하므로 사용된 특정 obfuscation 타입이 무엇인지와는 무관합니다.

APKiD

APKiD는 APK가 어떻게 만들어졌는지에 대한 정보를 제공합니다. 여러 compilers, packers, obfuscators 및 기타 이상한 것들을 식별합니다. Android용 PEiD입니다.

Manual

Read this tutorial to learn some tricks on how to reverse custom obfuscation

Labs

Androl4b

AndroL4b는 ubuntu-mate 기반의 Android security virtual machine으로, 최신 프레임워크, 튜토리얼 및 reverse engineering 및 malware analysis를 위한 다양한 연구자/공동체의 랩을 포함합니다.

References

tip

AWS 해킹 배우기 및 연습하기:HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 배우기 및 연습하기: HackTricks Training GCP Red Team Expert (GRTE) Azure 해킹 배우기 및 연습하기: HackTricks Training Azure Red Team Expert (AzRTE)

HackTricks 지원하기