blob: 2f6aa1a13d39fb6e89a09b482c5d6d524e075e2b [file] [log] [blame]
Paul Crowley1ef25582016-01-21 20:26:12 +00001/*
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 "KeyStorage.h"
18
19#include "Keymaster.h"
Paul Crowley63c18d32016-02-10 14:02:47 +000020#include "ScryptParameters.h"
Paul Crowley1ef25582016-01-21 20:26:12 +000021#include "Utils.h"
22
23#include <vector>
24
25#include <errno.h>
Paul Crowleydff8c722016-05-16 08:14:56 -070026#include <stdio.h>
Paul Crowley1ef25582016-01-21 20:26:12 +000027#include <sys/stat.h>
28#include <sys/types.h>
29#include <sys/wait.h>
30#include <unistd.h>
31
Paul Crowley6ab2cab2017-01-04 22:32:40 -080032#include <openssl/err.h>
33#include <openssl/evp.h>
Paul Crowley1ef25582016-01-21 20:26:12 +000034#include <openssl/sha.h>
35
36#include <android-base/file.h>
37#include <android-base/logging.h>
Wei Wang701d05d2017-11-07 09:44:16 -080038#include <android-base/unique_fd.h>
Paul Crowley1ef25582016-01-21 20:26:12 +000039
Paul Crowley63c18d32016-02-10 14:02:47 +000040#include <cutils/properties.h>
41
Paul Crowley320e5e12016-03-04 14:07:05 -080042#include <hardware/hw_auth_token.h>
43
Paul Crowley1ef25582016-01-21 20:26:12 +000044
Paul Crowley63c18d32016-02-10 14:02:47 +000045extern "C" {
46
47#include "crypto_scrypt.h"
Paul Crowley63c18d32016-02-10 14:02:47 +000048}
49
Shawn Willdenf4527742017-11-09 15:59:39 -070050#include "authorization_set.h"
51#include "keystore_hidl_support.h"
52
Paul Crowley1ef25582016-01-21 20:26:12 +000053namespace android {
54namespace vold {
Janis Danisevskis8e537b82016-10-26 14:27:10 +010055using namespace keystore;
Paul Crowley1ef25582016-01-21 20:26:12 +000056
Paul Crowleydf528a72016-03-09 09:31:37 -080057const KeyAuthentication kEmptyAuthentication{"", ""};
Paul Crowley05720802016-02-08 15:55:41 +000058
Paul Crowley1ef25582016-01-21 20:26:12 +000059static constexpr size_t AES_KEY_BYTES = 32;
60static constexpr size_t GCM_NONCE_BYTES = 12;
61static constexpr size_t GCM_MAC_BYTES = 16;
Paul Crowleydf528a72016-03-09 09:31:37 -080062static constexpr size_t SALT_BYTES = 1 << 4;
63static constexpr size_t SECDISCARDABLE_BYTES = 1 << 14;
64static constexpr size_t STRETCHED_BYTES = 1 << 6;
Paul Crowley1ef25582016-01-21 20:26:12 +000065
Paul Crowleyb3de3372016-04-27 12:58:41 -070066static constexpr uint32_t AUTH_TIMEOUT = 30; // Seconds
67
Paul Crowley05720802016-02-08 15:55:41 +000068static const char* kCurrentVersion = "1";
Paul Crowley1ef25582016-01-21 20:26:12 +000069static const char* kRmPath = "/system/bin/rm";
70static const char* kSecdiscardPath = "/system/bin/secdiscard";
Paul Crowley63c18d32016-02-10 14:02:47 +000071static const char* kStretch_none = "none";
72static const char* kStretch_nopassword = "nopassword";
73static const std::string kStretchPrefix_scrypt = "scrypt ";
Paul Crowley6ab2cab2017-01-04 22:32:40 -080074static const char* kHashPrefix_secdiscardable = "Android secdiscardable SHA512";
75static const char* kHashPrefix_keygen = "Android key wrapping key generation SHA512";
Paul Crowley1ef25582016-01-21 20:26:12 +000076static const char* kFn_encrypted_key = "encrypted_key";
Paul Crowley05720802016-02-08 15:55:41 +000077static const char* kFn_keymaster_key_blob = "keymaster_key_blob";
Paul Crowleydff8c722016-05-16 08:14:56 -070078static const char* kFn_keymaster_key_blob_upgraded = "keymaster_key_blob_upgraded";
Paul Crowley63c18d32016-02-10 14:02:47 +000079static const char* kFn_salt = "salt";
Paul Crowley1ef25582016-01-21 20:26:12 +000080static const char* kFn_secdiscardable = "secdiscardable";
Paul Crowley05720802016-02-08 15:55:41 +000081static const char* kFn_stretching = "stretching";
82static const char* kFn_version = "version";
Paul Crowley1ef25582016-01-21 20:26:12 +000083
Paul Crowley13ffd8e2016-01-27 14:30:22 +000084static bool checkSize(const std::string& kind, size_t actual, size_t expected) {
Paul Crowley1ef25582016-01-21 20:26:12 +000085 if (actual != expected) {
Paul Crowleydf528a72016-03-09 09:31:37 -080086 LOG(ERROR) << "Wrong number of bytes in " << kind << ", expected " << expected << " got "
87 << actual;
Paul Crowley1ef25582016-01-21 20:26:12 +000088 return false;
89 }
90 return true;
91}
92
Paul Crowley26a53882017-10-26 11:16:39 -070093static void hashWithPrefix(char const* prefix, const std::string& tohash, std::string* res) {
Paul Crowley1ef25582016-01-21 20:26:12 +000094 SHA512_CTX c;
95
96 SHA512_Init(&c);
97 // Personalise the hashing by introducing a fixed prefix.
98 // Hashing applications should use personalization except when there is a
99 // specific reason not to; see section 4.11 of https://www.schneier.com/skein1.3.pdf
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800100 std::string hashingPrefix = prefix;
101 hashingPrefix.resize(SHA512_CBLOCK);
102 SHA512_Update(&c, hashingPrefix.data(), hashingPrefix.size());
103 SHA512_Update(&c, tohash.data(), tohash.size());
Paul Crowley26a53882017-10-26 11:16:39 -0700104 res->assign(SHA512_DIGEST_LENGTH, '\0');
105 SHA512_Final(reinterpret_cast<uint8_t*>(&(*res)[0]), &c);
Paul Crowley1ef25582016-01-21 20:26:12 +0000106}
107
Paul Crowleydf528a72016-03-09 09:31:37 -0800108static bool generateKeymasterKey(Keymaster& keymaster, const KeyAuthentication& auth,
109 const std::string& appId, std::string* key) {
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100110 auto paramBuilder = AuthorizationSetBuilder()
Paul Crowleydf528a72016-03-09 09:31:37 -0800111 .AesEncryptionKey(AES_KEY_BYTES * 8)
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100112 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
113 .Authorization(TAG_MIN_MAC_LENGTH, GCM_MAC_BYTES * 8)
114 .Authorization(TAG_PADDING, PaddingMode::NONE)
115 .Authorization(TAG_APPLICATION_ID, blob2hidlVec(appId));
Paul Crowley320e5e12016-03-04 14:07:05 -0800116 if (auth.token.empty()) {
117 LOG(DEBUG) << "Creating key that doesn't need auth token";
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100118 paramBuilder.Authorization(TAG_NO_AUTH_REQUIRED);
Paul Crowley320e5e12016-03-04 14:07:05 -0800119 } else {
120 LOG(DEBUG) << "Auth token required for key";
121 if (auth.token.size() != sizeof(hw_auth_token_t)) {
122 LOG(ERROR) << "Auth token should be " << sizeof(hw_auth_token_t) << " bytes, was "
Paul Crowleydf528a72016-03-09 09:31:37 -0800123 << auth.token.size() << " bytes";
Paul Crowley320e5e12016-03-04 14:07:05 -0800124 return false;
125 }
Paul Crowleydf528a72016-03-09 09:31:37 -0800126 const hw_auth_token_t* at = reinterpret_cast<const hw_auth_token_t*>(auth.token.data());
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100127 paramBuilder.Authorization(TAG_USER_SECURE_ID, at->user_id);
128 paramBuilder.Authorization(TAG_USER_AUTH_TYPE, HardwareAuthenticatorType::PASSWORD);
129 paramBuilder.Authorization(TAG_AUTH_TIMEOUT, AUTH_TIMEOUT);
Paul Crowley320e5e12016-03-04 14:07:05 -0800130 }
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100131 return keymaster.generateKey(paramBuilder, key);
Paul Crowley320e5e12016-03-04 14:07:05 -0800132}
133
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100134static AuthorizationSet beginParams(const KeyAuthentication& auth,
Paul Crowleydff8c722016-05-16 08:14:56 -0700135 const std::string& appId) {
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100136 auto paramBuilder = AuthorizationSetBuilder()
137 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
138 .Authorization(TAG_MAC_LENGTH, GCM_MAC_BYTES * 8)
139 .Authorization(TAG_PADDING, PaddingMode::NONE)
140 .Authorization(TAG_APPLICATION_ID, blob2hidlVec(appId));
Paul Crowley320e5e12016-03-04 14:07:05 -0800141 if (!auth.token.empty()) {
142 LOG(DEBUG) << "Supplying auth token to Keymaster";
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100143 paramBuilder.Authorization(TAG_AUTH_TOKEN, blob2hidlVec(auth.token));
Paul Crowley320e5e12016-03-04 14:07:05 -0800144 }
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100145 return paramBuilder;
Paul Crowley1ef25582016-01-21 20:26:12 +0000146}
147
Paul Crowleydf528a72016-03-09 09:31:37 -0800148static bool readFileToString(const std::string& filename, std::string* result) {
Paul Crowleya051eb72016-03-08 16:08:32 -0800149 if (!android::base::ReadFileToString(filename, result)) {
Paul Crowleydf528a72016-03-09 09:31:37 -0800150 PLOG(ERROR) << "Failed to read from " << filename;
151 return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000152 }
153 return true;
154}
155
Paul Crowleydf528a72016-03-09 09:31:37 -0800156static bool writeStringToFile(const std::string& payload, const std::string& filename) {
Wei Wang701d05d2017-11-07 09:44:16 -0800157 android::base::unique_fd fd(TEMP_FAILURE_RETRY(
158 open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
159 if (fd == -1) {
160 PLOG(ERROR) << "Failed to open " << filename;
Paul Crowleydf528a72016-03-09 09:31:37 -0800161 return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000162 }
Wei Wang701d05d2017-11-07 09:44:16 -0800163 if (!android::base::WriteStringToFd(payload, fd)) {
164 PLOG(ERROR) << "Failed to write to " << filename;
165 unlink(filename.c_str());
166 return false;
167 }
168 // fsync as close won't guarantee flush data
169 // see close(2), fsync(2) and b/68901441
170 if (fsync(fd) == -1) {
171 if (errno == EROFS || errno == EINVAL) {
172 PLOG(WARNING) << "Skip fsync " << filename
173 << " on a file system does not support synchronization";
174 } else {
175 PLOG(ERROR) << "Failed to fsync " << filename;
176 unlink(filename.c_str());
177 return false;
178 }
179 }
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000180 return true;
181}
182
Paul Crowley26a53882017-10-26 11:16:39 -0700183static bool readRandomBytesOrLog(size_t count, std::string* out) {
184 auto status = ReadRandomBytes(count, *out);
185 if (status != OK) {
186 LOG(ERROR) << "Random read failed with status: " << status;
187 return false;
188 }
189 return true;
190}
191
192bool createSecdiscardable(const std::string& filename, std::string* hash) {
193 std::string secdiscardable;
194 if (!readRandomBytesOrLog(SECDISCARDABLE_BYTES, &secdiscardable)) return false;
195 if (!writeStringToFile(secdiscardable, filename)) return false;
196 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
197 return true;
198}
199
200bool readSecdiscardable(const std::string& filename, std::string* hash) {
201 std::string secdiscardable;
202 if (!readFileToString(filename, &secdiscardable)) return false;
203 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
204 return true;
205}
206
Paul Crowleydff8c722016-05-16 08:14:56 -0700207static KeymasterOperation begin(Keymaster& keymaster, const std::string& dir,
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100208 KeyPurpose purpose,
209 const AuthorizationSet &keyParams,
210 const AuthorizationSet &opParams,
211 AuthorizationSet* outParams) {
Paul Crowleydff8c722016-05-16 08:14:56 -0700212 auto kmKeyPath = dir + "/" + kFn_keymaster_key_blob;
213 std::string kmKey;
214 if (!readFileToString(kmKeyPath, &kmKey)) return KeymasterOperation();
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100215 AuthorizationSet inParams(keyParams);
216 inParams.append(opParams.begin(), opParams.end());
Paul Crowleydff8c722016-05-16 08:14:56 -0700217 for (;;) {
218 auto opHandle = keymaster.begin(purpose, kmKey, inParams, outParams);
219 if (opHandle) {
220 return opHandle;
221 }
Wei Wang4375f1b2017-02-24 17:43:01 -0800222 if (opHandle.errorCode() != ErrorCode::KEY_REQUIRES_UPGRADE) return opHandle;
Paul Crowleydff8c722016-05-16 08:14:56 -0700223 LOG(DEBUG) << "Upgrading key: " << dir;
224 std::string newKey;
225 if (!keymaster.upgradeKey(kmKey, keyParams, &newKey)) return KeymasterOperation();
226 auto newKeyPath = dir + "/" + kFn_keymaster_key_blob_upgraded;
227 if (!writeStringToFile(newKey, newKeyPath)) return KeymasterOperation();
228 if (rename(newKeyPath.c_str(), kmKeyPath.c_str()) != 0) {
229 PLOG(ERROR) << "Unable to move upgraded key to location: " << kmKeyPath;
230 return KeymasterOperation();
231 }
232 if (!keymaster.deleteKey(kmKey)) {
233 LOG(ERROR) << "Key deletion failed during upgrade, continuing anyway: " << dir;
234 }
235 kmKey = newKey;
236 LOG(INFO) << "Key upgraded: " << dir;
237 }
238}
239
240static bool encryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100241 const AuthorizationSet &keyParams,
Pavel Grafove2e2d302017-08-01 17:15:53 +0100242 const KeyBuffer& message, std::string* ciphertext) {
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100243 AuthorizationSet opParams;
244 AuthorizationSet outParams;
245 auto opHandle = begin(keymaster, dir, KeyPurpose::ENCRYPT, keyParams, opParams, &outParams);
Paul Crowleydff8c722016-05-16 08:14:56 -0700246 if (!opHandle) return false;
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100247 auto nonceBlob = outParams.GetTagValue(TAG_NONCE);
248 if (!nonceBlob.isOk()) {
Paul Crowleydff8c722016-05-16 08:14:56 -0700249 LOG(ERROR) << "GCM encryption but no nonce generated";
250 return false;
251 }
252 // nonceBlob here is just a pointer into existing data, must not be freed
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100253 std::string nonce(reinterpret_cast<const char*>(&nonceBlob.value()[0]), nonceBlob.value().size());
Paul Crowleydff8c722016-05-16 08:14:56 -0700254 if (!checkSize("nonce", nonce.size(), GCM_NONCE_BYTES)) return false;
255 std::string body;
256 if (!opHandle.updateCompletely(message, &body)) return false;
257
258 std::string mac;
259 if (!opHandle.finish(&mac)) return false;
260 if (!checkSize("mac", mac.size(), GCM_MAC_BYTES)) return false;
261 *ciphertext = nonce + body + mac;
262 return true;
263}
264
265static bool decryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100266 const AuthorizationSet &keyParams,
Pavel Grafove2e2d302017-08-01 17:15:53 +0100267 const std::string& ciphertext, KeyBuffer* message) {
Paul Crowleydff8c722016-05-16 08:14:56 -0700268 auto nonce = ciphertext.substr(0, GCM_NONCE_BYTES);
269 auto bodyAndMac = ciphertext.substr(GCM_NONCE_BYTES);
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100270 auto opParams = AuthorizationSetBuilder()
271 .Authorization(TAG_NONCE, blob2hidlVec(nonce));
272 auto opHandle = begin(keymaster, dir, KeyPurpose::DECRYPT, keyParams, opParams, nullptr);
Paul Crowleydff8c722016-05-16 08:14:56 -0700273 if (!opHandle) return false;
274 if (!opHandle.updateCompletely(bodyAndMac, message)) return false;
275 if (!opHandle.finish(nullptr)) return false;
276 return true;
277}
278
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800279static std::string getStretching(const KeyAuthentication& auth) {
280 if (!auth.usesKeymaster()) {
281 return kStretch_none;
282 } else if (auth.secret.empty()) {
283 return kStretch_nopassword;
284 } else {
285 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000286
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800287 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
288 return std::string() + kStretchPrefix_scrypt + paramstr;
289 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000290}
291
Paul Crowleydf528a72016-03-09 09:31:37 -0800292static bool stretchingNeedsSalt(const std::string& stretching) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000293 return stretching != kStretch_nopassword && stretching != kStretch_none;
294}
295
Paul Crowleydf528a72016-03-09 09:31:37 -0800296static bool stretchSecret(const std::string& stretching, const std::string& secret,
297 const std::string& salt, std::string* stretched) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000298 if (stretching == kStretch_nopassword) {
299 if (!secret.empty()) {
Paul Crowleyd9b92952016-03-04 13:45:00 -0800300 LOG(WARNING) << "Password present but stretching is nopassword";
Paul Crowley63c18d32016-02-10 14:02:47 +0000301 // Continue anyway
302 }
Paul Crowleya051eb72016-03-08 16:08:32 -0800303 stretched->clear();
Paul Crowley63c18d32016-02-10 14:02:47 +0000304 } else if (stretching == kStretch_none) {
Paul Crowleya051eb72016-03-08 16:08:32 -0800305 *stretched = secret;
Paul Crowleydf528a72016-03-09 09:31:37 -0800306 } else if (std::equal(kStretchPrefix_scrypt.begin(), kStretchPrefix_scrypt.end(),
307 stretching.begin())) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000308 int Nf, rf, pf;
Paul Crowleydf528a72016-03-09 09:31:37 -0800309 if (!parse_scrypt_parameters(stretching.substr(kStretchPrefix_scrypt.size()).c_str(), &Nf,
310 &rf, &pf)) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000311 LOG(ERROR) << "Unable to parse scrypt params in stretching: " << stretching;
312 return false;
313 }
Paul Crowleya051eb72016-03-08 16:08:32 -0800314 stretched->assign(STRETCHED_BYTES, '\0');
Paul Crowleydf528a72016-03-09 09:31:37 -0800315 if (crypto_scrypt(reinterpret_cast<const uint8_t*>(secret.data()), secret.size(),
316 reinterpret_cast<const uint8_t*>(salt.data()), salt.size(),
317 1 << Nf, 1 << rf, 1 << pf,
318 reinterpret_cast<uint8_t*>(&(*stretched)[0]), stretched->size()) != 0) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000319 LOG(ERROR) << "scrypt failed with params: " << stretching;
320 return false;
321 }
322 } else {
323 LOG(ERROR) << "Unknown stretching type: " << stretching;
324 return false;
325 }
326 return true;
327}
328
Paul Crowleydf528a72016-03-09 09:31:37 -0800329static bool generateAppId(const KeyAuthentication& auth, const std::string& stretching,
Paul Crowley26a53882017-10-26 11:16:39 -0700330 const std::string& salt, const std::string& secdiscardable_hash,
Paul Crowleydf528a72016-03-09 09:31:37 -0800331 std::string* appId) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000332 std::string stretched;
Paul Crowleya051eb72016-03-08 16:08:32 -0800333 if (!stretchSecret(stretching, auth.secret, salt, &stretched)) return false;
Paul Crowley26a53882017-10-26 11:16:39 -0700334 *appId = secdiscardable_hash + stretched;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800335 return true;
336}
337
338static void logOpensslError() {
339 LOG(ERROR) << "Openssl error: " << ERR_get_error();
340}
341
342static bool encryptWithoutKeymaster(const std::string& preKey,
Pavel Grafove2e2d302017-08-01 17:15:53 +0100343 const KeyBuffer& plaintext, std::string* ciphertext) {
Paul Crowley26a53882017-10-26 11:16:39 -0700344 std::string key;
345 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800346 key.resize(AES_KEY_BYTES);
347 if (!readRandomBytesOrLog(GCM_NONCE_BYTES, ciphertext)) return false;
348 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
349 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
350 if (!ctx) {
351 logOpensslError();
352 return false;
353 }
354 if (1 != EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
355 reinterpret_cast<const uint8_t*>(key.data()),
356 reinterpret_cast<const uint8_t*>(ciphertext->data()))) {
357 logOpensslError();
358 return false;
359 }
360 ciphertext->resize(GCM_NONCE_BYTES + plaintext.size() + GCM_MAC_BYTES);
361 int outlen;
362 if (1 != EVP_EncryptUpdate(ctx.get(),
363 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES), &outlen,
364 reinterpret_cast<const uint8_t*>(plaintext.data()), plaintext.size())) {
365 logOpensslError();
366 return false;
367 }
368 if (outlen != static_cast<int>(plaintext.size())) {
369 LOG(ERROR) << "GCM ciphertext length should be " << plaintext.size() << " was " << outlen;
370 return false;
371 }
372 if (1 != EVP_EncryptFinal_ex(ctx.get(),
373 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES + plaintext.size()), &outlen)) {
374 logOpensslError();
375 return false;
376 }
377 if (outlen != 0) {
378 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
379 return false;
380 }
381 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, GCM_MAC_BYTES,
382 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES + plaintext.size()))) {
383 logOpensslError();
384 return false;
385 }
386 return true;
387}
388
389static bool decryptWithoutKeymaster(const std::string& preKey,
Pavel Grafove2e2d302017-08-01 17:15:53 +0100390 const std::string& ciphertext, KeyBuffer* plaintext) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800391 if (ciphertext.size() < GCM_NONCE_BYTES + GCM_MAC_BYTES) {
392 LOG(ERROR) << "GCM ciphertext too small: " << ciphertext.size();
393 return false;
394 }
Paul Crowley26a53882017-10-26 11:16:39 -0700395 std::string key;
396 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800397 key.resize(AES_KEY_BYTES);
398 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
399 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
400 if (!ctx) {
401 logOpensslError();
402 return false;
403 }
404 if (1 != EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
405 reinterpret_cast<const uint8_t*>(key.data()),
406 reinterpret_cast<const uint8_t*>(ciphertext.data()))) {
407 logOpensslError();
408 return false;
409 }
Pavel Grafove2e2d302017-08-01 17:15:53 +0100410 *plaintext = KeyBuffer(ciphertext.size() - GCM_NONCE_BYTES - GCM_MAC_BYTES);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800411 int outlen;
412 if (1 != EVP_DecryptUpdate(ctx.get(),
413 reinterpret_cast<uint8_t*>(&(*plaintext)[0]), &outlen,
414 reinterpret_cast<const uint8_t*>(ciphertext.data() + GCM_NONCE_BYTES), plaintext->size())) {
415 logOpensslError();
416 return false;
417 }
418 if (outlen != static_cast<int>(plaintext->size())) {
419 LOG(ERROR) << "GCM plaintext length should be " << plaintext->size() << " was " << outlen;
420 return false;
421 }
422 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, GCM_MAC_BYTES,
423 const_cast<void *>(
424 reinterpret_cast<const void*>(ciphertext.data() + GCM_NONCE_BYTES + plaintext->size())))) {
425 logOpensslError();
426 return false;
427 }
428 if (1 != EVP_DecryptFinal_ex(ctx.get(),
429 reinterpret_cast<uint8_t*>(&(*plaintext)[0] + plaintext->size()), &outlen)) {
430 logOpensslError();
431 return false;
432 }
433 if (outlen != 0) {
434 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
435 return false;
436 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000437 return true;
Paul Crowley05720802016-02-08 15:55:41 +0000438}
439
Paul Crowleyf71ace32016-06-02 11:01:19 -0700440bool pathExists(const std::string& path) {
441 return access(path.c_str(), F_OK) == 0;
442}
443
Pavel Grafove2e2d302017-08-01 17:15:53 +0100444bool storeKey(const std::string& dir, const KeyAuthentication& auth, const KeyBuffer& key) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000445 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), 0700)) == -1) {
446 PLOG(ERROR) << "key mkdir " << dir;
447 return false;
448 }
Paul Crowleydf528a72016-03-09 09:31:37 -0800449 if (!writeStringToFile(kCurrentVersion, dir + "/" + kFn_version)) return false;
Paul Crowley26a53882017-10-26 11:16:39 -0700450 std::string secdiscardable_hash;
451 if (!createSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800452 std::string stretching = getStretching(auth);
Paul Crowleydf528a72016-03-09 09:31:37 -0800453 if (!writeStringToFile(stretching, dir + "/" + kFn_stretching)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000454 std::string salt;
455 if (stretchingNeedsSalt(stretching)) {
456 if (ReadRandomBytes(SALT_BYTES, salt) != OK) {
457 LOG(ERROR) << "Random read failed";
458 return false;
459 }
Paul Crowleydf528a72016-03-09 09:31:37 -0800460 if (!writeStringToFile(salt, dir + "/" + kFn_salt)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000461 }
Paul Crowley320e5e12016-03-04 14:07:05 -0800462 std::string appId;
Paul Crowley26a53882017-10-26 11:16:39 -0700463 if (!generateAppId(auth, stretching, salt, secdiscardable_hash, &appId)) return false;
Paul Crowley320e5e12016-03-04 14:07:05 -0800464 std::string encryptedKey;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800465 if (auth.usesKeymaster()) {
466 Keymaster keymaster;
467 if (!keymaster) return false;
468 std::string kmKey;
469 if (!generateKeymasterKey(keymaster, auth, appId, &kmKey)) return false;
470 if (!writeStringToFile(kmKey, dir + "/" + kFn_keymaster_key_blob)) return false;
471 auto keyParams = beginParams(auth, appId);
472 if (!encryptWithKeymasterKey(keymaster, dir, keyParams, key, &encryptedKey)) return false;
473 } else {
474 if (!encryptWithoutKeymaster(appId, key, &encryptedKey)) return false;
475 }
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000476 if (!writeStringToFile(encryptedKey, dir + "/" + kFn_encrypted_key)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000477 return true;
478}
479
Paul Crowleyf71ace32016-06-02 11:01:19 -0700480bool storeKeyAtomically(const std::string& key_path, const std::string& tmp_path,
Pavel Grafove2e2d302017-08-01 17:15:53 +0100481 const KeyAuthentication& auth, const KeyBuffer& key) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700482 if (pathExists(key_path)) {
483 LOG(ERROR) << "Already exists, cannot create key at: " << key_path;
484 return false;
485 }
486 if (pathExists(tmp_path)) {
487 LOG(DEBUG) << "Already exists, destroying: " << tmp_path;
488 destroyKey(tmp_path); // May be partially created so ignore errors
489 }
490 if (!storeKey(tmp_path, auth, key)) return false;
491 if (rename(tmp_path.c_str(), key_path.c_str()) != 0) {
492 PLOG(ERROR) << "Unable to move new key to location: " << key_path;
493 return false;
494 }
495 LOG(DEBUG) << "Created key: " << key_path;
496 return true;
497}
498
Pavel Grafove2e2d302017-08-01 17:15:53 +0100499bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, KeyBuffer* key) {
Paul Crowley05720802016-02-08 15:55:41 +0000500 std::string version;
Paul Crowleya051eb72016-03-08 16:08:32 -0800501 if (!readFileToString(dir + "/" + kFn_version, &version)) return false;
Paul Crowley05720802016-02-08 15:55:41 +0000502 if (version != kCurrentVersion) {
503 LOG(ERROR) << "Version mismatch, expected " << kCurrentVersion << " got " << version;
504 return false;
505 }
Paul Crowley26a53882017-10-26 11:16:39 -0700506 std::string secdiscardable_hash;
507 if (!readSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000508 std::string stretching;
Paul Crowleya051eb72016-03-08 16:08:32 -0800509 if (!readFileToString(dir + "/" + kFn_stretching, &stretching)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000510 std::string salt;
511 if (stretchingNeedsSalt(stretching)) {
Paul Crowleydf528a72016-03-09 09:31:37 -0800512 if (!readFileToString(dir + "/" + kFn_salt, &salt)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000513 }
Paul Crowley320e5e12016-03-04 14:07:05 -0800514 std::string appId;
Paul Crowley26a53882017-10-26 11:16:39 -0700515 if (!generateAppId(auth, stretching, salt, secdiscardable_hash, &appId)) return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000516 std::string encryptedMessage;
Paul Crowleya051eb72016-03-08 16:08:32 -0800517 if (!readFileToString(dir + "/" + kFn_encrypted_key, &encryptedMessage)) return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800518 if (auth.usesKeymaster()) {
519 Keymaster keymaster;
520 if (!keymaster) return false;
521 auto keyParams = beginParams(auth, appId);
522 if (!decryptWithKeymasterKey(keymaster, dir, keyParams, encryptedMessage, key)) return false;
523 } else {
524 if (!decryptWithoutKeymaster(appId, encryptedMessage, key)) return false;
525 }
526 return true;
Paul Crowley1ef25582016-01-21 20:26:12 +0000527}
528
Paul Crowleydf528a72016-03-09 09:31:37 -0800529static bool deleteKey(const std::string& dir) {
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000530 std::string kmKey;
Paul Crowleya051eb72016-03-08 16:08:32 -0800531 if (!readFileToString(dir + "/" + kFn_keymaster_key_blob, &kmKey)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000532 Keymaster keymaster;
533 if (!keymaster) return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000534 if (!keymaster.deleteKey(kmKey)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000535 return true;
536}
537
Rubin Xu2436e272017-04-27 20:43:10 +0100538bool runSecdiscardSingle(const std::string& file) {
539 if (ForkExecvp(
540 std::vector<std::string>{kSecdiscardPath, "--",
541 file}) != 0) {
542 LOG(ERROR) << "secdiscard failed";
543 return false;
544 }
545 return true;
546}
547
Paul Crowleydf528a72016-03-09 09:31:37 -0800548static bool recursiveDeleteKey(const std::string& dir) {
549 if (ForkExecvp(std::vector<std::string>{kRmPath, "-rf", dir}) != 0) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000550 LOG(ERROR) << "recursive delete failed";
551 return false;
552 }
553 return true;
554}
555
Paul Crowleydf528a72016-03-09 09:31:37 -0800556bool destroyKey(const std::string& dir) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000557 bool success = true;
558 // Try each thing, even if previous things failed.
Paul Crowleyff19b052017-10-26 11:28:55 -0700559 bool uses_km = pathExists(dir + "/" + kFn_keymaster_key_blob);
560 if (uses_km) {
561 success &= deleteKey(dir);
562 }
563 auto secdiscard_cmd = std::vector<std::string>{
564 kSecdiscardPath, "--", dir + "/" + kFn_encrypted_key, dir + "/" + kFn_secdiscardable,
565 };
566 if (uses_km) {
567 secdiscard_cmd.emplace_back(dir + "/" + kFn_keymaster_key_blob);
568 }
569 if (ForkExecvp(secdiscard_cmd) != 0) {
570 LOG(ERROR) << "secdiscard failed";
571 success = false;
572 }
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000573 success &= recursiveDeleteKey(dir);
Paul Crowley1ef25582016-01-21 20:26:12 +0000574 return success;
575}
576
577} // namespace vold
578} // namespace android