Contact usRequest a demo

Protecting Android app integrity

The integrity module of the Unblu Android mobile SDK checks whether your app and the device it runs on can be trusted. It also lets your app take part in device binding. The module reports what it finds; your app decides how to respond.

The device and app checks work in any app. Attestation and device binding are only available in agent apps.

Adding the integrity module

The integrity module is a separate dependency, integritymodule. Add it to your app’s dependencies:

Listing 1. app/build.gradle entry to include the integrity module
dependencies {
    //...
    implementation 'com.unblu.mobile-sdk-android:integritymodule:4.x.x'
    //...
}

You don’t register the integrity module in the UnbluClientConfiguration. Its entry point is the AppIntegrityModuleApi class, which you create with a Context.

Listing 2. Creating the integrity module’s entry point
// Pass an Activity if you want to use addBackgroundOverlay() or isScreenOverlayActive().
val integrityModule = AppIntegrityModuleApi(this)

Device and app checks

The AppIntegrityModuleApi class provides the following methods:

  • isUpdateAvailable(Context, UpdateAvailabilityCallback) asks Google Play whether a newer version of the app is available.

  • forceUpdate() opens the app’s Google Play page if Google Play reports an update that can be installed as an immediate update. It doesn’t install the update. If there’s no such update, it does nothing, even if isUpdateAvailable reports a newer version.

  • isDeviceScreenLockEnabled() returns true if the device is protected by a PIN, pattern, or password.

  • isRunningOnEmulatorOrDebugger() returns true if a debugger is attached, or if the device’s build fingerprint starts with generic or its model name contains google_sdk, as on some emulators.

  • addBackgroundOverlay(boolean) sets or clears FLAG_SECURE on the window of the Activity, which prevents screenshots and screen recordings. If you created AppIntegrityModuleApi with a Context that isn’t an Activity, the method throws a ClassCastException.

  • isScreenOverlayActive() sets FLAG_SECURE on the window of the Activity and returns true if the window doesn’t accept touches or the app may draw over other apps. If you created AppIntegrityModuleApi with a Context that isn’t an Activity, the method throws a ClassCastException.

  • isUsingThirdPartyKeyboard() returns true if the device’s default keyboard doesn’t belong to your app.

  • isDeviceRooted() returns true if the RootBeer library detects that the device is rooted.

  • isFridaRunning() returns true if the process list the app gets from ps contains frida or gum-js-loop, processes of the Frida instrumentation toolkit.

Attestation

The module can have the Collaboration Server verify the integrity of the device with Google Play Integrity:

  • requestIntegrityToken requests an integrity token from Play Integrity for a nonce. By default, it uses Unblu’s Google Cloud project number. If the Collaboration Server uses a service account of your own Google Cloud project, pass that project’s number.

  • getChallenge and verifyAttestation fetch a challenge from the Collaboration Server and send an integrity token to it for verification.

  • handleDeviceIntegrityChecks runs the whole flow: it fetches a challenge, requests an integrity token for it, and has the Collaboration Server verify the token. Its callback receives true if every step succeeds. Called with an UnbluAgentClient, it uses Unblu’s Google Cloud project number. To use your own project, create a verifier with createDeviceIntegrityVerifier(UnbluAgentClient, DeviceIntegrityVerifier.IntegrityTokenRequester) and pass it a requester that calls requestIntegrityToken with your project number. Then pass the verifier to handleDeviceIntegrityChecks(DeviceIntegrityVerifier, DeviceIntegrityResultCallback).

To verify integrity tokens, the Collaboration Server needs the following configuration, none of which has a default:

If the Collaboration Server rejects the Play Integrity verdict and the device has an active binding, it revokes the binding, logs the device out, and disconnects the agent from their open sessions. For information on what the app has to do afterward, refer to When a device loses its binding.

Device binding

The DeviceBindingApi class creates, verifies, and revokes the device’s binding.

To get a DeviceBindingApi, call AppIntegrityModuleApi.getDeviceBindingApi(clientConfiguration, username, password, restPath). The method takes the server URL, entry path, preferences storage, custom cookies, and client certificate from the UnbluClientConfiguration. If you pass null as restPath, the API uses /rest/v4. The device binding API logs in to the Collaboration Server with username and password. The API has no other way to authenticate. It doesn’t use an access token or an existing Unblu session, and it removes Unblu’s own session cookies from the custom cookies. The login only works if com.unblu.authentication.internal.sources includes LOCAL and the user doesn’t log in with two-factor authentication.

If the configuration has no entry path, the device binding API sends its requests without one, whereas the Unblu agent client uses /app by default. Without an entry path, the requests don’t reach the Collaboration Server’s device binding endpoints. Set the entry path explicitly to /app, or to your internal path prefix if your Collaboration Server uses a different one.

Create one DeviceBindingApi and use it for all device binding calls. Each instance logs in to the Collaboration Server on its first call and keeps that session, so every additional instance opens another session. The instance doesn’t renew its session. If the session ends, create a new instance.

DeviceBindingApi provides the following methods:

  • registerWithQrPayload binds the device with the payload of the QR code the user scanned, an unblu-bind:// URI.

  • registerWithToken binds the device with the token the user entered.

  • verify has the Collaboration Server check that the device still holds the binding with the given ID. The device uses its private key to sign a challenge from the Collaboration Server. After a successful verification, the Collaboration Server accepts the device for the period set in com.unblu.devicebinding.verifiedValiditySeconds.

  • revoke revokes the binding with the given ID and deletes the device’s key pair and binding ID.

  • getLocalBindingId returns the ID of the binding stored on the device, or null if there’s none. It doesn’t contact the Collaboration Server.

  • getSessionUnbluCookies returns the cookies of the device binding API’s session. Pass them to UnbluClientConfiguration.Builder.setCustomCookies to reuse the session in the Unblu client without logging in again.

Errors arrive in the callback’s onError method as a DeviceBindingException. Its getReason() method returns an EDeviceBindingErrorReason, such as INVALID_TOKEN or BINDING_REVOKED. Results from the Collaboration Server arrive on the main thread. Errors that the API detects before it sends a request arrive on the calling thread.

The registration methods pass the binding ID to the callback’s onSuccess method and store it on the device. The module stores one binding per app installation. AppIntegrityModuleApi.resetKeyPair() deletes the device’s key pair and the stored binding ID.

If the Collaboration Server revokes the binding, the device keeps the stored binding ID, and verify fails with BINDING_REVOKED. To bind the device again, call resetKeyPair() first. By default, the Collaboration Server keeps revoked bindings for 30 days, as set in com.unblu.devicebinding.revokedBindingRetentionDays. Until it deletes the revoked binding, it doesn’t accept the old key pair again: registering with it fails with the reason UNKNOWN, and getRawReason() returns PUBLIC_KEY_ALREADY_ENROLLED.

A binding from before the app’s data was cleared, or from an earlier installation, stays active on the Collaboration Server. By default, com.unblu.devicebinding.maxBindingsPerUser is 1, so binding the device again fails with BINDING_LIMIT_REACHED until that binding is revoked or the Collaboration Server deletes it for not being verified.

To scan the QR code, call AppIntegrityModuleApi.scanQRCode. It opens the SDK’s full-screen scanner and passes the payload of the first QR code it reads to your callback. The module declares the camera permission in its manifest and asks the user for it when the scanner opens.

The SDK never calls verify itself. Call getLocalBindingId and verify whenever the app starts or returns to the foreground.

Listing 3. Binding the device and verifying the binding
import com.unblu.sdk.module.integrity.AppIntegrityModuleApi
import com.unblu.sdk.module.integrity.devicebinding.DeviceBindingCallback
import com.unblu.sdk.module.integrity.devicebinding.DeviceBindingException
import com.unblu.sdk.module.integrity.devicebinding.EDeviceBindingErrorReason

// This example leaves out the following parts, which your app provides:
// - buildUnbluClientConfiguration() stands for your own code that builds the
//   configuration you also pass to the Unblu client.
// - integrityModule is the AppIntegrityModuleApi created in the previous example.
// - username and password are credentials your app obtains itself.
val configuration = buildUnbluClientConfiguration()

// Create one DeviceBindingApi and use it for all device binding calls.
// Passing null as the last argument uses the default REST path, /rest/v4.
val deviceBinding = integrityModule.getDeviceBindingApi(configuration, username, password, null)

fun bindDevice() {
    integrityModule.scanQRCode(
        { qrPayload ->
            deviceBinding.registerWithQrPayload(qrPayload, object : DeviceBindingCallback<String> {
                override fun onSuccess(result: String?) {
                    // The device is bound. The SDK has already stored the binding ID
                    // that "result" contains.
                }

                override fun onError(error: DeviceBindingException) {
                    // INVALID_TOKEN, for example, means the token is unknown or has expired,
                    // so the user has to generate a new one.
                }
            })
        },
        { errorMessage ->
            // The user canceled the scan, denied camera access, or the camera failed.
        }
    )
}

// Call this whenever the app starts or returns to the foreground.
fun verifyDeviceBinding() {
    // If the device has no binding, start binding it and leave the function.
    val bindingId = deviceBinding.localBindingId ?: return bindDevice()

    deviceBinding.verify(bindingId, object : DeviceBindingCallback<Void> {
        override fun onSuccess(result: Void?) {
            // The binding is valid for the period configured on the Collaboration Server.
        }

        override fun onError(error: DeviceBindingException) {
            when (error.reason) {
                EDeviceBindingErrorReason.BINDING_REVOKED -> {
                    // The Collaboration Server doesn't accept the old key pair again.
                    integrityModule.resetKeyPair()
                    bindDevice()
                }
                EDeviceBindingErrorReason.BINDING_NOT_FOUND -> bindDevice()
                else -> {
                    // For example NETWORK_ERROR: try again later.
                }
            }
        }
    })
}

For information on how device binding works on the Collaboration Server, refer to Device binding.

See also