Add check for misprovisioned Pixel 2 device.

Some Pixel devices had a wrong brand value provisioned into keymaster.
Due to this misprovisioning those devices fail device ID attestation because it includes a check for the correct brand value.
This is now solved by re-trying Device ID attestation if we are running
on a potentially misprovisioned device, allowing for the known incorrect
brand value.

Bug: 69471841
Test: atest com.android.cts.devicepolicy.MixedDeviceOwnerTest#testKeyManagement
Change-Id: I99108659f9a7b65d4f80f0a4631a382bfb076738
Merged-In: I6737184eb5a34cf3213f9cb1c5d5e2f1cf02ea38
diff --git a/src/com/android/keychain/KeyChainService.java b/src/com/android/keychain/KeyChainService.java
index e109d6b..3f17636 100644
--- a/src/com/android/keychain/KeyChainService.java
+++ b/src/com/android/keychain/KeyChainService.java
@@ -182,7 +182,7 @@
                 return KeyChain.KEY_ATTESTATION_MISSING_CHALLENGE;
             }
 
-            final KeymasterArguments attestArgs;
+            KeymasterArguments attestArgs;
             try {
                 attestArgs = AttestationUtils.prepareAttestationArguments(
                         mContext, idAttestationFlags, attestationChallenge);
@@ -190,6 +190,31 @@
                 Log.e(TAG, "Failed collecting attestation data", e);
                 return KeyChain.KEY_ATTESTATION_CANNOT_COLLECT_DATA;
             }
+            int errorCode = checkKeyChainStatus(alias, attestationChain, attestArgs);
+            if (errorCode == KeyChain.KEY_ATTESTATION_CANNOT_ATTEST_IDS) {
+                // b/69471841: id attestation might fail due to incorrect provisioning of device
+                try {
+                    attestArgs =
+                            AttestationUtils.prepareAttestationArgumentsIfMisprovisioned(
+                            mContext, idAttestationFlags, attestationChallenge);
+                    if (attestArgs == null) {
+                        return errorCode;
+                    }
+                } catch (DeviceIdAttestationException e) {
+                    Log.e(TAG, "Failed collecting attestation data "
+                            + "during second attempt on misprovisioned device", e);
+                    return KeyChain.KEY_ATTESTATION_CANNOT_COLLECT_DATA;
+                }
+            }
+
+            return checkKeyChainStatus(alias, attestationChain, attestArgs);
+        }
+
+        private int checkKeyChainStatus(
+                String alias,
+                KeymasterCertificateChain attestationChain,
+                KeymasterArguments attestArgs) {
+
             final String keystoreAlias = Credentials.USER_PRIVATE_KEY + alias;
             final int errorCode = mKeyStore.attestKey(keystoreAlias, attestArgs, attestationChain);
             if (errorCode != KeyStore.NO_ERROR) {