OSDN Git Service

Merge "Change to use new WaitForProperty API"
[android-x86/system-vold.git] / Keymaster.cpp
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 <keystore/keymaster_tags.h>
21 #include <keystore/authorization_set.h>
22 #include <keystore/keystore_hidl_support.h>
23
24 using namespace ::keystore;
25
26 namespace android {
27 namespace vold {
28
29 KeymasterOperation::~KeymasterOperation() {
30     if (mDevice.get()) mDevice->abort(mOpHandle);
31 }
32
33 bool KeymasterOperation::updateCompletely(const std::string& input, std::string* output) {
34     if (output)
35         output->clear();
36     auto it = input.begin();
37     uint32_t inputConsumed;
38
39     ErrorCode km_error;
40     auto hidlCB = [&] (ErrorCode ret, uint32_t _inputConsumed,
41             const hidl_vec<KeyParameter>& /*ignored*/, const hidl_vec<uint8_t>& _output) {
42         km_error = ret;
43         if (km_error != ErrorCode::OK) return;
44         inputConsumed = _inputConsumed;
45         if (output)
46             output->append(reinterpret_cast<const char*>(&_output[0]), _output.size());
47     };
48
49     while (it != input.end()) {
50         size_t toRead = static_cast<size_t>(input.end() - it);
51         auto inputBlob = blob2hidlVec(reinterpret_cast<const uint8_t*>(&*it), toRead);
52         auto error = mDevice->update(mOpHandle, hidl_vec<KeyParameter>(), inputBlob, hidlCB);
53         if (!error.isOk()) {
54             LOG(ERROR) << "update failed: " << error.description();
55             mDevice = nullptr;
56             return false;
57         }
58         if (km_error != ErrorCode::OK) {
59             LOG(ERROR) << "update failed, code " << int32_t(km_error);
60             mDevice = nullptr;
61             return false;
62         }
63         if (inputConsumed > toRead) {
64             LOG(ERROR) << "update reported too much input consumed";
65             mDevice = nullptr;
66             return false;
67         }
68         it += inputConsumed;
69     }
70     return true;
71 }
72
73 bool KeymasterOperation::finish(std::string* output) {
74     ErrorCode km_error;
75     auto hidlCb = [&] (ErrorCode ret, const hidl_vec<KeyParameter>& /*ignored*/,
76             const hidl_vec<uint8_t>& _output) {
77         km_error = ret;
78         if (km_error != ErrorCode::OK) return;
79         if (output)
80             output->assign(reinterpret_cast<const char*>(&_output[0]), _output.size());
81     };
82     auto error = mDevice->finish(mOpHandle, hidl_vec<KeyParameter>(), hidl_vec<uint8_t>(),
83             hidl_vec<uint8_t>(), hidlCb);
84     mDevice = nullptr;
85     if (!error.isOk()) {
86         LOG(ERROR) << "finish failed: " << error.description();
87         return false;
88     }
89     if (km_error != ErrorCode::OK) {
90         LOG(ERROR) << "finish failed, code " << int32_t(km_error);
91         return false;
92     }
93     return true;
94 }
95
96 Keymaster::Keymaster() {
97     mDevice = ::android::hardware::keymaster::V3_0::IKeymasterDevice::getService();
98 }
99
100 bool Keymaster::generateKey(const AuthorizationSet& inParams, std::string* key) {
101     ErrorCode km_error;
102     auto hidlCb = [&] (ErrorCode ret, const hidl_vec<uint8_t>& keyBlob,
103             const KeyCharacteristics& /*ignored*/) {
104         km_error = ret;
105         if (km_error != ErrorCode::OK) return;
106         if (key)
107             key->assign(reinterpret_cast<const char*>(&keyBlob[0]), keyBlob.size());
108     };
109
110     auto error = mDevice->generateKey(inParams.hidl_data(), hidlCb);
111     if (!error.isOk()) {
112         LOG(ERROR) << "generate_key failed: " << error.description();
113         return false;
114     }
115     if (km_error != ErrorCode::OK) {
116         LOG(ERROR) << "generate_key failed, code " << int32_t(km_error);
117         return false;
118     }
119     return true;
120 }
121
122 bool Keymaster::deleteKey(const std::string& key) {
123     auto keyBlob = blob2hidlVec(key);
124     auto error = mDevice->deleteKey(keyBlob);
125     if (!error.isOk()) {
126         LOG(ERROR) << "delete_key failed: " << error.description();
127         return false;
128     }
129     if (ErrorCode(error) != ErrorCode::OK) {
130         LOG(ERROR) << "delete_key failed, code " << uint32_t(ErrorCode(error));
131         return false;
132     }
133     return true;
134 }
135
136 bool Keymaster::upgradeKey(const std::string& oldKey, const AuthorizationSet& inParams,
137                            std::string* newKey) {
138     auto oldKeyBlob = blob2hidlVec(oldKey);
139     ErrorCode km_error;
140     auto hidlCb = [&] (ErrorCode ret, const hidl_vec<uint8_t>& upgradedKeyBlob) {
141         km_error = ret;
142         if (km_error != ErrorCode::OK) return;
143         if (newKey)
144             newKey->assign(reinterpret_cast<const char*>(&upgradedKeyBlob[0]),
145                     upgradedKeyBlob.size());
146     };
147     auto error = mDevice->upgradeKey(oldKeyBlob, inParams.hidl_data(), hidlCb);
148     if (!error.isOk()) {
149         LOG(ERROR) << "upgrade_key failed: " << error.description();
150         return false;
151     }
152     if (km_error != ErrorCode::OK) {
153         LOG(ERROR) << "upgrade_key failed, code " << int32_t(km_error);
154         return false;
155     }
156     return true;
157 }
158
159 KeymasterOperation Keymaster::begin(KeyPurpose purpose, const std::string& key,
160                                     const AuthorizationSet& inParams,
161                                     AuthorizationSet* outParams) {
162     auto keyBlob = blob2hidlVec(key);
163     uint64_t mOpHandle;
164     ErrorCode km_error;
165
166     auto hidlCb = [&] (ErrorCode ret, const hidl_vec<KeyParameter>& _outParams,
167             uint64_t operationHandle) {
168         km_error = ret;
169         if (km_error != ErrorCode::OK) return;
170         if (outParams)
171             *outParams = _outParams;
172         mOpHandle = operationHandle;
173     };
174
175     auto error = mDevice->begin(purpose, keyBlob, inParams.hidl_data(), hidlCb);
176     if (!error.isOk()) {
177         LOG(ERROR) << "begin failed: " << error.description();
178         return KeymasterOperation(ErrorCode::UNKNOWN_ERROR);
179     }
180     if (km_error != ErrorCode::OK) {
181         LOG(ERROR) << "begin failed, code " << int32_t(km_error);
182         return KeymasterOperation(km_error);
183     }
184     return KeymasterOperation(mDevice, mOpHandle);
185 }
186 bool Keymaster::isSecure() {
187     bool _isSecure = false;
188     auto rc = mDevice->getHardwareFeatures(
189             [&] (bool isSecure, bool, bool, bool) { _isSecure = isSecure; });
190     return rc.isOk() && _isSecure;
191 }
192
193 }  // namespace vold
194 }  // namespace android
195
196 using namespace ::android::vold;
197
198 int keymaster_compatibility_cryptfs_scrypt() {
199     return Keymaster().isSecure();
200 }
201
202 int keymaster_create_key_for_cryptfs_scrypt(uint32_t rsa_key_size,
203                                             uint64_t rsa_exponent,
204                                             uint32_t ratelimit,
205                                             uint8_t* key_buffer,
206                                             uint32_t key_buffer_size,
207                                             uint32_t* key_out_size)
208 {
209     Keymaster dev;
210     std::string key;
211     if (!dev) {
212         LOG(ERROR) << "Failed to initiate keymaster session";
213         return -1;
214     }
215     if (!key_buffer || !key_out_size) {
216         LOG(ERROR) << __FILE__ << ":" << __LINE__ << ":Invalid argument";
217         return -1;
218     }
219     if (key_out_size) {
220         *key_out_size = 0;
221     }
222
223     auto paramBuilder = AuthorizationSetBuilder()
224                             .Authorization(TAG_ALGORITHM, Algorithm::RSA)
225                             .Authorization(TAG_KEY_SIZE, rsa_key_size)
226                             .Authorization(TAG_RSA_PUBLIC_EXPONENT, rsa_exponent)
227                             .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
228                             .Authorization(TAG_PADDING, PaddingMode::NONE)
229                             .Authorization(TAG_DIGEST, Digest::NONE)
230                             .Authorization(TAG_BLOB_USAGE_REQUIREMENTS,
231                                     KeyBlobUsageRequirements::STANDALONE)
232                             .Authorization(TAG_NO_AUTH_REQUIRED)
233                             .Authorization(TAG_MIN_SECONDS_BETWEEN_OPS, ratelimit);
234
235     if (!dev.generateKey(paramBuilder, &key)) {
236         return -1;
237     }
238
239     if (key_out_size) {
240         *key_out_size = key.size();
241     }
242
243     if (key_buffer_size < key.size()) {
244         return -1;
245     }
246
247     std::copy(key.data(), key.data() + key.size(), key_buffer);
248     return 0;
249 }
250
251 int keymaster_sign_object_for_cryptfs_scrypt(const uint8_t* key_blob,
252                                              size_t key_blob_size,
253                                              uint32_t ratelimit,
254                                              const uint8_t* object,
255                                              const size_t object_size,
256                                              uint8_t** signature_buffer,
257                                              size_t* signature_buffer_size)
258 {
259     Keymaster dev;
260     if (!dev) {
261         LOG(ERROR) << "Failed to initiate keymaster session";
262         return -1;
263     }
264     if (!key_blob || !object || !signature_buffer || !signature_buffer_size) {
265         LOG(ERROR) << __FILE__ << ":" << __LINE__ << ":Invalid argument";
266         return -1;
267     }
268
269     AuthorizationSet outParams;
270     std::string key(reinterpret_cast<const char*>(key_blob), key_blob_size);
271     std::string input(reinterpret_cast<const char*>(object), object_size);
272     std::string output;
273     KeymasterOperation op;
274
275     auto paramBuilder = AuthorizationSetBuilder()
276                             .Authorization(TAG_PADDING, PaddingMode::NONE)
277                             .Authorization(TAG_DIGEST, Digest::NONE);
278
279     while (true) {
280         op = dev.begin(KeyPurpose::SIGN, key, paramBuilder, &outParams);
281         if (op.errorCode() == ErrorCode::KEY_RATE_LIMIT_EXCEEDED) {
282             sleep(ratelimit);
283             continue;
284         } else break;
285     }
286
287     if (op.errorCode() != ErrorCode::OK) {
288         LOG(ERROR) << "Error starting keymaster signature transaction: " << int32_t(op.errorCode());
289         return -1;
290     }
291
292     if (!op.updateCompletely(input, &output)) {
293         LOG(ERROR) << "Error sending data to keymaster signature transaction: "
294                    << uint32_t(op.errorCode());
295         return -1;
296     }
297
298     if (!op.finish(&output)) {
299         LOG(ERROR) << "Error finalizing keymaster signature transaction: " << int32_t(op.errorCode());
300         return -1;
301     }
302
303     *signature_buffer = reinterpret_cast<uint8_t*>(malloc(output.size()));
304     if (*signature_buffer == nullptr) {
305         LOG(ERROR) << "Error allocation buffer for keymaster signature";
306         return -1;
307     }
308     *signature_buffer_size = output.size();
309     std::copy(output.data(), output.data() + output.size(), *signature_buffer);
310     return 0;
311 }