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