blob: 8878a3c0c1e6822f5bd18320031ce33add9e5265 [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>
38
Paul Crowley63c18d32016-02-10 14:02:47 +000039#include <cutils/properties.h>
40
Paul Crowley320e5e12016-03-04 14:07:05 -080041#include <hardware/hw_auth_token.h>
42
Janis Danisevskis8e537b82016-10-26 14:27:10 +010043#include <keystore/authorization_set.h>
44#include <keystore/keystore_hidl_support.h>
Paul Crowley1ef25582016-01-21 20:26:12 +000045
Paul Crowley63c18d32016-02-10 14:02:47 +000046extern "C" {
47
48#include "crypto_scrypt.h"
Paul Crowley63c18d32016-02-10 14:02:47 +000049}
50
Paul Crowley1ef25582016-01-21 20:26:12 +000051namespace android {
52namespace vold {
Janis Danisevskis8e537b82016-10-26 14:27:10 +010053using namespace keystore;
Paul Crowley1ef25582016-01-21 20:26:12 +000054
Paul Crowleydf528a72016-03-09 09:31:37 -080055const KeyAuthentication kEmptyAuthentication{"", ""};
Paul Crowley05720802016-02-08 15:55:41 +000056
Paul Crowley1ef25582016-01-21 20:26:12 +000057static constexpr size_t AES_KEY_BYTES = 32;
58static constexpr size_t GCM_NONCE_BYTES = 12;
59static constexpr size_t GCM_MAC_BYTES = 16;
Paul Crowleydf528a72016-03-09 09:31:37 -080060static constexpr size_t SALT_BYTES = 1 << 4;
61static constexpr size_t SECDISCARDABLE_BYTES = 1 << 14;
62static constexpr size_t STRETCHED_BYTES = 1 << 6;
Paul Crowley1ef25582016-01-21 20:26:12 +000063
Paul Crowleyb3de3372016-04-27 12:58:41 -070064static constexpr uint32_t AUTH_TIMEOUT = 30; // Seconds
65
Paul Crowley05720802016-02-08 15:55:41 +000066static const char* kCurrentVersion = "1";
Paul Crowley1ef25582016-01-21 20:26:12 +000067static const char* kRmPath = "/system/bin/rm";
68static const char* kSecdiscardPath = "/system/bin/secdiscard";
Paul Crowley63c18d32016-02-10 14:02:47 +000069static const char* kStretch_none = "none";
70static const char* kStretch_nopassword = "nopassword";
71static const std::string kStretchPrefix_scrypt = "scrypt ";
Paul Crowley6ab2cab2017-01-04 22:32:40 -080072static const char* kHashPrefix_secdiscardable = "Android secdiscardable SHA512";
73static const char* kHashPrefix_keygen = "Android key wrapping key generation SHA512";
Paul Crowley1ef25582016-01-21 20:26:12 +000074static const char* kFn_encrypted_key = "encrypted_key";
Paul Crowley05720802016-02-08 15:55:41 +000075static const char* kFn_keymaster_key_blob = "keymaster_key_blob";
Paul Crowleydff8c722016-05-16 08:14:56 -070076static const char* kFn_keymaster_key_blob_upgraded = "keymaster_key_blob_upgraded";
Paul Crowley63c18d32016-02-10 14:02:47 +000077static const char* kFn_salt = "salt";
Paul Crowley1ef25582016-01-21 20:26:12 +000078static const char* kFn_secdiscardable = "secdiscardable";
Paul Crowley05720802016-02-08 15:55:41 +000079static const char* kFn_stretching = "stretching";
80static const char* kFn_version = "version";
Paul Crowley1ef25582016-01-21 20:26:12 +000081
Paul Crowley13ffd8e2016-01-27 14:30:22 +000082static bool checkSize(const std::string& kind, size_t actual, size_t expected) {
Paul Crowley1ef25582016-01-21 20:26:12 +000083 if (actual != expected) {
Paul Crowleydf528a72016-03-09 09:31:37 -080084 LOG(ERROR) << "Wrong number of bytes in " << kind << ", expected " << expected << " got "
85 << actual;
Paul Crowley1ef25582016-01-21 20:26:12 +000086 return false;
87 }
88 return true;
89}
90
Paul Crowley26a53882017-10-26 11:16:39 -070091static void hashWithPrefix(char const* prefix, const std::string& tohash, std::string* res) {
Paul Crowley1ef25582016-01-21 20:26:12 +000092 SHA512_CTX c;
93
94 SHA512_Init(&c);
95 // Personalise the hashing by introducing a fixed prefix.
96 // Hashing applications should use personalization except when there is a
97 // specific reason not to; see section 4.11 of https://www.schneier.com/skein1.3.pdf
Paul Crowley6ab2cab2017-01-04 22:32:40 -080098 std::string hashingPrefix = prefix;
99 hashingPrefix.resize(SHA512_CBLOCK);
100 SHA512_Update(&c, hashingPrefix.data(), hashingPrefix.size());
101 SHA512_Update(&c, tohash.data(), tohash.size());
Paul Crowley26a53882017-10-26 11:16:39 -0700102 res->assign(SHA512_DIGEST_LENGTH, '\0');
103 SHA512_Final(reinterpret_cast<uint8_t*>(&(*res)[0]), &c);
Paul Crowley1ef25582016-01-21 20:26:12 +0000104}
105
Paul Crowleydf528a72016-03-09 09:31:37 -0800106static bool generateKeymasterKey(Keymaster& keymaster, const KeyAuthentication& auth,
107 const std::string& appId, std::string* key) {
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100108 auto paramBuilder = AuthorizationSetBuilder()
Paul Crowleydf528a72016-03-09 09:31:37 -0800109 .AesEncryptionKey(AES_KEY_BYTES * 8)
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100110 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
111 .Authorization(TAG_MIN_MAC_LENGTH, GCM_MAC_BYTES * 8)
112 .Authorization(TAG_PADDING, PaddingMode::NONE)
113 .Authorization(TAG_APPLICATION_ID, blob2hidlVec(appId));
Paul Crowley320e5e12016-03-04 14:07:05 -0800114 if (auth.token.empty()) {
115 LOG(DEBUG) << "Creating key that doesn't need auth token";
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100116 paramBuilder.Authorization(TAG_NO_AUTH_REQUIRED);
Paul Crowley320e5e12016-03-04 14:07:05 -0800117 } else {
118 LOG(DEBUG) << "Auth token required for key";
119 if (auth.token.size() != sizeof(hw_auth_token_t)) {
120 LOG(ERROR) << "Auth token should be " << sizeof(hw_auth_token_t) << " bytes, was "
Paul Crowleydf528a72016-03-09 09:31:37 -0800121 << auth.token.size() << " bytes";
Paul Crowley320e5e12016-03-04 14:07:05 -0800122 return false;
123 }
Paul Crowleydf528a72016-03-09 09:31:37 -0800124 const hw_auth_token_t* at = reinterpret_cast<const hw_auth_token_t*>(auth.token.data());
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100125 paramBuilder.Authorization(TAG_USER_SECURE_ID, at->user_id);
126 paramBuilder.Authorization(TAG_USER_AUTH_TYPE, HardwareAuthenticatorType::PASSWORD);
127 paramBuilder.Authorization(TAG_AUTH_TIMEOUT, AUTH_TIMEOUT);
Paul Crowley320e5e12016-03-04 14:07:05 -0800128 }
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100129 return keymaster.generateKey(paramBuilder, key);
Paul Crowley320e5e12016-03-04 14:07:05 -0800130}
131
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100132static AuthorizationSet beginParams(const KeyAuthentication& auth,
Paul Crowleydff8c722016-05-16 08:14:56 -0700133 const std::string& appId) {
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100134 auto paramBuilder = AuthorizationSetBuilder()
135 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
136 .Authorization(TAG_MAC_LENGTH, GCM_MAC_BYTES * 8)
137 .Authorization(TAG_PADDING, PaddingMode::NONE)
138 .Authorization(TAG_APPLICATION_ID, blob2hidlVec(appId));
Paul Crowley320e5e12016-03-04 14:07:05 -0800139 if (!auth.token.empty()) {
140 LOG(DEBUG) << "Supplying auth token to Keymaster";
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100141 paramBuilder.Authorization(TAG_AUTH_TOKEN, blob2hidlVec(auth.token));
Paul Crowley320e5e12016-03-04 14:07:05 -0800142 }
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100143 return paramBuilder;
Paul Crowley1ef25582016-01-21 20:26:12 +0000144}
145
Paul Crowleydf528a72016-03-09 09:31:37 -0800146static bool readFileToString(const std::string& filename, std::string* result) {
Paul Crowleya051eb72016-03-08 16:08:32 -0800147 if (!android::base::ReadFileToString(filename, result)) {
Paul Crowleydf528a72016-03-09 09:31:37 -0800148 PLOG(ERROR) << "Failed to read from " << filename;
149 return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000150 }
151 return true;
152}
153
Paul Crowleydf528a72016-03-09 09:31:37 -0800154static bool writeStringToFile(const std::string& payload, const std::string& filename) {
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000155 if (!android::base::WriteStringToFile(payload, filename)) {
Paul Crowleydf528a72016-03-09 09:31:37 -0800156 PLOG(ERROR) << "Failed to write to " << filename;
157 return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000158 }
159 return true;
160}
161
Paul Crowley26a53882017-10-26 11:16:39 -0700162static bool readRandomBytesOrLog(size_t count, std::string* out) {
163 auto status = ReadRandomBytes(count, *out);
164 if (status != OK) {
165 LOG(ERROR) << "Random read failed with status: " << status;
166 return false;
167 }
168 return true;
169}
170
171bool createSecdiscardable(const std::string& filename, std::string* hash) {
172 std::string secdiscardable;
173 if (!readRandomBytesOrLog(SECDISCARDABLE_BYTES, &secdiscardable)) return false;
174 if (!writeStringToFile(secdiscardable, filename)) return false;
175 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
176 return true;
177}
178
179bool readSecdiscardable(const std::string& filename, std::string* hash) {
180 std::string secdiscardable;
181 if (!readFileToString(filename, &secdiscardable)) return false;
182 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
183 return true;
184}
185
Paul Crowleydff8c722016-05-16 08:14:56 -0700186static KeymasterOperation begin(Keymaster& keymaster, const std::string& dir,
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100187 KeyPurpose purpose,
188 const AuthorizationSet &keyParams,
189 const AuthorizationSet &opParams,
190 AuthorizationSet* outParams) {
Paul Crowleydff8c722016-05-16 08:14:56 -0700191 auto kmKeyPath = dir + "/" + kFn_keymaster_key_blob;
192 std::string kmKey;
193 if (!readFileToString(kmKeyPath, &kmKey)) return KeymasterOperation();
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100194 AuthorizationSet inParams(keyParams);
195 inParams.append(opParams.begin(), opParams.end());
Paul Crowleydff8c722016-05-16 08:14:56 -0700196 for (;;) {
197 auto opHandle = keymaster.begin(purpose, kmKey, inParams, outParams);
198 if (opHandle) {
199 return opHandle;
200 }
Wei Wang4375f1b2017-02-24 17:43:01 -0800201 if (opHandle.errorCode() != ErrorCode::KEY_REQUIRES_UPGRADE) return opHandle;
Paul Crowleydff8c722016-05-16 08:14:56 -0700202 LOG(DEBUG) << "Upgrading key: " << dir;
203 std::string newKey;
204 if (!keymaster.upgradeKey(kmKey, keyParams, &newKey)) return KeymasterOperation();
205 auto newKeyPath = dir + "/" + kFn_keymaster_key_blob_upgraded;
206 if (!writeStringToFile(newKey, newKeyPath)) return KeymasterOperation();
207 if (rename(newKeyPath.c_str(), kmKeyPath.c_str()) != 0) {
208 PLOG(ERROR) << "Unable to move upgraded key to location: " << kmKeyPath;
209 return KeymasterOperation();
210 }
211 if (!keymaster.deleteKey(kmKey)) {
212 LOG(ERROR) << "Key deletion failed during upgrade, continuing anyway: " << dir;
213 }
214 kmKey = newKey;
215 LOG(INFO) << "Key upgraded: " << dir;
216 }
217}
218
219static bool encryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100220 const AuthorizationSet &keyParams,
Pavel Grafove2e2d302017-08-01 17:15:53 +0100221 const KeyBuffer& message, std::string* ciphertext) {
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100222 AuthorizationSet opParams;
223 AuthorizationSet outParams;
224 auto opHandle = begin(keymaster, dir, KeyPurpose::ENCRYPT, keyParams, opParams, &outParams);
Paul Crowleydff8c722016-05-16 08:14:56 -0700225 if (!opHandle) return false;
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100226 auto nonceBlob = outParams.GetTagValue(TAG_NONCE);
227 if (!nonceBlob.isOk()) {
Paul Crowleydff8c722016-05-16 08:14:56 -0700228 LOG(ERROR) << "GCM encryption but no nonce generated";
229 return false;
230 }
231 // nonceBlob here is just a pointer into existing data, must not be freed
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100232 std::string nonce(reinterpret_cast<const char*>(&nonceBlob.value()[0]), nonceBlob.value().size());
Paul Crowleydff8c722016-05-16 08:14:56 -0700233 if (!checkSize("nonce", nonce.size(), GCM_NONCE_BYTES)) return false;
234 std::string body;
235 if (!opHandle.updateCompletely(message, &body)) return false;
236
237 std::string mac;
238 if (!opHandle.finish(&mac)) return false;
239 if (!checkSize("mac", mac.size(), GCM_MAC_BYTES)) return false;
240 *ciphertext = nonce + body + mac;
241 return true;
242}
243
244static bool decryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100245 const AuthorizationSet &keyParams,
Pavel Grafove2e2d302017-08-01 17:15:53 +0100246 const std::string& ciphertext, KeyBuffer* message) {
Paul Crowleydff8c722016-05-16 08:14:56 -0700247 auto nonce = ciphertext.substr(0, GCM_NONCE_BYTES);
248 auto bodyAndMac = ciphertext.substr(GCM_NONCE_BYTES);
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100249 auto opParams = AuthorizationSetBuilder()
250 .Authorization(TAG_NONCE, blob2hidlVec(nonce));
251 auto opHandle = begin(keymaster, dir, KeyPurpose::DECRYPT, keyParams, opParams, nullptr);
Paul Crowleydff8c722016-05-16 08:14:56 -0700252 if (!opHandle) return false;
253 if (!opHandle.updateCompletely(bodyAndMac, message)) return false;
254 if (!opHandle.finish(nullptr)) return false;
255 return true;
256}
257
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800258static std::string getStretching(const KeyAuthentication& auth) {
259 if (!auth.usesKeymaster()) {
260 return kStretch_none;
261 } else if (auth.secret.empty()) {
262 return kStretch_nopassword;
263 } else {
264 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000265
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800266 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
267 return std::string() + kStretchPrefix_scrypt + paramstr;
268 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000269}
270
Paul Crowleydf528a72016-03-09 09:31:37 -0800271static bool stretchingNeedsSalt(const std::string& stretching) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000272 return stretching != kStretch_nopassword && stretching != kStretch_none;
273}
274
Paul Crowleydf528a72016-03-09 09:31:37 -0800275static bool stretchSecret(const std::string& stretching, const std::string& secret,
276 const std::string& salt, std::string* stretched) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000277 if (stretching == kStretch_nopassword) {
278 if (!secret.empty()) {
Paul Crowleyd9b92952016-03-04 13:45:00 -0800279 LOG(WARNING) << "Password present but stretching is nopassword";
Paul Crowley63c18d32016-02-10 14:02:47 +0000280 // Continue anyway
281 }
Paul Crowleya051eb72016-03-08 16:08:32 -0800282 stretched->clear();
Paul Crowley63c18d32016-02-10 14:02:47 +0000283 } else if (stretching == kStretch_none) {
Paul Crowleya051eb72016-03-08 16:08:32 -0800284 *stretched = secret;
Paul Crowleydf528a72016-03-09 09:31:37 -0800285 } else if (std::equal(kStretchPrefix_scrypt.begin(), kStretchPrefix_scrypt.end(),
286 stretching.begin())) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000287 int Nf, rf, pf;
Paul Crowleydf528a72016-03-09 09:31:37 -0800288 if (!parse_scrypt_parameters(stretching.substr(kStretchPrefix_scrypt.size()).c_str(), &Nf,
289 &rf, &pf)) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000290 LOG(ERROR) << "Unable to parse scrypt params in stretching: " << stretching;
291 return false;
292 }
Paul Crowleya051eb72016-03-08 16:08:32 -0800293 stretched->assign(STRETCHED_BYTES, '\0');
Paul Crowleydf528a72016-03-09 09:31:37 -0800294 if (crypto_scrypt(reinterpret_cast<const uint8_t*>(secret.data()), secret.size(),
295 reinterpret_cast<const uint8_t*>(salt.data()), salt.size(),
296 1 << Nf, 1 << rf, 1 << pf,
297 reinterpret_cast<uint8_t*>(&(*stretched)[0]), stretched->size()) != 0) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000298 LOG(ERROR) << "scrypt failed with params: " << stretching;
299 return false;
300 }
301 } else {
302 LOG(ERROR) << "Unknown stretching type: " << stretching;
303 return false;
304 }
305 return true;
306}
307
Paul Crowleydf528a72016-03-09 09:31:37 -0800308static bool generateAppId(const KeyAuthentication& auth, const std::string& stretching,
Paul Crowley26a53882017-10-26 11:16:39 -0700309 const std::string& salt, const std::string& secdiscardable_hash,
Paul Crowleydf528a72016-03-09 09:31:37 -0800310 std::string* appId) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000311 std::string stretched;
Paul Crowleya051eb72016-03-08 16:08:32 -0800312 if (!stretchSecret(stretching, auth.secret, salt, &stretched)) return false;
Paul Crowley26a53882017-10-26 11:16:39 -0700313 *appId = secdiscardable_hash + stretched;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800314 return true;
315}
316
317static void logOpensslError() {
318 LOG(ERROR) << "Openssl error: " << ERR_get_error();
319}
320
321static bool encryptWithoutKeymaster(const std::string& preKey,
Pavel Grafove2e2d302017-08-01 17:15:53 +0100322 const KeyBuffer& plaintext, std::string* ciphertext) {
Paul Crowley26a53882017-10-26 11:16:39 -0700323 std::string key;
324 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800325 key.resize(AES_KEY_BYTES);
326 if (!readRandomBytesOrLog(GCM_NONCE_BYTES, ciphertext)) return false;
327 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
328 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
329 if (!ctx) {
330 logOpensslError();
331 return false;
332 }
333 if (1 != EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
334 reinterpret_cast<const uint8_t*>(key.data()),
335 reinterpret_cast<const uint8_t*>(ciphertext->data()))) {
336 logOpensslError();
337 return false;
338 }
339 ciphertext->resize(GCM_NONCE_BYTES + plaintext.size() + GCM_MAC_BYTES);
340 int outlen;
341 if (1 != EVP_EncryptUpdate(ctx.get(),
342 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES), &outlen,
343 reinterpret_cast<const uint8_t*>(plaintext.data()), plaintext.size())) {
344 logOpensslError();
345 return false;
346 }
347 if (outlen != static_cast<int>(plaintext.size())) {
348 LOG(ERROR) << "GCM ciphertext length should be " << plaintext.size() << " was " << outlen;
349 return false;
350 }
351 if (1 != EVP_EncryptFinal_ex(ctx.get(),
352 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES + plaintext.size()), &outlen)) {
353 logOpensslError();
354 return false;
355 }
356 if (outlen != 0) {
357 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
358 return false;
359 }
360 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, GCM_MAC_BYTES,
361 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES + plaintext.size()))) {
362 logOpensslError();
363 return false;
364 }
365 return true;
366}
367
368static bool decryptWithoutKeymaster(const std::string& preKey,
Pavel Grafove2e2d302017-08-01 17:15:53 +0100369 const std::string& ciphertext, KeyBuffer* plaintext) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800370 if (ciphertext.size() < GCM_NONCE_BYTES + GCM_MAC_BYTES) {
371 LOG(ERROR) << "GCM ciphertext too small: " << ciphertext.size();
372 return false;
373 }
Paul Crowley26a53882017-10-26 11:16:39 -0700374 std::string key;
375 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800376 key.resize(AES_KEY_BYTES);
377 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
378 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
379 if (!ctx) {
380 logOpensslError();
381 return false;
382 }
383 if (1 != EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
384 reinterpret_cast<const uint8_t*>(key.data()),
385 reinterpret_cast<const uint8_t*>(ciphertext.data()))) {
386 logOpensslError();
387 return false;
388 }
Pavel Grafove2e2d302017-08-01 17:15:53 +0100389 *plaintext = KeyBuffer(ciphertext.size() - GCM_NONCE_BYTES - GCM_MAC_BYTES);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800390 int outlen;
391 if (1 != EVP_DecryptUpdate(ctx.get(),
392 reinterpret_cast<uint8_t*>(&(*plaintext)[0]), &outlen,
393 reinterpret_cast<const uint8_t*>(ciphertext.data() + GCM_NONCE_BYTES), plaintext->size())) {
394 logOpensslError();
395 return false;
396 }
397 if (outlen != static_cast<int>(plaintext->size())) {
398 LOG(ERROR) << "GCM plaintext length should be " << plaintext->size() << " was " << outlen;
399 return false;
400 }
401 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, GCM_MAC_BYTES,
402 const_cast<void *>(
403 reinterpret_cast<const void*>(ciphertext.data() + GCM_NONCE_BYTES + plaintext->size())))) {
404 logOpensslError();
405 return false;
406 }
407 if (1 != EVP_DecryptFinal_ex(ctx.get(),
408 reinterpret_cast<uint8_t*>(&(*plaintext)[0] + plaintext->size()), &outlen)) {
409 logOpensslError();
410 return false;
411 }
412 if (outlen != 0) {
413 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
414 return false;
415 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000416 return true;
Paul Crowley05720802016-02-08 15:55:41 +0000417}
418
Paul Crowleyf71ace32016-06-02 11:01:19 -0700419bool pathExists(const std::string& path) {
420 return access(path.c_str(), F_OK) == 0;
421}
422
Pavel Grafove2e2d302017-08-01 17:15:53 +0100423bool storeKey(const std::string& dir, const KeyAuthentication& auth, const KeyBuffer& key) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000424 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), 0700)) == -1) {
425 PLOG(ERROR) << "key mkdir " << dir;
426 return false;
427 }
Paul Crowleydf528a72016-03-09 09:31:37 -0800428 if (!writeStringToFile(kCurrentVersion, dir + "/" + kFn_version)) return false;
Paul Crowley26a53882017-10-26 11:16:39 -0700429 std::string secdiscardable_hash;
430 if (!createSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800431 std::string stretching = getStretching(auth);
Paul Crowleydf528a72016-03-09 09:31:37 -0800432 if (!writeStringToFile(stretching, dir + "/" + kFn_stretching)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000433 std::string salt;
434 if (stretchingNeedsSalt(stretching)) {
435 if (ReadRandomBytes(SALT_BYTES, salt) != OK) {
436 LOG(ERROR) << "Random read failed";
437 return false;
438 }
Paul Crowleydf528a72016-03-09 09:31:37 -0800439 if (!writeStringToFile(salt, dir + "/" + kFn_salt)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000440 }
Paul Crowley320e5e12016-03-04 14:07:05 -0800441 std::string appId;
Paul Crowley26a53882017-10-26 11:16:39 -0700442 if (!generateAppId(auth, stretching, salt, secdiscardable_hash, &appId)) return false;
Paul Crowley320e5e12016-03-04 14:07:05 -0800443 std::string encryptedKey;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800444 if (auth.usesKeymaster()) {
445 Keymaster keymaster;
446 if (!keymaster) return false;
447 std::string kmKey;
448 if (!generateKeymasterKey(keymaster, auth, appId, &kmKey)) return false;
449 if (!writeStringToFile(kmKey, dir + "/" + kFn_keymaster_key_blob)) return false;
450 auto keyParams = beginParams(auth, appId);
451 if (!encryptWithKeymasterKey(keymaster, dir, keyParams, key, &encryptedKey)) return false;
452 } else {
453 if (!encryptWithoutKeymaster(appId, key, &encryptedKey)) return false;
454 }
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000455 if (!writeStringToFile(encryptedKey, dir + "/" + kFn_encrypted_key)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000456 return true;
457}
458
Paul Crowleyf71ace32016-06-02 11:01:19 -0700459bool storeKeyAtomically(const std::string& key_path, const std::string& tmp_path,
Pavel Grafove2e2d302017-08-01 17:15:53 +0100460 const KeyAuthentication& auth, const KeyBuffer& key) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700461 if (pathExists(key_path)) {
462 LOG(ERROR) << "Already exists, cannot create key at: " << key_path;
463 return false;
464 }
465 if (pathExists(tmp_path)) {
466 LOG(DEBUG) << "Already exists, destroying: " << tmp_path;
467 destroyKey(tmp_path); // May be partially created so ignore errors
468 }
469 if (!storeKey(tmp_path, auth, key)) return false;
470 if (rename(tmp_path.c_str(), key_path.c_str()) != 0) {
471 PLOG(ERROR) << "Unable to move new key to location: " << key_path;
472 return false;
473 }
474 LOG(DEBUG) << "Created key: " << key_path;
475 return true;
476}
477
Pavel Grafove2e2d302017-08-01 17:15:53 +0100478bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, KeyBuffer* key) {
Paul Crowley05720802016-02-08 15:55:41 +0000479 std::string version;
Paul Crowleya051eb72016-03-08 16:08:32 -0800480 if (!readFileToString(dir + "/" + kFn_version, &version)) return false;
Paul Crowley05720802016-02-08 15:55:41 +0000481 if (version != kCurrentVersion) {
482 LOG(ERROR) << "Version mismatch, expected " << kCurrentVersion << " got " << version;
483 return false;
484 }
Paul Crowley26a53882017-10-26 11:16:39 -0700485 std::string secdiscardable_hash;
486 if (!readSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000487 std::string stretching;
Paul Crowleya051eb72016-03-08 16:08:32 -0800488 if (!readFileToString(dir + "/" + kFn_stretching, &stretching)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000489 std::string salt;
490 if (stretchingNeedsSalt(stretching)) {
Paul Crowleydf528a72016-03-09 09:31:37 -0800491 if (!readFileToString(dir + "/" + kFn_salt, &salt)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000492 }
Paul Crowley320e5e12016-03-04 14:07:05 -0800493 std::string appId;
Paul Crowley26a53882017-10-26 11:16:39 -0700494 if (!generateAppId(auth, stretching, salt, secdiscardable_hash, &appId)) return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000495 std::string encryptedMessage;
Paul Crowleya051eb72016-03-08 16:08:32 -0800496 if (!readFileToString(dir + "/" + kFn_encrypted_key, &encryptedMessage)) return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800497 if (auth.usesKeymaster()) {
498 Keymaster keymaster;
499 if (!keymaster) return false;
500 auto keyParams = beginParams(auth, appId);
501 if (!decryptWithKeymasterKey(keymaster, dir, keyParams, encryptedMessage, key)) return false;
502 } else {
503 if (!decryptWithoutKeymaster(appId, encryptedMessage, key)) return false;
504 }
505 return true;
Paul Crowley1ef25582016-01-21 20:26:12 +0000506}
507
Paul Crowleydf528a72016-03-09 09:31:37 -0800508static bool deleteKey(const std::string& dir) {
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000509 std::string kmKey;
Paul Crowleya051eb72016-03-08 16:08:32 -0800510 if (!readFileToString(dir + "/" + kFn_keymaster_key_blob, &kmKey)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000511 Keymaster keymaster;
512 if (!keymaster) return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000513 if (!keymaster.deleteKey(kmKey)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000514 return true;
515}
516
Rubin Xu2436e272017-04-27 20:43:10 +0100517bool runSecdiscardSingle(const std::string& file) {
518 if (ForkExecvp(
519 std::vector<std::string>{kSecdiscardPath, "--",
520 file}) != 0) {
521 LOG(ERROR) << "secdiscard failed";
522 return false;
523 }
524 return true;
525}
526
Paul Crowleydf528a72016-03-09 09:31:37 -0800527static bool recursiveDeleteKey(const std::string& dir) {
528 if (ForkExecvp(std::vector<std::string>{kRmPath, "-rf", dir}) != 0) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000529 LOG(ERROR) << "recursive delete failed";
530 return false;
531 }
532 return true;
533}
534
Paul Crowleydf528a72016-03-09 09:31:37 -0800535bool destroyKey(const std::string& dir) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000536 bool success = true;
537 // Try each thing, even if previous things failed.
Paul Crowleyff19b052017-10-26 11:28:55 -0700538 bool uses_km = pathExists(dir + "/" + kFn_keymaster_key_blob);
539 if (uses_km) {
540 success &= deleteKey(dir);
541 }
542 auto secdiscard_cmd = std::vector<std::string>{
543 kSecdiscardPath, "--", dir + "/" + kFn_encrypted_key, dir + "/" + kFn_secdiscardable,
544 };
545 if (uses_km) {
546 secdiscard_cmd.emplace_back(dir + "/" + kFn_keymaster_key_blob);
547 }
548 if (ForkExecvp(secdiscard_cmd) != 0) {
549 LOG(ERROR) << "secdiscard failed";
550 success = false;
551 }
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000552 success &= recursiveDeleteKey(dir);
Paul Crowley1ef25582016-01-21 20:26:12 +0000553 return success;
554}
555
556} // namespace vold
557} // namespace android