OSDN Git Service

resolve merge conflicts of 2b6f9ce823 to master.
[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 "Utils.h"
21
22 #include <vector>
23
24 #include <errno.h>
25 #include <sys/stat.h>
26 #include <sys/types.h>
27 #include <sys/wait.h>
28 #include <unistd.h>
29
30 #include <openssl/sha.h>
31
32 #include <android-base/file.h>
33 #include <android-base/logging.h>
34
35 #include <keymaster/authorization_set.h>
36
37 namespace android {
38 namespace vold {
39
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;
45
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";
51
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
55             << " got " << actual;
56         return false;
57     }
58     return true;
59 }
60
61 static std::string hashSecdiscardable(const std::string &secdiscardable) {
62     SHA512_CTX c;
63
64     SHA512_Init(&c);
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);
74     return res;
75 }
76
77 static bool generateKeymasterKey(Keymaster &keymaster,
78         const keymaster::AuthorizationSet &extraParams,
79         std::string &key) {
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
86         .build();
87     params.push_back(extraParams);
88     return keymaster.generateKey(params, key);
89 }
90
91 static bool encryptWithKeymasterKey(
92         Keymaster &keymaster,
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)
102         .build();
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";
110         return false;
111     }
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;
115     std::string body;
116     if (!opHandle.updateCompletely(message, body)) return false;
117
118     std::string mac;
119     if (!opHandle.finishWithOutput(mac)) return false;
120     if (!checkSize("mac", mac.size(), GCM_MAC_BYTES)) return false;
121     ciphertext = nonce + body + mac;
122     return true;
123 }
124
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)
137         .build();
138     params.push_back(extraParams);
139
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;
144     return true;
145 }
146
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;
150          return false;
151     }
152     return true;
153 }
154
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;
158          return false;
159     }
160     return true;
161 }
162
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;
166         return false;
167     }
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";
172         return false;
173     }
174     if (!writeStringToFile(secdiscardable, dir + "/" + kFn_secdiscardable)) return false;
175     auto extraParams = addStringParam(keymaster::AuthorizationSetBuilder(),
176             keymaster::TAG_APPLICATION_ID, hashSecdiscardable(secdiscardable)).build();
177     Keymaster keymaster;
178     if (!keymaster) return false;
179     std::string kmKey;
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;
186     return true;
187 }
188
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();
194     std::string kmKey;
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;
198     Keymaster keymaster;
199     if (!keymaster) return false;
200     return decryptWithKeymasterKey(keymaster, kmKey, extraParams, encryptedMessage, key);
201 }
202
203 static bool deleteKey(const std::string &dir) {
204     std::string kmKey;
205     if (!readFileToString(dir + "/" + kFn_keymaster_key_blob, kmKey)) return false;
206     Keymaster keymaster;
207     if (!keymaster) return false;
208     if (!keymaster.deleteKey(kmKey)) return false;
209     return true;
210 }
211
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";
216         return false;
217     }
218     return true;
219 }
220
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";
225         return false;
226     }
227     return true;
228 }
229
230 bool destroyKey(const std::string &dir) {
231     bool success = true;
232     // Try each thing, even if previous things failed.
233     success &= deleteKey(dir);
234     success &= secdiscardSecdiscardable(dir);
235     success &= recursiveDeleteKey(dir);
236     return success;
237 }
238
239 }  // namespace vold
240 }  // namespace android