Keystore: Enable key attestation from the system context.

When key attestation is requested by the system context, indicate, in
the attestation record, that the requesting package is the system and
not a user app.
This is done by including a single package information with
"AndroidSystem" as the package name and an empty signature.

This change is needed because the package manager currently fails to
provide package details for the system context (UID 1000). Even if it did,
it would be too verbose and include irrelevant packages.

This is necessary for supporting key attestation for keys generated
directly by KeyChain.

Bug: 63388672
Test: Combined with CTS tests for the attestation feature.
Change-Id: I33492ad1286709fe94b11be77e94d4effdf7566f
diff --git a/keystore/keystore_attestation_id.cpp b/keystore/keystore_attestation_id.cpp
index 830482b..97d81c5 100644
--- a/keystore/keystore_attestation_id.cpp
+++ b/keystore/keystore_attestation_id.cpp
@@ -34,6 +34,8 @@
 #include <keystore/KeyAttestationPackageInfo.h>
 #include <keystore/Signature.h>
 
+#include <private/android_filesystem_config.h> /* for AID_SYSTEM */
+
 #include <openssl/asn1t.h>
 #include <openssl/sha.h>
 
@@ -229,16 +231,28 @@
     auto& pm = KeyAttestationApplicationIdProvider::get();
 
     /* Get the attestation application ID from package manager */
-    KeyAttestationApplicationId key_attestation_id;
-    auto status = pm.getKeyAttestationApplicationId(uid, &key_attestation_id);
-    if (!status.isOk()) {
-        ALOGE("package manager request for key attestation ID failed with: %s",
-              status.exceptionMessage().string());
-        return FAILED_TRANSACTION;
+    KeyAttestationApplicationId* key_attestation_id = nullptr;
+    if (uid == AID_SYSTEM) {
+      KeyAttestationPackageInfo::SharedSignaturesVector signatures(
+                new KeyAttestationPackageInfo::SignaturesVector());
+        signatures->push_back(std::unique_ptr<content::pm::Signature>(
+                new content::pm::Signature()));
+
+        std::unique_ptr<KeyAttestationPackageInfo> package_info(
+                new KeyAttestationPackageInfo(
+                        String16("AndroidSystem"), 1, signatures));
+        key_attestation_id = new KeyAttestationApplicationId(std::move(package_info));
+    } else {
+        auto status = pm.getKeyAttestationApplicationId(uid, key_attestation_id);
+        if (!status.isOk()) {
+            ALOGE("package manager request for key attestation ID failed with: %s %d",
+                  status.exceptionMessage().string(), status.exceptionCode());
+            return FAILED_TRANSACTION;
+        }
     }
 
     /* DER encode the attestation application ID */
-    return build_attestation_application_id(key_attestation_id);
+    return build_attestation_application_id(*key_attestation_id);
 }
 
 }  // namespace security