blob: 706181dfe4a0c0016fa62a8aaccf5fccc0b8df6e [file] [log] [blame]
bigbiff7ba75002020-04-11 20:47:09 -04001/*
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_0/authorization_set.h>
21#include <keymasterV4_0/keymaster_utils.h>
22
23namespace android {
24namespace vold {
25
26using ::android::hardware::hidl_string;
27using ::android::hardware::hidl_vec;
28using ::android::hardware::keymaster::V4_0::SecurityLevel;
29
30KeymasterOperation::~KeymasterOperation() {
31 if (mDevice) mDevice->abort(mOpHandle);
32}
33
34bool 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
73bool 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
98Keymaster::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
120bool 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
mauronofrio matarresebd79db42020-05-25 20:18:52 +0200141km::ErrorCode Keymaster::exportKey(km::KeyFormat format, KeyBuffer& kmKey, const std::string& clientId,
mauronofrio matarrese79820322020-05-25 19:48:56 +0200142 const std::string& appData, std::string* key) {
143 auto kmKeyBlob = km::support::blob2hidlVec(std::string(kmKey.data(), kmKey.size()));
144 auto emptyAssign = NULL;
145 auto kmClientId = (clientId == "!") ? emptyAssign: km::support::blob2hidlVec(clientId);
146 auto kmAppData = (appData == "!") ? emptyAssign: km::support::blob2hidlVec(appData);
147 km::ErrorCode km_error;
148 auto hidlCb = [&](km::ErrorCode ret, const hidl_vec<uint8_t>& exportedKeyBlob) {
149 km_error = ret;
150 if (km_error != km::ErrorCode::OK) return;
151 if(key)
152 key->assign(reinterpret_cast<const char*>(&exportedKeyBlob[0]),
153 exportedKeyBlob.size());
154 };
155 auto error = mDevice->exportKey(format, kmKeyBlob, kmClientId, kmAppData, hidlCb);
156 if (!error.isOk()) {
157 LOG(ERROR) << "export_key failed: " << error.description();
mauronofrio matarresebd79db42020-05-25 20:18:52 +0200158 return km::ErrorCode::UNKNOWN_ERROR;
mauronofrio matarrese79820322020-05-25 19:48:56 +0200159 }
160 if (km_error != km::ErrorCode::OK) {
161 LOG(ERROR) << "export_key failed, code " << int32_t(km_error);
mauronofrio matarresebd79db42020-05-25 20:18:52 +0200162 return km_error;
mauronofrio matarrese79820322020-05-25 19:48:56 +0200163 }
mauronofrio matarresebd79db42020-05-25 20:18:52 +0200164 return km::ErrorCode::OK;
mauronofrio matarrese79820322020-05-25 19:48:56 +0200165}
166
bigbiff7ba75002020-04-11 20:47:09 -0400167bool Keymaster::deleteKey(const std::string& key) {
168 auto keyBlob = km::support::blob2hidlVec(key);
169 auto error = mDevice->deleteKey(keyBlob);
170 if (!error.isOk()) {
171 LOG(ERROR) << "delete_key failed: " << error.description();
172 return false;
173 }
174 if (error != km::ErrorCode::OK) {
175 LOG(ERROR) << "delete_key failed, code " << int32_t(km::ErrorCode(error));
176 return false;
177 }
178 return true;
179}
180
181bool Keymaster::upgradeKey(const std::string& oldKey, const km::AuthorizationSet& inParams,
182 std::string* newKey) {
183 auto oldKeyBlob = km::support::blob2hidlVec(oldKey);
184 km::ErrorCode km_error;
185 auto hidlCb = [&](km::ErrorCode ret, const hidl_vec<uint8_t>& upgradedKeyBlob) {
186 km_error = ret;
187 if (km_error != km::ErrorCode::OK) return;
188 if (newKey)
189 newKey->assign(reinterpret_cast<const char*>(&upgradedKeyBlob[0]),
190 upgradedKeyBlob.size());
191 };
192 auto error = mDevice->upgradeKey(oldKeyBlob, inParams.hidl_data(), hidlCb);
193 if (!error.isOk()) {
194 LOG(ERROR) << "upgrade_key failed: " << error.description();
195 return false;
196 }
197 if (km_error != km::ErrorCode::OK) {
198 LOG(ERROR) << "upgrade_key failed, code " << int32_t(km_error);
199 return false;
200 }
201 return true;
202}
203
204KeymasterOperation Keymaster::begin(km::KeyPurpose purpose, const std::string& key,
205 const km::AuthorizationSet& inParams,
206 const km::HardwareAuthToken& authToken,
207 km::AuthorizationSet* outParams) {
208 auto keyBlob = km::support::blob2hidlVec(key);
209 uint64_t mOpHandle;
210 km::ErrorCode km_error;
211
212 auto hidlCb = [&](km::ErrorCode ret, const hidl_vec<km::KeyParameter>& _outParams,
213 uint64_t operationHandle) {
214 km_error = ret;
215 if (km_error != km::ErrorCode::OK) return;
216 if (outParams) *outParams = _outParams;
217 mOpHandle = operationHandle;
218 };
219
220 auto error = mDevice->begin(purpose, keyBlob, inParams.hidl_data(), authToken, hidlCb);
221 if (!error.isOk()) {
222 LOG(ERROR) << "begin failed: " << error.description();
223 return KeymasterOperation(km::ErrorCode::UNKNOWN_ERROR);
224 }
225 if (km_error != km::ErrorCode::OK) {
226 LOG(ERROR) << "begin failed, code " << int32_t(km_error);
227 return KeymasterOperation(km_error);
228 }
229 return KeymasterOperation(mDevice.get(), mOpHandle);
230}
231
232bool Keymaster::isSecure() {
233 return mDevice->halVersion().securityLevel != km::SecurityLevel::SOFTWARE;
234}
235
236} // namespace vold
237} // namespace android
238
239using namespace ::android::vold;
240
241int keymaster_compatibility_cryptfs_scrypt() {
242 Keymaster dev;
243 if (!dev) {
244 LOG(ERROR) << "Failed to initiate keymaster session";
245 return -1;
246 }
247 return dev.isSecure();
248}
249
250static bool write_string_to_buf(const std::string& towrite, uint8_t* buffer, uint32_t buffer_size,
251 uint32_t* out_size) {
252 if (!buffer || !out_size) {
253 LOG(ERROR) << "Missing target pointers";
254 return false;
255 }
256 *out_size = towrite.size();
257 if (buffer_size < towrite.size()) {
258 LOG(ERROR) << "Buffer too small " << buffer_size << " < " << towrite.size();
259 return false;
260 }
261 memset(buffer, '\0', buffer_size);
262 std::copy(towrite.begin(), towrite.end(), buffer);
263 return true;
264}
265
266static km::AuthorizationSet keyParams(uint32_t rsa_key_size, uint64_t rsa_exponent,
267 uint32_t ratelimit) {
268 return km::AuthorizationSetBuilder()
269 .RsaSigningKey(rsa_key_size, rsa_exponent)
270 .NoDigestOrPadding()
271 .Authorization(km::TAG_BLOB_USAGE_REQUIREMENTS, km::KeyBlobUsageRequirements::STANDALONE)
272 .Authorization(km::TAG_NO_AUTH_REQUIRED)
273 .Authorization(km::TAG_MIN_SECONDS_BETWEEN_OPS, ratelimit);
274}
275
276int keymaster_create_key_for_cryptfs_scrypt(uint32_t rsa_key_size, uint64_t rsa_exponent,
277 uint32_t ratelimit, uint8_t* key_buffer,
278 uint32_t key_buffer_size, uint32_t* key_out_size) {
279 if (key_out_size) {
280 *key_out_size = 0;
281 }
282 Keymaster dev;
283 if (!dev) {
284 LOG(ERROR) << "Failed to initiate keymaster session";
285 return -1;
286 }
287 std::string key;
288 if (!dev.generateKey(keyParams(rsa_key_size, rsa_exponent, ratelimit), &key)) return -1;
289 if (!write_string_to_buf(key, key_buffer, key_buffer_size, key_out_size)) return -1;
290 return 0;
291}
292
293int keymaster_upgrade_key_for_cryptfs_scrypt(uint32_t rsa_key_size, uint64_t rsa_exponent,
294 uint32_t ratelimit, const uint8_t* key_blob,
295 size_t key_blob_size, uint8_t* key_buffer,
296 uint32_t key_buffer_size, uint32_t* key_out_size) {
297 if (key_out_size) {
298 *key_out_size = 0;
299 }
300 Keymaster dev;
301 if (!dev) {
302 LOG(ERROR) << "Failed to initiate keymaster session";
303 return -1;
304 }
305 std::string old_key(reinterpret_cast<const char*>(key_blob), key_blob_size);
306 std::string new_key;
307 if (!dev.upgradeKey(old_key, keyParams(rsa_key_size, rsa_exponent, ratelimit), &new_key))
308 return -1;
309 if (!write_string_to_buf(new_key, key_buffer, key_buffer_size, key_out_size)) return -1;
310 return 0;
311}
312
313KeymasterSignResult keymaster_sign_object_for_cryptfs_scrypt(
314 const uint8_t* key_blob, size_t key_blob_size, uint32_t ratelimit, const uint8_t* object,
315 const size_t object_size, uint8_t** signature_buffer, size_t* signature_buffer_size) {
316 Keymaster dev;
317 if (!dev) {
318 LOG(ERROR) << "Failed to initiate keymaster session";
319 return KeymasterSignResult::error;
320 }
321 if (!key_blob || !object || !signature_buffer || !signature_buffer_size) {
322 LOG(ERROR) << __FILE__ << ":" << __LINE__ << ":Invalid argument";
323 return KeymasterSignResult::error;
324 }
325
326 km::AuthorizationSet outParams;
327 std::string key(reinterpret_cast<const char*>(key_blob), key_blob_size);
328 std::string input(reinterpret_cast<const char*>(object), object_size);
329 std::string output;
330 KeymasterOperation op;
331
332 auto paramBuilder = km::AuthorizationSetBuilder().NoDigestOrPadding();
333 while (true) {
334 op = dev.begin(km::KeyPurpose::SIGN, key, paramBuilder, km::HardwareAuthToken(), &outParams);
335 if (op.errorCode() == km::ErrorCode::KEY_RATE_LIMIT_EXCEEDED) {
336 sleep(ratelimit);
337 continue;
338 } else
339 break;
340 }
341
342 if (op.errorCode() == km::ErrorCode::KEY_REQUIRES_UPGRADE) {
343 LOG(ERROR) << "Keymaster key requires upgrade";
344 return KeymasterSignResult::upgrade;
345 }
346
347 if (op.errorCode() != km::ErrorCode::OK) {
348 LOG(ERROR) << "Error starting keymaster signature transaction: " << int32_t(op.errorCode());
349 return KeymasterSignResult::error;
350 }
351
352 if (!op.updateCompletely(input, &output)) {
353 LOG(ERROR) << "Error sending data to keymaster signature transaction: "
354 << uint32_t(op.errorCode());
355 return KeymasterSignResult::error;
356 }
357
358 if (!op.finish(&output)) {
359 LOG(ERROR) << "Error finalizing keymaster signature transaction: "
360 << int32_t(op.errorCode());
361 return KeymasterSignResult::error;
362 }
363
364 *signature_buffer = reinterpret_cast<uint8_t*>(malloc(output.size()));
365 if (*signature_buffer == nullptr) {
366 LOG(ERROR) << "Error allocation buffer for keymaster signature";
367 return KeymasterSignResult::error;
368 }
369 *signature_buffer_size = output.size();
370 std::copy(output.data(), output.data() + output.size(), *signature_buffer);
371 return KeymasterSignResult::ok;
372}