1 /*
2  * Copyright (C) 2016 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 "Keymaster.h"
18 
19 #include <android-base/logging.h>
20 #include <keymasterV4_1/authorization_set.h>
21 #include <keymasterV4_1/keymaster_utils.h>
22 
23 namespace android {
24 namespace vold {
25 
26 using ::android::hardware::hidl_string;
27 using ::android::hardware::hidl_vec;
28 using ::android::hardware::keymaster::V4_0::SecurityLevel;
29 
~KeymasterOperation()30 KeymasterOperation::~KeymasterOperation() {
31     if (mDevice) mDevice->abort(mOpHandle);
32 }
33 
updateCompletely(const char * input,size_t inputLen,const std::function<void (const char *,size_t)> consumer)34 bool KeymasterOperation::updateCompletely(const char* input, size_t inputLen,
35                                           const std::function<void(const char*, size_t)> consumer) {
36     uint32_t inputConsumed = 0;
37 
38     km::ErrorCode km_error;
39     auto hidlCB = [&](km::ErrorCode ret, uint32_t inputConsumedDelta,
40                       const hidl_vec<km::KeyParameter>& /*ignored*/,
41                       const hidl_vec<uint8_t>& _output) {
42         km_error = ret;
43         if (km_error != km::ErrorCode::OK) return;
44         inputConsumed += inputConsumedDelta;
45         consumer(reinterpret_cast<const char*>(&_output[0]), _output.size());
46     };
47 
48     while (inputConsumed != inputLen) {
49         size_t toRead = static_cast<size_t>(inputLen - inputConsumed);
50         auto inputBlob = km::support::blob2hidlVec(
51             reinterpret_cast<const uint8_t*>(&input[inputConsumed]), toRead);
52         auto error = mDevice->update(mOpHandle, hidl_vec<km::KeyParameter>(), inputBlob,
53                                      km::HardwareAuthToken(), km::VerificationToken(), hidlCB);
54         if (!error.isOk()) {
55             LOG(ERROR) << "update failed: " << error.description();
56             mDevice = nullptr;
57             return false;
58         }
59         if (km_error != km::ErrorCode::OK) {
60             LOG(ERROR) << "update failed, code " << int32_t(km_error);
61             mDevice = nullptr;
62             return false;
63         }
64         if (inputConsumed > inputLen) {
65             LOG(ERROR) << "update reported too much input consumed";
66             mDevice = nullptr;
67             return false;
68         }
69     }
70     return true;
71 }
72 
finish(std::string * output)73 bool KeymasterOperation::finish(std::string* output) {
74     km::ErrorCode km_error;
75     auto hidlCb = [&](km::ErrorCode ret, const hidl_vec<km::KeyParameter>& /*ignored*/,
76                       const hidl_vec<uint8_t>& _output) {
77         km_error = ret;
78         if (km_error != km::ErrorCode::OK) return;
79         if (output) output->assign(reinterpret_cast<const char*>(&_output[0]), _output.size());
80     };
81     auto error = mDevice->finish(mOpHandle, hidl_vec<km::KeyParameter>(), hidl_vec<uint8_t>(),
82                                  hidl_vec<uint8_t>(), km::HardwareAuthToken(),
83                                  km::VerificationToken(), hidlCb);
84     mDevice = nullptr;
85     if (!error.isOk()) {
86         LOG(ERROR) << "finish failed: " << error.description();
87         return false;
88     }
89     if (km_error != km::ErrorCode::OK) {
90         LOG(ERROR) << "finish failed, code " << int32_t(km_error);
91         return false;
92     }
93     return true;
94 }
95 
96 /* static */ bool Keymaster::hmacKeyGenerated = false;
97 
Keymaster()98 Keymaster::Keymaster() {
99     auto devices = KmDevice::enumerateAvailableDevices();
100     if (!hmacKeyGenerated) {
101         KmDevice::performHmacKeyAgreement(devices);
102         hmacKeyGenerated = true;
103     }
104     for (auto& dev : devices) {
105         // Do not use StrongBox for device encryption / credential encryption.  If a security chip
106         // is present it will have Weaver, which already strengthens CE.  We get no additional
107         // benefit from using StrongBox here, so skip it.
108         if (dev->halVersion().securityLevel != SecurityLevel::STRONGBOX) {
109             mDevice = std::move(dev);
110             break;
111         }
112     }
113     if (!mDevice) return;
114     auto& version = mDevice->halVersion();
115     LOG(INFO) << "Using " << version.keymasterName << " from " << version.authorName
116               << " for encryption.  Security level: " << toString(version.securityLevel)
117               << ", HAL: " << mDevice->descriptor() << "/" << mDevice->instanceName();
118 }
119 
generateKey(const km::AuthorizationSet & inParams,std::string * key)120 bool Keymaster::generateKey(const km::AuthorizationSet& inParams, std::string* key) {
121     km::ErrorCode km_error;
122     auto hidlCb = [&](km::ErrorCode ret, const hidl_vec<uint8_t>& keyBlob,
123                       const km::KeyCharacteristics& /*ignored*/) {
124         km_error = ret;
125         if (km_error != km::ErrorCode::OK) return;
126         if (key) key->assign(reinterpret_cast<const char*>(&keyBlob[0]), keyBlob.size());
127     };
128 
129     auto error = mDevice->generateKey(inParams.hidl_data(), hidlCb);
130     if (!error.isOk()) {
131         LOG(ERROR) << "generate_key failed: " << error.description();
132         return false;
133     }
134     if (km_error != km::ErrorCode::OK) {
135         LOG(ERROR) << "generate_key failed, code " << int32_t(km_error);
136         return false;
137     }
138     return true;
139 }
140 
exportKey(const KeyBuffer & kmKey,std::string * key)141 bool Keymaster::exportKey(const KeyBuffer& kmKey, std::string* key) {
142     auto kmKeyBlob = km::support::blob2hidlVec(std::string(kmKey.data(), kmKey.size()));
143     km::ErrorCode km_error;
144     auto hidlCb = [&](km::ErrorCode ret, const hidl_vec<uint8_t>& exportedKeyBlob) {
145         km_error = ret;
146         if (km_error != km::ErrorCode::OK) return;
147         if (key)
148             key->assign(reinterpret_cast<const char*>(&exportedKeyBlob[0]), exportedKeyBlob.size());
149     };
150     auto error = mDevice->exportKey(km::KeyFormat::RAW, kmKeyBlob, {}, {}, hidlCb);
151     if (!error.isOk()) {
152         LOG(ERROR) << "export_key failed: " << error.description();
153         return false;
154     }
155     if (km_error != km::ErrorCode::OK) {
156         LOG(ERROR) << "export_key failed, code " << int32_t(km_error);
157         return false;
158     }
159     return true;
160 }
161 
deleteKey(const std::string & key)162 bool Keymaster::deleteKey(const std::string& key) {
163     auto keyBlob = km::support::blob2hidlVec(key);
164     auto error = mDevice->deleteKey(keyBlob);
165     if (!error.isOk()) {
166         LOG(ERROR) << "delete_key failed: " << error.description();
167         return false;
168     }
169     if (error != km::ErrorCode::OK) {
170         LOG(ERROR) << "delete_key failed, code " << int32_t(km::ErrorCode(error));
171         return false;
172     }
173     return true;
174 }
175 
upgradeKey(const std::string & oldKey,const km::AuthorizationSet & inParams,std::string * newKey)176 bool Keymaster::upgradeKey(const std::string& oldKey, const km::AuthorizationSet& inParams,
177                            std::string* newKey) {
178     auto oldKeyBlob = km::support::blob2hidlVec(oldKey);
179     km::ErrorCode km_error;
180     auto hidlCb = [&](km::ErrorCode ret, const hidl_vec<uint8_t>& upgradedKeyBlob) {
181         km_error = ret;
182         if (km_error != km::ErrorCode::OK) return;
183         if (newKey)
184             newKey->assign(reinterpret_cast<const char*>(&upgradedKeyBlob[0]),
185                            upgradedKeyBlob.size());
186     };
187     auto error = mDevice->upgradeKey(oldKeyBlob, inParams.hidl_data(), hidlCb);
188     if (!error.isOk()) {
189         LOG(ERROR) << "upgrade_key failed: " << error.description();
190         return false;
191     }
192     if (km_error != km::ErrorCode::OK) {
193         LOG(ERROR) << "upgrade_key failed, code " << int32_t(km_error);
194         return false;
195     }
196     return true;
197 }
198 
begin(km::KeyPurpose purpose,const std::string & key,const km::AuthorizationSet & inParams,const km::HardwareAuthToken & authToken,km::AuthorizationSet * outParams)199 KeymasterOperation Keymaster::begin(km::KeyPurpose purpose, const std::string& key,
200                                     const km::AuthorizationSet& inParams,
201                                     const km::HardwareAuthToken& authToken,
202                                     km::AuthorizationSet* outParams) {
203     auto keyBlob = km::support::blob2hidlVec(key);
204     uint64_t mOpHandle;
205     km::ErrorCode km_error;
206 
207     auto hidlCb = [&](km::ErrorCode ret, const hidl_vec<km::KeyParameter>& _outParams,
208                       uint64_t operationHandle) {
209         km_error = ret;
210         if (km_error != km::ErrorCode::OK) return;
211         if (outParams) *outParams = _outParams;
212         mOpHandle = operationHandle;
213     };
214 
215     auto error = mDevice->begin(purpose, keyBlob, inParams.hidl_data(), authToken, hidlCb);
216     if (!error.isOk()) {
217         LOG(ERROR) << "begin failed: " << error.description();
218         return KeymasterOperation(km::ErrorCode::UNKNOWN_ERROR);
219     }
220     if (km_error != km::ErrorCode::OK) {
221         LOG(ERROR) << "begin failed, code " << int32_t(km_error);
222         return KeymasterOperation(km_error);
223     }
224     return KeymasterOperation(mDevice.get(), mOpHandle);
225 }
226 
isSecure()227 bool Keymaster::isSecure() {
228     return mDevice->halVersion().securityLevel != km::SecurityLevel::SOFTWARE;
229 }
230 
earlyBootEnded()231 void Keymaster::earlyBootEnded() {
232     auto devices = KmDevice::enumerateAvailableDevices();
233     for (auto& dev : devices) {
234         auto error = dev->earlyBootEnded();
235         if (!error.isOk()) {
236             LOG(ERROR) << "earlyBootEnded call failed: " << error.description() << " for "
237                        << dev->halVersion().keymasterName;
238         }
239         km::V4_1_ErrorCode km_error = error;
240         if (km_error != km::V4_1_ErrorCode::OK && km_error != km::V4_1_ErrorCode::UNIMPLEMENTED) {
241             LOG(ERROR) << "Error reporting early boot ending to keymaster: "
242                        << static_cast<int32_t>(km_error) << " for "
243                        << dev->halVersion().keymasterName;
244         }
245     }
246 }
247 
248 }  // namespace vold
249 }  // namespace android
250 
251 using namespace ::android::vold;
252 
keymaster_compatibility_cryptfs_scrypt()253 int keymaster_compatibility_cryptfs_scrypt() {
254     Keymaster dev;
255     if (!dev) {
256         LOG(ERROR) << "Failed to initiate keymaster session";
257         return -1;
258     }
259     return dev.isSecure();
260 }
261 
write_string_to_buf(const std::string & towrite,uint8_t * buffer,uint32_t buffer_size,uint32_t * out_size)262 static bool write_string_to_buf(const std::string& towrite, uint8_t* buffer, uint32_t buffer_size,
263                                 uint32_t* out_size) {
264     if (!buffer || !out_size) {
265         LOG(ERROR) << "Missing target pointers";
266         return false;
267     }
268     *out_size = towrite.size();
269     if (buffer_size < towrite.size()) {
270         LOG(ERROR) << "Buffer too small " << buffer_size << " < " << towrite.size();
271         return false;
272     }
273     memset(buffer, '\0', buffer_size);
274     std::copy(towrite.begin(), towrite.end(), buffer);
275     return true;
276 }
277 
keyParams(uint32_t rsa_key_size,uint64_t rsa_exponent,uint32_t ratelimit)278 static km::AuthorizationSet keyParams(uint32_t rsa_key_size, uint64_t rsa_exponent,
279                                       uint32_t ratelimit) {
280     return km::AuthorizationSetBuilder()
281         .RsaSigningKey(rsa_key_size, rsa_exponent)
282         .NoDigestOrPadding()
283         .Authorization(km::TAG_BLOB_USAGE_REQUIREMENTS, km::KeyBlobUsageRequirements::STANDALONE)
284         .Authorization(km::TAG_NO_AUTH_REQUIRED)
285         .Authorization(km::TAG_MIN_SECONDS_BETWEEN_OPS, ratelimit);
286 }
287 
keymaster_create_key_for_cryptfs_scrypt(uint32_t rsa_key_size,uint64_t rsa_exponent,uint32_t ratelimit,uint8_t * key_buffer,uint32_t key_buffer_size,uint32_t * key_out_size)288 int keymaster_create_key_for_cryptfs_scrypt(uint32_t rsa_key_size, uint64_t rsa_exponent,
289                                             uint32_t ratelimit, uint8_t* key_buffer,
290                                             uint32_t key_buffer_size, uint32_t* key_out_size) {
291     if (key_out_size) {
292         *key_out_size = 0;
293     }
294     Keymaster dev;
295     if (!dev) {
296         LOG(ERROR) << "Failed to initiate keymaster session";
297         return -1;
298     }
299     std::string key;
300     if (!dev.generateKey(keyParams(rsa_key_size, rsa_exponent, ratelimit), &key)) return -1;
301     if (!write_string_to_buf(key, key_buffer, key_buffer_size, key_out_size)) return -1;
302     return 0;
303 }
304 
keymaster_upgrade_key_for_cryptfs_scrypt(uint32_t rsa_key_size,uint64_t rsa_exponent,uint32_t ratelimit,const uint8_t * key_blob,size_t key_blob_size,uint8_t * key_buffer,uint32_t key_buffer_size,uint32_t * key_out_size)305 int keymaster_upgrade_key_for_cryptfs_scrypt(uint32_t rsa_key_size, uint64_t rsa_exponent,
306                                              uint32_t ratelimit, const uint8_t* key_blob,
307                                              size_t key_blob_size, uint8_t* key_buffer,
308                                              uint32_t key_buffer_size, uint32_t* key_out_size) {
309     if (key_out_size) {
310         *key_out_size = 0;
311     }
312     Keymaster dev;
313     if (!dev) {
314         LOG(ERROR) << "Failed to initiate keymaster session";
315         return -1;
316     }
317     std::string old_key(reinterpret_cast<const char*>(key_blob), key_blob_size);
318     std::string new_key;
319     if (!dev.upgradeKey(old_key, keyParams(rsa_key_size, rsa_exponent, ratelimit), &new_key))
320         return -1;
321     if (!write_string_to_buf(new_key, key_buffer, key_buffer_size, key_out_size)) return -1;
322     return 0;
323 }
324 
keymaster_sign_object_for_cryptfs_scrypt(const uint8_t * key_blob,size_t key_blob_size,uint32_t ratelimit,const uint8_t * object,const size_t object_size,uint8_t ** signature_buffer,size_t * signature_buffer_size)325 KeymasterSignResult keymaster_sign_object_for_cryptfs_scrypt(
326     const uint8_t* key_blob, size_t key_blob_size, uint32_t ratelimit, const uint8_t* object,
327     const size_t object_size, uint8_t** signature_buffer, size_t* signature_buffer_size) {
328     Keymaster dev;
329     if (!dev) {
330         LOG(ERROR) << "Failed to initiate keymaster session";
331         return KeymasterSignResult::error;
332     }
333     if (!key_blob || !object || !signature_buffer || !signature_buffer_size) {
334         LOG(ERROR) << __FILE__ << ":" << __LINE__ << ":Invalid argument";
335         return KeymasterSignResult::error;
336     }
337 
338     km::AuthorizationSet outParams;
339     std::string key(reinterpret_cast<const char*>(key_blob), key_blob_size);
340     std::string input(reinterpret_cast<const char*>(object), object_size);
341     std::string output;
342     KeymasterOperation op;
343 
344     auto paramBuilder = km::AuthorizationSetBuilder().NoDigestOrPadding();
345     while (true) {
346         op = dev.begin(km::KeyPurpose::SIGN, key, paramBuilder, km::HardwareAuthToken(), &outParams);
347         if (op.errorCode() == km::ErrorCode::KEY_RATE_LIMIT_EXCEEDED) {
348             sleep(ratelimit);
349             continue;
350         } else
351             break;
352     }
353 
354     if (op.errorCode() == km::ErrorCode::KEY_REQUIRES_UPGRADE) {
355         LOG(ERROR) << "Keymaster key requires upgrade";
356         return KeymasterSignResult::upgrade;
357     }
358 
359     if (op.errorCode() != km::ErrorCode::OK) {
360         LOG(ERROR) << "Error starting keymaster signature transaction: " << int32_t(op.errorCode());
361         return KeymasterSignResult::error;
362     }
363 
364     if (!op.updateCompletely(input, &output)) {
365         LOG(ERROR) << "Error sending data to keymaster signature transaction: "
366                    << uint32_t(op.errorCode());
367         return KeymasterSignResult::error;
368     }
369 
370     if (!op.finish(&output)) {
371         LOG(ERROR) << "Error finalizing keymaster signature transaction: "
372                    << int32_t(op.errorCode());
373         return KeymasterSignResult::error;
374     }
375 
376     *signature_buffer = reinterpret_cast<uint8_t*>(malloc(output.size()));
377     if (*signature_buffer == nullptr) {
378         LOG(ERROR) << "Error allocation buffer for keymaster signature";
379         return KeymasterSignResult::error;
380     }
381     *signature_buffer_size = output.size();
382     std::copy(output.data(), output.data() + output.size(), *signature_buffer);
383     return KeymasterSignResult::ok;
384 }
385