Android Anti-Reversing Defenses

Testing Root Detection (MSTG-RESILIENCE-1)

Overview

In the context of anti-reversing, the goal of root detection is to make running the app on a rooted device a bit more difficult, which in turn blocks some of the tools and techniques reverse engineers like to use. Like most other defenses, root detection is not very effective by itself, but implementing multiple root checks that are scattered throughout the app can improve the effectiveness of the overall anti-tampering scheme.
For Android, we define "root detection" a bit more broadly, including custom ROMs detection, i.e., determining whether the device is a stock Android build or a custom build.

Common Root Detection Methods

In the following section, we list some common root detection methods you'll encounter. You'll find some of these methods implemented in the crackme examples that accompany the OWASP Mobile Testing Guide.
Root detection can also be implemented through libraries such as RootBeer.

SafetyNet

SafetyNet is an Android API that provides a set of services and creates profiles of devices according to software and hardware information. This profile is then compared to a list of accepted device models that have passed Android compatibility testing. Google recommends using the feature as "an additional in-depth defense signal as part of an anti-abuse system".
How exactly SafetyNet works is not well documented and may change at any time. When you call this API, SafetyNet downloads a binary package containing the device validation code provided from Google, and the code is then dynamically executed via reflection. An analysis by John Kozyrakis showed that SafetyNet also attempts to detect whether the device is rooted, but exactly how that's determined is unclear.
To use the API, an app may call the SafetyNetApi.attest method (which returns a JWS message with the Attestation Result) and then check the following fields:
  • ctsProfileMatch: If 'true', the device profile matches one of Google's listed devices.
  • basicIntegrity: If 'true', the device running the app likely hasn't been tampered with.
  • nonces: To match the response to its request.
  • timestampMs: To check how much time has passed since you made the request and you got the response. A delayed response may suggest suspicious activity.
  • apkPackageName, apkCertificateDigestSha256, apkDigestSha256: Provide information about the APK, which is used to verify the identity of the calling app. These parameters are absent if the API cannot reliably determine the APK information.
The following is a sample attestation result:
1
{
2
"nonce": "R2Rra24fVm5xa2Mg",
3
"timestampMs": 9860437986543,
4
"apkPackageName": "com.package.name.of.requesting.app",
5
"apkCertificateDigestSha256": ["base64 encoded, SHA-256 hash of the
6
certificate used to sign requesting app"],
7
"apkDigestSha256": "base64 encoded, SHA-256 hash of the app's APK",
8
"ctsProfileMatch": true,
9
"basicIntegrity": true,
10
}
Copied!
ctsProfileMatch Vs basicIntegrity
The SafetyNet Attestation API initially provided a single value called basicIntegrity to help developers determine the integrity of a device. As the API evolved, Google introduced a new, stricter check whose results appear in a value called ctsProfileMatch, which allows developers to more finely evaluate the devices on which their app is running.
In broad terms, basicIntegrity gives you a signal about the general integrity of the device and its API. Many Rooted devices fail basicIntegrity, as do emulators, virtual devices, and devices with signs of tampering, such as API hooks.
On the other hand, ctsProfileMatch gives you a much stricter signal about the compatibility of the device. Only unmodified devices that have been certified by Google can pass ctsProfileMatch. Devices that will fail ctsProfileMatch include the following:
  • Devices that fail basicIntegrity
  • Devices with an unlocked bootloader
  • Devices with a custom system image (custom ROM)
  • Devices for which the manufacturer didn't apply for, or pass, Google certification
  • Devices with a system image built directly from the Android Open Source Program source files
  • Devices with a system image distributed as part of a beta or developer preview program (including the Android Beta Program)
Recommendations when using SafetyNetApi.attest
  • Create a large (16 bytes or longer) random number on your server using a cryptographically-secure random function so that a malicious user can not reuse a successful attestation result in place of an unsuccessful result
  • Trust APK information (apkPackageName, apkCertificateDigestSha256 and apkDigestSha256) only if the value of ctsProfileMatch is true.
  • The entire JWS response should be sent to your server, using a secure connection, for verification. It isn't recommended to perform the verification directly in the app because, in that case, there is no guarantee that the verification logic itself hasn't been modified.
  • The verify method only validates that the JWS message was signed by SafetyNet. It doesn't verify that the payload of the verdict matches your expectations. As useful as this service may seem, it is designed for test purposes only, and it has very strict usage quotas of 10,000 requests per day, per project which will not be increased upon request. Hence, you should refer SafetyNet Verification Samples and implement the digital signature verification logic on your server in a way that it doesn't depend on Google's servers.
  • The SafetyNet Attestation API gives you a snapshot of the state of a device at the moment when the attestation request was made. A successful attestation doesn't necessarily mean that the device would have passed attestation in the past, or that it will in the future. It's recommended to plan a strategy to use the least amount of attestations required to satisfy the use case.
  • To prevent inadvertently reaching your SafetyNetApi.attest quota and getting attestation errors, you should build a system that monitors your usage of the API and warns you well before you reach your quota so you can get it increased. You should also be prepared to handle attestation failures because of an exceeded quota and avoid blocking all your users in this situation. If you are close to reaching your quota, or expect a short-term spike that may lead you to exceed your quota, you can submit this form to request short or long-term increases to the quota for your API key. This process, as well as the additional quota, is free of charge.
Follow this checklist to ensure that you've completed each of the steps needed to integrate the SafetyNetApi.attest API into the app.

Programmatic Detection

File existence checks
Perhaps the most widely used method of programmatic detection is checking for files typically found on rooted devices, such as package files of common rooting apps and their associated files and directories, including the following:
1
/system/app/Superuser.apk
2
/system/etc/init.d/99SuperSUDaemon
3
/dev/com.koushikdutta.superuser.daemon/
4
/system/xbin/daemonsu
Copied!
Detection code also often looks for binaries that are usually installed once a device has been rooted. These searches include checking for busybox and attempting to open the su binary at different locations:
1
/sbin/su
2
/system/bin/su
3
/system/bin/failsafe/su
4
/system/xbin/su
5
/system/xbin/busybox
6
/system/sd/xbin/su
7
/data/local/su
8
/data/local/xbin/su
9
/data/local/bin/su
Copied!
Checking whether su is on the PATH also works:
1
public static boolean checkRoot(){
2
for(String pathDir : System.getenv("PATH").split(":")){
3
if(new File(pathDir, "su").exists()) {
4
return true;
5
}
6
}
7
return false;
8
}
Copied!
File checks can be easily implemented in both Java and native code. The following JNI example (adapted from rootinspector) uses the stat system call to retrieve information about a file and returns "1" if the file exists.
1
jboolean Java_com_example_statfile(JNIEnv * env, jobject this, jstring filepath) {
2
jboolean fileExists = 0;
3
jboolean isCopy;
4
const char * path = (*env)->GetStringUTFChars(env, filepath, &isCopy);
5
struct stat fileattrib;
6
if (stat(path, &fileattrib) < 0) {
7
__android_log_print(ANDROID_LOG_DEBUG, DEBUG_TAG, "NATIVE: stat error: [%s]", strerror(errno));
8
} else
9
{
10
__android_log_print(ANDROID_LOG_DEBUG, DEBUG_TAG, "NATIVE: stat success, access perms: [%d]", fileattrib.st_mode);
11
return 1;
12
}
13
14
return 0;
15
}
Copied!
Executing su and other commands
Another way of determining whether su exists is attempting to execute it through the Runtime.getRuntime.exec method. An IOException will be thrown if su is not on the PATH. The same method can be used to check for other programs often found on rooted devices, such as busybox and the symbolic links that typically point to it.
Checking running processes
Supersu-by far the most popular rooting tool-runs an authentication daemon named daemonsu, so the presence of this process is another sign of a rooted device. Running processes can be enumerated with the ActivityManager.getRunningAppProcesses and manager.getRunningServices APIs, the ps command, and browsing through the /proc directory. The following is an example implemented in rootinspector:
1
public boolean checkRunningProcesses() {
2
3
boolean returnValue = false;
4
5
// Get currently running application processes
6
List<RunningServiceInfo> list = manager.getRunningServices(300);
7
8
if(list != null){
9
String tempName;
10
for(int i=0;i<list.size();++i){
11
tempName = list.get(i).process;
12
13
if(tempName.contains("supersu") || tempName.contains("superuser")){
14
returnValue = true;
15
}
16
}
17
}
18
return returnValue;
19
}
Copied!
Checking installed app packages
You can use the Android package manager to obtain a list of installed packages. The following package names belong to popular rooting tools:
1
com.thirdparty.superuser
2
eu.chainfire.supersu
3
com.noshufou.android.su
4
com.koushikdutta.superuser
5
com.zachspong.temprootremovejb
6
com.ramdroid.appquarantine
7
com.topjohnwu.magisk
Copied!
Checking for writable partitions and system directories
Unusual permissions on system directories may indicate a customized or rooted device. Although the system and data directories are normally mounted read-only, you'll sometimes find them mounted read-write when the device is rooted. Look for these filesystems mounted with the "rw" flag or try to create a file in the data directories.
Checking for custom Android builds
Checking for signs of test builds and custom ROMs is also helpful. One way to do this is to check the BUILD tag for test-keys, which normally indicate a custom Android image. Check the BUILD tag as follows:
1
private boolean isTestKeyBuild()
2
{
3
String str = Build.TAGS;
4
if ((str != null) && (str.contains("test-keys")));
5
for (int i = 1; ; i = 0)
6
return i;
7
}
Copied!
Missing Google Over-The-Air (OTA) certificates is another sign of a custom ROM: on stock Android builds, OTA updates Google's public certificates.

Bypassing Root Detection

Run execution traces with jdb, DDMS, strace, and/or kernel modules to find out what the app is doing. You'll usually see all kinds of suspect interactions with the operating system, such as opening su for reading and obtaining a list of processes. These interactions are surefire signs of root detection. Identify and deactivate the root detection mechanisms, one at a time. If you're performing a black box resilience assessment, disabling the root detection mechanisms is your first step.
To bypass these checks, you can use several techniques, most of which were introduced in the "Reverse Engineering and Tampering" chapter:
  • Renaming binaries. For example, in some cases simply renaming the su binary is enough to defeat root detection (try not to break your environment though!).
  • Unmounting /proc to prevent reading of process lists. Sometimes, the unavailability of /proc is enough to bypass such checks.
  • Using Frida or Xposed to hook APIs on the Java and native layers. This hides files and processes, hides the contents of files, and returns all kinds of bogus values that the app requests.
  • Hooking low-level APIs by using kernel modules.
  • Patching the app to remove the checks.

Effectiveness Assessment

Check for root detection mechanisms, including the following criteria:
  • Multiple detection methods are scattered throughout the app (as opposed to putting everything into a single method).
  • The root detection mechanisms operate on multiple API layers (Java APIs, native library functions, assembler/system calls).
  • The mechanisms are somehow original (they're not copied and pasted from StackOverflow or other sources).
Develop bypass methods for the root detection mechanisms and answer the following questions:
  • Can the mechanisms be easily bypassed with standard tools, such as RootCloak?
  • Is static/dynamic analysis necessary to handle the root detection?
  • Do you need to write custom code?
  • How long did successfully bypassing the mechanisms take?
  • What is your assessment of the difficulty of bypassing the mechanisms?
If root detection is missing or too easily bypassed, make suggestions in line with the effectiveness criteria listed above. These suggestions may include more detection mechanisms and better integration of existing mechanisms with other defenses.

Testing Anti-Debugging Detection (MSTG-RESILIENCE-2)

Overview

Debugging is a highly effective way to analyze runtime app behavior. It allows the reverse engineer to step through the code, stop app execution at arbitrary points, inspect the state of variables, read and modify memory, and a lot more.
Anti-debugging features can be preventive or reactive. As the name implies, preventive anti-debugging prevents the debugger from attaching in the first place; reactive anti-debugging involves detecting debuggers and reacting to them in some way (e.g., terminating the app or triggering hidden behavior). The "more-is-better" rule applies: to maximize effectiveness, defenders combine multiple methods of prevention and detection that operate on different API layers and are well distributed throughout the app.
As mentioned in the "Reverse Engineering and Tampering" chapter, we have to deal with two debugging protocols on Android: we can debug on the Java level with JDWP or on the native layer via a ptrace-based debugger. A good anti-debugging scheme should defend against both types of debugging.

JDWP Anti-Debugging

In the chapter "Reverse Engineering and Tampering", we talked about JDWP, the protocol used for communication between the debugger and the Java Virtual Machine. We showed that it is easy to enable debugging for any app by patching its manifest file, and changing the ro.debuggable system property which enables debugging for all apps. Let's look at a few things developers do to detect and disable JDWP debuggers.

Checking the Debuggable Flag in ApplicationInfo

We have already encountered the android:debuggable attribute. This flag in the Android Manifest determines whether the JDWP thread is started for the app. Its value can be determined programmatically, via the app's ApplicationInfo object. If the flag is set, the manifest has been tampered with and allows debugging.
1
public static boolean isDebuggable(Context context){
2
3
return ((context.getApplicationContext().getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0);
4
5
}
Copied!

isDebuggerConnected

While this might be pretty obvious to circumvent for a reverse engineer, you can use isDebuggerConnected from the android.os.Debug class to determine whether a debugger is connected.
1
public static boolean detectDebugger() {
2
return Debug.isDebuggerConnected();
3
}
Copied!
The same API can be called via native code by accessing the DvmGlobals global structure.
1
JNIEXPORT jboolean JNICALL Java_com_test_debugging_DebuggerConnectedJNI(JNIenv * env, jobject obj) {
2
if (gDvm.debuggerConnected || gDvm.debuggerActive)
3
return JNI_TRUE;
4
return JNI_FALSE;
5
}
Copied!

Timer Checks

Debug.threadCpuTimeNanos indicates the amount of time that the current thread has been executing code. Because debugging slows down process execution, you can use the difference in execution time to guess whether a debugger is attached.
1
static boolean detect_threadCpuTimeNanos(){
2
long start = Debug.threadCpuTimeNanos();
3
4
for(int i=0; i<1000000; ++i)
5
continue;
6
7
long stop = Debug.threadCpuTimeNanos();
8
9
if(stop - start < 10000000) {
10
return false;
11
}
12
else {
13
return true;
14
}
15
}
Copied!
In Dalvik, the global virtual machine state is accessible via the DvmGlobals structure. The global variable gDvm holds a pointer to this structure. DvmGlobals contains various variables and pointers that are important for JDWP debugging and can be tampered with.
1
struct DvmGlobals {
2
/*
3
* Some options that could be worth tampering with :)
4
*/
5
6
bool jdwpAllowed; // debugging allowed for this process?
7
bool jdwpConfigured; // has debugging info been provided?
8
JdwpTransportType jdwpTransport;
9
bool jdwpServer;
10
char* jdwpHost;
11
int jdwpPort;
12
bool jdwpSuspend;
13
14
Thread* threadList;
15
16
bool nativeDebuggerActive;
17
bool debuggerConnected; /* debugger or DDMS is connected */
18
bool debuggerActive; /* debugger is making requests */
19
JdwpState* jdwpState;
20
21
};
Copied!
1
JNIEXPORT jboolean JNICALL Java_poc_c_crashOnInit ( JNIEnv* env , jobject ) {
2
gDvm.methDalvikDdmcServer_dispatch = NULL;
3
}
Copied!
You can disable debugging by using similar techniques in ART even though the gDvm variable is not available. The ART runtime exports some of the vtables of JDWP-related classes as global symbols (in C++, vtables are tables that hold pointers to class methods). This includes the vtables of the classes JdwpSocketState and JdwpAdbState, which handle JDWP connections via network sockets and ADB, respectively. You can manipulate the behavior of the debugging runtime by overwriting the method pointers in the associated vtables (archived).
One way to overwrite the method pointers is to overwrite the address of the function jdwpAdbState::ProcessIncoming with the address of JdwpAdbState::Shutdown. This will cause the debugger to disconnect immediately.
1
#include <jni.h>
2
#include <string>
3
#include <android/log.h>
4
#include <dlfcn.h>
5
#include <sys/mman.h>
6
#include <jdwp/jdwp.h>
7
8
#define log(FMT, ...) __android_log_print(ANDROID_LOG_VERBOSE, "JDWPFun", FMT, ##__VA_ARGS__)
9
10
// Vtable structure. Just to make messing around with it more intuitive
11
12
struct VT_JdwpAdbState {
13
unsigned long x;
14
unsigned long y;
15
void * JdwpSocketState_destructor;
16
void * _JdwpSocketState_destructor;
17
void * Accept;
18
void * showmanyc;
19
void * ShutDown;
20
void * ProcessIncoming;
21
};
22
23
extern "C"
24
25
JNIEXPORT void JNICALL Java_sg_vantagepoint_jdwptest_MainActivity_JDWPfun(
26
JNIEnv *env,
27
jobject /* this */) {
28
29
void* lib = dlopen("libart.so", RTLD_NOW);
30
31
if (lib == NULL) {
32
log("Error loading libart.so");
33
dlerror();
34
}else{
35
36
struct VT_JdwpAdbState *vtable = ( struct VT_JdwpAdbState *)dlsym(lib, "_ZTVN3art4JDWP12JdwpAdbStateE");
37
38
if (vtable == 0) {
39
log("Couldn't resolve symbol '_ZTVN3art4JDWP12JdwpAdbStateE'.\n");
40
}else {
41
42
log("Vtable for JdwpAdbState at: %08x\n", vtable);
43
44
// Let the fun begin!
45
46
unsigned long pagesize = sysconf(_SC_PAGE_SIZE);
47
unsigned long page = (unsigned long)vtable & ~(pagesize-1);
48
49
mprotect((void *)page, pagesize, PROT_READ | PROT_WRITE);
50
51
vtable->ProcessIncoming = vtable->ShutDown;
52
53
// Reset permissions & flush cache
54
55
mprotect((void *)page, pagesize, PROT_READ);
56
57
}
58
}
59
}
Copied!

Traditional Anti-Debugging

On Linux, the ptrace system call is used to observe and control the execution of a process (the tracee) and to examine and change that process' memory and registers. ptrace is the primary way to implement system call tracing and breakpoint debugging in native code. Most JDWP anti-debugging tricks (which may be safe for timer-based checks) won't catch classical debuggers based on ptrace and therefore, many Android anti-debugging tricks include ptrace, often exploiting the fact that only one debugger at a time can attach to a process.

Checking TracerPid

When you debug an app and set a breakpoint on native code, Android Studio will copy the needed files to the target device and start the lldb-server which will use ptrace to attach to the process. From this moment on, if you inspect the status file of the debugged process (/proc/<pid>/status or /proc/self/status), you will see that the "TracerPid" field has a value different from 0, which is a sign of debugging.
Remember that this only applies to native code. If you're debugging a Java/Kotlin-only app the value of the "TracerPid" field should be 0.
This technique is usually applied within the JNI native libraries in C, as shown in Google's gperftools (Google Performance Tools)) Heap Checker implementation of the IsDebuggerAttached method. However, if you prefer to include this check as part of your Java/Kotlin code you can refer to this Java implementation of the hasTracerPid method from Tim Strazzere's Anti-Emulator project.
When trying to implement such a method yourself, you can manually check the value of TracerPid with ADB. The following listing uses Google's NDK sample app hello-jni (com.example.hellojni) to perform the check after attaching Android Studio's debugger:
1
$ adb shell ps -A | grep com.example.hellojni
2
u0_a271 11657 573 4302108 50600 ptrace_stop 0 t com.example.hellojni
3
$ adb shell cat /proc/11657/status | grep -e "^TracerPid:" | sed "s/^TracerPid:\t//"
4
TracerPid: 11839
5
$ adb shell ps -A | grep 11839
6
u0_a271 11839 11837 14024 4548 poll_schedule_timeout 0 S lldb-server
Copied!
You can see how the status file of com.example.hellojni (PID=11657) contains a TracerPID of 11839, which we can identify as the lldb-server process.

Using Fork and ptrace

You can prevent debugging of a process by forking a child process and attaching it to the parent as a debugger via code similar to the following simple example code:
1
void fork_and_attach()
2
{
3
int pid = fork();
4
5
if (pid == 0)
6
{
7
int ppid = getppid();
8
9
if (ptrace(PTRACE_ATTACH, ppid, NULL, NULL) == 0)
10
{
11
waitpid(ppid, NULL, 0);
12
13
/* Continue the parent process */
14
ptrace(PTRACE_CONT, NULL, NULL);
15
}
16
}
17
}
Copied!
With the child attached, further attempts to attach to the parent will fail. We can verify this by compiling the code into a JNI function and packing it into an app we run on the device.
1
[email protected]:/ # ps | grep -i anti
2
u0_a151 18190 201 1535844 54908 ffffffff b6e0f124 S sg.vantagepoint.antidebug
3
u0_a151 18224 18190 1495180 35824 c019a3ac b6e0ee5c S sg.vantagepoint.antidebug
Copied!
Attempting to attach to the parent process with gdbserver fails with an error:
1
[email protected]:/ # ./gdbserver --attach localhost:12345 18190
2
warning: process 18190 is already traced by process 18224
3
Cannot attach to lwp 18190: Operation not permitted (1)
4
Exiting
Copied!
You can easily bypass this failure, however, by killing the child and "freeing" the parent from being traced. You'll therefore usually find more elaborate schemes, involving multiple processes and threads as well as some form of monitoring to impede tampering. Common methods include
  • forking multiple processes that trace one another,
  • keeping track of running processes to make sure the children stay alive,
  • monitoring values in the /proc filesystem, such as TracerPID in /proc/pid/status.
Let's look at a simple improvement for the method above. After the initial fork, we launch in the parent an extra thread that continually monitors the child's status. Depending on whether the app has been built in debug or release mode (which is indicated by the android:debuggable flag in the manifest), the child process should do one of the following things:
  • In release mode: The call to ptrace fails and the child crashes immediately with a segmentation fault (exit code 11).
  • In debug mode: The call to ptrace works and the child should run indefinitely. Consequently, a call to waitpid(child_pid) should never return. If it does, something is fishy and we would kill the whole process group.
The following is the complete code for implementing this improvement with a JNI function:
1
#include <jni.h>
2
#include <unistd.h>
3
#include <sys/ptrace.h>
4
#include <sys/wait.h>
5
#include <pthread.h>
6
7
static int child_pid;
8
9
void *monitor_pid() {
10
11
int status;
12
13
waitpid(child_pid, &status, 0);
14
15
/* Child status should never change. */
16
17
_exit(0); // Commit seppuku
18
19
}
20
21
void anti_debug() {
22
23
child_pid = fork();
24
25
if (child_pid == 0)
26
{
27
int ppid = getppid();
28
int status;
29
30
if (ptrace(PTRACE_ATTACH, ppid, NULL, NULL) == 0)
31
{
32
waitpid(ppid, &status, 0);
33
34
ptrace(PTRACE_CONT, ppid, NULL, NULL);
35
36
while (waitpid(ppid, &status, 0)) {
37
38
if (WIFSTOPPED(status)) {
39
ptrace(PTRACE_CONT, ppid, NULL, NULL);
40
} else {
41
// Process has exited
42
_exit(0);
43
}
44
}
45
}
46
47
} else {
48
pthread_t t;
49
50
/* Start the monitoring thread */
51
pthread_create(&t, NULL, monitor_pid, (void *)NULL);
52
}
53
}
54
55
JNIEXPORT void JNICALL
56
Java_sg_vantagepoint_antidebug_MainActivity_antidebug(JNIEnv *env, jobject instance) {
57
58
anti_debug();
59
}
Copied!
Again, we pack this into an Android app to see if it works. Just as before, two processes show up when we run the app's debug build.
1
[email protected]:/ # ps | grep -I anti-debug
2
u0_a152 20267 201 1552508 56796 ffffffff b6e0f124 S sg.vantagepoint.anti-debug
3
u0_a152 20301 20267 1495192 33980 c019a3ac b6e0ee5c S sg.vantagepoint.anti-debug
Copied!
However, if we terminate the child process at this point, the parent exits as well:
1
[email protected]:/ # kill -9 20301
2
130|[email protected]:/ # cd /data/local/tmp
3
[email protected]:/ # ./gdbserver --attach localhost:12345 20267
4
gdbserver: unable to open /proc file '/proc/20267/status'
5
Cannot attach to lwp 20267: No such file or directory (2)
6
Exiting
Copied!
To bypass this, we must modify the app's behavior slightly (the easiest ways to do so are patching the call to _exit with NOPs and hooking the function _exit in libc.so). At this point, we have entered the proverbial "arms race": implementing more intricate forms of this defense as well as bypassing it are always possible.

Bypassing Debugger Detection

There's no generic way to bypass anti-debugging: the best method depends on the particular mechanism(s) used to prevent or detect debugging and the other defenses in the overall protection scheme. For example, if there are no integrity checks or you've already deactivated them, patching the app might be the easiest method. In other cases, a hooking framework or kernel modules might be preferable. The following methods describe different approaches to bypass debugger detection:
  • Patching the anti-debugging functionality: Disable the unwanted behavior by simply overwriting it with NOP instructions. Note that more complex patches may be required if the anti-debugging mechanism is well designed.
  • Using Frida or Xposed to hook APIs on the Java and native layers: manipulate the return values of functions such as isDebuggable and isDebuggerConnected to hide the debugger.
  • Changing the environment: Android is an open environment. If nothing else works, you can modify the operating system to subvert the assumptions the developers made when designing the anti-debugging tricks.

Bypassing Example: UnCrackable App for Android Level 2

When dealing with obfuscated apps, you'll often find that developers purposely "hide away" data and functionality in native libraries. You'll find an example of this in level 2 of the "UnCrackable App for Android".
At first glance, the code looks like the prior challenge. A class called CodeCheck is responsible for verifying the code entered by the user. The actual check appears to occur in the bar method, which is declared as a native method.
1
package sg.vantagepoint.uncrackable2;
2
3
public class CodeCheck {
4
public CodeCheck() {
5
super();
6
}
7
8
public boolean a(String arg2) {
9
return this.bar(arg2.getBytes());
10
}
11
12
private native boolean bar(byte[] arg1) {
13
}
14
}
15
16
static {
17
System.loadLibrary("foo");
18
}
Copied!

Effectiveness Assessment

Check for anti-debugging mechanisms, including the following criteria:
  • Attaching jdb and ptrace-based debuggers fails or causes the app to terminate or malfunction.
  • Multiple detection methods are scattered throughout the app's source code (as opposed to their all being in a single method or function).
  • The anti-debugging defenses operate on multiple API layers (Java, native library functions, assembler/system calls).
  • The mechanisms are somehow original (as opposed to being copied and pasted from StackOverflow or other sources).
Work on bypassing the anti-debugging defenses and answer the following questions:
  • Can the mechanisms be bypassed trivially (e.g., by hooking a single API function)?
  • How difficult is identifying the anti-debugging code via static and dynamic analysis?
  • Did you need to write custom code to disable the defenses? How much time did you need?
  • What is your subjective assessment of the difficulty of bypassing the mechanisms?
If anti-debugging mechanisms are missing or too easily bypassed, make suggestions in line with the effectiveness criteria above. These suggestions may include adding more detection mechanisms and better integration of existing mechanisms with other defenses.

Testing File Integrity Checks (MSTG-RESILIENCE-3)

Overview

There are two topics related to file integrity:
  1. 1.
    Code integrity checks: In the "Tampering and Reverse Engineering on Android" chapter, we discussed Android's APK code signature check. We also saw that determined reverse engineers can easily bypass this check by re-packaging and re-signing an app. To make this bypassing process more involved, a protection scheme can be augmented with CRC checks on the app bytecode, native libraries, and important data files. These checks can be implemented on both the Java and the native layer. The idea is to have additional controls in place so that the app only runs correctly in its unmodified state, even if the code signature is valid.
  2. 2.
    The file storage integrity checks: The integrity of files that the application stores on the SD card or public storage and the integrity of key-value pairs that are stored in SharedPreferences should be protected.

Sample Implementation - Application Source Code

Integrity checks often calculate a checksum or hash over selected files. Commonly protected files include
  • AndroidManifest.xml,
  • class files *.dex,
  • native libraries (*.so).
The following sample implementation from the Android Cracking blog calculates a CRC over classes.dex and compares it to the expected value.
1
private void crcTest() throws IOException {
2
boolean modified = false;
3
// required dex crc value stored as a text string.
4
// it could be any invisible layout element
5
long dexCrc = Long.parseLong(Main.MyContext.getString(R.string.dex_crc));
6
7
ZipFile zf = new ZipFile(Main.MyContext.getPackageCodePath());
8
ZipEntry ze = zf.getEntry("classes.dex");
9
10
if ( ze.getCrc() != dexCrc ) {
11
// dex has been modified
12
modified = true;
13
}
14
else {
15
// dex not tampered with
16
modified = false;
17
}
18
}
Copied!

Sample Implementation - Storage

When providing integrity on the storage itself, you can either create an HMAC over a given key-value pair (as for the Android SharedPreferences) or create an HMAC over a complete file that's provided by the file system.
Complete the following procedure when generating an HMAC with BouncyCastle:
  1. 1.
    Make sure BouncyCastle or SpongyCastle is registered as a security provider.
  2. 2.
    Initialize the HMAC with a key (which can be stored in a keystore).
  3. 3.
    Get the byte array of the content that needs an HMAC.
  4. 4.
    Call doFinal on the HMAC with the bytecode.
  5. 5.
    Append the HMAC to the bytearray obtained in step 3.
  6. 6.
    Store the result of step 5.
Complete the following procedure when verifying the HMAC with BouncyCastle:
  1. 1.
    Make sure that BouncyCastle or SpongyCastle is registered as a security provider.
  2. 2.
    Extract the message and the HMAC-bytes as separate arrays.
  3. 3.
    Repeat steps 1-4 of the procedure for generating an HMAC.
  4. 4.
    Compare the extracted HMAC-bytes to the result of step 3.
When generating the HMAC based on the Android Keystore, then it is best to only do this for Android 6.0 (API level 23) and higher.
The following is a convenient HMAC implementation without AndroidKeyStore:
1
public enum HMACWrapper {
2
HMAC_512("HMac-SHA512"), //please note that this is the spec for the BC provider
3
HMAC_256("HMac-SHA256");
4
5
private final String algorithm;
6
7
private HMACWrapper(final String algorithm) {
8
this.algorithm = algorithm;
9
}
10
11
public Mac createHMAC(final SecretKey key) {
12
try {
13
Mac e = Mac.getInstance(this.algorithm, "BC");
14
SecretKeySpec secret = new SecretKeySpec(key.getKey().getEncoded(), this.algorithm);
15
e.init(secret);
16
return e;
17
} catch (NoSuchProviderException | InvalidKeyException | NoSuchAlgorithmException e) {
18
//handle them
19
}
20
}
21
22
public byte[] hmac(byte[] message, SecretKey key) {
23
Mac mac = this.createHMAC(key);
24
return mac.doFinal(message);
25
}
26
27
public boolean verify(byte[] messageWithHMAC, SecretKey key) {
28
Mac mac = this.createHMAC(key);
29
byte[] checksum = extractChecksum(messageWithHMAC, mac.getMacLength());
30
byte[] message = extractMessage(messageWithHMAC, mac.getMacLength());
31
byte[] calculatedChecksum = this.hmac(message, key);
32
int diff = checksum.length ^ calculatedChecksum.length;
33
34
for (int i = 0; i < checksum.length && i < calculatedChecksum.length; ++i) {
35
diff |= checksum[i] ^ calculatedChecksum[i];
36
}
37
38
return diff == 0;
39
}
40
41
public byte[] extractMessage(byte[] messageWithHMAC) {
42
Mac hmac = this.createHMAC(SecretKey.newKey());
43
return extractMessage(messageWithHMAC, hmac.getMacLength());
44
}
45
46
private static byte[] extractMessage(byte[] body, int checksumLength) {
47
if (body.length >= checksumLength) {
48
byte[] message = new byte[body.length - checksumLength];
49
System.arraycopy(body, 0, message, 0, message.length);
50
return message;
51
} else {
52
return new byte[0];
53
}
54
}
55
56
private static byte[] extractChecksum(byte[] body, int checksumLength) {
57
if (body.length >= checksumLength) {
58
byte[] checksum = new byte[checksumLength];
59
System.arraycopy(body, body.length - checksumLength, checksum, 0, checksumLength);
60
return checksum;
61
} else {
62
return new byte[0];
63
}
64
}
65
66
static {
67
Security.addProvider(new BouncyCastleProvider());
68
}
69
}
Copied!
Another way to provide integrity is to sign the byte array you obtained and add the signature to the original byte array.

Bypassing File Integrity Checks

Bypassing the application-source integrity checks
  1. 1.
    Patch the anti-debugging functionality. Disable the unwanted behavior by simply overwriting the associated bytecode or native code with NOP instructions.
  2. 2.
    Use Frida or Xposed to hook file system APIs on the Java and native layers. Return a handle to the original file instead of the modified file.
  3. 3.
    Use the kernel module to intercept file-related system calls. When the process attempts to open the modified file, return a file descriptor for the unmodified version of the file.
Refer to the "Tampering and Reverse Engineering on Android" chapter for examples of patching, code injection, and kernel modules.
Bypassing the storage integrity checks
  1. 1.
    Retrieve the data from the device, as described in the "Testing Device Binding" section.
  2. 2.
    Alter the retrieved data and then put it back into storage.

Effectiveness Assessment

For application-source integrity checks

Run the app in an unmodified state and make sure that everything works. Apply simple patches to classes.dex and any .so libraries in the app package. Re-package and re-sign the app as described in the "Basic Security Testing" chapter, then run the app. The app should detect the modification and respond in some way. At the very least, the app should alert the user and/or terminate. Work on bypassing the defenses and answer the following questions:
  • Can the mechanisms be bypassed trivially (e.g., by hooking a single API function)?
  • How difficult is identifying the anti-debugging code via static and dynamic analysis?
  • Did you need to write custom code to disable the defenses? How much time did you need?
  • What is your assessment of the difficulty of bypassing the mechanisms?

For storage integrity checks

An approach similar to that for application-source integrity checks applies. Answer the following questions:
  • Can the mechanisms be bypassed trivially (e.g., by changing the contents of a file or a key-value)?
  • How difficult is getting the HMAC key or the asymmetric private key?
  • Did you need to write custom code to disable the defenses? How much time did you need?
  • What is your assessment of the difficulty of bypassing the mechanisms?

Testing Reverse Engineering Tools Detection (MSTG-RESILIENCE-4)

Overview

The presence of tools, frameworks and apps commonly used by reverse engineers may indicate an attempt to reverse engineer the app. Some of these tools can only run on a rooted device, while others force the app into debugging mode or depend on starting a background service on the mobile phone. Therefore, there are different ways that an app may implement to detect a reverse engineering attack and react to it, e.g. by terminating itself.

Detection Methods

You can detect popular reverse engineering tools that have been installed in an unmodified form by looking for associated application packages, files, processes, or other tool-specific modifications and artifacts. In the following examples, we'll discuss different ways to detect the Frida instrumentation framework, which is used extensively in this guide. Other tools, such as Substrate and Xposed, can be detected similarly. Note that DBI/injection/hooking tools can often be detected implicitly, through runtime integrity checks, which are discussed below.
For instance, in its default configuration on a rooted device, Frida runs on the device as frida-server. When you explicitly attach to a target app (e.g. via frida-trace or the Frida REPL), Frida injects a frida-agent into the memory of the app. Therefore, you may expect to find it there after attaching to the app (and not before). If you check /proc/<pid>/maps you'll find the frida-agent as frida-agent-64.so:
1
bullhead:/ # cat /proc/18370/maps | grep -i frida
2
71b6bd6000-71b7d62000 r-xp /data/local/tmp/re.frida.server/frida-agent-64.so
3
71b7d7f000-71b7e06000 r--p /data/local/tmp/re.frida.server/frida-agent-64.so
4
71b7e06000-71b7e28000 rw-p /data/local/tmp/re.frida.server/frida-agent-64.so
Copied!
The other method (which also works for non-rooted devices) consists of embedding a frida-gadget into the APK and forcing the app to load it as one of its native libraries. If you inspect the app memory maps after starting the app (no need to attach explicitly to it) you'll find the embedded frida-gadget as libfrida-gadget.so.
1
bullhead:/ # cat /proc/18370/maps | grep -i frida
2
3
71b865a000-71b97f1000 r-xp /data/app/sg.vp.owasp_mobile.omtg_android-.../lib/arm64/libfrida-gadget.so
4
71b9802000-71b988a000 r--p /data/app/sg.vp.owasp_mobile.omtg_android-.../lib/arm64/libfrida-gadget.so
5
71b988a000-71b98ac000 rw-p /data/app/sg.vp.owasp_mobile.omtg_android-.../lib/arm64/libfrida-gadget.so
Copied!
Looking at these two traces that Frida lefts behind, you might already imagine that detecting those would be a trivial task. And actually, so trivial will be bypassing that detection. But things can get much more complicated. The following table shortly presents a set of some typical Frida detection methods and a short discussion on their effectiveness.
Some of the following detection methods are presented in the article "The Jiu-Jitsu of Detecting Frida" by Berdhard Mueller (archived). Please refer to it for more details and for example code snippets.
Method
Description
Discussion
Checking the App Signature
In order to embed the frida-gadget within the APK, it would need to be repackaged and resigned. You could check the signature of the APK when the app is starting (e.g. GET_SIGNING_CERTIFICATES since API level 28) and compare it to the one you pinned in your APK.
This is unfortunately too trivial to bypass, e.g. by patching the APK or performing system call hooking.
Check The Environment For Related Artifacts
Artifacts can be package files, binaries, libraries, processes, and temporary files. For Frida, this could be the frida-server running in the target (rooted) system (the daemon responsible for exposing Frida over TCP). Inspect the running services (getRunningServices) and processes (ps) searching for one whose name is "frida-server". You could also walk through the list of loaded libraries and check for suspicious ones (e.g. those including "frida" in their names).
Since Android 7.0 (API level 24), inspecting the running services/processes won't show you daemons like the frida-server as it is not being started by the app itself. Even if it would be possible, bypassing this would be as easy just renaming the corresponding Frida artifact (frida-server/frida-gadget/frida-agent).
Checking For Open TCP Ports
The frida-server process binds to TCP port 27042 by default. Check whether this port is open is another method of detecting the daemon.
This method detects frida-server in its default mode, but the listening port can be changed via a command line argument, so bypassing this is a little too trivial.
Checking For Ports Responding To D-Bus Auth
frida-server uses the D-Bus protocol to communicate, so you can expect it to respond to D-Bus AUTH. Send a D-Bus AUTH message to every open port and check for an answer, hoping that frida-server will reveal itself.
This is a fairly robust method of detecting frida-server, but Frida offers alternative modes of operation that don't require frida-server.
Scanning Process Memory for Known Artifacts
Scan the memory for artifacts found in Frida's libraries, e.g. the string "LIBFRIDA" present in all versions of frida-gadget and frida-agent. For example, use Runtime.getRuntime().exec and iterate through the memory mappings listed in /proc/self/maps or /proc/<pid>/maps (depending on the Android version) searching for the string.
This method is a bit more effective, and it is difficult to bypass with Frida only, especially if some obfuscation has been added and if multiple artifacts are being scanned. However, the chosen artifacts might be patched in the Frida binaries. Find the source code on Berdhard Mueller's GitHub.
Please remember that this table is far from exhaustive. We could start talking about named pipes (used by frida-server for external communication), detecting trampolines (indirect jump vectors inserted at the prologue of functions), which would help detecting Substrate or Frida's Interceptor but, for example, won't be effective against Frida's Stalker; and many other, more or less, effective detection methods. Each of them will depend on whether you're using a rooted device, the specific version of the rooting method and/or the version of the tool itself. Further, the app can try to make it harder to detect the implemented protection mechanisms by using various obfuscation techniques, as discussed below in section "Testing Resiliency Against Reverse Engineering". At the end, this is part of the cat and mouse game of protecting data being processed on an untrusted environment (an app running in the user device).
It is important to note that these controls are only increasing the complexity of the reverse engineering process. If used, the best approach is to combine the controls cleverly instead of using them individually. However, none of them can assure a 100% effectiveness, as the reverse engineer will always have full access to the device and will therefore always win! You also have to consider that integrating some of the controls into your app might increase the complexity of your app and even have an impact on its performance.

Effectiveness Assessment

Launch the app with various reverse engineering tools and frameworks installed in your test device. Include at least the following: Frida, Xposed, Substrate for Android, RootCloak, Android SSL Trust Killer.
The app should respond in some way to the presence of those tools. For example by:
  • Alerting the user and asking for accepting liability.
  • Preventing execution by gracefully terminating.
  • Securely wiping any sensitive data stored on the device.
  • Reporting to a backend server, e.g, for fraud detection.
Next, work on bypassing the detection of the reverse engineering tools and answer the following questions:
  • Can the mechanisms be bypassed trivially (e.g., by hooking a single API function)?
  • How difficult is identifying the anti reverse engineering code via static and dynamic analysis?
  • Did you need to write custom code to disable the defenses? How much time did you need?
  • What is your assessment of the difficulty of bypassing the mechanisms?
The following steps should guide you when bypassing detection of reverse engineering tools:
  1. 1.
    Patch the anti reverse engineering functionality. Disable the unwanted behavior by simply overwriting the associated bytecode or native code with NOP instructions.
  2. 2.
    Use Frida or Xposed to hook file system APIs on the Java and native layers. Return a handle to the original file, not the modified file.
  3. 3.
    Use a kernel module to intercept file-related system calls. When the process attempts to open the modified file, return a file descriptor for the unmodified version of the file.
Refer to the "Tampering and Reverse Engineering on Android" chapter for examples of patching, code injection, and kernel modules.

Testing Emulator Detection (MSTG-RESILIENCE-5)

Overview

In the context of anti-reversing, the goal of emulator detection is to increase the difficulty of running the app on an emulated device, which impedes some tools and techniques reverse engineers like to use. This increased difficulty forces the reverse engineer to defeat the emulator checks or utilize the physical device, thereby barring the access required for large-scale device analysis.

Emulator Detection Examples

There are several indicators that the device in question is being emulated. Although all these API calls can be hooked, these indicators provide a modest first line of defense.
The first set of indicators are in the file build.prop.
1
API Method Value Meaning
2
Build.ABI armeabi possibly emulator
3
BUILD.ABI2 unknown possibly emulator
4
Build.BOARD unknown emulator
5
Build.Brand generic emulator
6
Build.DEVICE generic emulator
7
Build.FINGERPRINT generic emulator
8
Build.Hardware goldfish emulator
9
Build.Host android-test possibly emulator
10
Build.ID FRF91 emulator
11
Build.MANUFACTURER unknown emulator
12
Build.MODEL sdk emulator
13
Build.PRODUCT sdk emulator
14
Build.RADIO unknown possibly emulator
15
Build.SERIAL null emulator
16
Build.USER android-build emulator
Copied!
You can edit the file build.prop on a rooted Android device or modify it while compiling AOSP from source. Both techniques will allow you to bypass the static string checks above.
The next set of static indicators utilize the Telephony manager. All Android emulators have fixed values that this API can query.
1
API Value Meaning
2
TelephonyManager.getDeviceId() 0's emulator
3
TelephonyManager.getLine1 Number() 155552155 emulator
4
TelephonyManager.getNetworkCountryIso() us possibly emulator
5
TelephonyManager.getNetworkType() 3 possibly emulator
6
TelephonyManager.getNetworkOperator().substring(0,3) 310 possibly emulator
7
TelephonyManager.getNetworkOperator().substring(3) 260 possibly emulator
8
TelephonyManager.getPhoneType() 1 possibly emulator
9
TelephonyManager.getSimCountryIso() us possibly emulator
10
TelephonyManager.getSimSerial Number() 89014103211118510720 emulator
11
TelephonyManager.getSubscriberId() 310260000000000 emulator
12
TelephonyManager.getVoiceMailNumber() 15552175049 emulator
Copied!
Keep in mind that a hooking framework, such as Xposed or Frida, can hook this API to provide false data.

Bypassing Emulator Detection

  1. 1.
    Patch the emulator detection functionality. Disable the unwanted behavior by simply overwriting the associated bytecode or native code with NOP instructions.
  2. 2.
    Use Frida or Xposed APIs to hook file system APIs on the Java and native layers. Return innocent-looking values (preferably taken from a real device) instead of the telltale emulator values. For example, you can override the TelephonyManager.getDeviceID method to return an IMEI value.
Refer to the "Tampering and Reverse Engineering on Android" chapter for examples of patching, code injection, and kernel modules.

Effectiveness Assessment

Install and run the app in the emulator. The app should detect that it is being executed in an emulator and terminate or refuse to execute the functionality that's meant to be protected.
Work on bypassing the defenses and answer the following questions:
  • How difficult is identifying the emulator detection code via static and dynamic analysis?
  • Can the detection mechanisms be bypassed trivially (e.g., by hooking a single API function)?
  • Did you need to write custom code to disable the anti-emulation feature(s)? How much time did you need?
  • What is your assessment of the difficulty of bypassing the mechanisms?

Testing Runtime Integrity Checks (MSTG-RESILIENCE-6)

Overview

Controls in this category verify the integrity of the app's memory space to defend the app against memory patches applied during runtime. Such patches include unwanted changes to binary code, bytecode, function pointer tables, and important data structures, as well as rogue code loaded into process memory. Integrity can be verified by:
  1. 1.
    comparing the contents of memory or a checksum over the contents to good values,
  2. 2.
    searching memory for the signatures of unwanted modifications.
There's some overlap with the category "detecting reverse engineering tools and frameworks", and, in fact, we demonstrated the signature-based approach in that chapter when we showed how to search process memory for Frida-related strings. Below are a few more examples of various kinds of integrity monitoring.

Runtime Integrity Check Examples

Detecting tampering with the Java Runtime**
This detection code is from the dead && end blog.
1
try {
2
throw new Exception();
3
}
4
catch(Exception e) {
5
int zygoteInitCallCount = 0;
6
for(StackTraceElement stackTraceElement : e.getStackTrace()) {
7
if(stackTraceElement.getClassName().equals("com.android.internal.os.ZygoteInit")) {
8
zygoteInitCallCount++;
9
if(zygoteInitCallCount == 2) {
10
Log.wtf("HookDetection", "Substrate is active on the device.");
11
}
12
}
13
if(stackTraceElement.getClassName().equals("com.saurik.substrate.MS$2") &&
14
stackTraceElement.getMethodName().equals("invoked")) {
15
Log.wtf("HookDetection", "A method on the stack trace has been hooked using Substrate.");
16
}
17
if(stackTraceElement.getClassName().equals("de.robv.android.xposed.XposedBridge") &&
18
stackTraceElement.getMethodName().equals("main")) {
19
Log.wtf("HookDetection", "Xposed is active on the device.");
20
}
21
if(stackTraceElement.getClassName().equals("de.robv.android.xposed.XposedBridge") &&
22
stackTraceElement.getMethodName().equals("handleHookedMethod")) {
23
Log.wtf("HookDetection", "A method on the stack trace has been hooked using Xposed.");
24
}
25
26
}
27
}
Copied!
Detecting Native Hooks
By using ELF binaries, native function hooks can be installed by overwriting function pointers in memory (e.g., Global Offset Table or PLT hooking) or patching parts of the function code itself (inline hooking). Checking the integrity of the respective memory regions is one way to detect this kind of hook.
The Global Offset Table (GOT) is used to resolve library functions. During runtime, the dynamic linker patches this table with the absolute addresses of global symbols. GOT hooks overwrite the stored function addresses and redirect legitimate function calls to adversary-controlled code. This type of hook can be detected by enumerating the process memory map and verifying that each GOT entry points to a legitimately loaded library.
In contrast to GNU ld, which resolves symbol addresses only after they are needed for the first time (lazy binding), the Android linker resolves all external functions and writes the respective GOT entries immediately after a library is loaded (immediate binding). You can therefore expect all GOT entries to point to valid memory locations in the code sections of their respective libraries during runtime. GOT hook detection methods usually walk the GOT and verify this.
Inline hooks work by overwriting a few instructions at the beginning or end of the function code. During runtime, this so-called trampoline redirects execution to the injected code. You can detect inline hooks by inspecting the prologues and epilogues of library functions for suspect instructions, such as far jumps to locations outside the library.

Bypass and Effectiveness Assessment

Make sure that all file-based detection of reverse engineering tools is disabled. Then, inject code by using Xposed, Frida, and Substrate, and attempt to install native hooks and Java method hooks. The app should detect the "hostile" code in its memory and respond accordingly.
Work on bypassing the checks with the following techniques:
  1. 1.
    Patch the integrity checks. Disable the unwanted behavior by overwriting the respective bytecode or native code with NOP instructions.
  2. 2.
    Use Frida or Xposed to hook the APIs used for detection and return fake values.
Refer to the "Tampering and Reverse Engineering on Android" chapter for examples of patching, code injection, and kernel modules.

Testing Obfuscation (MSTG-RESILIENCE-9)

Overview

Obfuscation is the process of transforming code and data to make it more difficult to comprehend. It is an integral part of every software protection scheme. What's important to understand is that obfuscation isn't something that can be simply turned on or off. Programs can be made incomprehensible, in whole or in part, in many ways and to different degrees.
In the test case "Make Sure That Free Security Features Are Activated (MSTG-CODE-9)" in chapter "Code Quality and Build Settings of Android Apps", we describe a few basic obfuscation techniques that are commonly used on Android with R8 and Pro-Guard.

Effectiveness Assessment

Attempt to decompile the bytecode, disassemble any included library files and try to understand it. When doing so, consider the following:
  • Obfuscation often carries a cost in runtime performance, therefore it might have been only applied to certain very specific parts of the code, typically those dealing with security and runtime protection.
  • Meaningful identifiers, such as class names, method names, and variable names, might have been discarded.
  • String resources and strings in binaries might have been encrypted.
  • Code and data related to the protected functionality might be encrypted, packed, or otherwise concealed.
  • For native code, libc APIs (e.g open, read) might have been replaced with OS syscalls.
  • Additional obfuscation techniques such as "Control Flow Flattening" or "Bogus Control Flow" might have been applied using e.g. Obfuscator-LLVM.
Some of these techniques are discussed and analyzed in the blog post "Security hardening of Android native code" by Gautam Arvind.
For a more detailed assessment, you need a detailed understanding of the relevant threats and the obfuscation methods used. There are some tools such as APKiD that might be able to give you some indications about the kind of obfuscators being used.

Testing Device Binding (MSTG-RESILIENCE-10)

Overview

The goal of device binding is to impede an attacker who tries to both copy an app and its state from device A to device B and continue executing the app on device B. After device A has been determined trustworthy, it may have more privileges than device B. These differential privileges should not change when an app is copied from device A to device B.
Before we describe the usable identifiers, let's quickly discuss how they can be used for binding. There are three methods that allow device binding:
  • Augmenting the credentials used for authentication with device identifiers. This make sense if the application needs to re-authenticate itself and/or the user frequently.
  • Encrypting the data stored in the device with the key material which is strongly bound to the device can strengthen the device binding. The Android Keystore offers non-exportable private keys which we can use for this. When a malicious actor would extract such data from a device, it wouldn't be possible to decrypt the data, as the key is not accessible. Implementing this, takes the following steps:
    • Generate the key pair in the Android Keystore using KeyGenParameterSpec API.
      1
      //Source: <https://developer.android.com/reference/android/security/keystore/KeyGenParameterSpec.html>
      2
      KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
      3
      KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
      4
      keyPairGenerator.initialize(