2 * Copyright (C) 2016 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include "KeyStorage.h"
19 #include "Keymaster.h"
26 #include <sys/types.h>
30 #include <openssl/sha.h>
32 #include <android-base/file.h>
33 #include <android-base/logging.h>
35 #include <keymaster/authorization_set.h>
40 static constexpr size_t AES_KEY_BYTES = 32;
41 static constexpr size_t GCM_NONCE_BYTES = 12;
42 static constexpr size_t GCM_MAC_BYTES = 16;
43 // FIXME: better name than "secdiscardable" sought!
44 static constexpr size_t SECDISCARDABLE_BYTES = 1<<14;
46 static const char* kRmPath = "/system/bin/rm";
47 static const char* kSecdiscardPath = "/system/bin/secdiscard";
48 static const char* kFn_keymaster_key_blob = "keymaster_key_blob";
49 static const char* kFn_encrypted_key = "encrypted_key";
50 static const char* kFn_secdiscardable = "secdiscardable";
52 static bool checkSize(const std::string& kind, size_t actual, size_t expected) {
53 if (actual != expected) {
54 LOG(ERROR) << "Wrong number of bytes in " << kind << ", expected " << expected
61 static std::string hashSecdiscardable(const std::string &secdiscardable) {
65 // Personalise the hashing by introducing a fixed prefix.
66 // Hashing applications should use personalization except when there is a
67 // specific reason not to; see section 4.11 of https://www.schneier.com/skein1.3.pdf
68 std::string secdiscardableHashingPrefix = "Android secdiscardable SHA512";
69 secdiscardableHashingPrefix.resize(SHA512_CBLOCK);
70 SHA512_Update(&c, secdiscardableHashingPrefix.data(), secdiscardableHashingPrefix.size());
71 SHA512_Update(&c, secdiscardable.data(), secdiscardable.size());
72 std::string res(SHA512_DIGEST_LENGTH, '\0');
73 SHA512_Final(reinterpret_cast<uint8_t *>(&res[0]), &c);
77 static bool generateKeymasterKey(Keymaster &keymaster,
78 const keymaster::AuthorizationSet &extraParams,
80 auto params = keymaster::AuthorizationSetBuilder()
81 .AesEncryptionKey(AES_KEY_BYTES * 8)
82 .Authorization(keymaster::TAG_BLOCK_MODE, KM_MODE_GCM)
83 .Authorization(keymaster::TAG_MIN_MAC_LENGTH, GCM_MAC_BYTES * 8)
84 .Authorization(keymaster::TAG_PADDING, KM_PAD_NONE)
85 .Authorization(keymaster::TAG_NO_AUTH_REQUIRED) // FIXME integrate with gatekeeper
87 params.push_back(extraParams);
88 return keymaster.generateKey(params, key);
91 static bool encryptWithKeymasterKey(
93 const std::string &key,
94 const keymaster::AuthorizationSet &extraParams,
95 const std::string &message,
96 std::string &ciphertext) {
97 // FIXME fix repetition
98 auto params = keymaster::AuthorizationSetBuilder()
99 .Authorization(keymaster::TAG_BLOCK_MODE, KM_MODE_GCM)
100 .Authorization(keymaster::TAG_MAC_LENGTH, GCM_MAC_BYTES * 8)
101 .Authorization(keymaster::TAG_PADDING, KM_PAD_NONE)
103 params.push_back(extraParams);
104 keymaster::AuthorizationSet outParams;
105 auto opHandle = keymaster.begin(KM_PURPOSE_ENCRYPT, key, params, outParams);
106 if (!opHandle) return false;
107 keymaster_blob_t nonceBlob;
108 if (!outParams.GetTagValue(keymaster::TAG_NONCE, &nonceBlob)) {
109 LOG(ERROR) << "GCM encryption but no nonce generated";
112 // nonceBlob here is just a pointer into existing data, must not be freed
113 std::string nonce(reinterpret_cast<const char *>(nonceBlob.data), nonceBlob.data_length);
114 if (!checkSize("nonce", nonce.size(), GCM_NONCE_BYTES)) return false;
116 if (!opHandle.updateCompletely(message, body)) return false;
119 if (!opHandle.finishWithOutput(mac)) return false;
120 if (!checkSize("mac", mac.size(), GCM_MAC_BYTES)) return false;
121 ciphertext = nonce + body + mac;
125 static bool decryptWithKeymasterKey(
126 Keymaster &keymaster, const std::string &key,
127 const keymaster::AuthorizationSet &extraParams,
128 const std::string &ciphertext,
129 std::string &message) {
130 auto nonce = ciphertext.substr(0, GCM_NONCE_BYTES);
131 auto bodyAndMac = ciphertext.substr(GCM_NONCE_BYTES);
132 // FIXME fix repetition
133 auto params = addStringParam(keymaster::AuthorizationSetBuilder(), keymaster::TAG_NONCE, nonce)
134 .Authorization(keymaster::TAG_BLOCK_MODE, KM_MODE_GCM)
135 .Authorization(keymaster::TAG_MAC_LENGTH, GCM_MAC_BYTES * 8)
136 .Authorization(keymaster::TAG_PADDING, KM_PAD_NONE)
138 params.push_back(extraParams);
140 auto opHandle = keymaster.begin(KM_PURPOSE_DECRYPT, key, params);
141 if (!opHandle) return false;
142 if (!opHandle.updateCompletely(bodyAndMac, message)) return false;
143 if (!opHandle.finish()) return false;
147 static bool readFileToString(const std::string &filename, std::string &result) {
148 if (!android::base::ReadFileToString(filename, &result)) {
149 PLOG(ERROR) << "Failed to read from " << filename;
155 static bool writeStringToFile(const std::string &payload, const std::string &filename) {
156 if (!android::base::WriteStringToFile(payload, filename)) {
157 PLOG(ERROR) << "Failed to write to " << filename;
163 bool storeKey(const std::string &dir, const std::string &key) {
164 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), 0700)) == -1) {
165 PLOG(ERROR) << "key mkdir " << dir;
168 std::string secdiscardable;
169 if (ReadRandomBytes(SECDISCARDABLE_BYTES, secdiscardable) != OK) {
170 // TODO status_t plays badly with PLOG, fix it.
171 LOG(ERROR) << "Random read failed";
174 if (!writeStringToFile(secdiscardable, dir + "/" + kFn_secdiscardable)) return false;
175 auto extraParams = addStringParam(keymaster::AuthorizationSetBuilder(),
176 keymaster::TAG_APPLICATION_ID, hashSecdiscardable(secdiscardable)).build();
178 if (!keymaster) return false;
180 if (!generateKeymasterKey(keymaster, extraParams, kmKey)) return false;
181 std::string encryptedKey;
182 if (!encryptWithKeymasterKey(
183 keymaster, kmKey, extraParams, key, encryptedKey)) return false;
184 if (!writeStringToFile(kmKey, dir + "/" + kFn_keymaster_key_blob)) return false;
185 if (!writeStringToFile(encryptedKey, dir + "/" + kFn_encrypted_key)) return false;
189 bool retrieveKey(const std::string &dir, std::string &key) {
190 std::string secdiscardable;
191 if (!readFileToString(dir + "/" + kFn_secdiscardable, secdiscardable)) return false;
192 auto extraParams = addStringParam(keymaster::AuthorizationSetBuilder(),
193 keymaster::TAG_APPLICATION_ID, hashSecdiscardable(secdiscardable)).build();
195 if (!readFileToString(dir + "/" + kFn_keymaster_key_blob, kmKey)) return false;
196 std::string encryptedMessage;
197 if (!readFileToString(dir + "/" + kFn_encrypted_key, encryptedMessage)) return false;
199 if (!keymaster) return false;
200 return decryptWithKeymasterKey(keymaster, kmKey, extraParams, encryptedMessage, key);
203 static bool deleteKey(const std::string &dir) {
205 if (!readFileToString(dir + "/" + kFn_keymaster_key_blob, kmKey)) return false;
207 if (!keymaster) return false;
208 if (!keymaster.deleteKey(kmKey)) return false;
212 static bool secdiscardSecdiscardable(const std::string &dir) {
213 if (ForkExecvp(std::vector<std::string> {
214 kSecdiscardPath, "--", dir + "/" + kFn_secdiscardable}) != 0) {
215 LOG(ERROR) << "secdiscard failed";
221 static bool recursiveDeleteKey(const std::string &dir) {
222 if (ForkExecvp(std::vector<std::string> {
223 kRmPath, "-rf", dir}) != 0) {
224 LOG(ERROR) << "recursive delete failed";
230 bool destroyKey(const std::string &dir) {
232 // Try each thing, even if previous things failed.
233 success &= deleteKey(dir);
234 success &= secdiscardSecdiscardable(dir);
235 success &= recursiveDeleteKey(dir);
240 } // namespace android