1 /*
2  * Copyright (C) 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #pragma once
18 
19 #include <functional>
20 #include <string_view>
21 
22 #include <aidl/Gtest.h>
23 #include <aidl/Vintf.h>
24 #include <android-base/properties.h>
25 #include <binder/IServiceManager.h>
26 #include <binder/ProcessState.h>
27 #include <gtest/gtest.h>
28 #include <openssl/x509.h>
29 
30 #include <aidl/android/hardware/security/keymint/ErrorCode.h>
31 #include <aidl/android/hardware/security/keymint/IKeyMintDevice.h>
32 #include <aidl/android/hardware/security/keymint/MacedPublicKey.h>
33 
34 #include <keymint_support/attestation_record.h>
35 #include <keymint_support/authorization_set.h>
36 #include <keymint_support/openssl_utils.h>
37 
38 namespace aidl::android::hardware::security::keymint {
39 
40 ::std::ostream& operator<<(::std::ostream& os, const AuthorizationSet& set);
41 
42 inline bool operator==(const keymint::AuthorizationSet& a, const keymint::AuthorizationSet& b) {
43     return a.size() == b.size() && std::equal(a.begin(), a.end(), b.begin());
44 }
45 
46 namespace test {
47 
48 using ::android::sp;
49 using Status = ::ndk::ScopedAStatus;
50 using ::std::optional;
51 using ::std::shared_ptr;
52 using ::std::string;
53 using ::std::vector;
54 
55 constexpr uint64_t kOpHandleSentinel = 0xFFFFFFFFFFFFFFFF;
56 
57 const string FEATURE_KEYSTORE_APP_ATTEST_KEY = "android.hardware.keystore.app_attest_key";
58 const string FEATURE_STRONGBOX_KEYSTORE = "android.hardware.strongbox_keystore";
59 const string FEATURE_HARDWARE_KEYSTORE = "android.hardware.hardware_keystore";
60 
61 // RAII class to ensure that a keyblob is deleted regardless of how a test exits.
62 class KeyBlobDeleter {
63   public:
KeyBlobDeleter(const shared_ptr<IKeyMintDevice> & keymint,const vector<uint8_t> & key_blob)64     KeyBlobDeleter(const shared_ptr<IKeyMintDevice>& keymint, const vector<uint8_t>& key_blob)
65         : keymint_(keymint), key_blob_(key_blob) {}
66     ~KeyBlobDeleter();
67 
68   private:
69     shared_ptr<IKeyMintDevice> keymint_;
70     vector<uint8_t> key_blob_;
71 };
72 
73 class KeyMintAidlTestBase : public ::testing::TestWithParam<string> {
74   public:
75     struct KeyData {
76         vector<uint8_t> blob;
77         vector<KeyCharacteristics> characteristics;
78     };
79 
80     static bool arm_deleteAllKeys;
81     static bool dump_Attestations;
82 
83     // Directory to store/retrieve keyblobs, using subdirectories named for the
84     // KeyMint instance in question (e.g. "./default/", "./strongbox/").
85     static std::string keyblob_dir;
86     // To specify if users expect an upgrade on the keyBlobs.
87     static std::optional<bool> expect_upgrade;
88 
89     void SetUp() override;
TearDown()90     void TearDown() override {
91         if (key_blob_.size()) {
92             CheckedDeleteKey();
93         }
94         AbortIfNeeded();
95     }
96 
97     void InitializeKeyMint(std::shared_ptr<IKeyMintDevice> keyMint);
keyMint()98     IKeyMintDevice& keyMint() { return *keymint_; }
99     int32_t AidlVersion() const;
os_version()100     uint32_t os_version() { return os_version_; }
os_patch_level()101     uint32_t os_patch_level() { return os_patch_level_; }
vendor_patch_level()102     uint32_t vendor_patch_level() { return vendor_patch_level_; }
103     uint32_t boot_patch_level(const vector<KeyCharacteristics>& key_characteristics);
104     uint32_t boot_patch_level();
105     bool isDeviceIdAttestationRequired();
106     bool isSecondImeiIdAttestationRequired();
107     bool isRkpOnly();
108 
109     bool Curve25519Supported();
110 
111     ErrorCode GenerateKey(const AuthorizationSet& key_desc);
112 
113     ErrorCode GenerateKey(const AuthorizationSet& key_desc, vector<uint8_t>* key_blob,
114                           vector<KeyCharacteristics>* key_characteristics);
115 
116     ErrorCode GenerateKey(const AuthorizationSet& key_desc,
117                           const optional<AttestationKey>& attest_key, vector<uint8_t>* key_blob,
118                           vector<KeyCharacteristics>* key_characteristics,
119                           vector<Certificate>* cert_chain);
120 
121     ErrorCode ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
122                         const string& key_material, vector<uint8_t>* key_blob,
123                         vector<KeyCharacteristics>* key_characteristics);
124     ErrorCode ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
125                         const string& key_material);
126 
127     ErrorCode ImportWrappedKey(string wrapped_key, string wrapping_key,
128                                const AuthorizationSet& wrapping_key_desc, string masking_key,
129                                const AuthorizationSet& unwrapping_params, int64_t password_sid,
130                                int64_t biometric_sid);
ImportWrappedKey(string wrapped_key,string wrapping_key,const AuthorizationSet & wrapping_key_desc,string masking_key,const AuthorizationSet & unwrapping_params)131     ErrorCode ImportWrappedKey(string wrapped_key, string wrapping_key,
132                                const AuthorizationSet& wrapping_key_desc, string masking_key,
133                                const AuthorizationSet& unwrapping_params) {
134         return ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, masking_key,
135                                 unwrapping_params, 0 /* password_sid */, 0 /* biometric_sid */);
136     }
137 
138     ErrorCode GetCharacteristics(const vector<uint8_t>& key_blob, const vector<uint8_t>& app_id,
139                                  const vector<uint8_t>& app_data,
140                                  vector<KeyCharacteristics>* key_characteristics);
141     ErrorCode GetCharacteristics(const vector<uint8_t>& key_blob,
142                                  vector<KeyCharacteristics>* key_characteristics);
143 
144     void CheckCharacteristics(const vector<uint8_t>& key_blob,
145                               const vector<KeyCharacteristics>& generate_characteristics);
146     void CheckAppIdCharacteristics(const vector<uint8_t>& key_blob, std::string_view app_id_string,
147                                    std::string_view app_data_string,
148                                    const vector<KeyCharacteristics>& generate_characteristics);
149 
150     ErrorCode DeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob = false);
151     ErrorCode DeleteKey(bool keep_key_blob = false);
152 
153     ErrorCode DeleteAllKeys();
154 
155     ErrorCode DestroyAttestationIds();
156 
157     void CheckedDeleteKey();
158 
159     ErrorCode Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
160                     const AuthorizationSet& in_params, AuthorizationSet* out_params,
161                     std::shared_ptr<IKeyMintOperation>& op);
162     ErrorCode Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
163                     const AuthorizationSet& in_params, AuthorizationSet* out_params,
164                     std::optional<HardwareAuthToken> hat = std::nullopt);
165     ErrorCode Begin(KeyPurpose purpose, const AuthorizationSet& in_params,
166                     AuthorizationSet* out_params);
167     ErrorCode Begin(KeyPurpose purpose, const AuthorizationSet& in_params);
168 
169     ErrorCode UpdateAad(const string& input);
170     ErrorCode Update(const string& input, string* output);
171 
172     ErrorCode Finish(const string& message, const string& signature, string* output,
173                      std::optional<HardwareAuthToken> hat = std::nullopt,
174                      std::optional<secureclock::TimeStampToken> time_token = std::nullopt);
Finish(const string & message,string * output)175     ErrorCode Finish(const string& message, string* output) {
176         return Finish(message, {} /* signature */, output);
177     }
Finish(string * output)178     ErrorCode Finish(string* output) { return Finish({} /* message */, output); }
179 
180     ErrorCode Abort();
181     ErrorCode Abort(const shared_ptr<IKeyMintOperation>& op);
182     void AbortIfNeeded();
183 
184     string ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
185                           const string& message, const AuthorizationSet& in_params,
186                           AuthorizationSet* out_params);
187     std::tuple<ErrorCode, std::string /* processedMessage */> ProcessMessage(
188             const vector<uint8_t>& key_blob, KeyPurpose operation, const std::string& message,
189             const AuthorizationSet& in_params);
190     string SignMessage(const vector<uint8_t>& key_blob, const string& message,
191                        const AuthorizationSet& params);
192     string SignMessage(const string& message, const AuthorizationSet& params);
193 
194     string MacMessage(const string& message, Digest digest, size_t mac_length);
195 
196     void CheckAesIncrementalEncryptOperation(BlockMode block_mode, int message_size);
197 
198     void AesCheckEncryptOneByteAtATime(const string& key, BlockMode block_mode,
199                                        PaddingMode padding_mode, const string& iv,
200                                        const string& plaintext, const string& exp_cipher_text);
201 
202     void CheckHmacTestVector(const string& key, const string& message, Digest digest,
203                              const string& expected_mac);
204 
205     void CheckAesCtrTestVector(const string& key, const string& nonce, const string& message,
206                                const string& expected_ciphertext);
207 
208     void CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode,
209                                   PaddingMode padding_mode, const string& key, const string& iv,
210                                   const string& input, const string& expected_output);
211 
212     void VerifyMessage(const vector<uint8_t>& key_blob, const string& message,
213                        const string& signature, const AuthorizationSet& params);
214     void VerifyMessage(const string& message, const string& signature,
215                        const AuthorizationSet& params);
216     void LocalVerifyMessage(const vector<uint8_t>& der_cert, const string& message,
217                             const string& signature, const AuthorizationSet& params);
218     void LocalVerifyMessage(const string& message, const string& signature,
219                             const AuthorizationSet& params);
220 
221     string LocalRsaEncryptMessage(const string& message, const AuthorizationSet& params);
222     string EncryptMessage(const vector<uint8_t>& key_blob, const string& message,
223                           const AuthorizationSet& in_params, AuthorizationSet* out_params);
224     string EncryptMessage(const string& message, const AuthorizationSet& params,
225                           AuthorizationSet* out_params);
226     string EncryptMessage(const string& message, const AuthorizationSet& params);
227     string EncryptMessage(const string& message, BlockMode block_mode, PaddingMode padding);
228     string EncryptMessage(const string& message, BlockMode block_mode, PaddingMode padding,
229                           vector<uint8_t>* iv_out);
230     string EncryptMessage(const string& message, BlockMode block_mode, PaddingMode padding,
231                           const vector<uint8_t>& iv_in);
232     string EncryptMessage(const string& message, BlockMode block_mode, PaddingMode padding,
233                           uint8_t mac_length_bits, const vector<uint8_t>& iv_in);
234     string EncryptMessage(const string& message, BlockMode block_mode, PaddingMode padding,
235                           uint8_t mac_length_bits);
236 
237     string DecryptMessage(const vector<uint8_t>& key_blob, const string& ciphertext,
238                           const AuthorizationSet& params);
239     string DecryptMessage(const string& ciphertext, const AuthorizationSet& params);
240     string DecryptMessage(const string& ciphertext, BlockMode block_mode, PaddingMode padding_mode,
241                           const vector<uint8_t>& iv);
242 
243     std::pair<ErrorCode, vector<uint8_t>> UpgradeKey(const vector<uint8_t>& key_blob);
244 
245     template <typename TagType>
246     std::tuple<KeyData /* aesKey */, KeyData /* hmacKey */, KeyData /* rsaKey */,
247                KeyData /* ecdsaKey */>
248     CreateTestKeys(
249             TagType tagToTest, ErrorCode expectedReturn,
250             std::function<void(AuthorizationSetBuilder*)> tagModifier =
251                     [](AuthorizationSetBuilder*) {}) {
252         /* AES */
253         KeyData aesKeyData;
254         AuthorizationSetBuilder aesBuilder = AuthorizationSetBuilder()
255                                                      .AesEncryptionKey(128)
256                                                      .Authorization(tagToTest)
257                                                      .BlockMode(BlockMode::ECB)
258                                                      .Padding(PaddingMode::NONE)
259                                                      .Authorization(TAG_NO_AUTH_REQUIRED);
260         tagModifier(&aesBuilder);
261         ErrorCode errorCode =
262                 GenerateKey(aesBuilder, &aesKeyData.blob, &aesKeyData.characteristics);
263         EXPECT_EQ(expectedReturn, errorCode);
264 
265         /* HMAC */
266         KeyData hmacKeyData;
267         AuthorizationSetBuilder hmacBuilder = AuthorizationSetBuilder()
268                                                       .HmacKey(128)
269                                                       .Authorization(tagToTest)
270                                                       .Digest(Digest::SHA_2_256)
271                                                       .Authorization(TAG_MIN_MAC_LENGTH, 128)
272                                                       .Authorization(TAG_NO_AUTH_REQUIRED);
273         tagModifier(&hmacBuilder);
274         errorCode = GenerateKey(hmacBuilder, &hmacKeyData.blob, &hmacKeyData.characteristics);
275         EXPECT_EQ(expectedReturn, errorCode);
276 
277         /* RSA */
278         KeyData rsaKeyData;
279         AuthorizationSetBuilder rsaBuilder = AuthorizationSetBuilder()
280                                                      .RsaSigningKey(2048, 65537)
281                                                      .Authorization(tagToTest)
282                                                      .Digest(Digest::NONE)
283                                                      .Padding(PaddingMode::NONE)
284                                                      .Authorization(TAG_NO_AUTH_REQUIRED)
285                                                      .SetDefaultValidity();
286         tagModifier(&rsaBuilder);
287         errorCode = GenerateKey(rsaBuilder, &rsaKeyData.blob, &rsaKeyData.characteristics);
288         if (!(SecLevel() == SecurityLevel::STRONGBOX &&
289               ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED == errorCode)) {
290             EXPECT_EQ(expectedReturn, errorCode);
291         }
292 
293         /* ECDSA */
294         KeyData ecdsaKeyData;
295         AuthorizationSetBuilder ecdsaBuilder = AuthorizationSetBuilder()
296                                                        .EcdsaSigningKey(EcCurve::P_256)
297                                                        .Authorization(tagToTest)
298                                                        .Digest(Digest::SHA_2_256)
299                                                        .Authorization(TAG_NO_AUTH_REQUIRED)
300                                                        .SetDefaultValidity();
301         tagModifier(&ecdsaBuilder);
302         errorCode = GenerateKey(ecdsaBuilder, &ecdsaKeyData.blob, &ecdsaKeyData.characteristics);
303         if (!(SecLevel() == SecurityLevel::STRONGBOX &&
304               ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED == errorCode)) {
305             EXPECT_EQ(expectedReturn, errorCode);
306         }
307         return {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData};
308     }
IsSecure()309     bool IsSecure() const { return securityLevel_ != SecurityLevel::SOFTWARE; }
SecLevel()310     SecurityLevel SecLevel() const { return securityLevel_; }
311     bool IsRkpSupportRequired() const;
312 
313     vector<uint32_t> ValidKeySizes(Algorithm algorithm);
314     vector<uint32_t> InvalidKeySizes(Algorithm algorithm);
315 
316     vector<BlockMode> ValidBlockModes(Algorithm algorithm);
317     vector<PaddingMode> ValidPaddingModes(Algorithm algorithm, BlockMode blockMode);
318     vector<PaddingMode> InvalidPaddingModes(Algorithm algorithm, BlockMode blockMode);
319 
320     vector<EcCurve> ValidCurves();
321     vector<EcCurve> InvalidCurves();
322 
323     vector<Digest> ValidDigests(bool withNone, bool withMD5);
324     vector<uint64_t> ValidExponents();
325 
build_params()326     static vector<string> build_params() {
327         auto params = ::android::getAidlHalInstanceNames(IKeyMintDevice::descriptor);
328         return params;
329     }
330 
331     std::shared_ptr<IKeyMintOperation> op_;
332     vector<Certificate> cert_chain_;
333     vector<uint8_t> key_blob_;
334     vector<KeyCharacteristics> key_characteristics_;
335 
336     const vector<KeyParameter>& SecLevelAuthorizations(
337             const vector<KeyCharacteristics>& key_characteristics);
SecLevelAuthorizations()338     inline const vector<KeyParameter>& SecLevelAuthorizations() {
339         return SecLevelAuthorizations(key_characteristics_);
340     }
341     const vector<KeyParameter>& SecLevelAuthorizations(
342             const vector<KeyCharacteristics>& key_characteristics, SecurityLevel securityLevel);
343 
344     ErrorCode UseAesKey(const vector<uint8_t>& aesKeyBlob);
345     ErrorCode UseHmacKey(const vector<uint8_t>& hmacKeyBlob);
346     ErrorCode UseRsaKey(const vector<uint8_t>& rsaKeyBlob);
347     ErrorCode UseEcdsaKey(const vector<uint8_t>& ecdsaKeyBlob);
348 
349     ErrorCode GenerateAttestKey(const AuthorizationSet& key_desc,
350                                 const optional<AttestationKey>& attest_key,
351                                 vector<uint8_t>* key_blob,
352                                 vector<KeyCharacteristics>* key_characteristics,
353                                 vector<Certificate>* cert_chain);
354 
355     bool is_attest_key_feature_disabled(void) const;
356     bool is_strongbox_enabled(void) const;
357     bool is_chipset_allowed_km4_strongbox(void) const;
358     bool shouldSkipAttestKeyTest(void) const;
359     void skipAttestKeyTestIfNeeded() const;
360 
361     void assert_mgf_digests_present_or_not_in_key_characteristics(
362             const vector<KeyCharacteristics>& key_characteristics,
363             std::vector<android::hardware::security::keymint::Digest>& expected_mgf_digests,
364             bool is_mgf_digest_expected) const;
365 
366     void assert_mgf_digests_present_or_not_in_key_characteristics(
367             std::vector<android::hardware::security::keymint::Digest>& expected_mgf_digests,
368             bool is_mgf_digest_expected) const;
369 
370   protected:
371     std::shared_ptr<IKeyMintDevice> keymint_;
372     uint32_t os_version_;
373     uint32_t os_patch_level_;
374     uint32_t vendor_patch_level_;
375     bool timestamp_token_required_;
376 
377     SecurityLevel securityLevel_;
378     string name_;
379     string author_;
380     int64_t challenge_;
381 
382   private:
383     void CheckEncryptOneByteAtATime(BlockMode block_mode, const int block_size,
384                                     PaddingMode padding_mode, const string& iv,
385                                     const string& plaintext, const string& exp_cipher_text);
386 };
387 
388 // If the given property is available, add it to the tag set under the given tag ID.
389 template <Tag tag>
add_tag_from_prop(AuthorizationSetBuilder * tags,TypedTag<TagType::BYTES,tag> ttag,const char * prop)390 void add_tag_from_prop(AuthorizationSetBuilder* tags, TypedTag<TagType::BYTES, tag> ttag,
391                        const char* prop) {
392     std::string prop_value = ::android::base::GetProperty(prop, /* default= */ "");
393     if (!prop_value.empty()) {
394         tags->Authorization(ttag, prop_value.data(), prop_value.size());
395     }
396 }
397 
398 // Return the VSR API level for this device.
399 int get_vsr_api_level();
400 
401 // Indicate whether the test is running on a GSI image.
402 bool is_gsi_image();
403 
404 vector<uint8_t> build_serial_blob(const uint64_t serial_int);
405 void verify_subject(const X509* cert, const string& subject, bool self_signed);
406 void verify_serial(X509* cert, const uint64_t expected_serial);
407 void verify_subject_and_serial(const Certificate& certificate,  //
408                                const uint64_t expected_serial,  //
409                                const string& subject, bool self_signed);
410 void verify_root_of_trust(const vector<uint8_t>& verified_boot_key,  //
411                           bool device_locked,                        //
412                           VerifiedBoot verified_boot_state,          //
413                           const vector<uint8_t>& verified_boot_hash);
414 bool verify_attestation_record(int aidl_version,                       //
415                                const string& challenge,                //
416                                const string& app_id,                   //
417                                AuthorizationSet expected_sw_enforced,  //
418                                AuthorizationSet expected_hw_enforced,  //
419                                SecurityLevel security_level,
420                                const vector<uint8_t>& attestation_cert,
421                                vector<uint8_t>* unique_id = nullptr);
422 
423 string bin2hex(const vector<uint8_t>& data);
424 X509_Ptr parse_cert_blob(const vector<uint8_t>& blob);
425 ASN1_OCTET_STRING* get_attestation_record(X509* certificate);
426 vector<uint8_t> make_name_from_str(const string& name);
427 void check_maced_pubkey(const MacedPublicKey& macedPubKey, bool testMode,
428                         vector<uint8_t>* payload_value);
429 void p256_pub_key(const vector<uint8_t>& coseKeyData, EVP_PKEY_Ptr* signingKey);
430 void device_id_attestation_check_acceptable_error(Tag tag, const ErrorCode& result);
431 bool check_feature(const std::string& name);
432 std::optional<int32_t> keymint_feature_value(bool strongbox);
433 std::string get_imei(int slot);
434 
435 AuthorizationSet HwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics);
436 AuthorizationSet SwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics);
437 ::testing::AssertionResult ChainSignaturesAreValid(const vector<Certificate>& chain,
438                                                    bool strict_issuer_check = true);
439 
440 ErrorCode GetReturnErrorCode(const Status& result);
441 
442 #define INSTANTIATE_KEYMINT_AIDL_TEST(name)                                          \
443     INSTANTIATE_TEST_SUITE_P(PerInstance, name,                                      \
444                              testing::ValuesIn(KeyMintAidlTestBase::build_params()), \
445                              ::android::PrintInstanceNameToString);                  \
446     GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(name);
447 
448 // Use `ro.product.<property>_for_attestation` property for attestation if it is present else
449 // fallback to use `ro.product.vendor.<property>` if it is present else fallback to
450 // `ro.product.<property>`. Similar logic can be seen in Java method `getVendorDeviceIdProperty`
451 // in frameworks/base/core/java/android/os/Build.java.
452 template <Tag tag>
add_attestation_id(AuthorizationSetBuilder * attestation_id_tags,TypedTag<TagType::BYTES,tag> tag_type,const char * prop)453 void add_attestation_id(AuthorizationSetBuilder* attestation_id_tags,
454                         TypedTag<TagType::BYTES, tag> tag_type, const char* prop) {
455     ::android::String8 prop_name =
456             ::android::String8::format("ro.product.%s_for_attestation", prop);
457     std::string prop_value = ::android::base::GetProperty(prop_name.c_str(), /* default= */ "");
458     if (!prop_value.empty()) {
459         add_tag_from_prop(attestation_id_tags, tag_type, prop_name.c_str());
460     } else {
461         prop_name = ::android::String8::format("ro.product.vendor.%s", prop);
462         prop_value = ::android::base::GetProperty(prop_name.c_str(), /* default= */ "");
463         if (!prop_value.empty()) {
464             add_tag_from_prop(attestation_id_tags, tag_type, prop_name.c_str());
465         } else {
466             prop_name = ::android::String8::format("ro.product.%s", prop);
467             add_tag_from_prop(attestation_id_tags, tag_type, prop_name.c_str());
468         }
469     }
470 }
471 }  // namespace test
472 
473 }  // namespace aidl::android::hardware::security::keymint
474