How can you make your Android apps more secure

As an Android application developer, it is worth being happy and satisfied to develop an application that users like and are satisfied with. On the basis of powerful functions, how to ensure the application is more secure is also particularly important. Based on the actual development process, we will use the following best practices to make our application “more secure”.

1. Avoid exposing unnecessary components (Android: Exported property)

Android: Exported is a property available in the four major Components of Android: Activity, Service, Provider, and Receiver. It is used to indicate whether to support other applications to call the current component. Android: Exported =true indicates that the specified component is available for use by other apps. Android: Exported =false indicates that the specified component is only available within your App.

The default value for the exported attribute is slightly different for the four major components:

  • Activity/Service/Receiver: The default value is true if the Intent filter is set; otherwise, it is false.
  • Provider: If the Android SDK version is 16 or later, the default value is true. If the Android SDK version is 17 or later, the default value is false.

The Android :exported attribute should be configured according to your requirements.

  • Unexposed Component: In this case, the component is limited to the same App. If the intent-filter is not set, the exported attribute can be omitted (false by default). If intent-filter is specified, you must set exported=false.
  • Partially exposed component: In this case, the component needs to be called by some “specific” apps. In addition to the above “internal use”, it is recommended that the called App and the App of the current exposed component use the same UID:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
             ...
              android:sharedUserId="xxx.xxx.xxx">Copy the code

Or by setting permission on exposed components:

<activity android:name=".xxxActivity" Android :label=" custom Permission "Android: Permission ="com.xxx.permission" > <intent-filter> <action android:name="android.xxx.action" /> <category android:name="android.intent.category.DEFAULT" />  </intent-filter> </activity>Copy the code

The above two methods can not only meet the requirements of exposed components, but also protect data security.

  • Fully exposed components: The component can be invoked by any App. You can manually set exported=true(or intent-filter). However, you need to capture exceptions for intents received by the exposed component to avoid denial of service or crash caused by abnormal intents received by other apps.

# # # # #

For the four components, you need to set the Android: Exported attribute based on actual requirements to avoid sensitive operations or phishing spoofing caused by excessively exposing components.

2. Avoid WebView usage vulnerabilities

At present, more and more apps adopt Hybrid mode for development, and use WebView components to realize the interaction between native and Js. In recent years, webView-related vulnerabilities emerge one after another, so we should pay attention to the following points when using WebView:

2.1 Avoid remote code execution Vulnerability caused by addJavascriptInterface

why

Since JS can call Android objects via the addJavascriptInterface interface:

webView.addJavascriptInterface(new JSObject(), "myObj"); // Parameter 1: Android local object // parameter 2: JS object // Through object mapping Android local object and JS object are associated, so as to realize JS call Android objects and methodsCopy the code

So when JS gets the Android object, it can call all the methods in the Android object, including the system class (java.lang.Runtime class), so as to carry out arbitrary code execution.

The solution
  • API >= 17: Google specifies in API 17(Android 4.2) that functions allowed to be called must be called with@JavascriptInterfaceAnnotate to avoid vulnerability attacks.
  • API < 17: Intercept prompt () is required to fix the bug.

2.2 searchBoxJavaBridge_, accessibility, and accessibilityTraversal remote code execution vulnerability

why
  • Under Android 3.0, The Android system will pass by defaultsearchBoxJavaBridge_Add a Js mapping object to the WebView:searchBoxJavaBridge_object
  • This interface may be exploited to implement remote arbitrary code.
The solution
webview.removeJavascriptInterface("searchBoxJavaBridge_");
webview.removeJavascriptInterface("accessibility");
webview.removeJavascriptInterface("accessibilityTraversal");Copy the code

2.3 WebView domain control is not strict vulnerability

why
  • SetAllowFileAccess: Android default webView.getSettings().setallowFileAccess (true), in the file field, can execute arbitrary JavaScript code, same-origin policy cross-domain access can access private directory files, etc.
  • SetAllowFileAccessFromFileURLs: In JELLY_BEAN (API = 16) previous versions. Default is webView getSettings () setAllowFileAccessFromFileURLs (true), allows Javascript file domain in the url read other local file, This is disabled by default in jelly_beans and later versions.
  • SetAllowUniversalAccessFromFileURLs: Version before JELLY_BEAN. Default is webView getSettings () setAllowUniversalAccessFromFileURLs (true), allows Javascript file domain in the url to access other sources, Includes other local files and HTTP, HTTPS source data. This is disabled by default in jelly_beans and later versions.
The solution

You can set the following parameters to prevent unauthorized access and cross-domain security problems:

setAllowFileAccess(false);
setAllowFileAccessFromFileURLs(false);
setAllowUniversalAccessFromFileURLs(false);Copy the code

2.4 WebView Password plaintext Storage Vulnerability

why

WebView default open password function, if this feature is not closed, when the user to enter the password, will pop-up prompts, asks the user whether to save the password, if you select “yes”, the password will be definitely confirmed to/data/data/com. The package. The name/databases/WebView. Db

The solution
webView.setSavePassword(false)Copy the code

3. Use Https to make network requests

3.1 introduction of HTTPS

HTTP is a plaintext transmission protocol without encryption. If our application uses HTTP to transmit data, the transmitted content will be leaked, and it is easy to be hijacked by middlemen to modify the transmitted content.

HTTPS: HTTP over SSL/TLS. SSL/TLS is a protocol at the top of the transport layer, the lower layer of the application layer, which exists as a secure layer, commonly known as transport layer security protocol.

In the case of HTTP, the secure transport layer is transparent and invisible, and the application layer uses SSLSocket just like normal sockets.

TLS is based on X.509 authentication, which assumes that all digital certificates are issued by a hierarchical digital certificate authority (CA). It is also worth mentioning that TLS is independent of HTTP. Any application layer protocol, such as SSH, can establish secure transport channels based on TLS.

3.2 Digital Certificates and Certificate Chain

A digital Certificate is a string of numbers that marks the identity information of all parties in Internet communication. It is issued by an authoritative organization — CA, also known as Certificate Authority Center. The public key for security is stored in the digital Certificate, which links the user’s identity with the public key. A CA must ensure that the user identity of each certificate it issues is unique.

Link relationships (certificate chains) are created through the registration and publication process and, depending on the level of guarantee, may be done by the CA’s various software or under human supervision. This role of PKI in determining link relationships is called a registry (RA), also known as an intermediate certificate authority or intermediary authority. RA ensures that public keys and personal identity links can prevent repudiation. If there is no RA, the Root certificate of a CA is damaged or leaked, and all other certificates issued by the CA lose security. Therefore, the mainstream commercial digital certificate authority (CA) generally provides level 3 certificates, Root certificates issue intermediate RA certificates, and RA certificates issue user certificates.

The Web browser is preconfigured with a set of root CA certificates that the browser automatically trusts. All certificates from other certification authorities must be accompanied by a certificate chain to verify the validity of these certificates. A certificate chain is a sequence of certificates issued by a series of CA certificates, culminating in the root CA certificate.

General process of certificate verification: After the HTTPS connection is established, the certificate sent by the CA to the client is a layered certificate chain. To verify whether a layer certificate is issued by the upper-layer CA, you need to verify the digital signature attached to the certificate (the digital signature generated by the upper-layer CA through its signature function and private key). To decrypt the digital signature, you need to use the upper-layer CA’s public key. The public key is stored in the upper-level certificate in the certificate chain. The root certificate is signed by itself, that is, the signature of the root certificate is decrypted using the public key saved by itself. This ensures that the lowest level website certificate is actually issued by the CA identified in the certificate. Lower-level certificates can be trusted only when the root certificate is trusted.

3.3 Using HTTPS for Communication

HttpURLConnection is used as an example:

If you use the system’s default SSL, you assume that all cas are trusted, and not all cas are, so it’s best to use a custom trust policy. SSL is verified by X509ExtendedTrustManager, that is, X509TrustManager:

public interface X509TrustManager extends TrustManager {
    public void checkClientTrusted(X509Certificate[] chain, String authType)
            throws CertificateException;

    public void checkServerTrusted(X509Certificate[] chain, String authType)
            throws CertificateException;

    public X509Certificate[] getAcceptedIssuers();
}Copy the code

The final verification of the server certificate will be in the checkServerTrusted method, and a CertificateException will be thrown if the verification fails. Note that: If you do nothing in the checkServerTrusted method, then you trust any certificate by default, and there is no security at all. Don’t do it!

There are two ways to verify a certificate:

Verify certificates using the TrustManager:

By setting a certificate anchor that establishes trust, only that certificate and the issued certificate can be trusted:

This is the general process of using HTTPS for network communication. For HTTPS in WebView, there is no further explanation here. Please refer to related documents. For network communication, HTTPS communication will greatly improve the security of our application communication.

4. Make it harder for applications to be decompiled (repackaged)

APK decompilation is a headache for application developers at present. Although we cannot achieve absolute security (not to be decompilated), we can increase the threshold of application decompilation through relevant technical means.

4.1 Application Hardening

Generally speaking, APP reinforcement refers to a certain degree of protection for programs and running logic that are easy to expose, without affecting the running results of the program itself. The essence of this is to embed code in the binary (hardening) and do some extra work (shinning) to remove control of the program prior to runtime.

APP reinforcement is generally divided into DEX reinforcement and SO reinforcement. Because Java code after dex decompilation is more readable, encryption of DEX files is generally preferred at present.

To put it simply, the basic steps of DEX reinforcement are as follows: the Apk to be encrypted and its shell program Apk, the source Apk is encrypted with the encryption algorithm, and the shell Apk is merged to obtain the new DEX file. Finally, the dex file in the shell program is replaced to obtain the new Apk, so the new Apk is also called the shell program Apk. It is not a complete Apk program, its main job is: responsible for decrypting source Apk. Then load the Apk and get it up and running. Android Apk reinforcement (shell) principle analysis and implementation

The hardened APP can effectively reduce the secondary packaging after decompilation, resulting in counterfeit applications, and repackaging by criminals after adding malicious codes, which affects the interests of manufacturers and threatens the information security of users.

4.2 confused

If you don’t want to open source your application, the code needs to be obfuscated before the application is released, making it harder to read even if the application is decompilated. In addition to making decompilation more difficult, obfuscation can reduce application size, remove unused classes and members, and optimize bytecode execution. The commonly used confounders include ProGuard, DexGuard and DexProtector.

ProGuard is a code obfuscation tool that comes with Android Studio. A ProGuard configuration file is automatically generated when you create a new Android Studio project. Named proguard-rules.pro in project.

Open the ProGuard:

android {
  ...
  buildTypes {
      release {
          minifyEnabled true
          proguardFiles getDefaultProguardFile('proguard-android.txt'),'proguard-rules.pro'
      }
  }
}Copy the code

Note that in ProGuard-rules. pro, keep operation is performed for classes that do not need to be confused to avoid abnormal operation of the program. For more information, please refer to it by yourself.

There are many other ways to improve the security level of an APP, such as storing encryption and properly storing the APP signature. Security is no small matter. As an application developer, we should put APP security and function development on the same footing, try to carry out static scanning and vulnerability scanning on various security platforms before the application goes online, and consider using reinforcement platforms to reinforce the application to improve the security of APP. If the content of this article is biased, please correct it.

References:

  • Jaq.alibaba.com/community/a…
  • Jaq.alibaba.com/community/a…
  • Jaq.alibaba.com/community/a…
  • Blog. Uptech. Team/how-to – make…
  • Blog.csdn.net/carson_ho/a…