blob: 7e0a66f9a7f55df6e3c15171836e24bbeafed314 [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 }
Shawn Willden8431fe22018-12-06 07:45:02 -0700126
127 auto paramsWithRollback = paramBuilder;
128 paramsWithRollback.Authorization(km::TAG_ROLLBACK_RESISTANCE);
129
130 // Generate rollback-resistant key if possible.
131 return keymaster.generateKey(paramsWithRollback, key) ||
132 keymaster.generateKey(paramBuilder, key);
Paul Crowley320e5e12016-03-04 14:07:05 -0800133}
134
Shawn Willden35351812018-01-22 09:08:32 -0700135static std::pair<km::AuthorizationSet, km::HardwareAuthToken> beginParams(
136 const KeyAuthentication& auth, const std::string& appId) {
137 auto paramBuilder = km::AuthorizationSetBuilder()
138 .GcmModeMacLen(GCM_MAC_BYTES * 8)
139 .Authorization(km::TAG_APPLICATION_ID, km::support::blob2hidlVec(appId));
140 km::HardwareAuthToken authToken;
Paul Crowley320e5e12016-03-04 14:07:05 -0800141 if (!auth.token.empty()) {
142 LOG(DEBUG) << "Supplying auth token to Keymaster";
Shawn Willden35351812018-01-22 09:08:32 -0700143 authToken = km::support::hidlVec2AuthToken(km::support::blob2hidlVec(auth.token));
Paul Crowley320e5e12016-03-04 14:07:05 -0800144 }
Shawn Willden35351812018-01-22 09:08:32 -0700145 return {paramBuilder, authToken};
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
Shawn Willden35351812018-01-22 09:08:32 -0700207static KeymasterOperation begin(Keymaster& keymaster, const std::string& dir,
208 km::KeyPurpose purpose, const km::AuthorizationSet& keyParams,
209 const km::AuthorizationSet& opParams,
210 const km::HardwareAuthToken& authToken,
211 km::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();
Shawn Willden35351812018-01-22 09:08:32 -0700215 km::AuthorizationSet inParams(keyParams);
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100216 inParams.append(opParams.begin(), opParams.end());
Paul Crowleydff8c722016-05-16 08:14:56 -0700217 for (;;) {
Shawn Willden35351812018-01-22 09:08:32 -0700218 auto opHandle = keymaster.begin(purpose, kmKey, inParams, authToken, outParams);
Paul Crowleydff8c722016-05-16 08:14:56 -0700219 if (opHandle) {
220 return opHandle;
221 }
Shawn Willden35351812018-01-22 09:08:32 -0700222 if (opHandle.errorCode() != km::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,
Shawn Willden35351812018-01-22 09:08:32 -0700241 const km::AuthorizationSet& keyParams,
242 const km::HardwareAuthToken& authToken,
243 const KeyBuffer& message, std::string* ciphertext) {
244 km::AuthorizationSet opParams;
245 km::AuthorizationSet outParams;
246 auto opHandle =
247 begin(keymaster, dir, km::KeyPurpose::ENCRYPT, keyParams, opParams, authToken, &outParams);
Paul Crowleydff8c722016-05-16 08:14:56 -0700248 if (!opHandle) return false;
Shawn Willden35351812018-01-22 09:08:32 -0700249 auto nonceBlob = outParams.GetTagValue(km::TAG_NONCE);
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100250 if (!nonceBlob.isOk()) {
Paul Crowleydff8c722016-05-16 08:14:56 -0700251 LOG(ERROR) << "GCM encryption but no nonce generated";
252 return false;
253 }
254 // nonceBlob here is just a pointer into existing data, must not be freed
Shawn Willden785365b2018-01-20 09:37:36 -0700255 std::string nonce(reinterpret_cast<const char*>(&nonceBlob.value()[0]),
256 nonceBlob.value().size());
Paul Crowleydff8c722016-05-16 08:14:56 -0700257 if (!checkSize("nonce", nonce.size(), GCM_NONCE_BYTES)) return false;
258 std::string body;
259 if (!opHandle.updateCompletely(message, &body)) return false;
260
261 std::string mac;
262 if (!opHandle.finish(&mac)) return false;
263 if (!checkSize("mac", mac.size(), GCM_MAC_BYTES)) return false;
264 *ciphertext = nonce + body + mac;
265 return true;
266}
267
268static bool decryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
Shawn Willden35351812018-01-22 09:08:32 -0700269 const km::AuthorizationSet& keyParams,
270 const km::HardwareAuthToken& authToken,
Pavel Grafove2e2d302017-08-01 17:15:53 +0100271 const std::string& ciphertext, KeyBuffer* message) {
Paul Crowleydff8c722016-05-16 08:14:56 -0700272 auto nonce = ciphertext.substr(0, GCM_NONCE_BYTES);
273 auto bodyAndMac = ciphertext.substr(GCM_NONCE_BYTES);
Shawn Willden35351812018-01-22 09:08:32 -0700274 auto opParams = km::AuthorizationSetBuilder().Authorization(km::TAG_NONCE,
275 km::support::blob2hidlVec(nonce));
276 auto opHandle =
277 begin(keymaster, dir, km::KeyPurpose::DECRYPT, keyParams, opParams, authToken, nullptr);
Paul Crowleydff8c722016-05-16 08:14:56 -0700278 if (!opHandle) return false;
279 if (!opHandle.updateCompletely(bodyAndMac, message)) return false;
280 if (!opHandle.finish(nullptr)) return false;
281 return true;
282}
283
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800284static std::string getStretching(const KeyAuthentication& auth) {
285 if (!auth.usesKeymaster()) {
286 return kStretch_none;
287 } else if (auth.secret.empty()) {
288 return kStretch_nopassword;
289 } else {
290 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000291
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800292 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
293 return std::string() + kStretchPrefix_scrypt + paramstr;
294 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000295}
296
Paul Crowleydf528a72016-03-09 09:31:37 -0800297static bool stretchingNeedsSalt(const std::string& stretching) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000298 return stretching != kStretch_nopassword && stretching != kStretch_none;
299}
300
Paul Crowleydf528a72016-03-09 09:31:37 -0800301static bool stretchSecret(const std::string& stretching, const std::string& secret,
302 const std::string& salt, std::string* stretched) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000303 if (stretching == kStretch_nopassword) {
304 if (!secret.empty()) {
Paul Crowleyd9b92952016-03-04 13:45:00 -0800305 LOG(WARNING) << "Password present but stretching is nopassword";
Paul Crowley63c18d32016-02-10 14:02:47 +0000306 // Continue anyway
307 }
Paul Crowleya051eb72016-03-08 16:08:32 -0800308 stretched->clear();
Paul Crowley63c18d32016-02-10 14:02:47 +0000309 } else if (stretching == kStretch_none) {
Paul Crowleya051eb72016-03-08 16:08:32 -0800310 *stretched = secret;
Paul Crowleydf528a72016-03-09 09:31:37 -0800311 } else if (std::equal(kStretchPrefix_scrypt.begin(), kStretchPrefix_scrypt.end(),
312 stretching.begin())) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000313 int Nf, rf, pf;
Paul Crowleydf528a72016-03-09 09:31:37 -0800314 if (!parse_scrypt_parameters(stretching.substr(kStretchPrefix_scrypt.size()).c_str(), &Nf,
315 &rf, &pf)) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000316 LOG(ERROR) << "Unable to parse scrypt params in stretching: " << stretching;
317 return false;
318 }
Paul Crowleya051eb72016-03-08 16:08:32 -0800319 stretched->assign(STRETCHED_BYTES, '\0');
Paul Crowleydf528a72016-03-09 09:31:37 -0800320 if (crypto_scrypt(reinterpret_cast<const uint8_t*>(secret.data()), secret.size(),
Shawn Willden785365b2018-01-20 09:37:36 -0700321 reinterpret_cast<const uint8_t*>(salt.data()), salt.size(), 1 << Nf,
322 1 << rf, 1 << pf, reinterpret_cast<uint8_t*>(&(*stretched)[0]),
323 stretched->size()) != 0) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000324 LOG(ERROR) << "scrypt failed with params: " << stretching;
325 return false;
326 }
327 } else {
328 LOG(ERROR) << "Unknown stretching type: " << stretching;
329 return false;
330 }
331 return true;
332}
333
Paul Crowleydf528a72016-03-09 09:31:37 -0800334static bool generateAppId(const KeyAuthentication& auth, const std::string& stretching,
Paul Crowley26a53882017-10-26 11:16:39 -0700335 const std::string& salt, const std::string& secdiscardable_hash,
Paul Crowleydf528a72016-03-09 09:31:37 -0800336 std::string* appId) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000337 std::string stretched;
Paul Crowleya051eb72016-03-08 16:08:32 -0800338 if (!stretchSecret(stretching, auth.secret, salt, &stretched)) return false;
Paul Crowley26a53882017-10-26 11:16:39 -0700339 *appId = secdiscardable_hash + stretched;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800340 return true;
341}
342
343static void logOpensslError() {
344 LOG(ERROR) << "Openssl error: " << ERR_get_error();
345}
346
Shawn Willden785365b2018-01-20 09:37:36 -0700347static bool encryptWithoutKeymaster(const std::string& preKey, const KeyBuffer& plaintext,
348 std::string* ciphertext) {
Paul Crowley26a53882017-10-26 11:16:39 -0700349 std::string key;
350 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800351 key.resize(AES_KEY_BYTES);
352 if (!readRandomBytesOrLog(GCM_NONCE_BYTES, ciphertext)) return false;
353 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
354 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
355 if (!ctx) {
356 logOpensslError();
357 return false;
358 }
359 if (1 != EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
Shawn Willden785365b2018-01-20 09:37:36 -0700360 reinterpret_cast<const uint8_t*>(key.data()),
361 reinterpret_cast<const uint8_t*>(ciphertext->data()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800362 logOpensslError();
363 return false;
364 }
365 ciphertext->resize(GCM_NONCE_BYTES + plaintext.size() + GCM_MAC_BYTES);
366 int outlen;
Shawn Willden785365b2018-01-20 09:37:36 -0700367 if (1 != EVP_EncryptUpdate(
368 ctx.get(), reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES),
369 &outlen, reinterpret_cast<const uint8_t*>(plaintext.data()), plaintext.size())) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800370 logOpensslError();
371 return false;
372 }
373 if (outlen != static_cast<int>(plaintext.size())) {
374 LOG(ERROR) << "GCM ciphertext length should be " << plaintext.size() << " was " << outlen;
375 return false;
376 }
Shawn Willden785365b2018-01-20 09:37:36 -0700377 if (1 != EVP_EncryptFinal_ex(
378 ctx.get(),
379 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES + plaintext.size()),
380 &outlen)) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800381 logOpensslError();
382 return false;
383 }
384 if (outlen != 0) {
385 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
386 return false;
387 }
388 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, GCM_MAC_BYTES,
Shawn Willden785365b2018-01-20 09:37:36 -0700389 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES +
390 plaintext.size()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800391 logOpensslError();
392 return false;
393 }
394 return true;
395}
396
Shawn Willden785365b2018-01-20 09:37:36 -0700397static bool decryptWithoutKeymaster(const std::string& preKey, const std::string& ciphertext,
398 KeyBuffer* plaintext) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800399 if (ciphertext.size() < GCM_NONCE_BYTES + GCM_MAC_BYTES) {
400 LOG(ERROR) << "GCM ciphertext too small: " << ciphertext.size();
401 return false;
402 }
Paul Crowley26a53882017-10-26 11:16:39 -0700403 std::string key;
404 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800405 key.resize(AES_KEY_BYTES);
406 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
407 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
408 if (!ctx) {
409 logOpensslError();
410 return false;
411 }
412 if (1 != EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
Shawn Willden785365b2018-01-20 09:37:36 -0700413 reinterpret_cast<const uint8_t*>(key.data()),
414 reinterpret_cast<const uint8_t*>(ciphertext.data()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800415 logOpensslError();
416 return false;
417 }
Pavel Grafove2e2d302017-08-01 17:15:53 +0100418 *plaintext = KeyBuffer(ciphertext.size() - GCM_NONCE_BYTES - GCM_MAC_BYTES);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800419 int outlen;
Shawn Willden785365b2018-01-20 09:37:36 -0700420 if (1 != EVP_DecryptUpdate(ctx.get(), reinterpret_cast<uint8_t*>(&(*plaintext)[0]), &outlen,
421 reinterpret_cast<const uint8_t*>(ciphertext.data() + GCM_NONCE_BYTES),
422 plaintext->size())) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800423 logOpensslError();
424 return false;
425 }
426 if (outlen != static_cast<int>(plaintext->size())) {
427 LOG(ERROR) << "GCM plaintext length should be " << plaintext->size() << " was " << outlen;
428 return false;
429 }
430 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, GCM_MAC_BYTES,
Shawn Willden785365b2018-01-20 09:37:36 -0700431 const_cast<void*>(reinterpret_cast<const void*>(
432 ciphertext.data() + GCM_NONCE_BYTES + plaintext->size())))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800433 logOpensslError();
434 return false;
435 }
436 if (1 != EVP_DecryptFinal_ex(ctx.get(),
Shawn Willden785365b2018-01-20 09:37:36 -0700437 reinterpret_cast<uint8_t*>(&(*plaintext)[0] + plaintext->size()),
438 &outlen)) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800439 logOpensslError();
440 return false;
441 }
442 if (outlen != 0) {
443 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
444 return false;
445 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000446 return true;
Paul Crowley05720802016-02-08 15:55:41 +0000447}
448
Paul Crowleyf71ace32016-06-02 11:01:19 -0700449bool pathExists(const std::string& path) {
450 return access(path.c_str(), F_OK) == 0;
451}
452
Pavel Grafove2e2d302017-08-01 17:15:53 +0100453bool storeKey(const std::string& dir, const KeyAuthentication& auth, const KeyBuffer& key) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000454 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), 0700)) == -1) {
455 PLOG(ERROR) << "key mkdir " << dir;
456 return false;
457 }
Paul Crowleydf528a72016-03-09 09:31:37 -0800458 if (!writeStringToFile(kCurrentVersion, dir + "/" + kFn_version)) return false;
Paul Crowley26a53882017-10-26 11:16:39 -0700459 std::string secdiscardable_hash;
460 if (!createSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800461 std::string stretching = getStretching(auth);
Paul Crowleydf528a72016-03-09 09:31:37 -0800462 if (!writeStringToFile(stretching, dir + "/" + kFn_stretching)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000463 std::string salt;
464 if (stretchingNeedsSalt(stretching)) {
465 if (ReadRandomBytes(SALT_BYTES, salt) != OK) {
466 LOG(ERROR) << "Random read failed";
467 return false;
468 }
Paul Crowleydf528a72016-03-09 09:31:37 -0800469 if (!writeStringToFile(salt, dir + "/" + kFn_salt)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000470 }
Paul Crowley320e5e12016-03-04 14:07:05 -0800471 std::string appId;
Paul Crowley26a53882017-10-26 11:16:39 -0700472 if (!generateAppId(auth, stretching, salt, secdiscardable_hash, &appId)) return false;
Paul Crowley320e5e12016-03-04 14:07:05 -0800473 std::string encryptedKey;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800474 if (auth.usesKeymaster()) {
475 Keymaster keymaster;
476 if (!keymaster) return false;
477 std::string kmKey;
478 if (!generateKeymasterKey(keymaster, auth, appId, &kmKey)) return false;
479 if (!writeStringToFile(kmKey, dir + "/" + kFn_keymaster_key_blob)) return false;
Shawn Willden35351812018-01-22 09:08:32 -0700480 km::AuthorizationSet keyParams;
481 km::HardwareAuthToken authToken;
482 std::tie(keyParams, authToken) = beginParams(auth, appId);
483 if (!encryptWithKeymasterKey(keymaster, dir, keyParams, authToken, key, &encryptedKey))
484 return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800485 } else {
486 if (!encryptWithoutKeymaster(appId, key, &encryptedKey)) return false;
487 }
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000488 if (!writeStringToFile(encryptedKey, dir + "/" + kFn_encrypted_key)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000489 return true;
490}
491
Paul Crowleyf71ace32016-06-02 11:01:19 -0700492bool storeKeyAtomically(const std::string& key_path, const std::string& tmp_path,
Pavel Grafove2e2d302017-08-01 17:15:53 +0100493 const KeyAuthentication& auth, const KeyBuffer& key) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700494 if (pathExists(key_path)) {
495 LOG(ERROR) << "Already exists, cannot create key at: " << key_path;
496 return false;
497 }
498 if (pathExists(tmp_path)) {
499 LOG(DEBUG) << "Already exists, destroying: " << tmp_path;
500 destroyKey(tmp_path); // May be partially created so ignore errors
501 }
502 if (!storeKey(tmp_path, auth, key)) return false;
503 if (rename(tmp_path.c_str(), key_path.c_str()) != 0) {
504 PLOG(ERROR) << "Unable to move new key to location: " << key_path;
505 return false;
506 }
507 LOG(DEBUG) << "Created key: " << key_path;
508 return true;
509}
510
Pavel Grafove2e2d302017-08-01 17:15:53 +0100511bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, KeyBuffer* key) {
Paul Crowley05720802016-02-08 15:55:41 +0000512 std::string version;
Paul Crowleya051eb72016-03-08 16:08:32 -0800513 if (!readFileToString(dir + "/" + kFn_version, &version)) return false;
Paul Crowley05720802016-02-08 15:55:41 +0000514 if (version != kCurrentVersion) {
515 LOG(ERROR) << "Version mismatch, expected " << kCurrentVersion << " got " << version;
516 return false;
517 }
Paul Crowley26a53882017-10-26 11:16:39 -0700518 std::string secdiscardable_hash;
519 if (!readSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000520 std::string stretching;
Paul Crowleya051eb72016-03-08 16:08:32 -0800521 if (!readFileToString(dir + "/" + kFn_stretching, &stretching)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000522 std::string salt;
523 if (stretchingNeedsSalt(stretching)) {
Paul Crowleydf528a72016-03-09 09:31:37 -0800524 if (!readFileToString(dir + "/" + kFn_salt, &salt)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000525 }
Paul Crowley320e5e12016-03-04 14:07:05 -0800526 std::string appId;
Paul Crowley26a53882017-10-26 11:16:39 -0700527 if (!generateAppId(auth, stretching, salt, secdiscardable_hash, &appId)) return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000528 std::string encryptedMessage;
Paul Crowleya051eb72016-03-08 16:08:32 -0800529 if (!readFileToString(dir + "/" + kFn_encrypted_key, &encryptedMessage)) return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800530 if (auth.usesKeymaster()) {
531 Keymaster keymaster;
532 if (!keymaster) return false;
Shawn Willden35351812018-01-22 09:08:32 -0700533 km::AuthorizationSet keyParams;
534 km::HardwareAuthToken authToken;
535 std::tie(keyParams, authToken) = beginParams(auth, appId);
536 if (!decryptWithKeymasterKey(keymaster, dir, keyParams, authToken, encryptedMessage, key))
Shawn Willden785365b2018-01-20 09:37:36 -0700537 return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800538 } else {
539 if (!decryptWithoutKeymaster(appId, encryptedMessage, key)) return false;
540 }
541 return true;
Paul Crowley1ef25582016-01-21 20:26:12 +0000542}
543
Paul Crowleydf528a72016-03-09 09:31:37 -0800544static bool deleteKey(const std::string& dir) {
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000545 std::string kmKey;
Paul Crowleya051eb72016-03-08 16:08:32 -0800546 if (!readFileToString(dir + "/" + kFn_keymaster_key_blob, &kmKey)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000547 Keymaster keymaster;
548 if (!keymaster) return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000549 if (!keymaster.deleteKey(kmKey)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000550 return true;
551}
552
Rubin Xu2436e272017-04-27 20:43:10 +0100553bool runSecdiscardSingle(const std::string& file) {
Shawn Willden785365b2018-01-20 09:37:36 -0700554 if (ForkExecvp(std::vector<std::string>{kSecdiscardPath, "--", file}) != 0) {
Rubin Xu2436e272017-04-27 20:43:10 +0100555 LOG(ERROR) << "secdiscard failed";
556 return false;
557 }
558 return true;
559}
560
Paul Crowleydf528a72016-03-09 09:31:37 -0800561static bool recursiveDeleteKey(const std::string& dir) {
562 if (ForkExecvp(std::vector<std::string>{kRmPath, "-rf", dir}) != 0) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000563 LOG(ERROR) << "recursive delete failed";
564 return false;
565 }
566 return true;
567}
568
Paul Crowleydf528a72016-03-09 09:31:37 -0800569bool destroyKey(const std::string& dir) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000570 bool success = true;
571 // Try each thing, even if previous things failed.
Paul Crowleyff19b052017-10-26 11:28:55 -0700572 bool uses_km = pathExists(dir + "/" + kFn_keymaster_key_blob);
573 if (uses_km) {
574 success &= deleteKey(dir);
575 }
576 auto secdiscard_cmd = std::vector<std::string>{
Paul Crowley14c8c072018-09-18 13:30:21 -0700577 kSecdiscardPath,
578 "--",
579 dir + "/" + kFn_encrypted_key,
580 dir + "/" + kFn_secdiscardable,
Paul Crowleyff19b052017-10-26 11:28:55 -0700581 };
582 if (uses_km) {
583 secdiscard_cmd.emplace_back(dir + "/" + kFn_keymaster_key_blob);
584 }
585 if (ForkExecvp(secdiscard_cmd) != 0) {
586 LOG(ERROR) << "secdiscard failed";
587 success = false;
588 }
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000589 success &= recursiveDeleteKey(dir);
Paul Crowley1ef25582016-01-21 20:26:12 +0000590 return success;
591}
592
593} // namespace vold
594} // namespace android