blob: 7e1d4a7bdfcb5e53098014d8cd4cdbe85f1a1d2c [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
Paul Crowley1ef25582016-01-21 20:26:12 +000043
Paul Crowley63c18d32016-02-10 14:02:47 +000044extern "C" {
45
46#include "crypto_scrypt.h"
Paul Crowley63c18d32016-02-10 14:02:47 +000047}
48
Shawn Willdenf4527742017-11-09 15:59:39 -070049#include "authorization_set.h"
50#include "keystore_hidl_support.h"
51
Paul Crowley1ef25582016-01-21 20:26:12 +000052namespace android {
53namespace vold {
Janis Danisevskis8e537b82016-10-26 14:27:10 +010054using namespace keystore;
Paul Crowley1ef25582016-01-21 20:26:12 +000055
Paul Crowleydf528a72016-03-09 09:31:37 -080056const KeyAuthentication kEmptyAuthentication{"", ""};
Paul Crowley05720802016-02-08 15:55:41 +000057
Paul Crowley1ef25582016-01-21 20:26:12 +000058static constexpr size_t AES_KEY_BYTES = 32;
59static constexpr size_t GCM_NONCE_BYTES = 12;
60static constexpr size_t GCM_MAC_BYTES = 16;
Paul Crowleydf528a72016-03-09 09:31:37 -080061static constexpr size_t SALT_BYTES = 1 << 4;
62static constexpr size_t SECDISCARDABLE_BYTES = 1 << 14;
63static constexpr size_t STRETCHED_BYTES = 1 << 6;
Paul Crowley1ef25582016-01-21 20:26:12 +000064
Paul Crowleyb3de3372016-04-27 12:58:41 -070065static constexpr uint32_t AUTH_TIMEOUT = 30; // Seconds
66
Paul Crowley05720802016-02-08 15:55:41 +000067static const char* kCurrentVersion = "1";
Paul Crowley1ef25582016-01-21 20:26:12 +000068static const char* kRmPath = "/system/bin/rm";
69static const char* kSecdiscardPath = "/system/bin/secdiscard";
Paul Crowley63c18d32016-02-10 14:02:47 +000070static const char* kStretch_none = "none";
71static const char* kStretch_nopassword = "nopassword";
72static const std::string kStretchPrefix_scrypt = "scrypt ";
Paul Crowley6ab2cab2017-01-04 22:32:40 -080073static const char* kHashPrefix_secdiscardable = "Android secdiscardable SHA512";
74static const char* kHashPrefix_keygen = "Android key wrapping key generation SHA512";
Paul Crowley1ef25582016-01-21 20:26:12 +000075static const char* kFn_encrypted_key = "encrypted_key";
Paul Crowley05720802016-02-08 15:55:41 +000076static const char* kFn_keymaster_key_blob = "keymaster_key_blob";
Paul Crowleydff8c722016-05-16 08:14:56 -070077static const char* kFn_keymaster_key_blob_upgraded = "keymaster_key_blob_upgraded";
Paul Crowley63c18d32016-02-10 14:02:47 +000078static const char* kFn_salt = "salt";
Paul Crowley1ef25582016-01-21 20:26:12 +000079static const char* kFn_secdiscardable = "secdiscardable";
Paul Crowley05720802016-02-08 15:55:41 +000080static const char* kFn_stretching = "stretching";
81static const char* kFn_version = "version";
Paul Crowley1ef25582016-01-21 20:26:12 +000082
Paul Crowley13ffd8e2016-01-27 14:30:22 +000083static bool checkSize(const std::string& kind, size_t actual, size_t expected) {
Paul Crowley1ef25582016-01-21 20:26:12 +000084 if (actual != expected) {
Paul Crowleydf528a72016-03-09 09:31:37 -080085 LOG(ERROR) << "Wrong number of bytes in " << kind << ", expected " << expected << " got "
86 << actual;
Paul Crowley1ef25582016-01-21 20:26:12 +000087 return false;
88 }
89 return true;
90}
91
Paul Crowley26a53882017-10-26 11:16:39 -070092static void hashWithPrefix(char const* prefix, const std::string& tohash, std::string* res) {
Paul Crowley1ef25582016-01-21 20:26:12 +000093 SHA512_CTX c;
94
95 SHA512_Init(&c);
96 // Personalise the hashing by introducing a fixed prefix.
97 // Hashing applications should use personalization except when there is a
98 // specific reason not to; see section 4.11 of https://www.schneier.com/skein1.3.pdf
Paul Crowley6ab2cab2017-01-04 22:32:40 -080099 std::string hashingPrefix = prefix;
100 hashingPrefix.resize(SHA512_CBLOCK);
101 SHA512_Update(&c, hashingPrefix.data(), hashingPrefix.size());
102 SHA512_Update(&c, tohash.data(), tohash.size());
Paul Crowley26a53882017-10-26 11:16:39 -0700103 res->assign(SHA512_DIGEST_LENGTH, '\0');
104 SHA512_Final(reinterpret_cast<uint8_t*>(&(*res)[0]), &c);
Paul Crowley1ef25582016-01-21 20:26:12 +0000105}
106
Paul Crowleydf528a72016-03-09 09:31:37 -0800107static bool generateKeymasterKey(Keymaster& keymaster, const KeyAuthentication& auth,
108 const std::string& appId, std::string* key) {
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100109 auto paramBuilder = AuthorizationSetBuilder()
Paul Crowleydf528a72016-03-09 09:31:37 -0800110 .AesEncryptionKey(AES_KEY_BYTES * 8)
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100111 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
112 .Authorization(TAG_MIN_MAC_LENGTH, GCM_MAC_BYTES * 8)
113 .Authorization(TAG_PADDING, PaddingMode::NONE)
114 .Authorization(TAG_APPLICATION_ID, blob2hidlVec(appId));
Paul Crowley320e5e12016-03-04 14:07:05 -0800115 if (auth.token.empty()) {
116 LOG(DEBUG) << "Creating key that doesn't need auth token";
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100117 paramBuilder.Authorization(TAG_NO_AUTH_REQUIRED);
Paul Crowley320e5e12016-03-04 14:07:05 -0800118 } else {
119 LOG(DEBUG) << "Auth token required for key";
120 if (auth.token.size() != sizeof(hw_auth_token_t)) {
121 LOG(ERROR) << "Auth token should be " << sizeof(hw_auth_token_t) << " bytes, was "
Paul Crowleydf528a72016-03-09 09:31:37 -0800122 << auth.token.size() << " bytes";
Paul Crowley320e5e12016-03-04 14:07:05 -0800123 return false;
124 }
Paul Crowleydf528a72016-03-09 09:31:37 -0800125 const hw_auth_token_t* at = reinterpret_cast<const hw_auth_token_t*>(auth.token.data());
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100126 paramBuilder.Authorization(TAG_USER_SECURE_ID, at->user_id);
127 paramBuilder.Authorization(TAG_USER_AUTH_TYPE, HardwareAuthenticatorType::PASSWORD);
128 paramBuilder.Authorization(TAG_AUTH_TIMEOUT, AUTH_TIMEOUT);
Paul Crowley320e5e12016-03-04 14:07:05 -0800129 }
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100130 return keymaster.generateKey(paramBuilder, key);
Paul Crowley320e5e12016-03-04 14:07:05 -0800131}
132
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100133static AuthorizationSet beginParams(const KeyAuthentication& auth,
Paul Crowleydff8c722016-05-16 08:14:56 -0700134 const std::string& appId) {
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100135 auto paramBuilder = AuthorizationSetBuilder()
136 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
137 .Authorization(TAG_MAC_LENGTH, GCM_MAC_BYTES * 8)
138 .Authorization(TAG_PADDING, PaddingMode::NONE)
139 .Authorization(TAG_APPLICATION_ID, blob2hidlVec(appId));
Paul Crowley320e5e12016-03-04 14:07:05 -0800140 if (!auth.token.empty()) {
141 LOG(DEBUG) << "Supplying auth token to Keymaster";
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100142 paramBuilder.Authorization(TAG_AUTH_TOKEN, blob2hidlVec(auth.token));
Paul Crowley320e5e12016-03-04 14:07:05 -0800143 }
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100144 return paramBuilder;
Paul Crowley1ef25582016-01-21 20:26:12 +0000145}
146
Paul Crowleydf528a72016-03-09 09:31:37 -0800147static bool readFileToString(const std::string& filename, std::string* result) {
Paul Crowleya051eb72016-03-08 16:08:32 -0800148 if (!android::base::ReadFileToString(filename, result)) {
Paul Crowleydf528a72016-03-09 09:31:37 -0800149 PLOG(ERROR) << "Failed to read from " << filename;
150 return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000151 }
152 return true;
153}
154
Paul Crowleydf528a72016-03-09 09:31:37 -0800155static bool writeStringToFile(const std::string& payload, const std::string& filename) {
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000156 if (!android::base::WriteStringToFile(payload, filename)) {
Paul Crowleydf528a72016-03-09 09:31:37 -0800157 PLOG(ERROR) << "Failed to write to " << filename;
158 return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000159 }
160 return true;
161}
162
Paul Crowley26a53882017-10-26 11:16:39 -0700163static bool readRandomBytesOrLog(size_t count, std::string* out) {
164 auto status = ReadRandomBytes(count, *out);
165 if (status != OK) {
166 LOG(ERROR) << "Random read failed with status: " << status;
167 return false;
168 }
169 return true;
170}
171
172bool createSecdiscardable(const std::string& filename, std::string* hash) {
173 std::string secdiscardable;
174 if (!readRandomBytesOrLog(SECDISCARDABLE_BYTES, &secdiscardable)) return false;
175 if (!writeStringToFile(secdiscardable, filename)) return false;
176 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
177 return true;
178}
179
180bool readSecdiscardable(const std::string& filename, std::string* hash) {
181 std::string secdiscardable;
182 if (!readFileToString(filename, &secdiscardable)) return false;
183 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
184 return true;
185}
186
Paul Crowleydff8c722016-05-16 08:14:56 -0700187static KeymasterOperation begin(Keymaster& keymaster, const std::string& dir,
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100188 KeyPurpose purpose,
189 const AuthorizationSet &keyParams,
190 const AuthorizationSet &opParams,
191 AuthorizationSet* outParams) {
Paul Crowleydff8c722016-05-16 08:14:56 -0700192 auto kmKeyPath = dir + "/" + kFn_keymaster_key_blob;
193 std::string kmKey;
194 if (!readFileToString(kmKeyPath, &kmKey)) return KeymasterOperation();
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100195 AuthorizationSet inParams(keyParams);
196 inParams.append(opParams.begin(), opParams.end());
Paul Crowleydff8c722016-05-16 08:14:56 -0700197 for (;;) {
198 auto opHandle = keymaster.begin(purpose, kmKey, inParams, outParams);
199 if (opHandle) {
200 return opHandle;
201 }
Wei Wang4375f1b2017-02-24 17:43:01 -0800202 if (opHandle.errorCode() != ErrorCode::KEY_REQUIRES_UPGRADE) return opHandle;
Paul Crowleydff8c722016-05-16 08:14:56 -0700203 LOG(DEBUG) << "Upgrading key: " << dir;
204 std::string newKey;
205 if (!keymaster.upgradeKey(kmKey, keyParams, &newKey)) return KeymasterOperation();
206 auto newKeyPath = dir + "/" + kFn_keymaster_key_blob_upgraded;
207 if (!writeStringToFile(newKey, newKeyPath)) return KeymasterOperation();
208 if (rename(newKeyPath.c_str(), kmKeyPath.c_str()) != 0) {
209 PLOG(ERROR) << "Unable to move upgraded key to location: " << kmKeyPath;
210 return KeymasterOperation();
211 }
212 if (!keymaster.deleteKey(kmKey)) {
213 LOG(ERROR) << "Key deletion failed during upgrade, continuing anyway: " << dir;
214 }
215 kmKey = newKey;
216 LOG(INFO) << "Key upgraded: " << dir;
217 }
218}
219
220static bool encryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100221 const AuthorizationSet &keyParams,
Pavel Grafove2e2d302017-08-01 17:15:53 +0100222 const KeyBuffer& message, std::string* ciphertext) {
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100223 AuthorizationSet opParams;
224 AuthorizationSet outParams;
225 auto opHandle = begin(keymaster, dir, KeyPurpose::ENCRYPT, keyParams, opParams, &outParams);
Paul Crowleydff8c722016-05-16 08:14:56 -0700226 if (!opHandle) return false;
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100227 auto nonceBlob = outParams.GetTagValue(TAG_NONCE);
228 if (!nonceBlob.isOk()) {
Paul Crowleydff8c722016-05-16 08:14:56 -0700229 LOG(ERROR) << "GCM encryption but no nonce generated";
230 return false;
231 }
232 // nonceBlob here is just a pointer into existing data, must not be freed
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100233 std::string nonce(reinterpret_cast<const char*>(&nonceBlob.value()[0]), nonceBlob.value().size());
Paul Crowleydff8c722016-05-16 08:14:56 -0700234 if (!checkSize("nonce", nonce.size(), GCM_NONCE_BYTES)) return false;
235 std::string body;
236 if (!opHandle.updateCompletely(message, &body)) return false;
237
238 std::string mac;
239 if (!opHandle.finish(&mac)) return false;
240 if (!checkSize("mac", mac.size(), GCM_MAC_BYTES)) return false;
241 *ciphertext = nonce + body + mac;
242 return true;
243}
244
245static bool decryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100246 const AuthorizationSet &keyParams,
Pavel Grafove2e2d302017-08-01 17:15:53 +0100247 const std::string& ciphertext, KeyBuffer* message) {
Paul Crowleydff8c722016-05-16 08:14:56 -0700248 auto nonce = ciphertext.substr(0, GCM_NONCE_BYTES);
249 auto bodyAndMac = ciphertext.substr(GCM_NONCE_BYTES);
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100250 auto opParams = AuthorizationSetBuilder()
251 .Authorization(TAG_NONCE, blob2hidlVec(nonce));
252 auto opHandle = begin(keymaster, dir, KeyPurpose::DECRYPT, keyParams, opParams, nullptr);
Paul Crowleydff8c722016-05-16 08:14:56 -0700253 if (!opHandle) return false;
254 if (!opHandle.updateCompletely(bodyAndMac, message)) return false;
255 if (!opHandle.finish(nullptr)) return false;
256 return true;
257}
258
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800259static std::string getStretching(const KeyAuthentication& auth) {
260 if (!auth.usesKeymaster()) {
261 return kStretch_none;
262 } else if (auth.secret.empty()) {
263 return kStretch_nopassword;
264 } else {
265 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000266
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800267 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
268 return std::string() + kStretchPrefix_scrypt + paramstr;
269 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000270}
271
Paul Crowleydf528a72016-03-09 09:31:37 -0800272static bool stretchingNeedsSalt(const std::string& stretching) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000273 return stretching != kStretch_nopassword && stretching != kStretch_none;
274}
275
Paul Crowleydf528a72016-03-09 09:31:37 -0800276static bool stretchSecret(const std::string& stretching, const std::string& secret,
277 const std::string& salt, std::string* stretched) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000278 if (stretching == kStretch_nopassword) {
279 if (!secret.empty()) {
Paul Crowleyd9b92952016-03-04 13:45:00 -0800280 LOG(WARNING) << "Password present but stretching is nopassword";
Paul Crowley63c18d32016-02-10 14:02:47 +0000281 // Continue anyway
282 }
Paul Crowleya051eb72016-03-08 16:08:32 -0800283 stretched->clear();
Paul Crowley63c18d32016-02-10 14:02:47 +0000284 } else if (stretching == kStretch_none) {
Paul Crowleya051eb72016-03-08 16:08:32 -0800285 *stretched = secret;
Paul Crowleydf528a72016-03-09 09:31:37 -0800286 } else if (std::equal(kStretchPrefix_scrypt.begin(), kStretchPrefix_scrypt.end(),
287 stretching.begin())) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000288 int Nf, rf, pf;
Paul Crowleydf528a72016-03-09 09:31:37 -0800289 if (!parse_scrypt_parameters(stretching.substr(kStretchPrefix_scrypt.size()).c_str(), &Nf,
290 &rf, &pf)) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000291 LOG(ERROR) << "Unable to parse scrypt params in stretching: " << stretching;
292 return false;
293 }
Paul Crowleya051eb72016-03-08 16:08:32 -0800294 stretched->assign(STRETCHED_BYTES, '\0');
Paul Crowleydf528a72016-03-09 09:31:37 -0800295 if (crypto_scrypt(reinterpret_cast<const uint8_t*>(secret.data()), secret.size(),
296 reinterpret_cast<const uint8_t*>(salt.data()), salt.size(),
297 1 << Nf, 1 << rf, 1 << pf,
298 reinterpret_cast<uint8_t*>(&(*stretched)[0]), stretched->size()) != 0) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000299 LOG(ERROR) << "scrypt failed with params: " << stretching;
300 return false;
301 }
302 } else {
303 LOG(ERROR) << "Unknown stretching type: " << stretching;
304 return false;
305 }
306 return true;
307}
308
Paul Crowleydf528a72016-03-09 09:31:37 -0800309static bool generateAppId(const KeyAuthentication& auth, const std::string& stretching,
Paul Crowley26a53882017-10-26 11:16:39 -0700310 const std::string& salt, const std::string& secdiscardable_hash,
Paul Crowleydf528a72016-03-09 09:31:37 -0800311 std::string* appId) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000312 std::string stretched;
Paul Crowleya051eb72016-03-08 16:08:32 -0800313 if (!stretchSecret(stretching, auth.secret, salt, &stretched)) return false;
Paul Crowley26a53882017-10-26 11:16:39 -0700314 *appId = secdiscardable_hash + stretched;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800315 return true;
316}
317
318static void logOpensslError() {
319 LOG(ERROR) << "Openssl error: " << ERR_get_error();
320}
321
322static bool encryptWithoutKeymaster(const std::string& preKey,
Pavel Grafove2e2d302017-08-01 17:15:53 +0100323 const KeyBuffer& plaintext, std::string* ciphertext) {
Paul Crowley26a53882017-10-26 11:16:39 -0700324 std::string key;
325 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800326 key.resize(AES_KEY_BYTES);
327 if (!readRandomBytesOrLog(GCM_NONCE_BYTES, ciphertext)) return false;
328 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
329 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
330 if (!ctx) {
331 logOpensslError();
332 return false;
333 }
334 if (1 != EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
335 reinterpret_cast<const uint8_t*>(key.data()),
336 reinterpret_cast<const uint8_t*>(ciphertext->data()))) {
337 logOpensslError();
338 return false;
339 }
340 ciphertext->resize(GCM_NONCE_BYTES + plaintext.size() + GCM_MAC_BYTES);
341 int outlen;
342 if (1 != EVP_EncryptUpdate(ctx.get(),
343 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES), &outlen,
344 reinterpret_cast<const uint8_t*>(plaintext.data()), plaintext.size())) {
345 logOpensslError();
346 return false;
347 }
348 if (outlen != static_cast<int>(plaintext.size())) {
349 LOG(ERROR) << "GCM ciphertext length should be " << plaintext.size() << " was " << outlen;
350 return false;
351 }
352 if (1 != EVP_EncryptFinal_ex(ctx.get(),
353 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES + plaintext.size()), &outlen)) {
354 logOpensslError();
355 return false;
356 }
357 if (outlen != 0) {
358 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
359 return false;
360 }
361 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, GCM_MAC_BYTES,
362 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES + plaintext.size()))) {
363 logOpensslError();
364 return false;
365 }
366 return true;
367}
368
369static bool decryptWithoutKeymaster(const std::string& preKey,
Pavel Grafove2e2d302017-08-01 17:15:53 +0100370 const std::string& ciphertext, KeyBuffer* plaintext) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800371 if (ciphertext.size() < GCM_NONCE_BYTES + GCM_MAC_BYTES) {
372 LOG(ERROR) << "GCM ciphertext too small: " << ciphertext.size();
373 return false;
374 }
Paul Crowley26a53882017-10-26 11:16:39 -0700375 std::string key;
376 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800377 key.resize(AES_KEY_BYTES);
378 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
379 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
380 if (!ctx) {
381 logOpensslError();
382 return false;
383 }
384 if (1 != EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
385 reinterpret_cast<const uint8_t*>(key.data()),
386 reinterpret_cast<const uint8_t*>(ciphertext.data()))) {
387 logOpensslError();
388 return false;
389 }
Pavel Grafove2e2d302017-08-01 17:15:53 +0100390 *plaintext = KeyBuffer(ciphertext.size() - GCM_NONCE_BYTES - GCM_MAC_BYTES);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800391 int outlen;
392 if (1 != EVP_DecryptUpdate(ctx.get(),
393 reinterpret_cast<uint8_t*>(&(*plaintext)[0]), &outlen,
394 reinterpret_cast<const uint8_t*>(ciphertext.data() + GCM_NONCE_BYTES), plaintext->size())) {
395 logOpensslError();
396 return false;
397 }
398 if (outlen != static_cast<int>(plaintext->size())) {
399 LOG(ERROR) << "GCM plaintext length should be " << plaintext->size() << " was " << outlen;
400 return false;
401 }
402 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, GCM_MAC_BYTES,
403 const_cast<void *>(
404 reinterpret_cast<const void*>(ciphertext.data() + GCM_NONCE_BYTES + plaintext->size())))) {
405 logOpensslError();
406 return false;
407 }
408 if (1 != EVP_DecryptFinal_ex(ctx.get(),
409 reinterpret_cast<uint8_t*>(&(*plaintext)[0] + plaintext->size()), &outlen)) {
410 logOpensslError();
411 return false;
412 }
413 if (outlen != 0) {
414 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
415 return false;
416 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000417 return true;
Paul Crowley05720802016-02-08 15:55:41 +0000418}
419
Paul Crowleyf71ace32016-06-02 11:01:19 -0700420bool pathExists(const std::string& path) {
421 return access(path.c_str(), F_OK) == 0;
422}
423
Pavel Grafove2e2d302017-08-01 17:15:53 +0100424bool storeKey(const std::string& dir, const KeyAuthentication& auth, const KeyBuffer& key) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000425 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), 0700)) == -1) {
426 PLOG(ERROR) << "key mkdir " << dir;
427 return false;
428 }
Paul Crowleydf528a72016-03-09 09:31:37 -0800429 if (!writeStringToFile(kCurrentVersion, dir + "/" + kFn_version)) return false;
Paul Crowley26a53882017-10-26 11:16:39 -0700430 std::string secdiscardable_hash;
431 if (!createSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800432 std::string stretching = getStretching(auth);
Paul Crowleydf528a72016-03-09 09:31:37 -0800433 if (!writeStringToFile(stretching, dir + "/" + kFn_stretching)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000434 std::string salt;
435 if (stretchingNeedsSalt(stretching)) {
436 if (ReadRandomBytes(SALT_BYTES, salt) != OK) {
437 LOG(ERROR) << "Random read failed";
438 return false;
439 }
Paul Crowleydf528a72016-03-09 09:31:37 -0800440 if (!writeStringToFile(salt, dir + "/" + kFn_salt)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000441 }
Paul Crowley320e5e12016-03-04 14:07:05 -0800442 std::string appId;
Paul Crowley26a53882017-10-26 11:16:39 -0700443 if (!generateAppId(auth, stretching, salt, secdiscardable_hash, &appId)) return false;
Paul Crowley320e5e12016-03-04 14:07:05 -0800444 std::string encryptedKey;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800445 if (auth.usesKeymaster()) {
446 Keymaster keymaster;
447 if (!keymaster) return false;
448 std::string kmKey;
449 if (!generateKeymasterKey(keymaster, auth, appId, &kmKey)) return false;
450 if (!writeStringToFile(kmKey, dir + "/" + kFn_keymaster_key_blob)) return false;
451 auto keyParams = beginParams(auth, appId);
452 if (!encryptWithKeymasterKey(keymaster, dir, keyParams, key, &encryptedKey)) return false;
453 } else {
454 if (!encryptWithoutKeymaster(appId, key, &encryptedKey)) return false;
455 }
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000456 if (!writeStringToFile(encryptedKey, dir + "/" + kFn_encrypted_key)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000457 return true;
458}
459
Paul Crowleyf71ace32016-06-02 11:01:19 -0700460bool storeKeyAtomically(const std::string& key_path, const std::string& tmp_path,
Pavel Grafove2e2d302017-08-01 17:15:53 +0100461 const KeyAuthentication& auth, const KeyBuffer& key) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700462 if (pathExists(key_path)) {
463 LOG(ERROR) << "Already exists, cannot create key at: " << key_path;
464 return false;
465 }
466 if (pathExists(tmp_path)) {
467 LOG(DEBUG) << "Already exists, destroying: " << tmp_path;
468 destroyKey(tmp_path); // May be partially created so ignore errors
469 }
470 if (!storeKey(tmp_path, auth, key)) return false;
471 if (rename(tmp_path.c_str(), key_path.c_str()) != 0) {
472 PLOG(ERROR) << "Unable to move new key to location: " << key_path;
473 return false;
474 }
475 LOG(DEBUG) << "Created key: " << key_path;
476 return true;
477}
478
Pavel Grafove2e2d302017-08-01 17:15:53 +0100479bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, KeyBuffer* key) {
Paul Crowley05720802016-02-08 15:55:41 +0000480 std::string version;
Paul Crowleya051eb72016-03-08 16:08:32 -0800481 if (!readFileToString(dir + "/" + kFn_version, &version)) return false;
Paul Crowley05720802016-02-08 15:55:41 +0000482 if (version != kCurrentVersion) {
483 LOG(ERROR) << "Version mismatch, expected " << kCurrentVersion << " got " << version;
484 return false;
485 }
Paul Crowley26a53882017-10-26 11:16:39 -0700486 std::string secdiscardable_hash;
487 if (!readSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000488 std::string stretching;
Paul Crowleya051eb72016-03-08 16:08:32 -0800489 if (!readFileToString(dir + "/" + kFn_stretching, &stretching)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000490 std::string salt;
491 if (stretchingNeedsSalt(stretching)) {
Paul Crowleydf528a72016-03-09 09:31:37 -0800492 if (!readFileToString(dir + "/" + kFn_salt, &salt)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000493 }
Paul Crowley320e5e12016-03-04 14:07:05 -0800494 std::string appId;
Paul Crowley26a53882017-10-26 11:16:39 -0700495 if (!generateAppId(auth, stretching, salt, secdiscardable_hash, &appId)) return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000496 std::string encryptedMessage;
Paul Crowleya051eb72016-03-08 16:08:32 -0800497 if (!readFileToString(dir + "/" + kFn_encrypted_key, &encryptedMessage)) return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800498 if (auth.usesKeymaster()) {
499 Keymaster keymaster;
500 if (!keymaster) return false;
501 auto keyParams = beginParams(auth, appId);
502 if (!decryptWithKeymasterKey(keymaster, dir, keyParams, encryptedMessage, key)) return false;
503 } else {
504 if (!decryptWithoutKeymaster(appId, encryptedMessage, key)) return false;
505 }
506 return true;
Paul Crowley1ef25582016-01-21 20:26:12 +0000507}
508
Paul Crowleydf528a72016-03-09 09:31:37 -0800509static bool deleteKey(const std::string& dir) {
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000510 std::string kmKey;
Paul Crowleya051eb72016-03-08 16:08:32 -0800511 if (!readFileToString(dir + "/" + kFn_keymaster_key_blob, &kmKey)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000512 Keymaster keymaster;
513 if (!keymaster) return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000514 if (!keymaster.deleteKey(kmKey)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000515 return true;
516}
517
Rubin Xu2436e272017-04-27 20:43:10 +0100518bool runSecdiscardSingle(const std::string& file) {
519 if (ForkExecvp(
520 std::vector<std::string>{kSecdiscardPath, "--",
521 file}) != 0) {
522 LOG(ERROR) << "secdiscard failed";
523 return false;
524 }
525 return true;
526}
527
Paul Crowleydf528a72016-03-09 09:31:37 -0800528static bool recursiveDeleteKey(const std::string& dir) {
529 if (ForkExecvp(std::vector<std::string>{kRmPath, "-rf", dir}) != 0) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000530 LOG(ERROR) << "recursive delete failed";
531 return false;
532 }
533 return true;
534}
535
Paul Crowleydf528a72016-03-09 09:31:37 -0800536bool destroyKey(const std::string& dir) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000537 bool success = true;
538 // Try each thing, even if previous things failed.
Paul Crowleyff19b052017-10-26 11:28:55 -0700539 bool uses_km = pathExists(dir + "/" + kFn_keymaster_key_blob);
540 if (uses_km) {
541 success &= deleteKey(dir);
542 }
543 auto secdiscard_cmd = std::vector<std::string>{
544 kSecdiscardPath, "--", dir + "/" + kFn_encrypted_key, dir + "/" + kFn_secdiscardable,
545 };
546 if (uses_km) {
547 secdiscard_cmd.emplace_back(dir + "/" + kFn_keymaster_key_blob);
548 }
549 if (ForkExecvp(secdiscard_cmd) != 0) {
550 LOG(ERROR) << "secdiscard failed";
551 success = false;
552 }
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000553 success &= recursiveDeleteKey(dir);
Paul Crowley1ef25582016-01-21 20:26:12 +0000554 return success;
555}
556
557} // namespace vold
558} // namespace android