Improve attestation record unit test.

Added checks for correct population of root-of-trust data, application
IDs, and the attestation challenge.

Bug: 64437520
Test: attestation_record_test
Test: all host unit tests

Change-Id: I686f47c250b50732f30394473139079e73e6d5d0
diff --git a/include/keymaster/attestation_record.h b/include/keymaster/attestation_record.h
index 2b47356..b337f0f 100644
--- a/include/keymaster/attestation_record.h
+++ b/include/keymaster/attestation_record.h
@@ -240,7 +240,8 @@
                                            size_t* asn1_key_desc_len);
 
 /**
- * helper function for attestation record test.
+ * Helper functions for attestation record tests. Caller takes ownership of
+ * |attestation_challenge->data| and |unique_id->data|, deallocate using delete[].
  */
 keymaster_error_t parse_attestation_record(const uint8_t* asn1_key_desc, size_t asn1_key_desc_len,
                                            uint32_t* attestation_version,  //
@@ -252,6 +253,14 @@
                                            AuthorizationSet* tee_enforced,
                                            keymaster_blob_t* unique_id);
 
+/**
+ * Caller takes ownership of |verified_boot_key->data|, deallocate using delete[].
+ */
+keymaster_error_t parse_root_of_trust(const uint8_t* asn1_key_desc, size_t asn1_key_desc_len,
+                                      keymaster_blob_t* verified_boot_key,
+                                      keymaster_verified_boot_t* verified_boot_state,
+                                      bool* device_locked);
+
 keymaster_error_t build_auth_list(const AuthorizationSet& auth_list, KM_AUTH_LIST* record);
 
 keymaster_error_t extract_auth_list(const KM_AUTH_LIST* record, AuthorizationSet* auth_list);
diff --git a/km_openssl/attestation_record.cpp b/km_openssl/attestation_record.cpp
index f59a9f3..2c94bbf 100644
--- a/km_openssl/attestation_record.cpp
+++ b/km_openssl/attestation_record.cpp
@@ -620,6 +620,13 @@
                               record->application_id->length))
         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
 
+    // Attestation application ID
+    if (record->attestation_application_id &&
+        !auth_list->push_back(TAG_ATTESTATION_APPLICATION_ID,
+                              record->attestation_application_id->data,
+                              record->attestation_application_id->length))
+        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
+
     // Creation date time
     if (!get_ulong(record->creation_date_time, TAG_CREATION_DATETIME, auth_list))
         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
@@ -741,4 +748,33 @@
     return extract_auth_list(record->tee_enforced, tee_enforced);
 }
 
+keymaster_error_t parse_root_of_trust(const uint8_t* asn1_key_desc, size_t asn1_key_desc_len,
+                                      keymaster_blob_t* verified_boot_key,
+                                      keymaster_verified_boot_t* verified_boot_state,
+                                      bool* device_locked) {
+    const uint8_t* p = asn1_key_desc;
+    UniquePtr<KM_KEY_DESCRIPTION, KM_KEY_DESCRIPTION_Delete> record(
+        d2i_KM_KEY_DESCRIPTION(nullptr, &p, asn1_key_desc_len));
+    if (!record.get()) {
+        return TranslateLastOpenSslError();
+    }
+    if (!record->tee_enforced) {
+        return KM_ERROR_INVALID_ARGUMENT;
+    }
+    if (!record->tee_enforced->root_of_trust) {
+        return KM_ERROR_INVALID_ARGUMENT;
+    }
+    if (!record->tee_enforced->root_of_trust->verified_boot_key) {
+        return KM_ERROR_INVALID_ARGUMENT;
+    }
+    KM_ROOT_OF_TRUST* root_of_trust = record->tee_enforced->root_of_trust;
+    verified_boot_key->data = dup_buffer(root_of_trust->verified_boot_key->data,
+                                         root_of_trust->verified_boot_key->length);
+    verified_boot_key->data_length = root_of_trust->verified_boot_key->length;
+    *verified_boot_state = static_cast<keymaster_verified_boot_t>(
+        ASN1_ENUMERATED_get(root_of_trust->verified_boot_state));
+    *device_locked = root_of_trust->device_locked;
+    return KM_ERROR_OK;
+}
+
 }  // namespace keymaster
diff --git a/tests/android_keymaster_test.cpp b/tests/android_keymaster_test.cpp
index 7e523f3..253ee92 100644
--- a/tests/android_keymaster_test.cpp
+++ b/tests/android_keymaster_test.cpp
@@ -2314,7 +2314,7 @@
     begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA1);
     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
-    EXPECT_EQ(KM_ERROR_INVALID_ARGUMENT, FinishOperation(&result));
+    EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, FinishOperation(&result));
     EXPECT_EQ(0U, result.size());
 
     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
@@ -2429,7 +2429,7 @@
     begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
-    EXPECT_EQ(KM_ERROR_INVALID_ARGUMENT, FinishOperation(&result));
+    EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, FinishOperation(&result));
     EXPECT_EQ(0U, result.size());
 
     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
@@ -3981,7 +3981,7 @@
     return attest_rec;
 }
 
-static bool verify_attestation_record(const string& challenge,
+static bool verify_attestation_record(const string& challenge, const string& attestation_app_id,
                                       AuthorizationSet expected_sw_enforced,
                                       AuthorizationSet expected_tee_enforced,
                                       uint32_t expected_keymaster_version,
@@ -4035,6 +4035,10 @@
     if (expected_tee_enforced.GetTagValue(TAG_INCLUDE_UNIQUE_ID))
         att_tee_enforced.push_back(TAG_INCLUDE_UNIQUE_ID);
 
+    // Add TAG_ATTESTATION_APPLICATION_ID to the expected sw-enforced list.
+    expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, attestation_app_id.data(),
+                                   attestation_app_id.size());
+
     att_sw_enforced.Sort();
     expected_sw_enforced.Sort();
     EXPECT_EQ(expected_sw_enforced, att_sw_enforced);
@@ -4073,7 +4077,7 @@
     }
 
     EXPECT_TRUE(verify_attestation_record(
-        "challenge", sw_enforced(), hw_enforced(), expected_keymaster_version,
+        "challenge", "attest_app_id", sw_enforced(), hw_enforced(), expected_keymaster_version,
         expected_keymaster_security_level, cert_chain.entries[0]));
 
     keymaster_free_cert_chain(&cert_chain);
@@ -4099,7 +4103,7 @@
     ASSERT_EQ(3U, cert_chain.entry_count);
     EXPECT_TRUE(verify_chain(cert_chain));
     EXPECT_TRUE(verify_attestation_record(
-        "challenge", sw_enforced(), hw_enforced(), expected_keymaster_version,
+        "challenge", "attest_app_id", sw_enforced(), hw_enforced(), expected_keymaster_version,
         expected_keymaster_security_level, cert_chain.entries[0]));
 
     keymaster_free_cert_chain(&cert_chain);
diff --git a/tests/attestation_record_test.cpp b/tests/attestation_record_test.cpp
index be36084..02b99f7 100644
--- a/tests/attestation_record_test.cpp
+++ b/tests/attestation_record_test.cpp
@@ -29,35 +29,62 @@
 class TestContext : public AttestationRecordContext {
   public:
     keymaster_security_level_t GetSecurityLevel() const override {
-        return KM_SECURITY_LEVEL_SOFTWARE;
+        return KM_SECURITY_LEVEL_TRUSTED_ENVIRONMENT;
     }
     keymaster_error_t GenerateUniqueId(uint64_t /* creation_date_time */,
-                                       const keymaster_blob_t& /* application_id */,
-                                       bool /* reset_since_rotation */, Buffer* unique_id) const override {
-        // Finally, the reason for defining this class:
-        unique_id->Reinitialize("foo", 3);
+                                       const keymaster_blob_t& application_id,
+                                       bool /* reset_since_rotation */,
+                                       Buffer* unique_id) const override {
+        // Use the application ID directly as the unique ID.
+        unique_id->Reinitialize(application_id.data, application_id.data_length);
         return KM_ERROR_OK;
     }
+    keymaster_error_t GetVerifiedBootParams(keymaster_blob_t* verified_boot_key,
+                                            keymaster_verified_boot_t* verified_boot_state,
+                                            bool* device_locked) const override {
+        verified_boot_key->data = vboot_key_;
+        verified_boot_key->data_length = sizeof(vboot_key_);
+        *verified_boot_state = KM_VERIFIED_BOOT_VERIFIED;
+        *device_locked = true;
+        return KM_ERROR_OK;
+    }
+
+    void VerifyRootOfTrust(const keymaster_blob_t& verified_boot_key,
+                           keymaster_verified_boot_t verified_boot_state, bool device_locked) {
+        EXPECT_EQ(sizeof(vboot_key_), verified_boot_key.data_length);
+        if (sizeof(vboot_key_) == verified_boot_key.data_length) {
+            EXPECT_EQ(0, memcmp(verified_boot_key.data, vboot_key_, sizeof(vboot_key_)));
+        }
+        EXPECT_TRUE(device_locked);
+        EXPECT_EQ(KM_VERIFIED_BOOT_VERIFIED, verified_boot_state);
+    }
+
+  private:
+    uint8_t vboot_key_[32]{"test_vboot_key"};
 };
 
 TEST(AttestTest, Simple) {
+    TestContext context;
     AuthorizationSet hw_set(AuthorizationSetBuilder()
                                 .RsaSigningKey(512, 3)
                                 .Digest(KM_DIGEST_SHA_2_256)
                                 .Digest(KM_DIGEST_SHA_2_384)
                                 .Authorization(TAG_OS_VERSION, 60000)
                                 .Authorization(TAG_OS_PATCHLEVEL, 201512)
-                                .Authorization(TAG_APPLICATION_ID, "bar", 3));
-    AuthorizationSet sw_set(AuthorizationSetBuilder().Authorization(TAG_ACTIVE_DATETIME, 10));
+                                .Authorization(TAG_INCLUDE_UNIQUE_ID));
+    AuthorizationSet sw_set(AuthorizationSetBuilder()
+                                .Authorization(TAG_ACTIVE_DATETIME, 10)
+                                .Authorization(TAG_CREATION_DATETIME, 10)
+                                .Authorization(TAG_APPLICATION_ID, "fake_app_id", 11));
 
     UniquePtr<uint8_t[]> asn1;
-    size_t asn1_len;
+    size_t asn1_len = 0;
     AuthorizationSet attest_params(
         AuthorizationSetBuilder()
-            .Authorization(TAG_ATTESTATION_CHALLENGE, "hello", 5)
-            .Authorization(TAG_ATTESTATION_APPLICATION_ID, "hello again", 11));
-    EXPECT_EQ(KM_ERROR_OK, build_attestation_record(attest_params, sw_set, hw_set, TestContext(),
-                                                    &asn1, &asn1_len));
+            .Authorization(TAG_ATTESTATION_CHALLENGE, "fake_challenge", 14)
+            .Authorization(TAG_ATTESTATION_APPLICATION_ID, "fake_attest_app_id", 18));
+    ASSERT_EQ(KM_ERROR_OK,
+              build_attestation_record(attest_params, sw_set, hw_set, context, &asn1, &asn1_len));
     EXPECT_GT(asn1_len, 0U);
 
     std::ofstream output("attest.der",
@@ -80,15 +107,37 @@
                                        &keymaster_security_level, &attestation_challenge,
                                        &parsed_sw_set, &parsed_hw_set, &unique_id));
 
+    // Check that the challenge is consistent across build and parse.
+    EXPECT_EQ("fake_challenge",
+              std::string(reinterpret_cast<const char*>(attestation_challenge.data), 14));
     delete[] attestation_challenge.data;
+
+    // Check that the unique id was populated as expected.
+    EXPECT_EQ("fake_app_id", std::string(reinterpret_cast<const char*>(unique_id.data), 11));
     delete[] unique_id.data;
 
+    // The attestation ID is expected to appear in parsed_sw_set.
+    sw_set.push_back(TAG_ATTESTATION_APPLICATION_ID, "fake_attest_app_id", 18);
+
+    // The TAG_INCLUDE_UNIQUE_ID tag is not expected to appear in parsed_hw_set.
+    hw_set.erase(hw_set.find(TAG_INCLUDE_UNIQUE_ID));
+
+    // Check that the list of tags is consistent across build and parse.
     hw_set.Sort();
     sw_set.Sort();
     parsed_hw_set.Sort();
     parsed_sw_set.Sort();
     EXPECT_EQ(hw_set, parsed_hw_set);
     EXPECT_EQ(sw_set, parsed_sw_set);
+
+    // Check the root of trust values.
+    keymaster_blob_t verified_boot_key;
+    keymaster_verified_boot_t verified_boot_state;
+    bool device_locked;
+    EXPECT_EQ(KM_ERROR_OK, parse_root_of_trust(asn1.get(), asn1_len, &verified_boot_key,
+                                               &verified_boot_state, &device_locked));
+    context.VerifyRootOfTrust(verified_boot_key, verified_boot_state, device_locked);
+    delete[] verified_boot_key.data;
 }
 
 }  // namespace test