blob: a7582c29e18ed4576990e62f9a299ec721df637a [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
Daniel Rosenbergd2906b82019-06-07 14:18:14 -070019#include "Checkpoint.h"
Paul Crowley1ef25582016-01-21 20:26:12 +000020#include "Keymaster.h"
Paul Crowley63c18d32016-02-10 14:02:47 +000021#include "ScryptParameters.h"
Paul Crowley1ef25582016-01-21 20:26:12 +000022#include "Utils.h"
23
Daniel Rosenberga48730a2019-06-06 20:38:38 -070024#include <thread>
Paul Crowley1ef25582016-01-21 20:26:12 +000025#include <vector>
26
27#include <errno.h>
Paul Crowleydff8c722016-05-16 08:14:56 -070028#include <stdio.h>
Paul Crowley1ef25582016-01-21 20:26:12 +000029#include <sys/stat.h>
30#include <sys/types.h>
31#include <sys/wait.h>
32#include <unistd.h>
33
Paul Crowley6ab2cab2017-01-04 22:32:40 -080034#include <openssl/err.h>
35#include <openssl/evp.h>
Paul Crowley1ef25582016-01-21 20:26:12 +000036#include <openssl/sha.h>
37
38#include <android-base/file.h>
39#include <android-base/logging.h>
Daniel Rosenberga48730a2019-06-06 20:38:38 -070040#include <android-base/properties.h>
Daniel Rosenbergd2906b82019-06-07 14:18:14 -070041#include <android-base/unique_fd.h>
Paul Crowley1ef25582016-01-21 20:26:12 +000042
Paul Crowley63c18d32016-02-10 14:02:47 +000043#include <cutils/properties.h>
44
Paul Crowley320e5e12016-03-04 14:07:05 -080045#include <hardware/hw_auth_token.h>
Shawn Willden35f0f222020-01-16 13:21:42 -070046#include <keymasterV4_1/authorization_set.h>
47#include <keymasterV4_1/keymaster_utils.h>
Paul Crowley320e5e12016-03-04 14:07:05 -080048
Paul Crowley63c18d32016-02-10 14:02:47 +000049extern "C" {
50
51#include "crypto_scrypt.h"
Paul Crowley63c18d32016-02-10 14:02:47 +000052}
53
Paul Crowley1ef25582016-01-21 20:26:12 +000054namespace android {
55namespace vold {
56
Paul Crowleydf528a72016-03-09 09:31:37 -080057const KeyAuthentication kEmptyAuthentication{"", ""};
Paul Crowley05720802016-02-08 15:55:41 +000058
Paul Crowley1ef25582016-01-21 20:26:12 +000059static constexpr size_t AES_KEY_BYTES = 32;
60static constexpr size_t GCM_NONCE_BYTES = 12;
61static constexpr size_t GCM_MAC_BYTES = 16;
Paul Crowleydf528a72016-03-09 09:31:37 -080062static constexpr size_t SALT_BYTES = 1 << 4;
63static constexpr size_t SECDISCARDABLE_BYTES = 1 << 14;
64static constexpr size_t STRETCHED_BYTES = 1 << 6;
Paul Crowley1ef25582016-01-21 20:26:12 +000065
Shawn Willden785365b2018-01-20 09:37:36 -070066static constexpr uint32_t AUTH_TIMEOUT = 30; // Seconds
Paul Crowleyb3de3372016-04-27 12:58:41 -070067
Paul Crowley05720802016-02-08 15:55:41 +000068static const char* kCurrentVersion = "1";
Paul Crowley1ef25582016-01-21 20:26:12 +000069static const char* kRmPath = "/system/bin/rm";
70static const char* kSecdiscardPath = "/system/bin/secdiscard";
Paul Crowley63c18d32016-02-10 14:02:47 +000071static const char* kStretch_none = "none";
72static const char* kStretch_nopassword = "nopassword";
73static const std::string kStretchPrefix_scrypt = "scrypt ";
Paul Crowley6ab2cab2017-01-04 22:32:40 -080074static const char* kHashPrefix_secdiscardable = "Android secdiscardable SHA512";
75static const char* kHashPrefix_keygen = "Android key wrapping key generation SHA512";
Paul Crowley1ef25582016-01-21 20:26:12 +000076static const char* kFn_encrypted_key = "encrypted_key";
Paul Crowley05720802016-02-08 15:55:41 +000077static const char* kFn_keymaster_key_blob = "keymaster_key_blob";
Paul Crowleydff8c722016-05-16 08:14:56 -070078static const char* kFn_keymaster_key_blob_upgraded = "keymaster_key_blob_upgraded";
Paul Crowley63c18d32016-02-10 14:02:47 +000079static const char* kFn_salt = "salt";
Paul Crowley1ef25582016-01-21 20:26:12 +000080static const char* kFn_secdiscardable = "secdiscardable";
Paul Crowley05720802016-02-08 15:55:41 +000081static const char* kFn_stretching = "stretching";
82static const char* kFn_version = "version";
Paul Crowley1ef25582016-01-21 20:26:12 +000083
Paul Crowley13ffd8e2016-01-27 14:30:22 +000084static bool checkSize(const std::string& kind, size_t actual, size_t expected) {
Paul Crowley1ef25582016-01-21 20:26:12 +000085 if (actual != expected) {
Paul Crowleydf528a72016-03-09 09:31:37 -080086 LOG(ERROR) << "Wrong number of bytes in " << kind << ", expected " << expected << " got "
87 << actual;
Paul Crowley1ef25582016-01-21 20:26:12 +000088 return false;
89 }
90 return true;
91}
92
Paul Crowley26a53882017-10-26 11:16:39 -070093static void hashWithPrefix(char const* prefix, const std::string& tohash, std::string* res) {
Paul Crowley1ef25582016-01-21 20:26:12 +000094 SHA512_CTX c;
95
96 SHA512_Init(&c);
97 // Personalise the hashing by introducing a fixed prefix.
98 // Hashing applications should use personalization except when there is a
99 // specific reason not to; see section 4.11 of https://www.schneier.com/skein1.3.pdf
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800100 std::string hashingPrefix = prefix;
101 hashingPrefix.resize(SHA512_CBLOCK);
102 SHA512_Update(&c, hashingPrefix.data(), hashingPrefix.size());
103 SHA512_Update(&c, tohash.data(), tohash.size());
Paul Crowley26a53882017-10-26 11:16:39 -0700104 res->assign(SHA512_DIGEST_LENGTH, '\0');
105 SHA512_Final(reinterpret_cast<uint8_t*>(&(*res)[0]), &c);
Paul Crowley1ef25582016-01-21 20:26:12 +0000106}
107
Paul Crowleydf528a72016-03-09 09:31:37 -0800108static bool generateKeymasterKey(Keymaster& keymaster, const KeyAuthentication& auth,
109 const std::string& appId, std::string* key) {
Shawn Willden35351812018-01-22 09:08:32 -0700110 auto paramBuilder = km::AuthorizationSetBuilder()
Paul Crowleydf528a72016-03-09 09:31:37 -0800111 .AesEncryptionKey(AES_KEY_BYTES * 8)
Shawn Willden35351812018-01-22 09:08:32 -0700112 .GcmModeMinMacLen(GCM_MAC_BYTES * 8)
113 .Authorization(km::TAG_APPLICATION_ID, km::support::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";
Shawn Willden35351812018-01-22 09:08:32 -0700116 paramBuilder.Authorization(km::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());
Shawn Willden35351812018-01-22 09:08:32 -0700125 paramBuilder.Authorization(km::TAG_USER_SECURE_ID, at->user_id);
126 paramBuilder.Authorization(km::TAG_USER_AUTH_TYPE, km::HardwareAuthenticatorType::PASSWORD);
127 paramBuilder.Authorization(km::TAG_AUTH_TIMEOUT, AUTH_TIMEOUT);
Paul Crowley320e5e12016-03-04 14:07:05 -0800128 }
Shawn Willden8431fe22018-12-06 07:45:02 -0700129
130 auto paramsWithRollback = paramBuilder;
131 paramsWithRollback.Authorization(km::TAG_ROLLBACK_RESISTANCE);
132
133 // Generate rollback-resistant key if possible.
134 return keymaster.generateKey(paramsWithRollback, key) ||
135 keymaster.generateKey(paramBuilder, key);
Paul Crowley320e5e12016-03-04 14:07:05 -0800136}
137
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800138bool generateWrappedStorageKey(KeyBuffer* key) {
139 Keymaster keymaster;
140 if (!keymaster) return false;
141 std::string key_temp;
142 auto paramBuilder = km::AuthorizationSetBuilder().AesEncryptionKey(AES_KEY_BYTES * 8);
143 paramBuilder.Authorization(km::TAG_ROLLBACK_RESISTANCE);
144 paramBuilder.Authorization(km::TAG_STORAGE_KEY);
145 if (!keymaster.generateKey(paramBuilder, &key_temp)) return false;
146 *key = KeyBuffer(key_temp.size());
147 memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
148 return true;
149}
150
151bool exportWrappedStorageKey(const KeyBuffer& kmKey, KeyBuffer* key) {
152 Keymaster keymaster;
153 if (!keymaster) return false;
154 std::string key_temp;
155
156 if (!keymaster.exportKey(kmKey, &key_temp)) return false;
157 *key = KeyBuffer(key_temp.size());
158 memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
159 return true;
160}
161
Shawn Willden35351812018-01-22 09:08:32 -0700162static std::pair<km::AuthorizationSet, km::HardwareAuthToken> beginParams(
163 const KeyAuthentication& auth, const std::string& appId) {
164 auto paramBuilder = km::AuthorizationSetBuilder()
165 .GcmModeMacLen(GCM_MAC_BYTES * 8)
166 .Authorization(km::TAG_APPLICATION_ID, km::support::blob2hidlVec(appId));
167 km::HardwareAuthToken authToken;
Paul Crowley320e5e12016-03-04 14:07:05 -0800168 if (!auth.token.empty()) {
169 LOG(DEBUG) << "Supplying auth token to Keymaster";
Shawn Willden35351812018-01-22 09:08:32 -0700170 authToken = km::support::hidlVec2AuthToken(km::support::blob2hidlVec(auth.token));
Paul Crowley320e5e12016-03-04 14:07:05 -0800171 }
Shawn Willden35351812018-01-22 09:08:32 -0700172 return {paramBuilder, authToken};
Paul Crowley1ef25582016-01-21 20:26:12 +0000173}
174
Paul Crowleydf528a72016-03-09 09:31:37 -0800175static bool readFileToString(const std::string& filename, std::string* result) {
Paul Crowleya051eb72016-03-08 16:08:32 -0800176 if (!android::base::ReadFileToString(filename, result)) {
Paul Crowleydf528a72016-03-09 09:31:37 -0800177 PLOG(ERROR) << "Failed to read from " << filename;
178 return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000179 }
180 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
Daniel Rosenberga48730a2019-06-06 20:38:38 -0700207static void deferedKmDeleteKey(const std::string& kmkey) {
208 while (!android::base::WaitForProperty("vold.checkpoint_committed", "1")) {
209 LOG(ERROR) << "Wait for boot timed out";
210 }
211 Keymaster keymaster;
212 if (!keymaster || !keymaster.deleteKey(kmkey)) {
213 LOG(ERROR) << "Defered Key deletion failed during upgrade";
214 }
215}
216
217bool kmDeleteKey(Keymaster& keymaster, const std::string& kmKey) {
218 bool needs_cp = cp_needsCheckpoint();
219
220 if (needs_cp) {
221 std::thread(deferedKmDeleteKey, kmKey).detach();
222 LOG(INFO) << "Deferring Key deletion during upgrade";
223 return true;
224 } else {
225 return keymaster.deleteKey(kmKey);
226 }
227}
228
Shawn Willden35351812018-01-22 09:08:32 -0700229static KeymasterOperation begin(Keymaster& keymaster, const std::string& dir,
230 km::KeyPurpose purpose, const km::AuthorizationSet& keyParams,
231 const km::AuthorizationSet& opParams,
232 const km::HardwareAuthToken& authToken,
Daniel Rosenberg690d6de2018-12-14 01:08:10 -0800233 km::AuthorizationSet* outParams, bool keepOld) {
Paul Crowleydff8c722016-05-16 08:14:56 -0700234 auto kmKeyPath = dir + "/" + kFn_keymaster_key_blob;
235 std::string kmKey;
236 if (!readFileToString(kmKeyPath, &kmKey)) return KeymasterOperation();
Shawn Willden35351812018-01-22 09:08:32 -0700237 km::AuthorizationSet inParams(keyParams);
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100238 inParams.append(opParams.begin(), opParams.end());
Paul Crowleydff8c722016-05-16 08:14:56 -0700239 for (;;) {
Shawn Willden35351812018-01-22 09:08:32 -0700240 auto opHandle = keymaster.begin(purpose, kmKey, inParams, authToken, outParams);
Paul Crowleydff8c722016-05-16 08:14:56 -0700241 if (opHandle) {
242 return opHandle;
243 }
Shawn Willden35351812018-01-22 09:08:32 -0700244 if (opHandle.errorCode() != km::ErrorCode::KEY_REQUIRES_UPGRADE) return opHandle;
Paul Crowleydff8c722016-05-16 08:14:56 -0700245 LOG(DEBUG) << "Upgrading key: " << dir;
246 std::string newKey;
247 if (!keymaster.upgradeKey(kmKey, keyParams, &newKey)) return KeymasterOperation();
248 auto newKeyPath = dir + "/" + kFn_keymaster_key_blob_upgraded;
249 if (!writeStringToFile(newKey, newKeyPath)) return KeymasterOperation();
Daniel Rosenberg690d6de2018-12-14 01:08:10 -0800250 if (!keepOld) {
251 if (rename(newKeyPath.c_str(), kmKeyPath.c_str()) != 0) {
252 PLOG(ERROR) << "Unable to move upgraded key to location: " << kmKeyPath;
253 return KeymasterOperation();
254 }
Woody Lin37c82f52019-03-11 20:58:20 +0800255 if (!android::vold::FsyncDirectory(dir)) {
256 LOG(ERROR) << "Key dir sync failed: " << dir;
257 return KeymasterOperation();
258 }
Daniel Rosenberga48730a2019-06-06 20:38:38 -0700259 if (!kmDeleteKey(keymaster, kmKey)) {
Daniel Rosenberg690d6de2018-12-14 01:08:10 -0800260 LOG(ERROR) << "Key deletion failed during upgrade, continuing anyway: " << dir;
261 }
Paul Crowleydff8c722016-05-16 08:14:56 -0700262 }
263 kmKey = newKey;
264 LOG(INFO) << "Key upgraded: " << dir;
265 }
266}
267
268static bool encryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
Shawn Willden35351812018-01-22 09:08:32 -0700269 const km::AuthorizationSet& keyParams,
Daniel Rosenberg690d6de2018-12-14 01:08:10 -0800270 const km::HardwareAuthToken& authToken, const KeyBuffer& message,
271 std::string* ciphertext, bool keepOld) {
Shawn Willden35351812018-01-22 09:08:32 -0700272 km::AuthorizationSet opParams;
273 km::AuthorizationSet outParams;
Daniel Rosenberg690d6de2018-12-14 01:08:10 -0800274 auto opHandle = begin(keymaster, dir, km::KeyPurpose::ENCRYPT, keyParams, opParams, authToken,
275 &outParams, keepOld);
Paul Crowleydff8c722016-05-16 08:14:56 -0700276 if (!opHandle) return false;
Shawn Willden35351812018-01-22 09:08:32 -0700277 auto nonceBlob = outParams.GetTagValue(km::TAG_NONCE);
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100278 if (!nonceBlob.isOk()) {
Paul Crowleydff8c722016-05-16 08:14:56 -0700279 LOG(ERROR) << "GCM encryption but no nonce generated";
280 return false;
281 }
282 // nonceBlob here is just a pointer into existing data, must not be freed
Shawn Willden785365b2018-01-20 09:37:36 -0700283 std::string nonce(reinterpret_cast<const char*>(&nonceBlob.value()[0]),
284 nonceBlob.value().size());
Paul Crowleydff8c722016-05-16 08:14:56 -0700285 if (!checkSize("nonce", nonce.size(), GCM_NONCE_BYTES)) return false;
286 std::string body;
287 if (!opHandle.updateCompletely(message, &body)) return false;
288
289 std::string mac;
290 if (!opHandle.finish(&mac)) return false;
291 if (!checkSize("mac", mac.size(), GCM_MAC_BYTES)) return false;
292 *ciphertext = nonce + body + mac;
293 return true;
294}
295
296static bool decryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
Shawn Willden35351812018-01-22 09:08:32 -0700297 const km::AuthorizationSet& keyParams,
298 const km::HardwareAuthToken& authToken,
Daniel Rosenberg690d6de2018-12-14 01:08:10 -0800299 const std::string& ciphertext, KeyBuffer* message,
300 bool keepOld) {
Paul Crowleydff8c722016-05-16 08:14:56 -0700301 auto nonce = ciphertext.substr(0, GCM_NONCE_BYTES);
302 auto bodyAndMac = ciphertext.substr(GCM_NONCE_BYTES);
Shawn Willden35351812018-01-22 09:08:32 -0700303 auto opParams = km::AuthorizationSetBuilder().Authorization(km::TAG_NONCE,
304 km::support::blob2hidlVec(nonce));
Daniel Rosenberg690d6de2018-12-14 01:08:10 -0800305 auto opHandle = begin(keymaster, dir, km::KeyPurpose::DECRYPT, keyParams, opParams, authToken,
306 nullptr, keepOld);
Paul Crowleydff8c722016-05-16 08:14:56 -0700307 if (!opHandle) return false;
308 if (!opHandle.updateCompletely(bodyAndMac, message)) return false;
309 if (!opHandle.finish(nullptr)) return false;
310 return true;
311}
312
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800313static std::string getStretching(const KeyAuthentication& auth) {
314 if (!auth.usesKeymaster()) {
315 return kStretch_none;
316 } else if (auth.secret.empty()) {
317 return kStretch_nopassword;
318 } else {
319 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000320
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800321 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
322 return std::string() + kStretchPrefix_scrypt + paramstr;
323 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000324}
325
Paul Crowleydf528a72016-03-09 09:31:37 -0800326static bool stretchingNeedsSalt(const std::string& stretching) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000327 return stretching != kStretch_nopassword && stretching != kStretch_none;
328}
329
Paul Crowleydf528a72016-03-09 09:31:37 -0800330static bool stretchSecret(const std::string& stretching, const std::string& secret,
331 const std::string& salt, std::string* stretched) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000332 if (stretching == kStretch_nopassword) {
333 if (!secret.empty()) {
Paul Crowleyd9b92952016-03-04 13:45:00 -0800334 LOG(WARNING) << "Password present but stretching is nopassword";
Paul Crowley63c18d32016-02-10 14:02:47 +0000335 // Continue anyway
336 }
Paul Crowleya051eb72016-03-08 16:08:32 -0800337 stretched->clear();
Paul Crowley63c18d32016-02-10 14:02:47 +0000338 } else if (stretching == kStretch_none) {
Paul Crowleya051eb72016-03-08 16:08:32 -0800339 *stretched = secret;
Paul Crowleydf528a72016-03-09 09:31:37 -0800340 } else if (std::equal(kStretchPrefix_scrypt.begin(), kStretchPrefix_scrypt.end(),
341 stretching.begin())) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000342 int Nf, rf, pf;
Paul Crowleydf528a72016-03-09 09:31:37 -0800343 if (!parse_scrypt_parameters(stretching.substr(kStretchPrefix_scrypt.size()).c_str(), &Nf,
344 &rf, &pf)) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000345 LOG(ERROR) << "Unable to parse scrypt params in stretching: " << stretching;
346 return false;
347 }
Paul Crowleya051eb72016-03-08 16:08:32 -0800348 stretched->assign(STRETCHED_BYTES, '\0');
Paul Crowleydf528a72016-03-09 09:31:37 -0800349 if (crypto_scrypt(reinterpret_cast<const uint8_t*>(secret.data()), secret.size(),
Shawn Willden785365b2018-01-20 09:37:36 -0700350 reinterpret_cast<const uint8_t*>(salt.data()), salt.size(), 1 << Nf,
351 1 << rf, 1 << pf, reinterpret_cast<uint8_t*>(&(*stretched)[0]),
352 stretched->size()) != 0) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000353 LOG(ERROR) << "scrypt failed with params: " << stretching;
354 return false;
355 }
356 } else {
357 LOG(ERROR) << "Unknown stretching type: " << stretching;
358 return false;
359 }
360 return true;
361}
362
Paul Crowleydf528a72016-03-09 09:31:37 -0800363static bool generateAppId(const KeyAuthentication& auth, const std::string& stretching,
Paul Crowley26a53882017-10-26 11:16:39 -0700364 const std::string& salt, const std::string& secdiscardable_hash,
Paul Crowleydf528a72016-03-09 09:31:37 -0800365 std::string* appId) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000366 std::string stretched;
Paul Crowleya051eb72016-03-08 16:08:32 -0800367 if (!stretchSecret(stretching, auth.secret, salt, &stretched)) return false;
Paul Crowley26a53882017-10-26 11:16:39 -0700368 *appId = secdiscardable_hash + stretched;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800369 return true;
370}
371
372static void logOpensslError() {
373 LOG(ERROR) << "Openssl error: " << ERR_get_error();
374}
375
Shawn Willden785365b2018-01-20 09:37:36 -0700376static bool encryptWithoutKeymaster(const std::string& preKey, const KeyBuffer& plaintext,
377 std::string* ciphertext) {
Paul Crowley26a53882017-10-26 11:16:39 -0700378 std::string key;
379 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800380 key.resize(AES_KEY_BYTES);
381 if (!readRandomBytesOrLog(GCM_NONCE_BYTES, ciphertext)) return false;
382 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
383 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
384 if (!ctx) {
385 logOpensslError();
386 return false;
387 }
388 if (1 != EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
Shawn Willden785365b2018-01-20 09:37:36 -0700389 reinterpret_cast<const uint8_t*>(key.data()),
390 reinterpret_cast<const uint8_t*>(ciphertext->data()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800391 logOpensslError();
392 return false;
393 }
394 ciphertext->resize(GCM_NONCE_BYTES + plaintext.size() + GCM_MAC_BYTES);
395 int outlen;
Shawn Willden785365b2018-01-20 09:37:36 -0700396 if (1 != EVP_EncryptUpdate(
397 ctx.get(), reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES),
398 &outlen, reinterpret_cast<const uint8_t*>(plaintext.data()), plaintext.size())) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800399 logOpensslError();
400 return false;
401 }
402 if (outlen != static_cast<int>(plaintext.size())) {
403 LOG(ERROR) << "GCM ciphertext length should be " << plaintext.size() << " was " << outlen;
404 return false;
405 }
Shawn Willden785365b2018-01-20 09:37:36 -0700406 if (1 != EVP_EncryptFinal_ex(
407 ctx.get(),
408 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES + plaintext.size()),
409 &outlen)) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800410 logOpensslError();
411 return false;
412 }
413 if (outlen != 0) {
414 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
415 return false;
416 }
417 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, GCM_MAC_BYTES,
Shawn Willden785365b2018-01-20 09:37:36 -0700418 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES +
419 plaintext.size()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800420 logOpensslError();
421 return false;
422 }
423 return true;
424}
425
Shawn Willden785365b2018-01-20 09:37:36 -0700426static bool decryptWithoutKeymaster(const std::string& preKey, const std::string& ciphertext,
427 KeyBuffer* plaintext) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800428 if (ciphertext.size() < GCM_NONCE_BYTES + GCM_MAC_BYTES) {
429 LOG(ERROR) << "GCM ciphertext too small: " << ciphertext.size();
430 return false;
431 }
Paul Crowley26a53882017-10-26 11:16:39 -0700432 std::string key;
433 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800434 key.resize(AES_KEY_BYTES);
435 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
436 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
437 if (!ctx) {
438 logOpensslError();
439 return false;
440 }
441 if (1 != EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
Shawn Willden785365b2018-01-20 09:37:36 -0700442 reinterpret_cast<const uint8_t*>(key.data()),
443 reinterpret_cast<const uint8_t*>(ciphertext.data()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800444 logOpensslError();
445 return false;
446 }
Pavel Grafove2e2d302017-08-01 17:15:53 +0100447 *plaintext = KeyBuffer(ciphertext.size() - GCM_NONCE_BYTES - GCM_MAC_BYTES);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800448 int outlen;
Shawn Willden785365b2018-01-20 09:37:36 -0700449 if (1 != EVP_DecryptUpdate(ctx.get(), reinterpret_cast<uint8_t*>(&(*plaintext)[0]), &outlen,
450 reinterpret_cast<const uint8_t*>(ciphertext.data() + GCM_NONCE_BYTES),
451 plaintext->size())) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800452 logOpensslError();
453 return false;
454 }
455 if (outlen != static_cast<int>(plaintext->size())) {
456 LOG(ERROR) << "GCM plaintext length should be " << plaintext->size() << " was " << outlen;
457 return false;
458 }
459 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, GCM_MAC_BYTES,
Shawn Willden785365b2018-01-20 09:37:36 -0700460 const_cast<void*>(reinterpret_cast<const void*>(
461 ciphertext.data() + GCM_NONCE_BYTES + plaintext->size())))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800462 logOpensslError();
463 return false;
464 }
465 if (1 != EVP_DecryptFinal_ex(ctx.get(),
Shawn Willden785365b2018-01-20 09:37:36 -0700466 reinterpret_cast<uint8_t*>(&(*plaintext)[0] + plaintext->size()),
467 &outlen)) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800468 logOpensslError();
469 return false;
470 }
471 if (outlen != 0) {
472 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
473 return false;
474 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000475 return true;
Paul Crowley05720802016-02-08 15:55:41 +0000476}
477
Paul Crowleyf71ace32016-06-02 11:01:19 -0700478bool pathExists(const std::string& path) {
479 return access(path.c_str(), F_OK) == 0;
480}
481
Pavel Grafove2e2d302017-08-01 17:15:53 +0100482bool storeKey(const std::string& dir, const KeyAuthentication& auth, const KeyBuffer& key) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000483 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), 0700)) == -1) {
484 PLOG(ERROR) << "key mkdir " << dir;
485 return false;
486 }
Paul Crowleydf528a72016-03-09 09:31:37 -0800487 if (!writeStringToFile(kCurrentVersion, dir + "/" + kFn_version)) return false;
Paul Crowley26a53882017-10-26 11:16:39 -0700488 std::string secdiscardable_hash;
489 if (!createSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800490 std::string stretching = getStretching(auth);
Paul Crowleydf528a72016-03-09 09:31:37 -0800491 if (!writeStringToFile(stretching, dir + "/" + kFn_stretching)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000492 std::string salt;
493 if (stretchingNeedsSalt(stretching)) {
494 if (ReadRandomBytes(SALT_BYTES, salt) != OK) {
495 LOG(ERROR) << "Random read failed";
496 return false;
497 }
Paul Crowleydf528a72016-03-09 09:31:37 -0800498 if (!writeStringToFile(salt, dir + "/" + kFn_salt)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000499 }
Paul Crowley320e5e12016-03-04 14:07:05 -0800500 std::string appId;
Paul Crowley26a53882017-10-26 11:16:39 -0700501 if (!generateAppId(auth, stretching, salt, secdiscardable_hash, &appId)) return false;
Paul Crowley320e5e12016-03-04 14:07:05 -0800502 std::string encryptedKey;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800503 if (auth.usesKeymaster()) {
504 Keymaster keymaster;
505 if (!keymaster) return false;
506 std::string kmKey;
507 if (!generateKeymasterKey(keymaster, auth, appId, &kmKey)) return false;
508 if (!writeStringToFile(kmKey, dir + "/" + kFn_keymaster_key_blob)) return false;
Shawn Willden35351812018-01-22 09:08:32 -0700509 km::AuthorizationSet keyParams;
510 km::HardwareAuthToken authToken;
511 std::tie(keyParams, authToken) = beginParams(auth, appId);
Daniel Rosenberg690d6de2018-12-14 01:08:10 -0800512 if (!encryptWithKeymasterKey(keymaster, dir, keyParams, authToken, key, &encryptedKey,
513 false))
Shawn Willden35351812018-01-22 09:08:32 -0700514 return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800515 } else {
516 if (!encryptWithoutKeymaster(appId, key, &encryptedKey)) return false;
517 }
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000518 if (!writeStringToFile(encryptedKey, dir + "/" + kFn_encrypted_key)) return false;
Paul Crowley621d9b92018-12-07 15:36:09 -0800519 if (!FsyncDirectory(dir)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000520 return true;
521}
522
Paul Crowleyf71ace32016-06-02 11:01:19 -0700523bool storeKeyAtomically(const std::string& key_path, const std::string& tmp_path,
Pavel Grafove2e2d302017-08-01 17:15:53 +0100524 const KeyAuthentication& auth, const KeyBuffer& key) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700525 if (pathExists(key_path)) {
526 LOG(ERROR) << "Already exists, cannot create key at: " << key_path;
527 return false;
528 }
529 if (pathExists(tmp_path)) {
530 LOG(DEBUG) << "Already exists, destroying: " << tmp_path;
531 destroyKey(tmp_path); // May be partially created so ignore errors
532 }
533 if (!storeKey(tmp_path, auth, key)) return false;
534 if (rename(tmp_path.c_str(), key_path.c_str()) != 0) {
535 PLOG(ERROR) << "Unable to move new key to location: " << key_path;
536 return false;
537 }
538 LOG(DEBUG) << "Created key: " << key_path;
539 return true;
540}
541
Daniel Rosenberg690d6de2018-12-14 01:08:10 -0800542bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, KeyBuffer* key,
543 bool keepOld) {
Paul Crowley05720802016-02-08 15:55:41 +0000544 std::string version;
Paul Crowleya051eb72016-03-08 16:08:32 -0800545 if (!readFileToString(dir + "/" + kFn_version, &version)) return false;
Paul Crowley05720802016-02-08 15:55:41 +0000546 if (version != kCurrentVersion) {
547 LOG(ERROR) << "Version mismatch, expected " << kCurrentVersion << " got " << version;
548 return false;
549 }
Paul Crowley26a53882017-10-26 11:16:39 -0700550 std::string secdiscardable_hash;
551 if (!readSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000552 std::string stretching;
Paul Crowleya051eb72016-03-08 16:08:32 -0800553 if (!readFileToString(dir + "/" + kFn_stretching, &stretching)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000554 std::string salt;
555 if (stretchingNeedsSalt(stretching)) {
Paul Crowleydf528a72016-03-09 09:31:37 -0800556 if (!readFileToString(dir + "/" + kFn_salt, &salt)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000557 }
Paul Crowley320e5e12016-03-04 14:07:05 -0800558 std::string appId;
Paul Crowley26a53882017-10-26 11:16:39 -0700559 if (!generateAppId(auth, stretching, salt, secdiscardable_hash, &appId)) return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000560 std::string encryptedMessage;
Paul Crowleya051eb72016-03-08 16:08:32 -0800561 if (!readFileToString(dir + "/" + kFn_encrypted_key, &encryptedMessage)) return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800562 if (auth.usesKeymaster()) {
563 Keymaster keymaster;
564 if (!keymaster) return false;
Shawn Willden35351812018-01-22 09:08:32 -0700565 km::AuthorizationSet keyParams;
566 km::HardwareAuthToken authToken;
567 std::tie(keyParams, authToken) = beginParams(auth, appId);
Daniel Rosenberg690d6de2018-12-14 01:08:10 -0800568 if (!decryptWithKeymasterKey(keymaster, dir, keyParams, authToken, encryptedMessage, key,
569 keepOld))
Shawn Willden785365b2018-01-20 09:37:36 -0700570 return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800571 } else {
572 if (!decryptWithoutKeymaster(appId, encryptedMessage, key)) return false;
573 }
574 return true;
Paul Crowley1ef25582016-01-21 20:26:12 +0000575}
576
Paul Crowleydf528a72016-03-09 09:31:37 -0800577static bool deleteKey(const std::string& dir) {
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000578 std::string kmKey;
Paul Crowleya051eb72016-03-08 16:08:32 -0800579 if (!readFileToString(dir + "/" + kFn_keymaster_key_blob, &kmKey)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000580 Keymaster keymaster;
581 if (!keymaster) return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000582 if (!keymaster.deleteKey(kmKey)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000583 return true;
584}
585
Rubin Xu2436e272017-04-27 20:43:10 +0100586bool runSecdiscardSingle(const std::string& file) {
Shawn Willden785365b2018-01-20 09:37:36 -0700587 if (ForkExecvp(std::vector<std::string>{kSecdiscardPath, "--", file}) != 0) {
Rubin Xu2436e272017-04-27 20:43:10 +0100588 LOG(ERROR) << "secdiscard failed";
589 return false;
590 }
591 return true;
592}
593
Paul Crowleydf528a72016-03-09 09:31:37 -0800594static bool recursiveDeleteKey(const std::string& dir) {
595 if (ForkExecvp(std::vector<std::string>{kRmPath, "-rf", dir}) != 0) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000596 LOG(ERROR) << "recursive delete failed";
597 return false;
598 }
599 return true;
600}
601
Paul Crowleydf528a72016-03-09 09:31:37 -0800602bool destroyKey(const std::string& dir) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000603 bool success = true;
604 // Try each thing, even if previous things failed.
Paul Crowleyff19b052017-10-26 11:28:55 -0700605 bool uses_km = pathExists(dir + "/" + kFn_keymaster_key_blob);
606 if (uses_km) {
607 success &= deleteKey(dir);
608 }
609 auto secdiscard_cmd = std::vector<std::string>{
Paul Crowley14c8c072018-09-18 13:30:21 -0700610 kSecdiscardPath,
611 "--",
612 dir + "/" + kFn_encrypted_key,
613 dir + "/" + kFn_secdiscardable,
Paul Crowleyff19b052017-10-26 11:28:55 -0700614 };
615 if (uses_km) {
616 secdiscard_cmd.emplace_back(dir + "/" + kFn_keymaster_key_blob);
617 }
618 if (ForkExecvp(secdiscard_cmd) != 0) {
619 LOG(ERROR) << "secdiscard failed";
620 success = false;
621 }
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000622 success &= recursiveDeleteKey(dir);
Paul Crowley1ef25582016-01-21 20:26:12 +0000623 return success;
624}
625
626} // namespace vold
627} // namespace android