xref: /aosp_15_r20/system/security/ondevice-signing/KeystoreKey.cpp (revision e1997b9af69e3155ead6e072d106a0077849ffba)
1 /*
2  * Copyright (C) 2021 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 #include <string>
18 
19 #include <android-base/file.h>
20 #include <android-base/logging.h>
21 #include <binder/IServiceManager.h>
22 
23 #include <fcntl.h>
24 #include <sys/stat.h>
25 #include <sys/types.h>
26 
27 #include "CertUtils.h"
28 #include "KeyConstants.h"
29 #include "KeystoreKey.h"
30 
31 using android::defaultServiceManager;
32 using android::IServiceManager;
33 using android::sp;
34 using android::String16;
35 
36 using android::hardware::security::keymint::Algorithm;
37 using android::hardware::security::keymint::Digest;
38 using android::hardware::security::keymint::KeyParameter;
39 using android::hardware::security::keymint::KeyParameterValue;
40 using android::hardware::security::keymint::KeyPurpose;
41 using android::hardware::security::keymint::PaddingMode;
42 using android::hardware::security::keymint::SecurityLevel;
43 using android::hardware::security::keymint::Tag;
44 
45 using android::system::keystore2::CreateOperationResponse;
46 using android::system::keystore2::Domain;
47 using android::system::keystore2::KeyDescriptor;
48 using android::system::keystore2::KeyEntryResponse;
49 
50 using android::base::Error;
51 using android::base::Result;
52 
getKeyDescriptor(const android::String16 & keyAlias,int64_t keyNspace)53 static KeyDescriptor getKeyDescriptor(const android::String16& keyAlias, int64_t keyNspace) {
54     // AIDL parcelable objects don't have constructor
55     static KeyDescriptor descriptor;
56     static std::once_flag flag;
57     std::call_once(flag, [&]() {
58         descriptor.domain = Domain::SELINUX;
59         descriptor.alias = keyAlias;
60         descriptor.nspace = keyNspace;
61     });
62 
63     return descriptor;
64 }
65 
KeystoreKey(std::string signedPubKeyPath,const android::String16 & keyAlias,int64_t keyNspace,int keyBootLevel)66 KeystoreKey::KeystoreKey(std::string signedPubKeyPath, const android::String16& keyAlias,
67                          int64_t keyNspace, int keyBootLevel)
68     : mDescriptor(getKeyDescriptor(keyAlias, keyNspace)),
69       mHmacKey(keyAlias, keyNspace, keyBootLevel), mSignedPubKeyPath(std::move(signedPubKeyPath)),
70       mKeyBootLevel(keyBootLevel) {}
71 
createKey()72 Result<std::vector<uint8_t>> KeystoreKey::createKey() {
73     std::vector<KeyParameter> params;
74 
75     KeyParameter algo;
76     algo.tag = Tag::ALGORITHM;
77     algo.value = KeyParameterValue::make<KeyParameterValue::algorithm>(Algorithm::RSA);
78     params.push_back(algo);
79 
80     KeyParameter key_size;
81     key_size.tag = Tag::KEY_SIZE;
82     key_size.value = KeyParameterValue::make<KeyParameterValue::integer>(kRsaKeySize);
83     params.push_back(key_size);
84 
85     KeyParameter digest;
86     digest.tag = Tag::DIGEST;
87     digest.value = KeyParameterValue::make<KeyParameterValue::digest>(Digest::SHA_2_256);
88     params.push_back(digest);
89 
90     KeyParameter padding;
91     padding.tag = Tag::PADDING;
92     padding.value =
93         KeyParameterValue::make<KeyParameterValue::paddingMode>(PaddingMode::RSA_PKCS1_1_5_SIGN);
94     params.push_back(padding);
95 
96     KeyParameter exponent;
97     exponent.tag = Tag::RSA_PUBLIC_EXPONENT;
98     exponent.value = KeyParameterValue::make<KeyParameterValue::longInteger>(kRsaKeyExponent);
99     params.push_back(exponent);
100 
101     KeyParameter purpose;
102     purpose.tag = Tag::PURPOSE;
103     purpose.value = KeyParameterValue::make<KeyParameterValue::keyPurpose>(KeyPurpose::SIGN);
104     params.push_back(purpose);
105 
106     KeyParameter auth;
107     auth.tag = Tag::NO_AUTH_REQUIRED;
108     auth.value = KeyParameterValue::make<KeyParameterValue::boolValue>(true);
109     params.push_back(auth);
110 
111     KeyParameter boot_level;
112     boot_level.tag = Tag::MAX_BOOT_LEVEL;
113     boot_level.value = KeyParameterValue::make<KeyParameterValue::integer>(mKeyBootLevel);
114     params.push_back(boot_level);
115 
116     KeyMetadata metadata;
117     auto status = mSecurityLevel->generateKey(mDescriptor, {}, params, 0, {}, &metadata);
118     if (!status.isOk()) {
119         return Error() << "Failed to create new key: " << status;
120     }
121 
122     // Extract the public key from the certificate, HMAC it and store the signature
123     auto cert = metadata.certificate;
124     if (!cert) {
125         return Error() << "Key did not have a certificate.";
126     }
127     auto publicKey = extractPublicKeyFromX509(cert.value());
128     if (!publicKey.ok()) {
129         return publicKey.error();
130     }
131     std::string publicKeyString = {publicKey->begin(), publicKey->end()};
132     auto signature = mHmacKey.sign(publicKeyString);
133     if (!signature.ok()) {
134         return Error() << "Failed to sign public key.";
135     }
136 
137     if (!android::base::WriteStringToFile(*signature, mSignedPubKeyPath)) {
138         return Error() << "Can't write public key signature.";
139     }
140 
141     return *publicKey;
142 }
143 
initialize()144 bool KeystoreKey::initialize() {
145     sp<IServiceManager> sm = defaultServiceManager();
146     if (sm == nullptr) {
147         return false;
148     }
149     auto service = sm->getService(String16("android.system.keystore2.IKeystoreService/default"));
150     if (service == nullptr) {
151         return false;
152     }
153     mService = interface_cast<android::system::keystore2::IKeystoreService>(service);
154     if (mService == nullptr) {
155         return false;
156     }
157 
158     auto status = mService->getSecurityLevel(SecurityLevel::TRUSTED_ENVIRONMENT, &mSecurityLevel);
159     if (!status.isOk()) {
160         return false;
161     }
162 
163     // Initialize the HMAC key we use to sign/verify information about this key
164     auto hmacStatus = mHmacKey.initialize(mService, mSecurityLevel);
165     if (!hmacStatus.ok()) {
166         LOG(ERROR) << hmacStatus.error().message();
167         return false;
168     }
169 
170     auto key = getOrCreateKey();
171     if (!key.ok()) {
172         // Delete the HMAC, just in case signing failed, and we could recover by recreating it.
173         mHmacKey.deleteKey();
174         LOG(ERROR) << key.error().message();
175         return false;
176     }
177     mPublicKey = *key;
178     LOG(INFO) << "Initialized Keystore key.";
179     return true;
180 }
181 
verifyExistingKey()182 Result<std::vector<uint8_t>> KeystoreKey::verifyExistingKey() {
183     // See if we can fetch an existing key
184     KeyEntryResponse keyEntryResponse;
185     LOG(INFO) << "Trying to retrieve existing keystore key...";
186     auto status = mService->getKeyEntry(mDescriptor, &keyEntryResponse);
187 
188     if (!status.isOk()) {
189         return Error() << "Failed to find keystore key...";
190     }
191 
192     // On some earlier builds, we created this key on the Strongbox security level;
193     // we now use TEE keys instead (mostly for speed). It shouldn't matter since
194     // verified boot is protected by the TEE anyway. If the key happens to be on
195     // the wrong security level, delete it (this should happen just once).
196     if (keyEntryResponse.metadata.keySecurityLevel != SecurityLevel::TRUSTED_ENVIRONMENT) {
197         return Error() << "Found invalid keystore key with security level: "
198                        << android::hardware::security::keymint::toString(
199                               keyEntryResponse.metadata.keySecurityLevel);
200     }
201 
202     // Make sure this is an early boot key
203     bool foundBootLevel = false;
204     for (const auto& auth : keyEntryResponse.metadata.authorizations) {
205         if (auth.keyParameter.tag == Tag::MAX_BOOT_LEVEL) {
206             if (auth.keyParameter.value.get<KeyParameterValue::integer>() == mKeyBootLevel) {
207                 foundBootLevel = true;
208                 break;
209             }
210         }
211     }
212     if (!foundBootLevel) {
213         return Error() << "Found invalid keystore key without MAX_BOOT_LEVEL tag";
214     }
215 
216     // If the key is still considered valid at this point, extract the public
217     // key from the certificate. Note that we cannot trust this public key,
218     // because it is a part of the keystore2 database, which can be modified by
219     // an attacker.  So instead, when creating the key we HMAC the public key
220     // with a key of the same boot level, and verify the signature here.
221     auto cert = keyEntryResponse.metadata.certificate;
222     if (!cert) {
223         return Error() << "Key did not have a certificate.";
224     }
225     auto publicKey = extractPublicKeyFromX509(cert.value());
226     if (!publicKey.ok()) {
227         return publicKey.error();
228     }
229     std::string publicKeyString = {publicKey->begin(), publicKey->end()};
230 
231     std::string signature;
232     if (!android::base::ReadFileToString(mSignedPubKeyPath, &signature)) {
233         return Error() << "Can't find signature for public key.";
234     }
235 
236     auto signatureValid = mHmacKey.verify(publicKeyString, signature);
237     if (!signatureValid.ok()) {
238         return Error() << "Signature of public key did not match.";
239     }
240     LOG(INFO) << "Verified public key signature.";
241 
242     return *publicKey;
243 }
244 
getOrCreateKey()245 Result<std::vector<uint8_t>> KeystoreKey::getOrCreateKey() {
246     auto existingKey = verifyExistingKey();
247     if (!existingKey.ok()) {
248         LOG(INFO) << existingKey.error().message();
249         LOG(INFO) << "Existing keystore key not found or invalid, creating new key";
250         return createKey();
251     }
252 
253     return *existingKey;
254 }
255 
getInstance(const std::string & signedPubKeyPath,const android::String16 & keyAlias,int64_t keyNspace,int keyBootLevel)256 Result<SigningKey*> KeystoreKey::getInstance(const std::string& signedPubKeyPath,
257                                              const android::String16& keyAlias, int64_t keyNspace,
258                                              int keyBootLevel) {
259     auto keystoreKey = new KeystoreKey(signedPubKeyPath, keyAlias, keyNspace, keyBootLevel);
260 
261     if (!keystoreKey->initialize()) {
262         return Error() << "Failed to initialize keystore key.";
263     } else {
264         return keystoreKey;
265     }
266 }
267 
getSignOpParameters()268 static std::vector<KeyParameter> getSignOpParameters() {
269     std::vector<KeyParameter> opParameters;
270 
271     KeyParameter algo;
272     algo.tag = Tag::ALGORITHM;
273     algo.value = KeyParameterValue::make<KeyParameterValue::algorithm>(Algorithm::RSA);
274     opParameters.push_back(algo);
275 
276     KeyParameter digest;
277     digest.tag = Tag::DIGEST;
278     digest.value = KeyParameterValue::make<KeyParameterValue::digest>(Digest::SHA_2_256);
279     opParameters.push_back(digest);
280 
281     KeyParameter padding;
282     padding.tag = Tag::PADDING;
283     padding.value =
284         KeyParameterValue::make<KeyParameterValue::paddingMode>(PaddingMode::RSA_PKCS1_1_5_SIGN);
285     opParameters.push_back(padding);
286 
287     KeyParameter purpose;
288     purpose.tag = Tag::PURPOSE;
289     purpose.value = KeyParameterValue::make<KeyParameterValue::keyPurpose>(KeyPurpose::SIGN);
290     opParameters.push_back(purpose);
291 
292     return opParameters;
293 }
294 
sign(const std::string & message) const295 Result<std::string> KeystoreKey::sign(const std::string& message) const {
296     static auto opParameters = getSignOpParameters();
297     CreateOperationResponse opResponse;
298 
299     auto status = mSecurityLevel->createOperation(mDescriptor, opParameters, false, &opResponse);
300     if (!status.isOk()) {
301         return Error() << "Failed to create keystore signing operation: " << status;
302     }
303     auto operation = opResponse.iOperation;
304 
305     std::optional<std::vector<uint8_t>> input{std::in_place, message.begin(), message.end()};
306     std::optional<std::vector<uint8_t>> signature;
307     status = operation->finish(input, {}, &signature);
308     if (!status.isOk()) {
309         return Error() << "Failed to call keystore finish operation.";
310     }
311 
312     if (!signature.has_value()) {
313         return Error() << "Didn't receive a signature from keystore finish operation.";
314     }
315 
316     return std::string{signature.value().begin(), signature.value().end()};
317 }
318 
getPublicKey() const319 Result<std::vector<uint8_t>> KeystoreKey::getPublicKey() const {
320     return mPublicKey;
321 }
322