Contact usRequest a demo

Protecting iOS app integrity

The integrity module of the Unblu iOS 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 the separate framework UnbluAppIntegrityModule. Add it to your project as described in Framework composition.

You don’t register the module in the UnbluClientConfiguration. Its entry point is the shared instance of the AppIntegrityModuleApi class, AppIntegrityModuleApi.instance.

The QR code scanner asks for camera access, so your app’s Info.plist must contain NSCameraUsageDescription.

Device and app checks

AppIntegrityModuleApi provides the following methods:

  • checkForAppUpdate(completion:) asks the App Store whether a newer version of the app is available. If there is, the completion handler also receives the latest version and the app’s App Store ID.

  • enforceAppUpdate(appID:completion:) opens the app’s App Store page, whether or not an update is available. Pass the App Store ID that checkForAppUpdate(completion:) returns. The completion handler receives true if the page opened.

  • checkDeviceSecurityPolicy() returns whether the device is protected by a passcode or biometrics, and which type of biometrics it uses.

  • isRunningInEmulatorOrDebugger() returns true if the app is running in the Simulator or a debugger is attached.

  • enableBackgroundModeOverlay() covers the app’s window with a black view whenever the app becomes inactive, so the app switcher doesn’t show the app’s content. The module removes the view when the app becomes active again. disableBackgroundModeOverlay() turns this off.

  • disableMainWindowCaptureAndRecording() prevents screenshots and screen recordings of the app’s main window.

Attestation

The module can have the Collaboration Server verify the integrity of the app and the device with Apple’s App Attest and DeviceCheck services:

  • attestKey(challenge:completion:) and generateAssertion(keyId:challenge:completion:) use App Attest to attest a key and generate assertions with it.

  • generateDeviceToken(completion:) generates a DeviceCheck token that identifies the device.

  • getChallenge, verifyDeviceToken, verifyAttestation, and verifyAssertion fetch a challenge from the Collaboration Server and send tokens, attestations, and assertions to it for verification.

  • handleDeviceIntegrityChecks(unbluAgent:completion:) runs the whole flow: it verifies a device token, fetches a challenge, attests a key if the app doesn’t have one yet, and verifies an assertion. Its completion handler receives true if every step succeeds. If the device token fails verification, it stops with false before it uses App Attest.

To verify DeviceCheck tokens and App Attest attestations, the Collaboration Server needs the following configuration, none of which has a default:

App Attest uses the sandbox environment for development builds unless you set the com.apple.developer.devicecheck.appattest-environment entitlement to production. Apps distributed through TestFlight, the App Store, or the Apple Developer Enterprise Program always use the production environment.

By default, the Collaboration Server sends DeviceCheck tokens to Apple’s development endpoint. To use the production endpoint, set com.unblu.mobile.security.verification.appleProductionEndpoint to true.

If the Collaboration Server rejects the DeviceCheck 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 the handling of mutual TLS from the UnbluClientConfiguration. restPath defaults to /rest/v4.

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 members:

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

  • registerWithToken(token:completion:) binds the device with the token the user entered.

  • verify(bindingId:completion:) 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(bindingId:completion:) revokes the binding with the given ID and deletes the device’s key pair and binding ID.

  • localBindingId is the ID of the binding stored on the device, or nil if there’s none. Reading it doesn’t contact the Collaboration Server.

  • sessionUnbluCookies holds the cookies of the device binding API’s session. Assign them to UnbluClient.customCookies to reuse the session without logging in again.

The completion handlers receive a Result. Errors are cases of DeviceBindingError, such as .invalidToken or .bindingRevoked. 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 return the binding ID on success and store it on the device. The module stores one binding per app installation. AppIntegrityModuleApi.instance.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(bindingId:completion:) fails with .bindingRevoked. 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 .unknown(reason:message:), and its reason is PUBLIC_KEY_ALREADY_ENROLLED.

The binding key is an RSA 2048 key pair in the Keychain. When the user deletes and reinstalls the app, the module deletes the key pair and the binding ID. The earlier installation’s binding stays active on the Collaboration Server. By default, com.unblu.devicebinding.maxBindingsPerUser is 1, so binding the device again fails with .bindingLimitReached until that binding is revoked or the Collaboration Server deletes it for not being verified.

To scan the QR code, call AppIntegrityModuleApi.instance.scanQRCode(hint:cancelTitle:success:fail:). It opens the SDK’s full-screen scanner and passes the payload of the first QR code it reads to success. hint and cancelTitle let you localize the scanner’s text.

The SDK never calls verify(bindingId:completion:) itself. Read localBindingId and call verify(bindingId:completion:) whenever the app starts or returns to the foreground.

Listing 1. Binding the device and verifying the binding
import UnbluAppIntegrityModule
import UnbluCoreSDK

final class DeviceBindingController {
    private let integrityModule = AppIntegrityModuleApi.instance
    private let deviceBinding: DeviceBindingApi

    // "configuration" is the UnbluClientConfiguration you also pass to the Unblu client.
    init(configuration: UnbluClientConfiguration, username: String, password: String) {
        // Create one DeviceBindingApi and use it for all device binding calls.
        // Leaving out restPath uses the default, /rest/v4.
        deviceBinding = integrityModule.getDeviceBindingApi(clientConfiguration: configuration,
                                                            username: username,
                                                            password: password)
    }

    func bindDevice() {
        integrityModule.scanQRCode(success: { [weak self] qrPayload in
            self?.deviceBinding.registerWithQrPayload(qrPayload: qrPayload) { result in
                switch result {
                case .success(let bindingId):
                    // The device is bound. The SDK has already stored bindingId.
                    print("Device bound: \(bindingId)")
                case .failure(.invalidToken):
                    // The token is unknown or has expired: the user has to generate a new one.
                    break
                case .failure(let error):
                    print("Binding failed: \(error)")
                }
            }
        }, fail: { reason in
            // The user canceled the scan or denied camera access, the camera isn't available,
            // or there was no view controller to present the scanner.
            print("Scan failed: \(reason)")
        })
    }

    // Call this whenever the app starts or returns to the foreground,
    // for example when you receive UIApplication.willEnterForegroundNotification.
    func verifyDeviceBinding() {
        // If the device has no binding, start binding it.
        guard let bindingId = deviceBinding.localBindingId else {
            bindDevice()
            return
        }

        deviceBinding.verify(bindingId: bindingId) { [weak self] result in
            switch result {
            case .success:
                // The binding is valid for the period configured on the Collaboration Server.
                break
            case .failure(.bindingRevoked):
                // The Collaboration Server doesn't accept the old key pair again.
                _ = self?.integrityModule.resetKeyPair()
                self?.bindDevice()
            case .failure(.bindingNotFound):
                self?.bindDevice()
            case .failure(let error):
                // For example .bridgeUnavailable: try again later.
                print("Verification failed: \(error)")
            }
        }
    }
}

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

See also