OSDN Git Service

Merge "Blocking mode for debugging purposes."
[android-x86/system-vold.git] / KeyStorage.cpp
1 /*
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"
20 #include "ScryptParameters.h"
21 #include "Utils.h"
22
23 #include <vector>
24
25 #include <errno.h>
26 #include <stdio.h>
27 #include <sys/stat.h>
28 #include <sys/types.h>
29 #include <sys/wait.h>
30 #include <unistd.h>
31
32 #include <openssl/sha.h>
33
34 #include <android-base/file.h>
35 #include <android-base/logging.h>
36
37 #include <cutils/properties.h>
38
39 #include <hardware/hw_auth_token.h>
40
41 #include <keymaster/authorization_set.h>
42
43 extern "C" {
44
45 #include "crypto_scrypt.h"
46 }
47
48 namespace android {
49 namespace vold {
50
51 const KeyAuthentication kEmptyAuthentication{"", ""};
52
53 static constexpr size_t AES_KEY_BYTES = 32;
54 static constexpr size_t GCM_NONCE_BYTES = 12;
55 static constexpr size_t GCM_MAC_BYTES = 16;
56 static constexpr size_t SALT_BYTES = 1 << 4;
57 static constexpr size_t SECDISCARDABLE_BYTES = 1 << 14;
58 static constexpr size_t STRETCHED_BYTES = 1 << 6;
59
60 static constexpr uint32_t AUTH_TIMEOUT = 30; // Seconds
61
62 static const char* kCurrentVersion = "1";
63 static const char* kRmPath = "/system/bin/rm";
64 static const char* kSecdiscardPath = "/system/bin/secdiscard";
65 static const char* kStretch_none = "none";
66 static const char* kStretch_nopassword = "nopassword";
67 static const std::string kStretchPrefix_scrypt = "scrypt ";
68 static const char* kFn_encrypted_key = "encrypted_key";
69 static const char* kFn_keymaster_key_blob = "keymaster_key_blob";
70 static const char* kFn_keymaster_key_blob_upgraded = "keymaster_key_blob_upgraded";
71 static const char* kFn_salt = "salt";
72 static const char* kFn_secdiscardable = "secdiscardable";
73 static const char* kFn_stretching = "stretching";
74 static const char* kFn_version = "version";
75
76 static bool checkSize(const std::string& kind, size_t actual, size_t expected) {
77     if (actual != expected) {
78         LOG(ERROR) << "Wrong number of bytes in " << kind << ", expected " << expected << " got "
79                    << actual;
80         return false;
81     }
82     return true;
83 }
84
85 static std::string hashSecdiscardable(const std::string& secdiscardable) {
86     SHA512_CTX c;
87
88     SHA512_Init(&c);
89     // Personalise the hashing by introducing a fixed prefix.
90     // Hashing applications should use personalization except when there is a
91     // specific reason not to; see section 4.11 of https://www.schneier.com/skein1.3.pdf
92     std::string secdiscardableHashingPrefix = "Android secdiscardable SHA512";
93     secdiscardableHashingPrefix.resize(SHA512_CBLOCK);
94     SHA512_Update(&c, secdiscardableHashingPrefix.data(), secdiscardableHashingPrefix.size());
95     SHA512_Update(&c, secdiscardable.data(), secdiscardable.size());
96     std::string res(SHA512_DIGEST_LENGTH, '\0');
97     SHA512_Final(reinterpret_cast<uint8_t*>(&res[0]), &c);
98     return res;
99 }
100
101 static bool generateKeymasterKey(Keymaster& keymaster, const KeyAuthentication& auth,
102                                  const std::string& appId, std::string* key) {
103     auto paramBuilder = keymaster::AuthorizationSetBuilder()
104                             .AesEncryptionKey(AES_KEY_BYTES * 8)
105                             .Authorization(keymaster::TAG_BLOCK_MODE, KM_MODE_GCM)
106                             .Authorization(keymaster::TAG_MIN_MAC_LENGTH, GCM_MAC_BYTES * 8)
107                             .Authorization(keymaster::TAG_PADDING, KM_PAD_NONE);
108     addStringParam(&paramBuilder, keymaster::TAG_APPLICATION_ID, appId);
109     if (auth.token.empty()) {
110         LOG(DEBUG) << "Creating key that doesn't need auth token";
111         paramBuilder.Authorization(keymaster::TAG_NO_AUTH_REQUIRED);
112     } else {
113         LOG(DEBUG) << "Auth token required for key";
114         if (auth.token.size() != sizeof(hw_auth_token_t)) {
115             LOG(ERROR) << "Auth token should be " << sizeof(hw_auth_token_t) << " bytes, was "
116                        << auth.token.size() << " bytes";
117             return false;
118         }
119         const hw_auth_token_t* at = reinterpret_cast<const hw_auth_token_t*>(auth.token.data());
120         paramBuilder.Authorization(keymaster::TAG_USER_SECURE_ID, at->user_id);
121         paramBuilder.Authorization(keymaster::TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD);
122         paramBuilder.Authorization(keymaster::TAG_AUTH_TIMEOUT, AUTH_TIMEOUT);
123     }
124     return keymaster.generateKey(paramBuilder.build(), key);
125 }
126
127 static keymaster::AuthorizationSet beginParams(const KeyAuthentication& auth,
128                                                const std::string& appId) {
129     auto paramBuilder = keymaster::AuthorizationSetBuilder()
130                             .Authorization(keymaster::TAG_BLOCK_MODE, KM_MODE_GCM)
131                             .Authorization(keymaster::TAG_MAC_LENGTH, GCM_MAC_BYTES * 8)
132                             .Authorization(keymaster::TAG_PADDING, KM_PAD_NONE);
133     addStringParam(&paramBuilder, keymaster::TAG_APPLICATION_ID, appId);
134     if (!auth.token.empty()) {
135         LOG(DEBUG) << "Supplying auth token to Keymaster";
136         addStringParam(&paramBuilder, keymaster::TAG_AUTH_TOKEN, auth.token);
137     }
138     return paramBuilder.build();
139 }
140
141 static bool readFileToString(const std::string& filename, std::string* result) {
142     if (!android::base::ReadFileToString(filename, result)) {
143         PLOG(ERROR) << "Failed to read from " << filename;
144         return false;
145     }
146     return true;
147 }
148
149 static bool writeStringToFile(const std::string& payload, const std::string& filename) {
150     if (!android::base::WriteStringToFile(payload, filename)) {
151         PLOG(ERROR) << "Failed to write to " << filename;
152         return false;
153     }
154     return true;
155 }
156
157 static KeymasterOperation begin(Keymaster& keymaster, const std::string& dir,
158                                 keymaster_purpose_t purpose,
159                                 const keymaster::AuthorizationSet &keyParams,
160                                 const keymaster::AuthorizationSet &opParams,
161                                 keymaster::AuthorizationSet* outParams) {
162     auto kmKeyPath = dir + "/" + kFn_keymaster_key_blob;
163     std::string kmKey;
164     if (!readFileToString(kmKeyPath, &kmKey)) return KeymasterOperation();
165     keymaster::AuthorizationSet inParams;
166     inParams.push_back(keyParams);
167     inParams.push_back(opParams);
168     for (;;) {
169         auto opHandle = keymaster.begin(purpose, kmKey, inParams, outParams);
170         if (opHandle) {
171             return opHandle;
172         }
173         if (opHandle.error() != KM_ERROR_KEY_REQUIRES_UPGRADE) return opHandle;
174         LOG(DEBUG) << "Upgrading key: " << dir;
175         std::string newKey;
176         if (!keymaster.upgradeKey(kmKey, keyParams, &newKey)) return KeymasterOperation();
177         auto newKeyPath = dir + "/" + kFn_keymaster_key_blob_upgraded;
178         if (!writeStringToFile(newKey, newKeyPath)) return KeymasterOperation();
179         if (rename(newKeyPath.c_str(), kmKeyPath.c_str()) != 0) {
180             PLOG(ERROR) << "Unable to move upgraded key to location: " << kmKeyPath;
181             return KeymasterOperation();
182         }
183         if (!keymaster.deleteKey(kmKey)) {
184             LOG(ERROR) << "Key deletion failed during upgrade, continuing anyway: " << dir;
185         }
186         kmKey = newKey;
187         LOG(INFO) << "Key upgraded: " << dir;
188     }
189 }
190
191 static bool encryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
192                                     const keymaster::AuthorizationSet &keyParams,
193                                     const std::string& message, std::string* ciphertext) {
194     keymaster::AuthorizationSet opParams;
195     keymaster::AuthorizationSet outParams;
196     auto opHandle = begin(keymaster, dir, KM_PURPOSE_ENCRYPT, keyParams, opParams, &outParams);
197     if (!opHandle) return false;
198     keymaster_blob_t nonceBlob;
199     if (!outParams.GetTagValue(keymaster::TAG_NONCE, &nonceBlob)) {
200         LOG(ERROR) << "GCM encryption but no nonce generated";
201         return false;
202     }
203     // nonceBlob here is just a pointer into existing data, must not be freed
204     std::string nonce(reinterpret_cast<const char*>(nonceBlob.data), nonceBlob.data_length);
205     if (!checkSize("nonce", nonce.size(), GCM_NONCE_BYTES)) return false;
206     std::string body;
207     if (!opHandle.updateCompletely(message, &body)) return false;
208
209     std::string mac;
210     if (!opHandle.finish(&mac)) return false;
211     if (!checkSize("mac", mac.size(), GCM_MAC_BYTES)) return false;
212     *ciphertext = nonce + body + mac;
213     return true;
214 }
215
216 static bool decryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
217                                     const keymaster::AuthorizationSet &keyParams,
218                                     const std::string& ciphertext, std::string* message) {
219     auto nonce = ciphertext.substr(0, GCM_NONCE_BYTES);
220     auto bodyAndMac = ciphertext.substr(GCM_NONCE_BYTES);
221     auto opParams = addStringParam(keymaster::AuthorizationSetBuilder(),
222                                    keymaster::TAG_NONCE, nonce).build();
223     auto opHandle = begin(keymaster, dir, KM_PURPOSE_DECRYPT, keyParams, opParams, nullptr);
224     if (!opHandle) return false;
225     if (!opHandle.updateCompletely(bodyAndMac, message)) return false;
226     if (!opHandle.finish(nullptr)) return false;
227     return true;
228 }
229
230 static std::string getStretching() {
231     char paramstr[PROPERTY_VALUE_MAX];
232
233     property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
234     return std::string() + kStretchPrefix_scrypt + paramstr;
235 }
236
237 static bool stretchingNeedsSalt(const std::string& stretching) {
238     return stretching != kStretch_nopassword && stretching != kStretch_none;
239 }
240
241 static bool stretchSecret(const std::string& stretching, const std::string& secret,
242                           const std::string& salt, std::string* stretched) {
243     if (stretching == kStretch_nopassword) {
244         if (!secret.empty()) {
245             LOG(WARNING) << "Password present but stretching is nopassword";
246             // Continue anyway
247         }
248         stretched->clear();
249     } else if (stretching == kStretch_none) {
250         *stretched = secret;
251     } else if (std::equal(kStretchPrefix_scrypt.begin(), kStretchPrefix_scrypt.end(),
252                           stretching.begin())) {
253         int Nf, rf, pf;
254         if (!parse_scrypt_parameters(stretching.substr(kStretchPrefix_scrypt.size()).c_str(), &Nf,
255                                      &rf, &pf)) {
256             LOG(ERROR) << "Unable to parse scrypt params in stretching: " << stretching;
257             return false;
258         }
259         stretched->assign(STRETCHED_BYTES, '\0');
260         if (crypto_scrypt(reinterpret_cast<const uint8_t*>(secret.data()), secret.size(),
261                           reinterpret_cast<const uint8_t*>(salt.data()), salt.size(),
262                           1 << Nf, 1 << rf, 1 << pf,
263                           reinterpret_cast<uint8_t*>(&(*stretched)[0]), stretched->size()) != 0) {
264             LOG(ERROR) << "scrypt failed with params: " << stretching;
265             return false;
266         }
267     } else {
268         LOG(ERROR) << "Unknown stretching type: " << stretching;
269         return false;
270     }
271     return true;
272 }
273
274 static bool generateAppId(const KeyAuthentication& auth, const std::string& stretching,
275                           const std::string& salt, const std::string& secdiscardable,
276                           std::string* appId) {
277     std::string stretched;
278     if (!stretchSecret(stretching, auth.secret, salt, &stretched)) return false;
279     *appId = hashSecdiscardable(secdiscardable) + stretched;
280     return true;
281 }
282
283 bool storeKey(const std::string& dir, const KeyAuthentication& auth, const std::string& key) {
284     if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), 0700)) == -1) {
285         PLOG(ERROR) << "key mkdir " << dir;
286         return false;
287     }
288     if (!writeStringToFile(kCurrentVersion, dir + "/" + kFn_version)) return false;
289     std::string secdiscardable;
290     if (ReadRandomBytes(SECDISCARDABLE_BYTES, secdiscardable) != OK) {
291         // TODO status_t plays badly with PLOG, fix it.
292         LOG(ERROR) << "Random read failed";
293         return false;
294     }
295     if (!writeStringToFile(secdiscardable, dir + "/" + kFn_secdiscardable)) return false;
296     std::string stretching = auth.secret.empty() ? kStretch_nopassword : getStretching();
297     if (!writeStringToFile(stretching, dir + "/" + kFn_stretching)) return false;
298     std::string salt;
299     if (stretchingNeedsSalt(stretching)) {
300         if (ReadRandomBytes(SALT_BYTES, salt) != OK) {
301             LOG(ERROR) << "Random read failed";
302             return false;
303         }
304         if (!writeStringToFile(salt, dir + "/" + kFn_salt)) return false;
305     }
306     std::string appId;
307     if (!generateAppId(auth, stretching, salt, secdiscardable, &appId)) return false;
308     Keymaster keymaster;
309     if (!keymaster) return false;
310     std::string kmKey;
311     if (!generateKeymasterKey(keymaster, auth, appId, &kmKey)) return false;
312     if (!writeStringToFile(kmKey, dir + "/" + kFn_keymaster_key_blob)) return false;
313     auto keyParams = beginParams(auth, appId);
314     std::string encryptedKey;
315     if (!encryptWithKeymasterKey(keymaster, dir, keyParams, key, &encryptedKey)) return false;
316     if (!writeStringToFile(encryptedKey, dir + "/" + kFn_encrypted_key)) return false;
317     return true;
318 }
319
320 bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, std::string* key) {
321     std::string version;
322     if (!readFileToString(dir + "/" + kFn_version, &version)) return false;
323     if (version != kCurrentVersion) {
324         LOG(ERROR) << "Version mismatch, expected " << kCurrentVersion << " got " << version;
325         return false;
326     }
327     std::string secdiscardable;
328     if (!readFileToString(dir + "/" + kFn_secdiscardable, &secdiscardable)) return false;
329     std::string stretching;
330     if (!readFileToString(dir + "/" + kFn_stretching, &stretching)) return false;
331     std::string salt;
332     if (stretchingNeedsSalt(stretching)) {
333         if (!readFileToString(dir + "/" + kFn_salt, &salt)) return false;
334     }
335     std::string appId;
336     if (!generateAppId(auth, stretching, salt, secdiscardable, &appId)) return false;
337     std::string encryptedMessage;
338     if (!readFileToString(dir + "/" + kFn_encrypted_key, &encryptedMessage)) return false;
339     Keymaster keymaster;
340     if (!keymaster) return false;
341     auto keyParams = beginParams(auth, appId);
342     return decryptWithKeymasterKey(keymaster, dir, keyParams, encryptedMessage, key);
343 }
344
345 static bool deleteKey(const std::string& dir) {
346     std::string kmKey;
347     if (!readFileToString(dir + "/" + kFn_keymaster_key_blob, &kmKey)) return false;
348     Keymaster keymaster;
349     if (!keymaster) return false;
350     if (!keymaster.deleteKey(kmKey)) return false;
351     return true;
352 }
353
354 static bool runSecdiscard(const std::string& dir) {
355     if (ForkExecvp(
356             std::vector<std::string>{kSecdiscardPath, "--",
357                 dir + "/" + kFn_encrypted_key,
358                 dir + "/" + kFn_keymaster_key_blob,
359                 dir + "/" + kFn_secdiscardable,
360                 }) != 0) {
361         LOG(ERROR) << "secdiscard failed";
362         return false;
363     }
364     return true;
365 }
366
367 static bool recursiveDeleteKey(const std::string& dir) {
368     if (ForkExecvp(std::vector<std::string>{kRmPath, "-rf", dir}) != 0) {
369         LOG(ERROR) << "recursive delete failed";
370         return false;
371     }
372     return true;
373 }
374
375 bool destroyKey(const std::string& dir) {
376     bool success = true;
377     // Try each thing, even if previous things failed.
378     success &= deleteKey(dir);
379     success &= runSecdiscard(dir);
380     success &= recursiveDeleteKey(dir);
381     return success;
382 }
383
384 }  // namespace vold
385 }  // namespace android