preface

APP development often asked: “How to ensure the security of the APP, the application is PJ how to do? What if the phone is picked up?” The security of mobile products is still viewed with suspicion, especially in the banking system, which is known for its “safety first and excellent risk control”. Then let’s summarize the direction and specific knowledge of APP security.

1. Application security

2. Secure the storage of sensitive data in applications

3. Data packet transmission security in the foreground and background of applications

One, decompilation

1. Decompile code

Dex2jar: Converts the dex file into a JAR file.

Jd-gui: Convert jar files to Java code, and use the JD-GUI tool to open classes-dex2jar.jar to view the Java code.

2. Decompile resources

The resource files in APK files are compiled at the time of packaging, so we can’t see the plaintext if we open them directly. To decompile the resources in APK files, use the ApkTool again.

Apktool: used for maximum restoration of 9-patch images, layouts, strings and a series of resources in APK files. Resource files such as Androidmanifest. XML and activity_main. XML are in plain text and cannot be read without decomcompiling the resource.

3. Repack

The directory structure of the smali folder is almost the same as the directory structure of SRC in our source code, the main difference being that all Java files become SMali files. Smali file is actually the real source code, but its syntax is completely different from Java, it is somewhat similar to assembly syntax, is the Register language used by the Android virtual machine. Using smALI syntax, you can recompile your APK by modifying the code.

So if this is someone else’s program, where can we get the original signature file? Obviously, there was no way to get this, so we had to re-sign the APK file with our own signature file, but it also showed that the repackaged software was completely pirated software.

Second, code confusion

1. Confusion

(1) It is difficult to reverse engineer APK and increase the cost of decompilation.

(2) Remove useless resources during packaging and reduce APK volume.

2. Confused startup

android {
  buildTypes {
    release {
        minifyEnabled true
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
Copy the code
  • Set minifyEnabled to true to enable obfuscation

  • Set shrinkResources to true to enable resource compression. Note that resource compression works only when obfuscation is enabled. It is not recommended to enable obfuge in debug mode because obfuge adds extra compile time.

  • TXT represents the default obfuscation rule file provided by the Android system, while proguard-rules.pro is the obfuscation rule we want to customize.

3. Elements that cannot be confused

(1) Enumeration

There is a values method inside the enumeration class, which is renamed after confusion and throws a NoSuchMethodException. The Android system’s default obfuscation rules already add handling for enumerated classes, so we don’t need to do any extra work.

(2) Reflected elements

During code obfuscation, the element used by reflection is renamed, but reflection still finds the element by its previous name, so NoSuchMethodException and NoSuchFiledException often occur.

(3) Entity class

Entity classes are often referred to as “data classes” and of course are often accompanied by serialization and deserialization operations. Many of us have also thought that confusion is to change the original “element” with a specific meaning into a meaningless name. Therefore, after the baptism of confusion, the key corresponding to the serialized value has become a meaningless field, which is definitely not what we want. The deserialization process of creating an object is essentially reflection, and obfuscation will change the key, so it will not work as expected.

(4) Four components

The four components of Android should not be confused either. The reason is that the four components need to be registered in the androidmanifest.xml file before they are used. However, after the confusion processing, the class names of the four components will be tampered, and the actual class used does not match the class registered in the manifest, so the error occurs. Other applications may use the package name of the class plus the class name when accessing the component. If the component is confused, the corresponding component may not be found or an exception may be generated.

(5) Java methods called by JNI

When a Java method called by JNI is obfuscated, the method name becomes a meaningless name that does not match the original Java method name in C++, and the called method cannot be found.

(6) Custom controls do not need to be confused

(7) JavaScript calling Java methods should not be confused

(8) Java native methods should not be confused

(9) Third-party libraries referenced in the project are not recommended to be confused

Three, four components

Problem 1: Dynamic registration of Receiver risk

To use the BroadcastReceiver component, you need to register the BroadcastReceiver either dynamically or statically. If you register the BroadcastReceiver dynamically, you need to register the BroadcastReceiver () method in your code. RegisterReceiver () is registered only when the registerReceiver() code is executed, and unregisterReceiver() is called when canceled. However, the BroadcastReceiver registered by the registerReceiver() method is global and exported by default. If there is no restricted access, it can be accessed by any external APP and delivered with an Intent to perform a specific function. Therefore, dynamic registration of BroadcastReceive can lead to security risks such as denial-of-service attacks, APP data leakage, or unauthorized calls

Solution:

1. Static registration of BroadcastReceiver in androidmanifest.xml and setting Exported =”false” to not be called by external applications.

2. When BroadcastReceiver must be registered dynamically, Use the registerReceiver (BroadcastReceiver, IntentFilter, broadcastPermission, android. OS. Handle) register function.

Intent.setcomponent (New ComponentName()); Intent.setComponent (New ComponentName())

Problem 2: Common component configuration risk

If the four components of Activity, Service, Provider, and Receiver are configured as Android: Exported = “true”, they can be invoked by external applications. As a result, security risks exist.

Solution:

In your application’s Androidmanifest.xml file, set android: Exported = “false” for components or restrict access to those components by setting custom permissions. It is worth mentioning that if the precondition of using some functions is that the configuration must use exported to be true, the developer should integrate them according to the actual situation

Problem 3: Unauthorized data backup risks

Android 2.1 and above can provide APP data backup and recovery functions controlled by the value of the allowBackup attribute in the androidMainfest.xml file, which defaults to true. If the property is not explicitly set to false, an attacker can use adb backup and adb restore to backup and restore the application data of the APP, thus obtaining user sensitive information stored in plaintext, such as user passwords, id numbers, mobile phone numbers, transaction passwords, identity tokens, and server communication records. Using such information attackers can forge user identities, steal user account assets, or directly attack the server.

Solution:

Set the allowBackup property value in the androidMainfest. XML file to false to turn off the backup and restore functionality of the application; You can also use the local data protection function of the professional security hardening solution to prevent local data leakage.

Four, screen capture screen recording

Problem: Screenshot attack risk

Screen capture attack refers to that during the running of an APP, the interface is monitored and a screen capture or recording is performed. Screen capture attacks mainly occur in the interface of APP login, identity authentication and fund operation. A MediaProjection interface has been added to Android5.0, which provides screenshots or recording services, allowing apps to capture the screen or record system audio. At the same time, the system allows other message Windows to cover the recording prompts of the system, so as to start recording or capturing tools without the user’s awareness. In this way, attackers can obtain screenshots or videos of key APP interfaces to obtain sensitive user information.

Solution:

Call getWindow().setflags (layoutparams.flag_secure, layoutparams.flag_secure) in the Activity onCreate () method; Or getWindow (). AddFlags (WindowManager. LayoutParams. FLAG_SECURE); To prevent screenshots from attacking.

Five, WebView security vulnerabilities

Problem 1: Security vulnerability caused by WebView plaintext password storage

The password saving function is enabled on the WebView component by default. The user is prompted whether to save the password. If the user chooses to save the user name and password entered in the WebView, the user name and password are saved in the Databases/webView. db directory in plain text. An attacker may access the WebView database of the application as root to steal the user name and password stored in the local plaintext.

Solution:

The developer calls webView.getSettings ().setSavepassWord (false), showing that the call API is set to false so that the WebView does not store passwords.

Problem 2: WebView remote code execution vulnerability

In Android API Level 17 and prior versions, because the program does not properly restrict the use of the addJavascriptInterface method, remote attackers can exploit this vulnerability by using the Java Reflection API to execute methods on arbitrary Java objects. AddJavascriptInterface adds a JavaScript bridge interface to the WebView. JavaScript can directly interact with the local Java interface by calling this interface. It is possible that the mobile phone is installed Trojan program, send buckle fee SMS, communication record or SMS is stolen, and even the mobile phone is remote control and other security problems.

Solution:

If you must use the addJavascriptInterface interface, use the following methods: Set minSdkVersion to a value greater than or equal to 17, so that the application cannot run on systems below 4.2. Methods that are allowed to be called by JavaScript must be declared as @javascriptInterface annotations.

Problem 3: Risky WebView system hidden interface vulnerability is not removed

According to WebView remote code execution vulnerability information disclosed by CVE (CVE-2012-663, CVE-2014-7224), there are altogether three hidden interfaces with remote code execution vulnerability in Android system. Are respectively located in android/its/webview “searchBoxJavaBridge” in the interface, the android/its/AccessibilityInjector. In Java “the org.eclipse.swt.accessibility interfaces and acces SibilityTraversal “interface. Apps that invoke these three interfaces will face remote code execution vulnerability on Android systems that enable third-party services in accessibility options.

Solution:

If applications use the WebView component, then the WebView. RemoveJavascriptInterface (String name) API, Remove searchBoxJavaBridge, accessibility, accessibilityTraversal.

6. Data storage security

1. Secret keys and sensitive information

Such configurations should be stored properly and sensitive information should not be hard-coded in the class, which can be written to the Native layer using JNI.

2.SharePreferences

First, SharePreferences should not be used to store sensitive information. Sharedpreferces store XML file data that can be decomcompiled. When storing some configuration information, configure the access permission, such as the private access permission MODE_PRIVATE (activity. MODE_PRIVATE,// default operation mode, indicating that the file is private data and can only be accessed by the application itself. In this mode, the content written to the file overwrites the content of the original file). Avoid configuration information tampering.

3. Security of SQLite database files

Solution:

Whether sensitive information is stored in plaintext, such as important information such as accounts and passwords, is encrypted. Encryption mainly includes symmetric encryption, asymmetric encryption, and summary algorithm.

(1) Symmetric encryption AES/SM4

AES is mainly used for data encryption, even if intercepted during transmission, it is encrypted data. But the drawback of AES is that if the client encrypts, the key must be stored in the app. If the app is successfully PJ, the data will be exposed. Therefore, only when the security of app itself is solved, app can be relatively safe.

Asymmetric encryption RSA/SM2

Because RSA encryption has a length limit, it cannot be used for all data interactions. However, some short data can be used, such as user personal information and so on. In the transaction, the data of an order is not very large and so on.

(3) Abstract algorithm

For example, MD5, SHA-1, and SM3. The so-called irreversible encryption is only one-way encryption, not reverse decryption. MD5 encrypts the data, resulting in a fixed-length hexadecimal code. The purpose of this encryption is generally to match validation, to verify that some data has changed. For example, passwords, when stored to the server, are generally not stored in plain text. Android stores a logo locally and generally doesn’t store it in clear text.

(4) JNI writes into Native layer

Seven, Log data leakage: Log control, formal environment does not print

Problem: Log data leakage risk

Debugging information functions may output important debugging information, the common is that the information contained in the Log class may lead to user information disclosure, disclosure of core code logic, etc., to facilitate attacks, for example: the component name of the Activity; Logs of communication interactions; Trace variable values, etc

Solution:

The application uses the unified Log control base class, which can control the Log output and print flexibly. (Logs are allowed in the test environment, but not in the formal environment); Or use a third-party logging framework

Zip package download vulnerability

Problem: ZipperDown vulnerability

If a large number of applications read zip packages for logical services, the common scenario is to download zip packages from the server for hot updates of resources and codes. When decompressing the ZIP package, if there is no restriction on the file name, add.. to the file name. /.. / prefix, you can decompress the file to any path. If an attacker are replaced with remote hijacked or local methods such as the APP will be loaded with normal zip bag replaced with path prefix malicious zip package, and the APP to unzip the files by processing the file name of the attacker may arise the application resources, the code can be arbitrarily tampering, replacement, so as to realize the remote code hijacking security issues, etc.

Solution:

1. When decompressing the ZIP package, after obtaining the file name, add the filtering code to the file name that may contain.. / Perform filtering judgment.

2. Use the communication protocol encryption technology to encrypt and protect data during communication to prevent data from being tampered.

3. It is recommended that the client and server use encrypted channels for data exchange and verify the integrity of transmitted data to prevent the ZIP package from being intercepted and replaced.

Ix. H5 resource file tampering

Problem: H5 files can be tampered with

If an H5 resource file is stored in plain text, the basic page layout and some important information, such as the login page and payment page, are disclosed. Attackers can tamper with H5 resource files, possibly implant phishing pages or malicious codes, resulting in the disclosure of sensitive information such as user accounts, passwords and payment passwords. What’s more, the H5 code exposes the business logic of relevant activities, which may be used by the black production team to brush red envelopes, collect wool and so on, causing economic losses.

Solution:

You can use a third-party professional security hardening solution to harden H5 files in applications.

X. so file PJ

Problem: So file hardening detection

So file is a dynamic link library file contained in APK. Android uses NDK technology to compile the core code of C/C++ language into so library file for Java layer to call. So file by PJ may lead to application core function code and algorithm leakage. By using core functions and algorithms, attackers can easily capture sensitive data of clients and decrypt it, leading to privacy disclosure or direct property loss of users.

Solution:

So file security hardening, can use the third-party security platform SO hardening scheme.

conclusion

The above are security issues that need to be paid attention to in APP development. Don’t wait until the project is put into production to uniformly test and check APP security issues. When you start a project, you have to know what the security issues are.