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/authorization_set.h>
35 #include <keymint_support/openssl_utils.h>
36 
37 namespace aidl::android::hardware::security::keymint {
38 
39 ::std::ostream& operator<<(::std::ostream& os, const AuthorizationSet& set);
40 
41 inline bool operator==(const keymint::AuthorizationSet& a, const keymint::AuthorizationSet& b) {
42     return a.size() == b.size() && std::equal(a.begin(), a.end(), b.begin());
43 }
44 
45 namespace test {
46 
47 using ::android::sp;
48 using Status = ::ndk::ScopedAStatus;
49 using ::std::optional;
50 using ::std::shared_ptr;
51 using ::std::string;
52 using ::std::vector;
53 
54 constexpr uint64_t kOpHandleSentinel = 0xFFFFFFFFFFFFFFFF;
55 
56 class KeyMintAidlTestBase : public ::testing::TestWithParam<string> {
57   public:
58     struct KeyData {
59         vector<uint8_t> blob;
60         vector<KeyCharacteristics> characteristics;
61     };
62 
63     static bool arm_deleteAllKeys;
64     static bool dump_Attestations;
65 
66     void SetUp() override;
TearDown()67     void TearDown() override {
68         if (key_blob_.size()) {
69             CheckedDeleteKey();
70         }
71         AbortIfNeeded();
72     }
73 
74     void InitializeKeyMint(std::shared_ptr<IKeyMintDevice> keyMint);
keyMint()75     IKeyMintDevice& keyMint() { return *keymint_; }
os_version()76     uint32_t os_version() { return os_version_; }
os_patch_level()77     uint32_t os_patch_level() { return os_patch_level_; }
vendor_patch_level()78     uint32_t vendor_patch_level() { return vendor_patch_level_; }
79     uint32_t boot_patch_level(const vector<KeyCharacteristics>& key_characteristics);
80     uint32_t boot_patch_level();
81 
82     ErrorCode GetReturnErrorCode(const Status& result);
83 
GenerateKey(const AuthorizationSet & key_desc,vector<uint8_t> * key_blob,vector<KeyCharacteristics> * key_characteristics)84     ErrorCode GenerateKey(const AuthorizationSet& key_desc, vector<uint8_t>* key_blob,
85                           vector<KeyCharacteristics>* key_characteristics) {
86         return GenerateKey(key_desc, std::nullopt /* attest_key */, key_blob, key_characteristics,
87                            &cert_chain_);
88     }
89     ErrorCode GenerateKey(const AuthorizationSet& key_desc,
90                           const optional<AttestationKey>& attest_key, vector<uint8_t>* key_blob,
91                           vector<KeyCharacteristics>* key_characteristics,
92                           vector<Certificate>* cert_chain);
93     ErrorCode GenerateKey(const AuthorizationSet& key_desc,
94                           const optional<AttestationKey>& attest_key = std::nullopt);
95 
96     ErrorCode ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
97                         const string& key_material, vector<uint8_t>* key_blob,
98                         vector<KeyCharacteristics>* key_characteristics);
99     ErrorCode ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
100                         const string& key_material);
101 
102     ErrorCode ImportWrappedKey(string wrapped_key, string wrapping_key,
103                                const AuthorizationSet& wrapping_key_desc, string masking_key,
104                                const AuthorizationSet& unwrapping_params, int64_t password_sid,
105                                int64_t biometric_sid);
ImportWrappedKey(string wrapped_key,string wrapping_key,const AuthorizationSet & wrapping_key_desc,string masking_key,const AuthorizationSet & unwrapping_params)106     ErrorCode ImportWrappedKey(string wrapped_key, string wrapping_key,
107                                const AuthorizationSet& wrapping_key_desc, string masking_key,
108                                const AuthorizationSet& unwrapping_params) {
109         return ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, masking_key,
110                                 unwrapping_params, 0 /* password_sid */, 0 /* biometric_sid */);
111     }
112 
113     ErrorCode GetCharacteristics(const vector<uint8_t>& key_blob, const vector<uint8_t>& app_id,
114                                  const vector<uint8_t>& app_data,
115                                  vector<KeyCharacteristics>* key_characteristics);
116     ErrorCode GetCharacteristics(const vector<uint8_t>& key_blob,
117                                  vector<KeyCharacteristics>* key_characteristics);
118 
119     void CheckCharacteristics(const vector<uint8_t>& key_blob,
120                               const vector<KeyCharacteristics>& generate_characteristics);
121     void CheckAppIdCharacteristics(const vector<uint8_t>& key_blob, std::string_view app_id_string,
122                                    std::string_view app_data_string,
123                                    const vector<KeyCharacteristics>& generate_characteristics);
124 
125     ErrorCode DeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob = false);
126     ErrorCode DeleteKey(bool keep_key_blob = false);
127 
128     ErrorCode DeleteAllKeys();
129 
130     ErrorCode DestroyAttestationIds();
131 
132     void CheckedDeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob = false);
133     void CheckedDeleteKey();
134 
135     ErrorCode Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
136                     const AuthorizationSet& in_params, AuthorizationSet* out_params,
137                     std::shared_ptr<IKeyMintOperation>& op);
138     ErrorCode Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
139                     const AuthorizationSet& in_params, AuthorizationSet* out_params);
140     ErrorCode Begin(KeyPurpose purpose, const AuthorizationSet& in_params,
141                     AuthorizationSet* out_params);
142     ErrorCode Begin(KeyPurpose purpose, const AuthorizationSet& in_params);
143 
144     ErrorCode UpdateAad(const string& input);
145     ErrorCode Update(const string& input, string* output);
146 
147     ErrorCode Finish(const string& message, const string& signature, string* output);
Finish(const string & message,string * output)148     ErrorCode Finish(const string& message, string* output) {
149         return Finish(message, {} /* signature */, output);
150     }
Finish(string * output)151     ErrorCode Finish(string* output) { return Finish({} /* message */, output); }
152 
153     ErrorCode Abort();
154     ErrorCode Abort(const shared_ptr<IKeyMintOperation>& op);
155     void AbortIfNeeded();
156 
157     string ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
158                           const string& message, const AuthorizationSet& in_params,
159                           AuthorizationSet* out_params);
160     std::tuple<ErrorCode, std::string /* processedMessage */> ProcessMessage(
161             const vector<uint8_t>& key_blob, KeyPurpose operation, const std::string& message,
162             const AuthorizationSet& in_params);
163     string SignMessage(const vector<uint8_t>& key_blob, const string& message,
164                        const AuthorizationSet& params);
165     string SignMessage(const string& message, const AuthorizationSet& params);
166 
167     string MacMessage(const string& message, Digest digest, size_t mac_length);
168 
169     void CheckHmacTestVector(const string& key, const string& message, Digest digest,
170                              const string& expected_mac);
171 
172     void CheckAesCtrTestVector(const string& key, const string& nonce, const string& message,
173                                const string& expected_ciphertext);
174 
175     void CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode,
176                                   PaddingMode padding_mode, const string& key, const string& iv,
177                                   const string& input, const string& expected_output);
178 
179     void VerifyMessage(const vector<uint8_t>& key_blob, const string& message,
180                        const string& signature, const AuthorizationSet& params);
181     void VerifyMessage(const string& message, const string& signature,
182                        const AuthorizationSet& params);
183     void LocalVerifyMessage(const string& message, const string& signature,
184                             const AuthorizationSet& params);
185 
186     string LocalRsaEncryptMessage(const string& message, const AuthorizationSet& params);
187     string EncryptMessage(const vector<uint8_t>& key_blob, const string& message,
188                           const AuthorizationSet& in_params, AuthorizationSet* out_params);
189     string EncryptMessage(const string& message, const AuthorizationSet& params,
190                           AuthorizationSet* out_params);
191     string EncryptMessage(const string& message, const AuthorizationSet& params);
192     string EncryptMessage(const string& message, BlockMode block_mode, PaddingMode padding);
193     string EncryptMessage(const string& message, BlockMode block_mode, PaddingMode padding,
194                           vector<uint8_t>* iv_out);
195     string EncryptMessage(const string& message, BlockMode block_mode, PaddingMode padding,
196                           const vector<uint8_t>& iv_in);
197     string EncryptMessage(const string& message, BlockMode block_mode, PaddingMode padding,
198                           uint8_t mac_length_bits, const vector<uint8_t>& iv_in);
199     string EncryptMessage(const string& message, BlockMode block_mode, PaddingMode padding,
200                           uint8_t mac_length_bits);
201 
202     string DecryptMessage(const vector<uint8_t>& key_blob, const string& ciphertext,
203                           const AuthorizationSet& params);
204     string DecryptMessage(const string& ciphertext, const AuthorizationSet& params);
205     string DecryptMessage(const string& ciphertext, BlockMode block_mode, PaddingMode padding_mode,
206                           const vector<uint8_t>& iv);
207 
208     std::pair<ErrorCode, vector<uint8_t>> UpgradeKey(const vector<uint8_t>& key_blob);
209 
210     template <typename TagType>
211     std::tuple<KeyData /* aesKey */, KeyData /* hmacKey */, KeyData /* rsaKey */,
212                KeyData /* ecdsaKey */>
213     CreateTestKeys(
214             TagType tagToTest, ErrorCode expectedReturn,
215             std::function<void(AuthorizationSetBuilder*)> tagModifier =
216                     [](AuthorizationSetBuilder*) {}) {
217         /* AES */
218         KeyData aesKeyData;
219         AuthorizationSetBuilder aesBuilder = AuthorizationSetBuilder()
220                                                      .AesEncryptionKey(128)
221                                                      .Authorization(tagToTest)
222                                                      .BlockMode(BlockMode::ECB)
223                                                      .Padding(PaddingMode::NONE)
224                                                      .Authorization(TAG_NO_AUTH_REQUIRED);
225         tagModifier(&aesBuilder);
226         ErrorCode errorCode =
227                 GenerateKey(aesBuilder, &aesKeyData.blob, &aesKeyData.characteristics);
228         EXPECT_EQ(expectedReturn, errorCode);
229 
230         /* HMAC */
231         KeyData hmacKeyData;
232         AuthorizationSetBuilder hmacBuilder = AuthorizationSetBuilder()
233                                                       .HmacKey(128)
234                                                       .Authorization(tagToTest)
235                                                       .Digest(Digest::SHA_2_256)
236                                                       .Authorization(TAG_MIN_MAC_LENGTH, 128)
237                                                       .Authorization(TAG_NO_AUTH_REQUIRED);
238         tagModifier(&hmacBuilder);
239         errorCode = GenerateKey(hmacBuilder, &hmacKeyData.blob, &hmacKeyData.characteristics);
240         EXPECT_EQ(expectedReturn, errorCode);
241 
242         /* RSA */
243         KeyData rsaKeyData;
244         AuthorizationSetBuilder rsaBuilder = AuthorizationSetBuilder()
245                                                      .RsaSigningKey(2048, 65537)
246                                                      .Authorization(tagToTest)
247                                                      .Digest(Digest::NONE)
248                                                      .Padding(PaddingMode::NONE)
249                                                      .Authorization(TAG_NO_AUTH_REQUIRED)
250                                                      .SetDefaultValidity();
251         tagModifier(&rsaBuilder);
252         errorCode = GenerateKey(rsaBuilder, &rsaKeyData.blob, &rsaKeyData.characteristics);
253         EXPECT_EQ(expectedReturn, errorCode);
254 
255         /* ECDSA */
256         KeyData ecdsaKeyData;
257         AuthorizationSetBuilder ecdsaBuilder = AuthorizationSetBuilder()
258                                                        .EcdsaSigningKey(EcCurve::P_256)
259                                                        .Authorization(tagToTest)
260                                                        .Digest(Digest::SHA_2_256)
261                                                        .Authorization(TAG_NO_AUTH_REQUIRED)
262                                                        .SetDefaultValidity();
263         tagModifier(&ecdsaBuilder);
264         errorCode = GenerateKey(ecdsaBuilder, &ecdsaKeyData.blob, &ecdsaKeyData.characteristics);
265         EXPECT_EQ(expectedReturn, errorCode);
266         return {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData};
267     }
IsSecure()268     bool IsSecure() const { return securityLevel_ != SecurityLevel::SOFTWARE; }
SecLevel()269     SecurityLevel SecLevel() const { return securityLevel_; }
270 
271     vector<uint32_t> ValidKeySizes(Algorithm algorithm);
272     vector<uint32_t> InvalidKeySizes(Algorithm algorithm);
273 
274     vector<BlockMode> ValidBlockModes(Algorithm algorithm);
275     vector<PaddingMode> ValidPaddingModes(Algorithm algorithm, BlockMode blockMode);
276     vector<PaddingMode> InvalidPaddingModes(Algorithm algorithm, BlockMode blockMode);
277 
278     vector<EcCurve> ValidCurves();
279     vector<EcCurve> InvalidCurves();
280 
281     vector<Digest> ValidDigests(bool withNone, bool withMD5);
282 
build_params()283     static vector<string> build_params() {
284         auto params = ::android::getAidlHalInstanceNames(IKeyMintDevice::descriptor);
285         return params;
286     }
287 
288     std::shared_ptr<IKeyMintOperation> op_;
289     vector<Certificate> cert_chain_;
290     vector<uint8_t> key_blob_;
291     vector<KeyCharacteristics> key_characteristics_;
292 
293     const vector<KeyParameter>& SecLevelAuthorizations(
294             const vector<KeyCharacteristics>& key_characteristics);
SecLevelAuthorizations()295     inline const vector<KeyParameter>& SecLevelAuthorizations() {
296         return SecLevelAuthorizations(key_characteristics_);
297     }
298     const vector<KeyParameter>& SecLevelAuthorizations(
299             const vector<KeyCharacteristics>& key_characteristics, SecurityLevel securityLevel);
300 
301     ErrorCode UseAesKey(const vector<uint8_t>& aesKeyBlob);
302     ErrorCode UseHmacKey(const vector<uint8_t>& hmacKeyBlob);
303     ErrorCode UseRsaKey(const vector<uint8_t>& rsaKeyBlob);
304     ErrorCode UseEcdsaKey(const vector<uint8_t>& ecdsaKeyBlob);
305 
306   protected:
307     std::shared_ptr<IKeyMintDevice> keymint_;
308     uint32_t os_version_;
309     uint32_t os_patch_level_;
310     uint32_t vendor_patch_level_;
311     bool timestamp_token_required_;
312 
313     SecurityLevel securityLevel_;
314     string name_;
315     string author_;
316     long challenge_;
317 };
318 
319 // If the given property is available, add it to the tag set under the given tag ID.
320 template <Tag tag>
add_tag_from_prop(AuthorizationSetBuilder * tags,TypedTag<TagType::BYTES,tag> ttag,const char * prop)321 void add_tag_from_prop(AuthorizationSetBuilder* tags, TypedTag<TagType::BYTES, tag> ttag,
322                        const char* prop) {
323     std::string prop_value = ::android::base::GetProperty(prop, /* default= */ "");
324     if (!prop_value.empty()) {
325         tags->Authorization(ttag, prop_value.data(), prop_value.size());
326     }
327 }
328 
329 vector<uint8_t> build_serial_blob(const uint64_t serial_int);
330 void verify_subject(const X509* cert, const string& subject, bool self_signed);
331 void verify_serial(X509* cert, const uint64_t expected_serial);
332 void verify_subject_and_serial(const Certificate& certificate,  //
333                                const uint64_t expected_serial,  //
334                                const string& subject, bool self_signed);
335 
336 bool verify_attestation_record(const string& challenge,                //
337                                const string& app_id,                   //
338                                AuthorizationSet expected_sw_enforced,  //
339                                AuthorizationSet expected_hw_enforced,  //
340                                SecurityLevel security_level,
341                                const vector<uint8_t>& attestation_cert,
342                                vector<uint8_t>* unique_id = nullptr);
343 
344 string bin2hex(const vector<uint8_t>& data);
345 X509_Ptr parse_cert_blob(const vector<uint8_t>& blob);
346 vector<uint8_t> make_name_from_str(const string& name);
347 void check_maced_pubkey(const MacedPublicKey& macedPubKey, bool testMode,
348                         vector<uint8_t>* payload_value);
349 void p256_pub_key(const vector<uint8_t>& coseKeyData, EVP_PKEY_Ptr* signingKey);
350 
351 AuthorizationSet HwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics);
352 AuthorizationSet SwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics);
353 ::testing::AssertionResult ChainSignaturesAreValid(const vector<Certificate>& chain,
354                                                    bool strict_issuer_check = true);
355 
356 #define INSTANTIATE_KEYMINT_AIDL_TEST(name)                                          \
357     INSTANTIATE_TEST_SUITE_P(PerInstance, name,                                      \
358                              testing::ValuesIn(KeyMintAidlTestBase::build_params()), \
359                              ::android::PrintInstanceNameToString);                  \
360     GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(name);
361 
362 }  // namespace test
363 
364 }  // namespace aidl::android::hardware::security::keymint
365