blob: d00225bf0879aa7f80f370c0f79e1eca8319a804 [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>
Shawn Willden35351812018-01-22 09:08:32 -070043#include <keymasterV4_0/authorization_set.h>
44#include <keymasterV4_0/keymaster_utils.h>
Paul Crowley320e5e12016-03-04 14:07:05 -080045
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 {
53
Paul Crowleydf528a72016-03-09 09:31:37 -080054const KeyAuthentication kEmptyAuthentication{"", ""};
Paul Crowley05720802016-02-08 15:55:41 +000055
Paul Crowley1ef25582016-01-21 20:26:12 +000056static constexpr size_t AES_KEY_BYTES = 32;
57static constexpr size_t GCM_NONCE_BYTES = 12;
58static constexpr size_t GCM_MAC_BYTES = 16;
Paul Crowleydf528a72016-03-09 09:31:37 -080059static constexpr size_t SALT_BYTES = 1 << 4;
60static constexpr size_t SECDISCARDABLE_BYTES = 1 << 14;
61static constexpr size_t STRETCHED_BYTES = 1 << 6;
Paul Crowley1ef25582016-01-21 20:26:12 +000062
Shawn Willden785365b2018-01-20 09:37:36 -070063static constexpr uint32_t AUTH_TIMEOUT = 30; // Seconds
Paul Crowleyb3de3372016-04-27 12:58:41 -070064
Paul Crowley05720802016-02-08 15:55:41 +000065static const char* kCurrentVersion = "1";
Paul Crowley1ef25582016-01-21 20:26:12 +000066static const char* kRmPath = "/system/bin/rm";
67static const char* kSecdiscardPath = "/system/bin/secdiscard";
Paul Crowley63c18d32016-02-10 14:02:47 +000068static const char* kStretch_none = "none";
69static const char* kStretch_nopassword = "nopassword";
70static const std::string kStretchPrefix_scrypt = "scrypt ";
Paul Crowley6ab2cab2017-01-04 22:32:40 -080071static const char* kHashPrefix_secdiscardable = "Android secdiscardable SHA512";
72static const char* kHashPrefix_keygen = "Android key wrapping key generation SHA512";
Paul Crowley1ef25582016-01-21 20:26:12 +000073static const char* kFn_encrypted_key = "encrypted_key";
Paul Crowley05720802016-02-08 15:55:41 +000074static const char* kFn_keymaster_key_blob = "keymaster_key_blob";
Paul Crowleydff8c722016-05-16 08:14:56 -070075static const char* kFn_keymaster_key_blob_upgraded = "keymaster_key_blob_upgraded";
Paul Crowley63c18d32016-02-10 14:02:47 +000076static const char* kFn_salt = "salt";
Paul Crowley1ef25582016-01-21 20:26:12 +000077static const char* kFn_secdiscardable = "secdiscardable";
Paul Crowley05720802016-02-08 15:55:41 +000078static const char* kFn_stretching = "stretching";
79static const char* kFn_version = "version";
Paul Crowley1ef25582016-01-21 20:26:12 +000080
Paul Crowley13ffd8e2016-01-27 14:30:22 +000081static bool checkSize(const std::string& kind, size_t actual, size_t expected) {
Paul Crowley1ef25582016-01-21 20:26:12 +000082 if (actual != expected) {
Paul Crowleydf528a72016-03-09 09:31:37 -080083 LOG(ERROR) << "Wrong number of bytes in " << kind << ", expected " << expected << " got "
84 << actual;
Paul Crowley1ef25582016-01-21 20:26:12 +000085 return false;
86 }
87 return true;
88}
89
Paul Crowley26a53882017-10-26 11:16:39 -070090static void hashWithPrefix(char const* prefix, const std::string& tohash, std::string* res) {
Paul Crowley1ef25582016-01-21 20:26:12 +000091 SHA512_CTX c;
92
93 SHA512_Init(&c);
94 // Personalise the hashing by introducing a fixed prefix.
95 // Hashing applications should use personalization except when there is a
96 // specific reason not to; see section 4.11 of https://www.schneier.com/skein1.3.pdf
Paul Crowley6ab2cab2017-01-04 22:32:40 -080097 std::string hashingPrefix = prefix;
98 hashingPrefix.resize(SHA512_CBLOCK);
99 SHA512_Update(&c, hashingPrefix.data(), hashingPrefix.size());
100 SHA512_Update(&c, tohash.data(), tohash.size());
Paul Crowley26a53882017-10-26 11:16:39 -0700101 res->assign(SHA512_DIGEST_LENGTH, '\0');
102 SHA512_Final(reinterpret_cast<uint8_t*>(&(*res)[0]), &c);
Paul Crowley1ef25582016-01-21 20:26:12 +0000103}
104
Paul Crowleydf528a72016-03-09 09:31:37 -0800105static bool generateKeymasterKey(Keymaster& keymaster, const KeyAuthentication& auth,
106 const std::string& appId, std::string* key) {
Shawn Willden35351812018-01-22 09:08:32 -0700107 auto paramBuilder = km::AuthorizationSetBuilder()
Paul Crowleydf528a72016-03-09 09:31:37 -0800108 .AesEncryptionKey(AES_KEY_BYTES * 8)
Shawn Willden35351812018-01-22 09:08:32 -0700109 .GcmModeMinMacLen(GCM_MAC_BYTES * 8)
110 .Authorization(km::TAG_APPLICATION_ID, km::support::blob2hidlVec(appId));
Paul Crowley320e5e12016-03-04 14:07:05 -0800111 if (auth.token.empty()) {
112 LOG(DEBUG) << "Creating key that doesn't need auth token";
Shawn Willden35351812018-01-22 09:08:32 -0700113 paramBuilder.Authorization(km::TAG_NO_AUTH_REQUIRED);
Paul Crowley320e5e12016-03-04 14:07:05 -0800114 } else {
115 LOG(DEBUG) << "Auth token required for key";
116 if (auth.token.size() != sizeof(hw_auth_token_t)) {
117 LOG(ERROR) << "Auth token should be " << sizeof(hw_auth_token_t) << " bytes, was "
Paul Crowleydf528a72016-03-09 09:31:37 -0800118 << auth.token.size() << " bytes";
Paul Crowley320e5e12016-03-04 14:07:05 -0800119 return false;
120 }
Paul Crowleydf528a72016-03-09 09:31:37 -0800121 const hw_auth_token_t* at = reinterpret_cast<const hw_auth_token_t*>(auth.token.data());
Shawn Willden35351812018-01-22 09:08:32 -0700122 paramBuilder.Authorization(km::TAG_USER_SECURE_ID, at->user_id);
123 paramBuilder.Authorization(km::TAG_USER_AUTH_TYPE, km::HardwareAuthenticatorType::PASSWORD);
124 paramBuilder.Authorization(km::TAG_AUTH_TIMEOUT, AUTH_TIMEOUT);
Paul Crowley320e5e12016-03-04 14:07:05 -0800125 }
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100126 return keymaster.generateKey(paramBuilder, key);
Paul Crowley320e5e12016-03-04 14:07:05 -0800127}
128
Shawn Willden35351812018-01-22 09:08:32 -0700129static std::pair<km::AuthorizationSet, km::HardwareAuthToken> beginParams(
130 const KeyAuthentication& auth, const std::string& appId) {
131 auto paramBuilder = km::AuthorizationSetBuilder()
132 .GcmModeMacLen(GCM_MAC_BYTES * 8)
133 .Authorization(km::TAG_APPLICATION_ID, km::support::blob2hidlVec(appId));
134 km::HardwareAuthToken authToken;
Paul Crowley320e5e12016-03-04 14:07:05 -0800135 if (!auth.token.empty()) {
136 LOG(DEBUG) << "Supplying auth token to Keymaster";
Shawn Willden35351812018-01-22 09:08:32 -0700137 authToken = km::support::hidlVec2AuthToken(km::support::blob2hidlVec(auth.token));
Paul Crowley320e5e12016-03-04 14:07:05 -0800138 }
Shawn Willden35351812018-01-22 09:08:32 -0700139 return {paramBuilder, authToken};
Paul Crowley1ef25582016-01-21 20:26:12 +0000140}
141
Paul Crowleydf528a72016-03-09 09:31:37 -0800142static bool readFileToString(const std::string& filename, std::string* result) {
Paul Crowleya051eb72016-03-08 16:08:32 -0800143 if (!android::base::ReadFileToString(filename, result)) {
Paul Crowleydf528a72016-03-09 09:31:37 -0800144 PLOG(ERROR) << "Failed to read from " << filename;
145 return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000146 }
147 return true;
148}
149
Paul Crowley26a53882017-10-26 11:16:39 -0700150static bool readRandomBytesOrLog(size_t count, std::string* out) {
151 auto status = ReadRandomBytes(count, *out);
152 if (status != OK) {
153 LOG(ERROR) << "Random read failed with status: " << status;
154 return false;
155 }
156 return true;
157}
158
159bool createSecdiscardable(const std::string& filename, std::string* hash) {
160 std::string secdiscardable;
161 if (!readRandomBytesOrLog(SECDISCARDABLE_BYTES, &secdiscardable)) return false;
162 if (!writeStringToFile(secdiscardable, filename)) return false;
163 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
164 return true;
165}
166
167bool readSecdiscardable(const std::string& filename, std::string* hash) {
168 std::string secdiscardable;
169 if (!readFileToString(filename, &secdiscardable)) return false;
170 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
171 return true;
172}
173
Shawn Willden35351812018-01-22 09:08:32 -0700174static KeymasterOperation begin(Keymaster& keymaster, const std::string& dir,
175 km::KeyPurpose purpose, const km::AuthorizationSet& keyParams,
176 const km::AuthorizationSet& opParams,
177 const km::HardwareAuthToken& authToken,
Daniel Rosenberg690d6de2018-12-14 01:08:10 -0800178 km::AuthorizationSet* outParams, bool keepOld) {
Paul Crowleydff8c722016-05-16 08:14:56 -0700179 auto kmKeyPath = dir + "/" + kFn_keymaster_key_blob;
180 std::string kmKey;
181 if (!readFileToString(kmKeyPath, &kmKey)) return KeymasterOperation();
Shawn Willden35351812018-01-22 09:08:32 -0700182 km::AuthorizationSet inParams(keyParams);
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100183 inParams.append(opParams.begin(), opParams.end());
Paul Crowleydff8c722016-05-16 08:14:56 -0700184 for (;;) {
Shawn Willden35351812018-01-22 09:08:32 -0700185 auto opHandle = keymaster.begin(purpose, kmKey, inParams, authToken, outParams);
Paul Crowleydff8c722016-05-16 08:14:56 -0700186 if (opHandle) {
187 return opHandle;
188 }
Shawn Willden35351812018-01-22 09:08:32 -0700189 if (opHandle.errorCode() != km::ErrorCode::KEY_REQUIRES_UPGRADE) return opHandle;
Paul Crowleydff8c722016-05-16 08:14:56 -0700190 LOG(DEBUG) << "Upgrading key: " << dir;
191 std::string newKey;
192 if (!keymaster.upgradeKey(kmKey, keyParams, &newKey)) return KeymasterOperation();
193 auto newKeyPath = dir + "/" + kFn_keymaster_key_blob_upgraded;
194 if (!writeStringToFile(newKey, newKeyPath)) return KeymasterOperation();
Daniel Rosenberg690d6de2018-12-14 01:08:10 -0800195 if (!keepOld) {
196 if (rename(newKeyPath.c_str(), kmKeyPath.c_str()) != 0) {
197 PLOG(ERROR) << "Unable to move upgraded key to location: " << kmKeyPath;
198 return KeymasterOperation();
199 }
Woody Lin37c82f52019-03-11 20:58:20 +0800200 if (!android::vold::FsyncDirectory(dir)) {
201 LOG(ERROR) << "Key dir sync failed: " << dir;
202 return KeymasterOperation();
203 }
Daniel Rosenberg690d6de2018-12-14 01:08:10 -0800204 if (!keymaster.deleteKey(kmKey)) {
205 LOG(ERROR) << "Key deletion failed during upgrade, continuing anyway: " << dir;
206 }
Paul Crowleydff8c722016-05-16 08:14:56 -0700207 }
208 kmKey = newKey;
209 LOG(INFO) << "Key upgraded: " << dir;
210 }
211}
212
213static bool encryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
Shawn Willden35351812018-01-22 09:08:32 -0700214 const km::AuthorizationSet& keyParams,
Daniel Rosenberg690d6de2018-12-14 01:08:10 -0800215 const km::HardwareAuthToken& authToken, const KeyBuffer& message,
216 std::string* ciphertext, bool keepOld) {
Shawn Willden35351812018-01-22 09:08:32 -0700217 km::AuthorizationSet opParams;
218 km::AuthorizationSet outParams;
Daniel Rosenberg690d6de2018-12-14 01:08:10 -0800219 auto opHandle = begin(keymaster, dir, km::KeyPurpose::ENCRYPT, keyParams, opParams, authToken,
220 &outParams, keepOld);
Paul Crowleydff8c722016-05-16 08:14:56 -0700221 if (!opHandle) return false;
Shawn Willden35351812018-01-22 09:08:32 -0700222 auto nonceBlob = outParams.GetTagValue(km::TAG_NONCE);
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100223 if (!nonceBlob.isOk()) {
Paul Crowleydff8c722016-05-16 08:14:56 -0700224 LOG(ERROR) << "GCM encryption but no nonce generated";
225 return false;
226 }
227 // nonceBlob here is just a pointer into existing data, must not be freed
Shawn Willden785365b2018-01-20 09:37:36 -0700228 std::string nonce(reinterpret_cast<const char*>(&nonceBlob.value()[0]),
229 nonceBlob.value().size());
Paul Crowleydff8c722016-05-16 08:14:56 -0700230 if (!checkSize("nonce", nonce.size(), GCM_NONCE_BYTES)) return false;
231 std::string body;
232 if (!opHandle.updateCompletely(message, &body)) return false;
233
234 std::string mac;
235 if (!opHandle.finish(&mac)) return false;
236 if (!checkSize("mac", mac.size(), GCM_MAC_BYTES)) return false;
237 *ciphertext = nonce + body + mac;
238 return true;
239}
240
241static bool decryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
Shawn Willden35351812018-01-22 09:08:32 -0700242 const km::AuthorizationSet& keyParams,
243 const km::HardwareAuthToken& authToken,
Daniel Rosenberg690d6de2018-12-14 01:08:10 -0800244 const std::string& ciphertext, KeyBuffer* message,
245 bool keepOld) {
Paul Crowleydff8c722016-05-16 08:14:56 -0700246 auto nonce = ciphertext.substr(0, GCM_NONCE_BYTES);
247 auto bodyAndMac = ciphertext.substr(GCM_NONCE_BYTES);
Shawn Willden35351812018-01-22 09:08:32 -0700248 auto opParams = km::AuthorizationSetBuilder().Authorization(km::TAG_NONCE,
249 km::support::blob2hidlVec(nonce));
Daniel Rosenberg690d6de2018-12-14 01:08:10 -0800250 auto opHandle = begin(keymaster, dir, km::KeyPurpose::DECRYPT, keyParams, opParams, authToken,
251 nullptr, keepOld);
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(),
Shawn Willden785365b2018-01-20 09:37:36 -0700295 reinterpret_cast<const uint8_t*>(salt.data()), salt.size(), 1 << Nf,
296 1 << rf, 1 << pf, reinterpret_cast<uint8_t*>(&(*stretched)[0]),
297 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
Shawn Willden785365b2018-01-20 09:37:36 -0700321static bool encryptWithoutKeymaster(const std::string& preKey, const KeyBuffer& plaintext,
322 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,
Shawn Willden785365b2018-01-20 09:37:36 -0700334 reinterpret_cast<const uint8_t*>(key.data()),
335 reinterpret_cast<const uint8_t*>(ciphertext->data()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800336 logOpensslError();
337 return false;
338 }
339 ciphertext->resize(GCM_NONCE_BYTES + plaintext.size() + GCM_MAC_BYTES);
340 int outlen;
Shawn Willden785365b2018-01-20 09:37:36 -0700341 if (1 != EVP_EncryptUpdate(
342 ctx.get(), reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES),
343 &outlen, reinterpret_cast<const uint8_t*>(plaintext.data()), plaintext.size())) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800344 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 }
Shawn Willden785365b2018-01-20 09:37:36 -0700351 if (1 != EVP_EncryptFinal_ex(
352 ctx.get(),
353 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES + plaintext.size()),
354 &outlen)) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800355 logOpensslError();
356 return false;
357 }
358 if (outlen != 0) {
359 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
360 return false;
361 }
362 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, GCM_MAC_BYTES,
Shawn Willden785365b2018-01-20 09:37:36 -0700363 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES +
364 plaintext.size()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800365 logOpensslError();
366 return false;
367 }
368 return true;
369}
370
Shawn Willden785365b2018-01-20 09:37:36 -0700371static bool decryptWithoutKeymaster(const std::string& preKey, const std::string& ciphertext,
372 KeyBuffer* plaintext) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800373 if (ciphertext.size() < GCM_NONCE_BYTES + GCM_MAC_BYTES) {
374 LOG(ERROR) << "GCM ciphertext too small: " << ciphertext.size();
375 return false;
376 }
Paul Crowley26a53882017-10-26 11:16:39 -0700377 std::string key;
378 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800379 key.resize(AES_KEY_BYTES);
380 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
381 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
382 if (!ctx) {
383 logOpensslError();
384 return false;
385 }
386 if (1 != EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
Shawn Willden785365b2018-01-20 09:37:36 -0700387 reinterpret_cast<const uint8_t*>(key.data()),
388 reinterpret_cast<const uint8_t*>(ciphertext.data()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800389 logOpensslError();
390 return false;
391 }
Pavel Grafove2e2d302017-08-01 17:15:53 +0100392 *plaintext = KeyBuffer(ciphertext.size() - GCM_NONCE_BYTES - GCM_MAC_BYTES);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800393 int outlen;
Shawn Willden785365b2018-01-20 09:37:36 -0700394 if (1 != EVP_DecryptUpdate(ctx.get(), reinterpret_cast<uint8_t*>(&(*plaintext)[0]), &outlen,
395 reinterpret_cast<const uint8_t*>(ciphertext.data() + GCM_NONCE_BYTES),
396 plaintext->size())) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800397 logOpensslError();
398 return false;
399 }
400 if (outlen != static_cast<int>(plaintext->size())) {
401 LOG(ERROR) << "GCM plaintext length should be " << plaintext->size() << " was " << outlen;
402 return false;
403 }
404 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, GCM_MAC_BYTES,
Shawn Willden785365b2018-01-20 09:37:36 -0700405 const_cast<void*>(reinterpret_cast<const void*>(
406 ciphertext.data() + GCM_NONCE_BYTES + plaintext->size())))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800407 logOpensslError();
408 return false;
409 }
410 if (1 != EVP_DecryptFinal_ex(ctx.get(),
Shawn Willden785365b2018-01-20 09:37:36 -0700411 reinterpret_cast<uint8_t*>(&(*plaintext)[0] + plaintext->size()),
412 &outlen)) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800413 logOpensslError();
414 return false;
415 }
416 if (outlen != 0) {
417 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
418 return false;
419 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000420 return true;
Paul Crowley05720802016-02-08 15:55:41 +0000421}
422
Paul Crowleyf71ace32016-06-02 11:01:19 -0700423bool pathExists(const std::string& path) {
424 return access(path.c_str(), F_OK) == 0;
425}
426
Pavel Grafove2e2d302017-08-01 17:15:53 +0100427bool storeKey(const std::string& dir, const KeyAuthentication& auth, const KeyBuffer& key) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000428 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), 0700)) == -1) {
429 PLOG(ERROR) << "key mkdir " << dir;
430 return false;
431 }
Paul Crowleydf528a72016-03-09 09:31:37 -0800432 if (!writeStringToFile(kCurrentVersion, dir + "/" + kFn_version)) return false;
Paul Crowley26a53882017-10-26 11:16:39 -0700433 std::string secdiscardable_hash;
434 if (!createSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800435 std::string stretching = getStretching(auth);
Paul Crowleydf528a72016-03-09 09:31:37 -0800436 if (!writeStringToFile(stretching, dir + "/" + kFn_stretching)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000437 std::string salt;
438 if (stretchingNeedsSalt(stretching)) {
439 if (ReadRandomBytes(SALT_BYTES, salt) != OK) {
440 LOG(ERROR) << "Random read failed";
441 return false;
442 }
Paul Crowleydf528a72016-03-09 09:31:37 -0800443 if (!writeStringToFile(salt, dir + "/" + kFn_salt)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000444 }
Paul Crowley320e5e12016-03-04 14:07:05 -0800445 std::string appId;
Paul Crowley26a53882017-10-26 11:16:39 -0700446 if (!generateAppId(auth, stretching, salt, secdiscardable_hash, &appId)) return false;
Paul Crowley320e5e12016-03-04 14:07:05 -0800447 std::string encryptedKey;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800448 if (auth.usesKeymaster()) {
449 Keymaster keymaster;
450 if (!keymaster) return false;
451 std::string kmKey;
452 if (!generateKeymasterKey(keymaster, auth, appId, &kmKey)) return false;
453 if (!writeStringToFile(kmKey, dir + "/" + kFn_keymaster_key_blob)) return false;
Shawn Willden35351812018-01-22 09:08:32 -0700454 km::AuthorizationSet keyParams;
455 km::HardwareAuthToken authToken;
456 std::tie(keyParams, authToken) = beginParams(auth, appId);
Daniel Rosenberg690d6de2018-12-14 01:08:10 -0800457 if (!encryptWithKeymasterKey(keymaster, dir, keyParams, authToken, key, &encryptedKey,
458 false))
Shawn Willden35351812018-01-22 09:08:32 -0700459 return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800460 } else {
461 if (!encryptWithoutKeymaster(appId, key, &encryptedKey)) return false;
462 }
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000463 if (!writeStringToFile(encryptedKey, dir + "/" + kFn_encrypted_key)) return false;
Paul Crowley621d9b92018-12-07 15:36:09 -0800464 if (!FsyncDirectory(dir)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000465 return true;
466}
467
Paul Crowleyf71ace32016-06-02 11:01:19 -0700468bool storeKeyAtomically(const std::string& key_path, const std::string& tmp_path,
Pavel Grafove2e2d302017-08-01 17:15:53 +0100469 const KeyAuthentication& auth, const KeyBuffer& key) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700470 if (pathExists(key_path)) {
471 LOG(ERROR) << "Already exists, cannot create key at: " << key_path;
472 return false;
473 }
474 if (pathExists(tmp_path)) {
475 LOG(DEBUG) << "Already exists, destroying: " << tmp_path;
476 destroyKey(tmp_path); // May be partially created so ignore errors
477 }
478 if (!storeKey(tmp_path, auth, key)) return false;
479 if (rename(tmp_path.c_str(), key_path.c_str()) != 0) {
480 PLOG(ERROR) << "Unable to move new key to location: " << key_path;
481 return false;
482 }
483 LOG(DEBUG) << "Created key: " << key_path;
484 return true;
485}
486
Daniel Rosenberg690d6de2018-12-14 01:08:10 -0800487bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, KeyBuffer* key,
488 bool keepOld) {
Paul Crowley05720802016-02-08 15:55:41 +0000489 std::string version;
Paul Crowleya051eb72016-03-08 16:08:32 -0800490 if (!readFileToString(dir + "/" + kFn_version, &version)) return false;
Paul Crowley05720802016-02-08 15:55:41 +0000491 if (version != kCurrentVersion) {
492 LOG(ERROR) << "Version mismatch, expected " << kCurrentVersion << " got " << version;
493 return false;
494 }
Paul Crowley26a53882017-10-26 11:16:39 -0700495 std::string secdiscardable_hash;
496 if (!readSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000497 std::string stretching;
Paul Crowleya051eb72016-03-08 16:08:32 -0800498 if (!readFileToString(dir + "/" + kFn_stretching, &stretching)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000499 std::string salt;
500 if (stretchingNeedsSalt(stretching)) {
Paul Crowleydf528a72016-03-09 09:31:37 -0800501 if (!readFileToString(dir + "/" + kFn_salt, &salt)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000502 }
Paul Crowley320e5e12016-03-04 14:07:05 -0800503 std::string appId;
Paul Crowley26a53882017-10-26 11:16:39 -0700504 if (!generateAppId(auth, stretching, salt, secdiscardable_hash, &appId)) return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000505 std::string encryptedMessage;
Paul Crowleya051eb72016-03-08 16:08:32 -0800506 if (!readFileToString(dir + "/" + kFn_encrypted_key, &encryptedMessage)) return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800507 if (auth.usesKeymaster()) {
508 Keymaster keymaster;
509 if (!keymaster) return false;
Shawn Willden35351812018-01-22 09:08:32 -0700510 km::AuthorizationSet keyParams;
511 km::HardwareAuthToken authToken;
512 std::tie(keyParams, authToken) = beginParams(auth, appId);
Daniel Rosenberg690d6de2018-12-14 01:08:10 -0800513 if (!decryptWithKeymasterKey(keymaster, dir, keyParams, authToken, encryptedMessage, key,
514 keepOld))
Shawn Willden785365b2018-01-20 09:37:36 -0700515 return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800516 } else {
517 if (!decryptWithoutKeymaster(appId, encryptedMessage, key)) return false;
518 }
519 return true;
Paul Crowley1ef25582016-01-21 20:26:12 +0000520}
521
Paul Crowleydf528a72016-03-09 09:31:37 -0800522static bool deleteKey(const std::string& dir) {
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000523 std::string kmKey;
Paul Crowleya051eb72016-03-08 16:08:32 -0800524 if (!readFileToString(dir + "/" + kFn_keymaster_key_blob, &kmKey)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000525 Keymaster keymaster;
526 if (!keymaster) return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000527 if (!keymaster.deleteKey(kmKey)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000528 return true;
529}
530
Rubin Xu2436e272017-04-27 20:43:10 +0100531bool runSecdiscardSingle(const std::string& file) {
Shawn Willden785365b2018-01-20 09:37:36 -0700532 if (ForkExecvp(std::vector<std::string>{kSecdiscardPath, "--", file}) != 0) {
Rubin Xu2436e272017-04-27 20:43:10 +0100533 LOG(ERROR) << "secdiscard failed";
534 return false;
535 }
536 return true;
537}
538
Paul Crowleydf528a72016-03-09 09:31:37 -0800539static bool recursiveDeleteKey(const std::string& dir) {
540 if (ForkExecvp(std::vector<std::string>{kRmPath, "-rf", dir}) != 0) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000541 LOG(ERROR) << "recursive delete failed";
542 return false;
543 }
544 return true;
545}
546
Paul Crowleydf528a72016-03-09 09:31:37 -0800547bool destroyKey(const std::string& dir) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000548 bool success = true;
549 // Try each thing, even if previous things failed.
Paul Crowleyff19b052017-10-26 11:28:55 -0700550 bool uses_km = pathExists(dir + "/" + kFn_keymaster_key_blob);
551 if (uses_km) {
552 success &= deleteKey(dir);
553 }
554 auto secdiscard_cmd = std::vector<std::string>{
Paul Crowley14c8c072018-09-18 13:30:21 -0700555 kSecdiscardPath,
556 "--",
557 dir + "/" + kFn_encrypted_key,
558 dir + "/" + kFn_secdiscardable,
Paul Crowleyff19b052017-10-26 11:28:55 -0700559 };
560 if (uses_km) {
561 secdiscard_cmd.emplace_back(dir + "/" + kFn_keymaster_key_blob);
562 }
563 if (ForkExecvp(secdiscard_cmd) != 0) {
564 LOG(ERROR) << "secdiscard failed";
565 success = false;
566 }
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000567 success &= recursiveDeleteKey(dir);
Paul Crowley1ef25582016-01-21 20:26:12 +0000568 return success;
569}
570
571} // namespace vold
572} // namespace android