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