> For the complete documentation index, see [llms.txt](https://docs.payments.thalescloud.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.payments.thalescloud.io/classic-push-provisioning/developer-guide/security-guidelines/android.md).

# Android

### Application-Level Protection <a href="#application-level-protection" id="application-level-protection"></a>

#### Verify the Installer of Your Application <a href="#verify-the-installer-of-your-application" id="verify-the-installer-of-your-application"></a>

To ensure the application is distributed through the official Google Play Store, verify that the installer package name is `com.android.vending`. This helps prevent side-channel distribution and unauthorized installations from third-party sources.

#### Force Application Update <a href="#force-application-update" id="force-application-update"></a>

When a security update is available on Google Play, force the end user to update before continuing to use the service. This ensures end users always use the latest version with the required security fixes.

#### Store the Application Resources Only in Internal Storage <a href="#store-the-application-resources-only-in-internal-storage" id="store-the-application-resources-only-in-internal-storage"></a>

Storing application resources in the internal storage (instead of external storage) mitigates the risk of a "Man-in-the-Disk" (MITD) attack. This means that the application should not allow itself to be moved to external storage using the `android:installLocation` manifest attribute.

#### Compatibility with SDK Supported OS Versions <a href="#compatibility-with-sdk-supported-os-versions" id="compatibility-with-sdk-supported-os-versions"></a>

Design the application to run on devices with OS versions supported by the SDK. This helps ensure a consistent and reliable end user experience.

#### Enable Device Lock Screen <a href="#enable-device-lock-screen" id="enable-device-lock-screen"></a>

It is recommended that the application checks that the device is protected with a PIN, pattern, or password by using the following code snippet:

{% code overflow="wrap" %}

```
KeyguardManager kgManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);kgManager.isDeviceSecure()
```

{% endcode %}

#### Prevent Excessive Permissions <a href="#prevent-excessive-permissions" id="prevent-excessive-permissions"></a>

It is recommended that the application declares only the required Android permissions. Otherwise, an adversary may gain access to privileged information.

#### Platform Security Exported Attributes <a href="#platform-security-exported-attributes" id="platform-security-exported-attributes"></a>

Android applications are composed of one or more of the following components:

* Activities
* Services
* Broadcast receivers
* Content providers

When using these components, be aware of the associated risks and attack paths. Inter-application communication is generally risky. Consider exposing only your main activity. Set `export=false` for all other components. If other components must be public, protect them with custom permissions.

#### Disable Application Debugging in Release Variant <a href="#disable-application-debugging-in-release-variant" id="disable-application-debugging-in-release-variant"></a>

To remove debug mode, explicitly set the `android:debuggable` attribute of the `<application>` element to `false` in the Android manifest file. Ensure the final APK is not debuggable by performing the following checks:

```
aapt d xmltree <myApplication.apk> AndroidManifest.xml
```

After verifying the final APK, ensure the attribute is present with the value `0x0`. You can automate this check in your build process.

#### Evaluate App Links and Deep Links <a href="#evaluate-app-links-and-deep-links" id="evaluate-app-links-and-deep-links"></a>

Deep links and app links can increase the application’s attack surface. Common risks include link hijacking and unintended exposure of sensitive functionality. Behavior also differs by Android version:

* Before Android 12 (API level 31), if the application has any non-verifiable links, it can cause the system to not verify all Android App Links for that application.
* Starting from Android 12 (API level 31), the applications benefit from a reduced attack surface. Unless the target application is approved for the specific domain contained in that web intent, a generic web intent resolves to the end user’s default browser application.

Enumerate all deep links and verify correct website association. Thoroughly test the supported operations. Treat all input data as untrusted and always validate it. Validation ensures only expected data is processed.

#### Prevent Auto-Generated Screenshot <a href="#prevent-auto-generated-screenshot" id="prevent-auto-generated-screenshot"></a>

Prevent sensitive data leakage through foreground screenshots by using the application’s `Activity.onCreate` method:

```
getWindow().addFlags(LayoutParams.FLAG_SECURE);.
```

You can also use the `onPause()` method of your activities to clear other sensitive information that should not be kept in the memory while the mobile application is running in the background.

#### Proper App Signing <a href="#proper-app-signing" id="proper-app-signing"></a>

Ensure that the release build has been signed via both the v1 and v2 schemes for Android 7.0 (API level 24) and later, and via all three schemes for Android 9 (API level 28) and later.

> <i class="fa-info-circle">:info-circle:</i>
>
> #### Note <a href="#note" id="note"></a>
>
> The developer is the owner of the code-signing certificate in the APK.

APK signatures can be verified using the apksigner tool which is available at \[SDK-Path]/build-tools/\[version].

{% code overflow="wrap" %}

```
$ apksigner verify --verbose Desktop/example.apkVerified using v1 scheme (JAR signing): trueVerified using v2 scheme (APK Signature Scheme v2): true Verified using v3 scheme (APK Signature Scheme v3): true Number of signers: 1
```

{% endcode %}

#### Prevent Backup of Application Data <a href="#prevent-backup-of-application-data" id="prevent-backup-of-application-data"></a>

To prevent the backup of application data, set the `allowBackup` attribute to `false` in the application tag of the `AndroidManifest.xml` file.

{% code overflow="wrap" %}

```
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android">    <application        android:allowBackup="false">    </application></manifest>
```

{% endcode %}

By default, the `android:allowBackup` attribute is set to `true`. When this flag is set to `true`, the end user can back up and restore application data. This may have security consequences for the application.

The backup feature allows end users who have enabled USB debugging to copy application data from the device. Once backed up, application data can be read by the end user.

Setting `allowBackup="false"` allows the application to opt out of both backup and restore capabilities.

#### Prevent Accessibility on Sensitive Screens <a href="#prevent-accessibility-on-sensitive-screens" id="prevent-accessibility-on-sensitive-screens"></a>

The accessibility service on Android is a powerful feature that allows end users with disabilities to interact with their devices in new ways. However, it also introduces security risks because accessibility services can be abused to steal sensitive data or control the device.

Malware targeting banking and payment applications often abuses accessibility features. The application should determine whether accessibility apps need access to sensitive content. The following techniques can detect accessibility services and reduce sensitive data leakage through accessibility events. Exercise caution when applying these checks, as they may make the application harder to use for end users with disabilities.

**Detect an Active Accessibility Service**

Check if there are any active accessibility services currently running. If any accessibility service is present, you can use this technique to limit the functionality of your application.

**Check the List of Allowed Accessibility Services**

A system API is available to retrieve enabled and running accessibility services. You can maintain an allowlist or blocklist of accessibility apps and their capabilities. If unwanted accessibility services are running in the background, warn the end user, abort the operation, or prompt the end user to disable those services.

**Disable Accessibility Access to a View**

An alternative approach is to disable accessibility access for a view. This prevents accessibility events from the view and its subviews.

```java
private void disableAccessibilityEvent() {
    ViewCompat.setImportantForAccessibility(this, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
}

```

**Prevent Accessibility Events Emitting from EditText Views**

By default, the system `EditText` for passwords will show the input value for a short while (say 1.5 seconds) before masking it into a dot, so accessibility services may receive texts such as "\*\*\*1", "\*\*\*\*\*3". The following code snippet is an intuitive way to hide such sensitive input values from the accessibility apps

```java
private fun hideLastDigit() {
    transformationMethod = SecureTransformationMethod()
}

class SecureTransformationMethod : PasswordTransformationMethod() {
    override fun getTransformation(source: CharSequence?, view: View?): CharSequence {
        if (source == null) return SecureCharSequence("")
        return SecureCharSequence(source)
    }

    class SecureCharSequence(private val charSequence: CharSequence) : CharSequence {
        override val length: Int
            get() = charSequence.length

        override fun get(index: Int): Char {
            return 'x'
        }

        override fun subSequence(startIndex: Int, endIndex: Int): CharSequence {
            return SecureCharSequence(charSequence.subSequence(startIndex, endIndex))
        }
    }
}
```

#### Prevent Overlay Attacks <a href="#prevent-overlay-attacks" id="prevent-overlay-attacks"></a>

Android overlays let one application draw on top of another application. They can improve the end user experience. They can also be abused for phishing, privilege escalation, and data theft. Android API 9 introduced methods to detect overlays based on touch events: `onTouch`, `onFilterTouchEventForSecurity`, and `setFilterTouchesWhenObscured`. On API 31 and later, you are protected against non-system overlays for every view where you call `setHideOverlayWindows(true)`. On API levels below 31, the application may still be vulnerable to overlays that do not pass touch events. For more details, refer to [Protecting against Android Overlay Attacks](https://www.guardsquare.com/blog/protecting-against-android-overlay-attacks-guardsquare).

#### Use Proprietary Keyboard <a href="#use-proprietary-keyboard" id="use-proprietary-keyboard"></a>

It is not recommended to use third-party keyboards for entering sensitive information such as a PIN, password, or PII. Prefer a proprietary keyboard used only by the application. This reduces the risk of third-party keyboards capturing sensitive input.

If a proprietary keyboard is not possible, prefer a customized PIN pad. You can also scramble the PIN pad layout. Scrambling generates a random key layout on the screen. This helps mitigate shoulder surfing and accessibility-based malware attacks.

### Data Protection <a href="#data-protection" id="data-protection"></a>

#### Data in Transit <a href="#data-in-transit" id="data-in-transit"></a>

The application must use TLS 1.2 or TLS 1.3. Configure the server to use strong cipher suites. Also apply the following measures to protect data in transit:

**Certificate Pinning**

The application should use certificate pinning for all communication with the server. Starting with Android 7.0, you can use Network Security Configuration to enforce certificate pinning for the domains the application communicates with. Refer to [Network Security Config](https://developer.android.com/training/articles/security-config) for more details.

**Protect Data with Encryption**

The application must exercise extra caution when sending sensitive data, such as personally identifiable information (PII), to its server. It is recommended to enforce confidentiality and authentication on top of TLS protections.

#### Data at Rest <a href="#data-at-rest" id="data-at-rest"></a>

The application must protect sensitive data, even when stored within the application sandbox. Privileged malware can still access sandboxed data. Enforce confidentiality, authentication, and device-bound security properties when storing sensitive data. On Android, applications can use `EncryptedSharedPreference` or `EncryptedFile` to meet these requirements. For more information, refer to [Protecting data at rest](https://developer.android.com/topic/security/data).

### Authentication <a href="#authentication" id="authentication"></a>

#### Enable Biometric Authentication <a href="#enable-biometric-authentication" id="enable-biometric-authentication"></a>

The application must enable biometric authentication for end user login. When using biometric authentication, it is recommended to use Android Keystore and biometric crypto object-based authentication for stronger security. This also helps detect when biometrics are added or removed.

#### Enforce Multi-Factor Authentication <a href="#enforce-multi-factor-authentication" id="enforce-multi-factor-authentication"></a>

Enforcing multi-factor authentication (MFA) is a crucial security measure to protect sensitive operations of the SDK and the application. MFA adds an extra layer of security by requiring users to provide multiple forms of authentication before accessing sensitive features or data. This can greatly reduce the risk of unauthorized access even if an end user's primary authentication factor is compromised.

### Cryptography Guidelines <a href="#cryptography-guidelines" id="cryptography-guidelines"></a>

#### Security Providers <a href="#security-providers" id="security-providers"></a>

It is recommended to use the [Google Play services updated security provider](https://developer.android.com/training/articles/security-gms-provider) to protect against future vulnerabilities in platform crypto providers.

Because the Thales TPC SDK is not responsible for updating or notifying the end user, the application should ensure the Google Play services security provider is up to date on the end user’s device.

#### Secure Random Number Generation <a href="#secure-random-number-generation" id="secure-random-number-generation"></a>

The application must always use methods of the `SecureRandom` class to generate sensitive cryptographic keys and other random values. For API level 29 and later, it is recommended to use `SecureRandom.getInstanceStrong()` to rely on the platform default security provider instead of an application-provided provider.

### Application Hardening <a href="#application-hardening" id="application-hardening"></a>

#### Detect Rooted Devices <a href="#detect-rooted-devices" id="detect-rooted-devices"></a>

Detect a compromised device environment, such as rooting frameworks and superuser binaries, before initializing the application and before performing any sensitive operations. For more details, refer to [Common Root Detection Methods](https://mas.owasp.org/MASTG/Android/0x05j-Testing-Resiliency-Against-Reverse-Engineering/#root-detection-and-common-root-detection-methods).

#### Detect Hooking on Application <a href="#detect-hooking-on-application" id="detect-hooking-on-application"></a>

Hooking injects a payload into the application process. Attackers use it to intercept sensitive data such as cryptographic keys and PII, study security mechanisms, or change application flow. Applications should detect hooking attempts. For more details, refer to [Hook Detection Methods](https://mas.owasp.org/MASTG/Android/0x05j-Testing-Resiliency-Against-Reverse-Engineering/#detection-of-reverse-engineering-tools).

#### Detect Debugger Attach <a href="#detect-debugger-attach" id="detect-debugger-attach"></a>

On compromised devices, an attacker can attach a debugger to the release variant of the application. This lets them debug application flow in both native and Java/Kotlin binaries. Detect debuggers in both Java/Kotlin and native code, especially before executing sensitive operations. For more details, refer to [Debug Detection Methods](https://mas.owasp.org/MASTG/Android/0x05j-Testing-Resiliency-Against-Reverse-Engineering/#anti-debugging).

#### Detect Emulator <a href="#detect-emulator" id="detect-emulator"></a>

Emulators can provide a less trusted environment and enable dynamic analysis. Detect emulator usage at application startup. For more details, refer to [Emulator Detection](https://mas.owasp.org/MASTG/Android/0x05j-Testing-Resiliency-Against-Reverse-Engineering/#emulator-detection).

#### Detect Application Tampering <a href="#detect-application-tampering" id="detect-application-tampering"></a>

To prevent malicious hacking into the application code, it is recommended to verify the application's signing certificate signature hash at runtime. Attackers cannot replicate this signature when they sign the application after tampering the binary or any resource files. However, a strong obfuscation is required to protect the signing certificate hash within the binary from modification. Refer to [Application Tamper Detection](https://books.nowsecure.com/secure-mobile-development/en/coding-practices/anti-tamper-techniques.html) for more details.

In addition, the application can also communicate the signing certificate signature hash to the application server. The application server verifies that the signature hash matches the configured application hash values before honoring further requests from the client.

#### Obfuscate Application <a href="#obfuscate-application" id="obfuscate-application"></a>

The application and all its components must be obfuscated. This increases the complexity for an attacker to reverse engineer the mobile application and work out the algorithms used or to identify its secret data.

Although Thales TPC SDK is already obfuscated using *DexGuard*, it is still important for the application to obfuscate the Thales TPC SDK public APIs by applying the rules shared with the binary packages. It is extremely important to follow the obfuscation recommendations provided and pay special attention to:

```
-flattenpackagehierachy util
```

Using the package name 'util' is recommended to ensure consistency in the obfuscation. Commercial tools are available for obfuscation. For Android, the current recommendation is to use *DexGuard*. For more information on obfuscation, refer to [Obfuscation Tools and Techniques](https://mas.owasp.org/MASTG/Android/0x05j-Testing-Resiliency-Against-Reverse-Engineering/#obfuscation).

### Secure Coding <a href="#secure-coding" id="secure-coding"></a>

#### Wiping Sensitive Data on Android <a href="#wiping-sensitive-data-on-android" id="wiping-sensitive-data-on-android"></a>

Store sensitive data such as cryptographic keys, PII, and other sensitive end user data in byte arrays. In Java, you cannot alter the underlying behavior of objects such as `String` and `StringBuilder`. You also cannot control how many copies exist in memory over time.

It is highly recommended to wipe sensitive data yourself rather than relying on the garbage collector. Always use a `finally` block so data is wiped even if an exception occurs, as shown in the following code snippet:

```java
byte[] password = this.getUserPassword();
try {
  // Use the password to login
  this.logUserIn(password);
} finally {
  	// Even if there is no exception catch here, there can be a
  	//RuntimeException that should still trigger this finally block
  	// to execute
  MemoryHelper.clearData(password);
}

//One way to implement a byte array wiping method is to rewrite every element in the arrays in the MemoryHelper
class public static void clearData(byte[] baBuffer) {
  if (baBuffer == null)
    return;
  for(i = 0;  i < baBuffer.length; i++) {
    baBuffer[i] = (byte)0;
  }
}
```

#### Secure Coding Rules <a href="#secure-coding-rules" id="secure-coding-rules"></a>

Gather secure coding guidelines from trusted sources such as Apple, Google, and OWASP (Open Web Application Security Project). You can also contact the Thales Handset Security Community to get access to these guidelines.

It is also recommended to use static code analysis tools (such as PMD or HP Fortify) to enforce these guidelines.

#### Use Lint Tool <a href="#use-lint-tool" id="use-lint-tool"></a>

Before each feature is complete, and before the completion of the final delivery, use lint to identify and fix any security issues.

Android documentation describes `lint` as a static code analysis tool. It checks project source files for potential bugs and optimization opportunities related to correctness, security, performance, usability, accessibility, and internationalization.

The complete list of checks performed by `lint` can be referenced from the Android Developer website.

### General Android Security Tips <a href="#general-android-security-tips" id="general-android-security-tips"></a>

Be aware of and follow the security features and technologies provided by Android. See [Android Security Tips](https://developer.android.com/training/articles/security-tips).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.payments.thalescloud.io/classic-push-provisioning/developer-guide/security-guidelines/android.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
