blob: 0cd05485e025fdf57546fc9bdf8554aefbc8a182 [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>
26#include <sys/stat.h>
27#include <sys/types.h>
28#include <sys/wait.h>
29#include <unistd.h>
30
31#include <openssl/sha.h>
32
33#include <android-base/file.h>
34#include <android-base/logging.h>
35
Paul Crowley63c18d32016-02-10 14:02:47 +000036#include <cutils/properties.h>
37
Paul Crowley320e5e12016-03-04 14:07:05 -080038#include <hardware/hw_auth_token.h>
39
Paul Crowley1ef25582016-01-21 20:26:12 +000040#include <keymaster/authorization_set.h>
41
Paul Crowley63c18d32016-02-10 14:02:47 +000042extern "C" {
43
44#include "crypto_scrypt.h"
45
46}
47
Paul Crowley1ef25582016-01-21 20:26:12 +000048namespace android {
49namespace vold {
50
Paul Crowley05720802016-02-08 15:55:41 +000051const KeyAuthentication kEmptyAuthentication { "", "" };
52
Paul Crowley1ef25582016-01-21 20:26:12 +000053static constexpr size_t AES_KEY_BYTES = 32;
54static constexpr size_t GCM_NONCE_BYTES = 12;
55static constexpr size_t GCM_MAC_BYTES = 16;
Paul Crowley63c18d32016-02-10 14:02:47 +000056static constexpr size_t SALT_BYTES = 1<<4;
Paul Crowley1ef25582016-01-21 20:26:12 +000057static constexpr size_t SECDISCARDABLE_BYTES = 1<<14;
Paul Crowley63c18d32016-02-10 14:02:47 +000058static constexpr size_t STRETCHED_BYTES = 1<<6;
Paul Crowley1ef25582016-01-21 20:26:12 +000059
Paul Crowley05720802016-02-08 15:55:41 +000060static const char* kCurrentVersion = "1";
Paul Crowley1ef25582016-01-21 20:26:12 +000061static const char* kRmPath = "/system/bin/rm";
62static const char* kSecdiscardPath = "/system/bin/secdiscard";
Paul Crowley63c18d32016-02-10 14:02:47 +000063static const char* kStretch_none = "none";
64static const char* kStretch_nopassword = "nopassword";
65static const std::string kStretchPrefix_scrypt = "scrypt ";
Paul Crowley1ef25582016-01-21 20:26:12 +000066static const char* kFn_encrypted_key = "encrypted_key";
Paul Crowley05720802016-02-08 15:55:41 +000067static const char* kFn_keymaster_key_blob = "keymaster_key_blob";
Paul Crowley63c18d32016-02-10 14:02:47 +000068static const char* kFn_salt = "salt";
Paul Crowley1ef25582016-01-21 20:26:12 +000069static const char* kFn_secdiscardable = "secdiscardable";
Paul Crowley05720802016-02-08 15:55:41 +000070static const char* kFn_stretching = "stretching";
71static const char* kFn_version = "version";
Paul Crowley1ef25582016-01-21 20:26:12 +000072
Paul Crowley13ffd8e2016-01-27 14:30:22 +000073static bool checkSize(const std::string& kind, size_t actual, size_t expected) {
Paul Crowley1ef25582016-01-21 20:26:12 +000074 if (actual != expected) {
75 LOG(ERROR) << "Wrong number of bytes in " << kind << ", expected " << expected
76 << " got " << actual;
77 return false;
78 }
79 return true;
80}
81
Paul Crowley13ffd8e2016-01-27 14:30:22 +000082static std::string hashSecdiscardable(const std::string &secdiscardable) {
Paul Crowley1ef25582016-01-21 20:26:12 +000083 SHA512_CTX c;
84
85 SHA512_Init(&c);
86 // Personalise the hashing by introducing a fixed prefix.
87 // Hashing applications should use personalization except when there is a
88 // specific reason not to; see section 4.11 of https://www.schneier.com/skein1.3.pdf
Paul Crowley13ffd8e2016-01-27 14:30:22 +000089 std::string secdiscardableHashingPrefix = "Android secdiscardable SHA512";
90 secdiscardableHashingPrefix.resize(SHA512_CBLOCK);
91 SHA512_Update(&c, secdiscardableHashingPrefix.data(), secdiscardableHashingPrefix.size());
Paul Crowley1ef25582016-01-21 20:26:12 +000092 SHA512_Update(&c, secdiscardable.data(), secdiscardable.size());
93 std::string res(SHA512_DIGEST_LENGTH, '\0');
94 SHA512_Final(reinterpret_cast<uint8_t *>(&res[0]), &c);
95 return res;
96}
97
Paul Crowley13ffd8e2016-01-27 14:30:22 +000098static bool generateKeymasterKey(Keymaster &keymaster,
Paul Crowley320e5e12016-03-04 14:07:05 -080099 const KeyAuthentication &auth, const std::string &appId,
Paul Crowley1ef25582016-01-21 20:26:12 +0000100 std::string &key) {
Paul Crowley320e5e12016-03-04 14:07:05 -0800101 auto paramBuilder = keymaster::AuthorizationSetBuilder()
Paul Crowley1ef25582016-01-21 20:26:12 +0000102 .AesEncryptionKey(AES_KEY_BYTES * 8)
103 .Authorization(keymaster::TAG_BLOCK_MODE, KM_MODE_GCM)
104 .Authorization(keymaster::TAG_MIN_MAC_LENGTH, GCM_MAC_BYTES * 8)
Paul Crowley320e5e12016-03-04 14:07:05 -0800105 .Authorization(keymaster::TAG_PADDING, KM_PAD_NONE);
106 addStringParam(paramBuilder, keymaster::TAG_APPLICATION_ID, appId);
107 if (auth.token.empty()) {
108 LOG(DEBUG) << "Creating key that doesn't need auth token";
109 paramBuilder.Authorization(keymaster::TAG_NO_AUTH_REQUIRED);
110 } else {
111 LOG(DEBUG) << "Auth token required for key";
112 if (auth.token.size() != sizeof(hw_auth_token_t)) {
113 LOG(ERROR) << "Auth token should be " << sizeof(hw_auth_token_t) << " bytes, was "
114 << auth.token.size() << " bytes";
115 return false;
116 }
117 const hw_auth_token_t *at = reinterpret_cast<const hw_auth_token_t *>(auth.token.data());
118 paramBuilder.Authorization(keymaster::TAG_USER_SECURE_ID, at->user_id);
119 paramBuilder.Authorization(keymaster::TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD);
120 paramBuilder.Authorization(keymaster::TAG_AUTH_TIMEOUT, 5);
121 }
122 return keymaster.generateKey(paramBuilder.build(), key);
123}
124
125static keymaster::AuthorizationSetBuilder beginParams(
126 const KeyAuthentication &auth, const std::string &appId) {
127 auto paramBuilder = keymaster::AuthorizationSetBuilder()
128 .Authorization(keymaster::TAG_BLOCK_MODE, KM_MODE_GCM)
129 .Authorization(keymaster::TAG_MAC_LENGTH, GCM_MAC_BYTES * 8)
130 .Authorization(keymaster::TAG_PADDING, KM_PAD_NONE);
131 addStringParam(paramBuilder, keymaster::TAG_APPLICATION_ID, appId);
132 if (!auth.token.empty()) {
133 LOG(DEBUG) << "Supplying auth token to Keymaster";
134 addStringParam(paramBuilder, keymaster::TAG_AUTH_TOKEN, auth.token);
135 }
136 return paramBuilder;
Paul Crowley1ef25582016-01-21 20:26:12 +0000137}
138
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000139static bool encryptWithKeymasterKey(
Paul Crowley1ef25582016-01-21 20:26:12 +0000140 Keymaster &keymaster,
141 const std::string &key,
Paul Crowley320e5e12016-03-04 14:07:05 -0800142 const KeyAuthentication &auth,
143 const std::string &appId,
Paul Crowley1ef25582016-01-21 20:26:12 +0000144 const std::string &message,
145 std::string &ciphertext) {
Paul Crowley320e5e12016-03-04 14:07:05 -0800146 auto params = beginParams(auth, appId).build();
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000147 keymaster::AuthorizationSet outParams;
148 auto opHandle = keymaster.begin(KM_PURPOSE_ENCRYPT, key, params, outParams);
149 if (!opHandle) return false;
150 keymaster_blob_t nonceBlob;
151 if (!outParams.GetTagValue(keymaster::TAG_NONCE, &nonceBlob)) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000152 LOG(ERROR) << "GCM encryption but no nonce generated";
153 return false;
154 }
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000155 // nonceBlob here is just a pointer into existing data, must not be freed
156 std::string nonce(reinterpret_cast<const char *>(nonceBlob.data), nonceBlob.data_length);
157 if (!checkSize("nonce", nonce.size(), GCM_NONCE_BYTES)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000158 std::string body;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000159 if (!opHandle.updateCompletely(message, body)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000160
161 std::string mac;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000162 if (!opHandle.finishWithOutput(mac)) return false;
163 if (!checkSize("mac", mac.size(), GCM_MAC_BYTES)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000164 ciphertext = nonce + body + mac;
165 return true;
166}
167
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000168static bool decryptWithKeymasterKey(
Paul Crowley320e5e12016-03-04 14:07:05 -0800169 Keymaster &keymaster,
170 const std::string &key,
171 const KeyAuthentication &auth,
172 const std::string &appId,
Paul Crowley1ef25582016-01-21 20:26:12 +0000173 const std::string &ciphertext,
174 std::string &message) {
175 auto nonce = ciphertext.substr(0, GCM_NONCE_BYTES);
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000176 auto bodyAndMac = ciphertext.substr(GCM_NONCE_BYTES);
Paul Crowley320e5e12016-03-04 14:07:05 -0800177 auto params = addStringParam(beginParams(auth, appId), keymaster::TAG_NONCE, nonce).build();
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000178 auto opHandle = keymaster.begin(KM_PURPOSE_DECRYPT, key, params);
179 if (!opHandle) return false;
180 if (!opHandle.updateCompletely(bodyAndMac, message)) return false;
181 if (!opHandle.finish()) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000182 return true;
183}
184
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000185static bool readFileToString(const std::string &filename, std::string &result) {
186 if (!android::base::ReadFileToString(filename, &result)) {
187 PLOG(ERROR) << "Failed to read from " << filename;
188 return false;
189 }
190 return true;
191}
192
193static bool writeStringToFile(const std::string &payload, const std::string &filename) {
194 if (!android::base::WriteStringToFile(payload, filename)) {
195 PLOG(ERROR) << "Failed to write to " << filename;
196 return false;
197 }
198 return true;
199}
200
Paul Crowley63c18d32016-02-10 14:02:47 +0000201static std::string getStretching() {
202 char paramstr[PROPERTY_VALUE_MAX];
203
204 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
205 return std::string() + kStretchPrefix_scrypt + paramstr;
206}
207
208static bool stretchingNeedsSalt(const std::string &stretching) {
209 return stretching != kStretch_nopassword && stretching != kStretch_none;
210}
211
212static bool stretchSecret(const std::string &stretching, const std::string &secret,
213 const std::string &salt, std::string &stretched) {
214 if (stretching == kStretch_nopassword) {
215 if (!secret.empty()) {
Paul Crowleyd9b92952016-03-04 13:45:00 -0800216 LOG(WARNING) << "Password present but stretching is nopassword";
Paul Crowley63c18d32016-02-10 14:02:47 +0000217 // Continue anyway
218 }
219 stretched.clear();
220 } else if (stretching == kStretch_none) {
221 stretched = secret;
222 } else if (std::equal(kStretchPrefix_scrypt.begin(),
223 kStretchPrefix_scrypt.end(), stretching.begin())) {
224 int Nf, rf, pf;
225 if (!parse_scrypt_parameters(
226 stretching.substr(kStretchPrefix_scrypt.size()).c_str(), &Nf, &rf, &pf)) {
227 LOG(ERROR) << "Unable to parse scrypt params in stretching: " << stretching;
228 return false;
229 }
230 stretched.assign(STRETCHED_BYTES, '\0');
231 if (crypto_scrypt(
232 reinterpret_cast<const uint8_t *>(secret.data()), secret.size(),
233 reinterpret_cast<const uint8_t *>(salt.data()), salt.size(),
234 1 << Nf, 1 << rf, 1 << pf,
235 reinterpret_cast<uint8_t *>(&stretched[0]), stretched.size()) != 0) {
236 LOG(ERROR) << "scrypt failed with params: " << stretching;
237 return false;
238 }
239 } else {
240 LOG(ERROR) << "Unknown stretching type: " << stretching;
241 return false;
242 }
243 return true;
244}
245
Paul Crowley320e5e12016-03-04 14:07:05 -0800246static bool generateAppId(const KeyAuthentication &auth, const std::string &stretching,
Paul Crowley63c18d32016-02-10 14:02:47 +0000247 const std::string &salt, const std::string &secdiscardable,
Paul Crowley320e5e12016-03-04 14:07:05 -0800248 std::string& result) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000249 std::string stretched;
250 if (!stretchSecret(stretching, auth.secret, salt, stretched)) return false;
Paul Crowley320e5e12016-03-04 14:07:05 -0800251 result = hashSecdiscardable(secdiscardable) + stretched;
Paul Crowley63c18d32016-02-10 14:02:47 +0000252 return true;
Paul Crowley05720802016-02-08 15:55:41 +0000253}
254
255bool storeKey(const std::string &dir, const KeyAuthentication &auth, const std::string &key) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000256 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), 0700)) == -1) {
257 PLOG(ERROR) << "key mkdir " << dir;
258 return false;
259 }
Paul Crowley05720802016-02-08 15:55:41 +0000260 if (!writeStringToFile(kCurrentVersion, dir + "/" + kFn_version)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000261 std::string secdiscardable;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000262 if (ReadRandomBytes(SECDISCARDABLE_BYTES, secdiscardable) != OK) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000263 // TODO status_t plays badly with PLOG, fix it.
264 LOG(ERROR) << "Random read failed";
265 return false;
266 }
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000267 if (!writeStringToFile(secdiscardable, dir + "/" + kFn_secdiscardable)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000268 std::string stretching = auth.secret.empty() ? kStretch_nopassword : getStretching();
Paul Crowley05720802016-02-08 15:55:41 +0000269 if (!writeStringToFile(stretching, dir + "/" + kFn_stretching)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000270 std::string salt;
271 if (stretchingNeedsSalt(stretching)) {
272 if (ReadRandomBytes(SALT_BYTES, salt) != OK) {
273 LOG(ERROR) << "Random read failed";
274 return false;
275 }
276 if (!writeStringToFile(salt, dir + "/" + kFn_salt)) return false;
277 }
Paul Crowley320e5e12016-03-04 14:07:05 -0800278 std::string appId;
279 if (!generateAppId(auth, stretching, salt, secdiscardable, appId)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000280 Keymaster keymaster;
281 if (!keymaster) return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000282 std::string kmKey;
Paul Crowley320e5e12016-03-04 14:07:05 -0800283 if (!generateKeymasterKey(keymaster, auth, appId, kmKey)) return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000284 if (!writeStringToFile(kmKey, dir + "/" + kFn_keymaster_key_blob)) return false;
Paul Crowley320e5e12016-03-04 14:07:05 -0800285 std::string encryptedKey;
286 if (!encryptWithKeymasterKey(keymaster, kmKey, auth, appId, key, encryptedKey)) return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000287 if (!writeStringToFile(encryptedKey, dir + "/" + kFn_encrypted_key)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000288 return true;
289}
290
Paul Crowley05720802016-02-08 15:55:41 +0000291bool retrieveKey(const std::string &dir, const KeyAuthentication &auth, std::string &key) {
292 std::string version;
293 if (!readFileToString(dir + "/" + kFn_version, version)) return false;
294 if (version != kCurrentVersion) {
295 LOG(ERROR) << "Version mismatch, expected " << kCurrentVersion << " got " << version;
296 return false;
297 }
Paul Crowley1ef25582016-01-21 20:26:12 +0000298 std::string secdiscardable;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000299 if (!readFileToString(dir + "/" + kFn_secdiscardable, secdiscardable)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000300 std::string stretching;
301 if (!readFileToString(dir + "/" + kFn_stretching, stretching)) return false;
302 std::string salt;
303 if (stretchingNeedsSalt(stretching)) {
304 if (!readFileToString(dir + "/" + kFn_salt, salt)) return false;
305 }
Paul Crowley320e5e12016-03-04 14:07:05 -0800306 std::string appId;
307 if (!generateAppId(auth, stretching, salt, secdiscardable, appId)) return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000308 std::string kmKey;
309 if (!readFileToString(dir + "/" + kFn_keymaster_key_blob, kmKey)) return false;
310 std::string encryptedMessage;
311 if (!readFileToString(dir + "/" + kFn_encrypted_key, encryptedMessage)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000312 Keymaster keymaster;
313 if (!keymaster) return false;
Paul Crowley320e5e12016-03-04 14:07:05 -0800314 return decryptWithKeymasterKey(keymaster, kmKey, auth, appId, encryptedMessage, key);
Paul Crowley1ef25582016-01-21 20:26:12 +0000315}
316
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000317static bool deleteKey(const std::string &dir) {
318 std::string kmKey;
319 if (!readFileToString(dir + "/" + kFn_keymaster_key_blob, kmKey)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000320 Keymaster keymaster;
321 if (!keymaster) return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000322 if (!keymaster.deleteKey(kmKey)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000323 return true;
324}
325
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000326static bool secdiscardSecdiscardable(const std::string &dir) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000327 if (ForkExecvp(std::vector<std::string> {
328 kSecdiscardPath, "--", dir + "/" + kFn_secdiscardable}) != 0) {
329 LOG(ERROR) << "secdiscard failed";
330 return false;
331 }
332 return true;
333}
334
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000335static bool recursiveDeleteKey(const std::string &dir) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000336 if (ForkExecvp(std::vector<std::string> {
337 kRmPath, "-rf", dir}) != 0) {
338 LOG(ERROR) << "recursive delete failed";
339 return false;
340 }
341 return true;
342}
343
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000344bool destroyKey(const std::string &dir) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000345 bool success = true;
346 // Try each thing, even if previous things failed.
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000347 success &= deleteKey(dir);
348 success &= secdiscardSecdiscardable(dir);
349 success &= recursiveDeleteKey(dir);
Paul Crowley1ef25582016-01-21 20:26:12 +0000350 return success;
351}
352
353} // namespace vold
354} // namespace android