blob: 6cfb56557cc2ac6ca85758e8da9a909c83cca7c3 [file] [log] [blame]
Martijn Coenen95194842020-09-24 16:56:46 +02001/*
2 * Copyright (C) 2020 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/logging.h>
20#include <keymasterV4_1/Keymaster.h>
21#include <keymasterV4_1/authorization_set.h>
22
23#include <fcntl.h>
24#include <sys/stat.h>
25#include <sys/types.h>
26
27#include "Keymaster.h"
28
29using AuthorizationSet = ::android::hardware::keymaster::V4_0::AuthorizationSet;
30using AuthorizationSetBuilder = ::android::hardware::keymaster::V4_0::AuthorizationSetBuilder;
31using Digest = ::android::hardware::keymaster::V4_0::Digest;
32using ErrorCode = ::android::hardware::keymaster::V4_0::ErrorCode;
33using HardwareAuthToken = ::android::hardware::keymaster::V4_0::HardwareAuthToken;
34using HidlBuf = ::android::hardware::hidl_vec<uint8_t>;
35using KeyCharacteristics = ::android::hardware::keymaster::V4_0::KeyCharacteristics;
36using KeyFormat = ::android::hardware::keymaster::V4_0::KeyFormat;
37using KeyParameter = ::android::hardware::keymaster::V4_0::KeyParameter;
38using KeyPurpose = ::android::hardware::keymaster::V4_0::KeyPurpose;
39using KmSupport = ::android::hardware::keymaster::V4_1::support::Keymaster;
40using KmDevice = ::android::hardware::keymaster::V4_1::IKeymasterDevice;
41using OperationHandle = ::android::hardware::keymaster::V4_0::OperationHandle;
42using PaddingMode = ::android::hardware::keymaster::V4_0::PaddingMode;
43using VerificationToken = ::android::hardware::keymaster::V4_0::VerificationToken;
44
45using android::sp;
46using android::base::Error;
47using android::base::Result;
48using android::base::unique_fd;
49using android::hardware::hidl_vec;
50
51Keymaster::Keymaster() {}
52
53bool Keymaster::initialize() {
54 // TODO(b/165630556): Stop using Keymaster directly and migrate to keystore2
55 // (once available).
56 auto devices = KmSupport::enumerateAvailableDevices();
57 sp<KmDevice> devToUse = nullptr;
58 for (const auto& dev : devices) {
59 auto version = dev->halVersion();
60 if (version.majorVersion > 4 || (version.majorVersion == 4 && version.minorVersion >= 1)) {
61 // TODO we probably have a preference for the SE, hoping Keystore2 will provide this
62 LOG(INFO) << "Using keymaster " << version.keymasterName << " "
63 << (int)version.majorVersion << "." << (int)version.minorVersion;
64 devToUse = dev;
65 break;
66 }
67 }
68
Martijn Coenen3883ec62021-02-25 09:14:01 +010069 if (devToUse == nullptr) {
70 LOG(WARNING) << "Didn't find a keymaster to use.";
71 }
Martijn Coenen95194842020-09-24 16:56:46 +020072 mDevice = devToUse;
73
Martijn Coenen2a6a5fd2021-02-24 07:13:09 +010074 return mDevice != nullptr;
Martijn Coenen95194842020-09-24 16:56:46 +020075}
76
77std::optional<Keymaster> Keymaster::getInstance() {
78 static Keymaster keymaster;
79
80 if (!keymaster.initialize()) {
81 return {};
82 } else {
83 return {keymaster};
84 }
85}
86
87Result<std::vector<uint8_t>> Keymaster::createKey() const {
88 ErrorCode error;
89 HidlBuf keyBlob;
90
91 auto params = AuthorizationSetBuilder()
92 .Authorization(::android::hardware::keymaster::V4_0::TAG_NO_AUTH_REQUIRED)
93 // TODO MAKE SURE WE ADD THE EARLY_BOOT_ONLY FLAG here
94 // currently doesn't work on cuttlefish (b/173618442)
95 //.Authorization(::android::hardware::keymaster::V4_1::TAG_EARLY_BOOT_ONLY)
96 .RsaSigningKey(2048, 65537)
97 .Digest(Digest::SHA_2_256)
98 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN);
99
100 mDevice->generateKey(params.hidl_data(), [&](ErrorCode hidl_error, const HidlBuf& hidl_key_blob,
101 const KeyCharacteristics&
102 /* hidl_key_characteristics */) {
103 error = hidl_error;
104 keyBlob = hidl_key_blob;
105 });
106
107 if (error != ErrorCode::OK) {
108 return Error() << "Error creating keymaster signing key: "
109 << static_cast<std::underlying_type<ErrorCode>::type>(error);
110 }
111
112 return keyBlob;
113}
114
115static ErrorCode Begin(const sp<KmDevice>& keymaster_, KeyPurpose purpose, const HidlBuf& key_blob,
116 const AuthorizationSet& in_params, AuthorizationSet* out_params,
117 OperationHandle* op_handle) {
118 ErrorCode error;
119 OperationHandle saved_handle = *op_handle;
120 CHECK(keymaster_
121 ->begin(purpose, key_blob, in_params.hidl_data(), HardwareAuthToken(),
122 [&](ErrorCode hidl_error, const hidl_vec<KeyParameter>& hidl_out_params,
123 uint64_t hidl_op_handle) {
124 error = hidl_error;
125 *out_params = hidl_out_params;
126 *op_handle = hidl_op_handle;
127 })
128 .isOk());
129 if (error != ErrorCode::OK) {
130 // Some implementations may modify *op_handle on error.
131 *op_handle = saved_handle;
132 }
133 return error;
134}
135
136static ErrorCode Update(const sp<KmDevice>& keymaster_, OperationHandle op_handle,
137 const AuthorizationSet& in_params, const std::string& input,
138 AuthorizationSet* out_params, std::string* output, size_t* input_consumed) {
139 ErrorCode error;
140 HidlBuf inputData(input.size());
141 memcpy(inputData.data(), input.c_str(), input.size());
142 CHECK(keymaster_
143 ->update(op_handle, in_params.hidl_data(), inputData, HardwareAuthToken(),
144 VerificationToken(),
145 [&](ErrorCode hidl_error, uint32_t hidl_input_consumed,
146 const hidl_vec<KeyParameter>& hidl_out_params,
147 const HidlBuf& hidl_output) {
148 error = hidl_error;
149 out_params->push_back(AuthorizationSet(hidl_out_params));
150 std::string retdata(reinterpret_cast<const char*>(hidl_output.data()),
151 hidl_output.size());
152 output->append(retdata);
153 *input_consumed = hidl_input_consumed;
154 })
155 .isOk());
156 return error;
157}
158
159static ErrorCode Finish(const sp<KmDevice>& keymaster_, OperationHandle op_handle,
160 const AuthorizationSet& in_params, const std::string& input,
161 const std::string& signature, AuthorizationSet* out_params,
162 std::string* output) {
163 ErrorCode error;
164 HidlBuf inputData(input.size());
165 memcpy(inputData.data(), input.c_str(), input.size());
166 HidlBuf signatureData(signature.size());
167 memcpy(signatureData.data(), signature.c_str(), signature.size());
168 // TODO still need to handle error -62 - key requires upgrade
169 CHECK(keymaster_
170 ->finish(op_handle, in_params.hidl_data(), inputData, signatureData,
171 HardwareAuthToken(), VerificationToken(),
172 [&](ErrorCode hidl_error, const hidl_vec<KeyParameter>& hidl_out_params,
173 const HidlBuf& hidl_output) {
174 error = hidl_error;
175 *out_params = hidl_out_params;
176 std::string retdata(reinterpret_cast<const char*>(hidl_output.data()),
177 hidl_output.size());
178 output->append(retdata);
179 })
180 .isOk());
181 return error;
182}
183
184static std::string ProcessMessage(const sp<KmDevice>& keymaster_, const HidlBuf& key_blob,
185 KeyPurpose operation, const std::string& message,
186 const AuthorizationSet& in_params, AuthorizationSet* out_params) {
187 AuthorizationSet begin_out_params;
188 OperationHandle op_handle_;
189 ErrorCode ec =
190 Begin(keymaster_, operation, key_blob, in_params, &begin_out_params, &op_handle_);
191
192 std::string output;
193 size_t consumed = 0;
194 AuthorizationSet update_params;
195 AuthorizationSet update_out_params;
196 ec = Update(keymaster_, op_handle_, update_params, message, &update_out_params, &output,
197 &consumed);
198
199 std::string unused;
200 AuthorizationSet finish_params;
201 AuthorizationSet finish_out_params;
202 ec = Finish(keymaster_, op_handle_, finish_params, message.substr(consumed), unused,
203 &finish_out_params, &output);
204
205 out_params->push_back(begin_out_params);
206 out_params->push_back(finish_out_params);
207 return output;
208}
209
210Result<std::vector<uint8_t>>
211Keymaster::extractPublicKey(const std::vector<uint8_t>& keyBlob) const {
212 std::vector<uint8_t> publicKey;
213 ErrorCode error;
214
215 mDevice->exportKey(KeyFormat::X509, keyBlob, {} /* clientId */, {} /* appData */,
216 [&](ErrorCode hidl_error, const HidlBuf& keyData) {
217 error = hidl_error;
218 publicKey = keyData;
219 });
220
221 if (error != ErrorCode::OK) {
222 return Error() << "Error extracting public key: "
223 << static_cast<std::underlying_type<ErrorCode>::type>(error);
224 }
225
226 return publicKey;
227}
228
229Result<KeymasterVerifyResult> Keymaster::verifyKey(const std::vector<uint8_t>& keyBlob) const {
230 ErrorCode error;
231 KeyCharacteristics characteristics;
232
233 mDevice->getKeyCharacteristics(
234 keyBlob, {} /* clientId */, {} /* appData */,
235 [&](ErrorCode hidl_error, const KeyCharacteristics& hidl_characteristics) {
236 error = hidl_error;
237 characteristics = hidl_characteristics;
238 });
239
240 if (error == ErrorCode::KEY_REQUIRES_UPGRADE) {
241 return KeymasterVerifyResult::UPGRADE;
242 }
243
244 if (error != ErrorCode::OK) {
245 return Error() << "Error getting key characteristics: "
246 << static_cast<std::underlying_type<ErrorCode>::type>(error);
247 }
248
249 // TODO(b/165630556)
250 // Verify this is an early boot key and the other key parameters
251 return KeymasterVerifyResult::OK;
252}
253
254Result<std::vector<uint8_t>> Keymaster::upgradeKey(const std::vector<uint8_t>& keyBlob) const {
255 ErrorCode error;
256 HidlBuf newKeyBlob;
257
258 // TODO deduplicate
259 auto params = AuthorizationSetBuilder()
260 .Authorization(::android::hardware::keymaster::V4_0::TAG_NO_AUTH_REQUIRED)
261 // TODO MAKE SURE WE ADD THE EARLY_BOOT_ONLY FLAG here
262 // currently doesn't work on cuttlefish (b/173618442)
263 //.Authorization(::android::hardware::keymaster::V4_1::TAG_EARLY_BOOT_ONLY)
264 .RsaSigningKey(2048, 65537)
265 .Digest(Digest::SHA_2_256)
266 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN);
267
268 mDevice->upgradeKey(keyBlob, params.hidl_data(),
269 [&](ErrorCode hidl_error, const HidlBuf& hidl_key_blob) {
270 error = hidl_error;
271 newKeyBlob = hidl_key_blob;
272 });
273
274 if (error != ErrorCode::OK) {
275 return Error() << "Error upgrading keymaster signing key: "
276 << static_cast<std::underlying_type<ErrorCode>::type>(error);
277 }
278
279 return newKeyBlob;
280}
281
282Result<std::string> Keymaster::sign(const std::vector<uint8_t>& keyBlob,
283 const std::string& message) const {
284 AuthorizationSet out_params;
285 auto params = AuthorizationSetBuilder()
286 .Digest(Digest::SHA_2_256)
287 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN);
288 std::string signature =
289 ProcessMessage(mDevice, keyBlob, KeyPurpose::SIGN, message, params, &out_params);
290 if (!out_params.empty()) {
291 return Error() << "Error signing key: expected empty out params.";
292 }
293 return signature;
294}