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