blob: ae6a9601b06433a342874092ed1ef6dc6f597be2 [file] [log] [blame]
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001/*
2 * Copyright (C) 2015 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
Paul Lawrence731a7a22015-04-28 22:14:15 +000017#include "Ext4Crypt.h"
18
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -080019#include "Utils.h"
20
Paul Lawrencefd7db732015-04-10 07:48:51 -070021#include <iomanip>
Paul Lawrence731a7a22015-04-28 22:14:15 +000022#include <map>
Paul Lawrencefd7db732015-04-10 07:48:51 -070023#include <fstream>
24#include <string>
25#include <sstream>
Paul Lawrence731a7a22015-04-28 22:14:15 +000026
27#include <errno.h>
Paul Crowley95376d62015-05-06 15:04:43 +010028#include <dirent.h>
Paul Lawrence731a7a22015-04-28 22:14:15 +000029#include <sys/mount.h>
Paul Crowley95376d62015-05-06 15:04:43 +010030#include <sys/types.h>
31#include <sys/stat.h>
32#include <fcntl.h>
Paul Lawrence731a7a22015-04-28 22:14:15 +000033#include <cutils/properties.h>
Paul Lawrencefd7db732015-04-10 07:48:51 -070034#include <openssl/sha.h>
Paul Lawrence731a7a22015-04-28 22:14:15 +000035
Paul Crowley480fcd22015-08-24 14:53:28 +010036#include <private/android_filesystem_config.h>
37
Paul Lawrence731a7a22015-04-28 22:14:15 +000038#include "unencrypted_properties.h"
39#include "key_control.h"
40#include "cryptfs.h"
Paul Crowley95376d62015-05-06 15:04:43 +010041#include "ext4_crypt_init_extensions.h"
Paul Lawrence731a7a22015-04-28 22:14:15 +000042
43#define LOG_TAG "Ext4Crypt"
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -080044
45#include <cutils/fs.h>
46#include <cutils/log.h>
Paul Lawrence731a7a22015-04-28 22:14:15 +000047#include <cutils/klog.h>
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -080048
Paul Crowley95376d62015-05-06 15:04:43 +010049#include <base/file.h>
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -080050#include <base/logging.h>
Paul Crowley95376d62015-05-06 15:04:43 +010051#include <base/stringprintf.h>
Paul Lawrence731a7a22015-04-28 22:14:15 +000052
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -080053using android::base::StringPrintf;
54
Paul Lawrence731a7a22015-04-28 22:14:15 +000055namespace {
56 // Key length in bits
57 const int key_length = 128;
Paul Lawrencefd7db732015-04-10 07:48:51 -070058 static_assert(key_length % 8 == 0,
59 "Key length must be multiple of 8 bits");
Paul Lawrence731a7a22015-04-28 22:14:15 +000060
Paul Lawrence86c942a2015-05-06 13:53:43 -070061 // How long do we store passwords for?
62 const int password_max_age_seconds = 60;
63
Paul Lawrence731a7a22015-04-28 22:14:15 +000064 // How is device encrypted
65 struct keys {
66 std::string master_key;
67 std::string password;
Paul Lawrence86c942a2015-05-06 13:53:43 -070068 time_t expiry_time;
Paul Lawrence731a7a22015-04-28 22:14:15 +000069 };
70 std::map<std::string, keys> s_key_store;
71
Paul Lawrencefd7db732015-04-10 07:48:51 -070072 // ext4enc:TODO get these consts from somewhere good
73 const int SHA512_LENGTH = 64;
74 const int EXT4_KEY_DESCRIPTOR_SIZE = 8;
75
Paul Lawrence731a7a22015-04-28 22:14:15 +000076 // ext4enc:TODO Include structure from somewhere sensible
77 // MUST be in sync with ext4_crypto.c in kernel
Paul Lawrencefd7db732015-04-10 07:48:51 -070078 const int EXT4_MAX_KEY_SIZE = 64;
79 const int EXT4_ENCRYPTION_MODE_AES_256_XTS = 1;
Paul Lawrence731a7a22015-04-28 22:14:15 +000080 struct ext4_encryption_key {
Paul Lawrencefd7db732015-04-10 07:48:51 -070081 uint32_t mode;
82 char raw[EXT4_MAX_KEY_SIZE];
83 uint32_t size;
Paul Lawrence731a7a22015-04-28 22:14:15 +000084 };
85
86 namespace tag {
87 const char* magic = "magic";
88 const char* major_version = "major_version";
89 const char* minor_version = "minor_version";
90 const char* flags = "flags";
91 const char* crypt_type = "crypt_type";
92 const char* failed_decrypt_count = "failed_decrypt_count";
93 const char* crypto_type_name = "crypto_type_name";
94 const char* master_key = "master_key";
95 const char* salt = "salt";
96 const char* kdf_type = "kdf_type";
97 const char* N_factor = "N_factor";
98 const char* r_factor = "r_factor";
99 const char* p_factor = "p_factor";
100 const char* keymaster_blob = "keymaster_blob";
101 const char* scrypted_intermediate_key = "scrypted_intermediate_key";
102 }
103}
104
Paul Crowley95376d62015-05-06 15:04:43 +0100105static std::string e4crypt_install_key(const std::string &key);
Paul Crowleyf25a35a2015-05-06 13:38:53 +0100106
Paul Lawrence731a7a22015-04-28 22:14:15 +0000107static int put_crypt_ftr_and_key(const crypt_mnt_ftr& crypt_ftr,
108 UnencryptedProperties& props)
109{
110 SLOGI("Putting crypt footer");
111
112 bool success = props.Set<int>(tag::magic, crypt_ftr.magic)
113 && props.Set<int>(tag::major_version, crypt_ftr.major_version)
114 && props.Set<int>(tag::minor_version, crypt_ftr.minor_version)
115 && props.Set<int>(tag::flags, crypt_ftr.flags)
116 && props.Set<int>(tag::crypt_type, crypt_ftr.crypt_type)
117 && props.Set<int>(tag::failed_decrypt_count,
118 crypt_ftr.failed_decrypt_count)
119 && props.Set<std::string>(tag::crypto_type_name,
120 std::string(reinterpret_cast<const char*>(crypt_ftr.crypto_type_name)))
121 && props.Set<std::string>(tag::master_key,
122 std::string((const char*) crypt_ftr.master_key,
123 crypt_ftr.keysize))
124 && props.Set<std::string>(tag::salt,
125 std::string((const char*) crypt_ftr.salt,
126 SALT_LEN))
127 && props.Set<int>(tag::kdf_type, crypt_ftr.kdf_type)
128 && props.Set<int>(tag::N_factor, crypt_ftr.N_factor)
129 && props.Set<int>(tag::r_factor, crypt_ftr.r_factor)
130 && props.Set<int>(tag::p_factor, crypt_ftr.p_factor)
131 && props.Set<std::string>(tag::keymaster_blob,
132 std::string((const char*) crypt_ftr.keymaster_blob,
133 crypt_ftr.keymaster_blob_size))
134 && props.Set<std::string>(tag::scrypted_intermediate_key,
135 std::string((const char*) crypt_ftr.scrypted_intermediate_key,
136 SCRYPT_LEN));
137 return success ? 0 : -1;
138}
139
140static int get_crypt_ftr_and_key(crypt_mnt_ftr& crypt_ftr,
141 const UnencryptedProperties& props)
142{
143 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
144 crypt_ftr.magic = props.Get<int>(tag::magic);
145 crypt_ftr.major_version = props.Get<int>(tag::major_version);
146 crypt_ftr.minor_version = props.Get<int>(tag::minor_version);
Paul Lawrence0d9cd9e2015-05-05 15:58:27 -0700147 crypt_ftr.ftr_size = sizeof(crypt_ftr);
Paul Lawrence731a7a22015-04-28 22:14:15 +0000148 crypt_ftr.flags = props.Get<int>(tag::flags);
149 crypt_ftr.crypt_type = props.Get<int>(tag::crypt_type);
150 crypt_ftr.failed_decrypt_count = props.Get<int>(tag::failed_decrypt_count);
151 std::string crypto_type_name = props.Get<std::string>(tag::crypto_type_name);
152 strlcpy(reinterpret_cast<char*>(crypt_ftr.crypto_type_name),
153 crypto_type_name.c_str(),
154 sizeof(crypt_ftr.crypto_type_name));
155 std::string master_key = props.Get<std::string>(tag::master_key);
156 crypt_ftr.keysize = master_key.size();
157 if (crypt_ftr.keysize > sizeof(crypt_ftr.master_key)) {
158 SLOGE("Master key size too long");
159 return -1;
160 }
161 memcpy(crypt_ftr.master_key, &master_key[0], crypt_ftr.keysize);
162 std::string salt = props.Get<std::string>(tag::salt);
163 if (salt.size() != SALT_LEN) {
164 SLOGE("Salt wrong length");
165 return -1;
166 }
167 memcpy(crypt_ftr.salt, &salt[0], SALT_LEN);
168 crypt_ftr.kdf_type = props.Get<int>(tag::kdf_type);
169 crypt_ftr.N_factor = props.Get<int>(tag::N_factor);
170 crypt_ftr.r_factor = props.Get<int>(tag::r_factor);
171 crypt_ftr.p_factor = props.Get<int>(tag::p_factor);
172 std::string keymaster_blob = props.Get<std::string>(tag::keymaster_blob);
173 crypt_ftr.keymaster_blob_size = keymaster_blob.size();
174 if (crypt_ftr.keymaster_blob_size > sizeof(crypt_ftr.keymaster_blob)) {
175 SLOGE("Keymaster blob too long");
176 return -1;
177 }
178 memcpy(crypt_ftr.keymaster_blob, &keymaster_blob[0],
179 crypt_ftr.keymaster_blob_size);
180 std::string scrypted_intermediate_key = props.Get<std::string>(tag::scrypted_intermediate_key);
181 if (scrypted_intermediate_key.size() != SCRYPT_LEN) {
182 SLOGE("scrypted intermediate key wrong length");
183 return -1;
184 }
185 memcpy(crypt_ftr.scrypted_intermediate_key, &scrypted_intermediate_key[0],
186 SCRYPT_LEN);
187
188 return 0;
189}
190
191static UnencryptedProperties GetProps(const char* path)
192{
193 return UnencryptedProperties(path);
194}
195
196static UnencryptedProperties GetAltProps(const char* path)
197{
198 return UnencryptedProperties((std::string() + path + "/tmp_mnt").c_str());
199}
200
201static UnencryptedProperties GetPropsOrAltProps(const char* path)
202{
203 UnencryptedProperties props = GetProps(path);
204 if (props.OK()) {
205 return props;
206 }
207 return GetAltProps(path);
208}
209
210int e4crypt_enable(const char* path)
211{
212 // Already enabled?
213 if (s_key_store.find(path) != s_key_store.end()) {
214 return 0;
215 }
216
217 // Not an encryptable device?
218 UnencryptedProperties key_props = GetProps(path).GetChild(properties::key);
219 if (!key_props.OK()) {
220 return 0;
221 }
222
223 if (key_props.Get<std::string>(tag::master_key).empty()) {
224 crypt_mnt_ftr ftr;
225 if (cryptfs_create_default_ftr(&ftr, key_length)) {
226 SLOGE("Failed to create crypto footer");
227 return -1;
228 }
229
Paul Lawrence0d9cd9e2015-05-05 15:58:27 -0700230 // Scrub fields not used by ext4enc
231 ftr.persist_data_offset[0] = 0;
232 ftr.persist_data_offset[1] = 0;
233 ftr.persist_data_size = 0;
234
Paul Lawrence731a7a22015-04-28 22:14:15 +0000235 if (put_crypt_ftr_and_key(ftr, key_props)) {
236 SLOGE("Failed to write crypto footer");
237 return -1;
238 }
239
240 crypt_mnt_ftr ftr2;
241 if (get_crypt_ftr_and_key(ftr2, key_props)) {
242 SLOGE("Failed to read crypto footer back");
243 return -1;
244 }
245
246 if (memcmp(&ftr, &ftr2, sizeof(ftr)) != 0) {
247 SLOGE("Crypto footer not correctly written");
Paul Lawrence0d9cd9e2015-05-05 15:58:27 -0700248 return -1;
Paul Lawrence731a7a22015-04-28 22:14:15 +0000249 }
250 }
251
252 if (!UnencryptedProperties(path).Remove(properties::ref)) {
253 SLOGE("Failed to remove key ref");
254 return -1;
255 }
256
257 return e4crypt_check_passwd(path, "");
258}
259
260int e4crypt_change_password(const char* path, int crypt_type,
261 const char* password)
262{
263 SLOGI("e4crypt_change_password");
Paul Lawrencea56d3132015-05-04 15:48:24 -0700264 auto key_props = GetProps(path).GetChild(properties::key);
Paul Lawrence731a7a22015-04-28 22:14:15 +0000265
266 crypt_mnt_ftr ftr;
267 if (get_crypt_ftr_and_key(ftr, key_props)) {
268 SLOGE("Failed to read crypto footer back");
269 return -1;
270 }
271
272 auto mki = s_key_store.find(path);
273 if (mki == s_key_store.end()) {
274 SLOGE("No stored master key - can't change password");
275 return -1;
276 }
277
Paul Crowley95376d62015-05-06 15:04:43 +0100278 const unsigned char* master_key_bytes
Paul Lawrence731a7a22015-04-28 22:14:15 +0000279 = reinterpret_cast<const unsigned char*>(&mki->second.master_key[0]);
280
Paul Crowley95376d62015-05-06 15:04:43 +0100281 if (cryptfs_set_password(&ftr, password, master_key_bytes)) {
Paul Lawrence731a7a22015-04-28 22:14:15 +0000282 SLOGE("Failed to set password");
283 return -1;
284 }
285
286 ftr.crypt_type = crypt_type;
287
288 if (put_crypt_ftr_and_key(ftr, key_props)) {
289 SLOGE("Failed to write crypto footer");
290 return -1;
291 }
292
293 if (!UnencryptedProperties(path).Set(properties::is_default,
294 crypt_type == CRYPT_TYPE_DEFAULT)) {
295 SLOGE("Failed to update default flag");
296 return -1;
297 }
298
299 return 0;
300}
301
302int e4crypt_crypto_complete(const char* path)
303{
304 SLOGI("ext4 crypto complete called on %s", path);
Paul Lawrencea56d3132015-05-04 15:48:24 -0700305 auto key_props = GetPropsOrAltProps(path).GetChild(properties::key);
Paul Lawrence731a7a22015-04-28 22:14:15 +0000306 if (key_props.Get<std::string>(tag::master_key).empty()) {
307 SLOGI("No master key, so not ext4enc");
308 return -1;
309 }
310
311 return 0;
312}
313
Paul Crowley93363482015-07-07 15:17:22 +0100314// Get raw keyref - used to make keyname and to pass to ioctl
Paul Lawrencefd7db732015-04-10 07:48:51 -0700315static std::string generate_key_ref(const char* key, int length)
316{
317 SHA512_CTX c;
318
319 SHA512_Init(&c);
320 SHA512_Update(&c, key, length);
321 unsigned char key_ref1[SHA512_LENGTH];
322 SHA512_Final(key_ref1, &c);
323
324 SHA512_Init(&c);
325 SHA512_Update(&c, key_ref1, SHA512_LENGTH);
326 unsigned char key_ref2[SHA512_LENGTH];
327 SHA512_Final(key_ref2, &c);
328
329 return std::string((char*)key_ref2, EXT4_KEY_DESCRIPTOR_SIZE);
330}
331
Paul Lawrence731a7a22015-04-28 22:14:15 +0000332int e4crypt_check_passwd(const char* path, const char* password)
333{
334 SLOGI("e4crypt_check_password");
Paul Lawrencea56d3132015-05-04 15:48:24 -0700335 auto props = GetPropsOrAltProps(path);
336 auto key_props = props.GetChild(properties::key);
Paul Lawrence731a7a22015-04-28 22:14:15 +0000337
338 crypt_mnt_ftr ftr;
339 if (get_crypt_ftr_and_key(ftr, key_props)) {
340 SLOGE("Failed to read crypto footer back");
341 return -1;
342 }
343
Paul Crowley95376d62015-05-06 15:04:43 +0100344 unsigned char master_key_bytes[key_length / 8];
345 if (cryptfs_get_master_key (&ftr, password, master_key_bytes)){
Paul Lawrence731a7a22015-04-28 22:14:15 +0000346 SLOGI("Incorrect password");
Paul Lawrencec78c71b2015-04-14 15:26:29 -0700347 ftr.failed_decrypt_count++;
348 if (put_crypt_ftr_and_key(ftr, key_props)) {
349 SLOGW("Failed to update failed_decrypt_count");
350 }
351 return ftr.failed_decrypt_count;
352 }
353
354 if (ftr.failed_decrypt_count) {
355 ftr.failed_decrypt_count = 0;
356 if (put_crypt_ftr_and_key(ftr, key_props)) {
357 SLOGW("Failed to reset failed_decrypt_count");
358 }
Paul Lawrence731a7a22015-04-28 22:14:15 +0000359 }
Paul Crowley95376d62015-05-06 15:04:43 +0100360 std::string master_key(reinterpret_cast<char*>(master_key_bytes),
361 sizeof(master_key_bytes));
Paul Lawrence731a7a22015-04-28 22:14:15 +0000362
Paul Lawrence86c942a2015-05-06 13:53:43 -0700363 struct timespec now;
364 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Crowley95376d62015-05-06 15:04:43 +0100365 s_key_store[path] = keys{master_key, password,
Paul Lawrence86c942a2015-05-06 13:53:43 -0700366 now.tv_sec + password_max_age_seconds};
Paul Crowleyf25a35a2015-05-06 13:38:53 +0100367 auto raw_ref = e4crypt_install_key(master_key);
368 if (raw_ref.empty()) {
369 return -1;
370 }
Paul Lawrence731a7a22015-04-28 22:14:15 +0000371
Paul Crowleyf25a35a2015-05-06 13:38:53 +0100372 // Save reference to key so we can set policy later
373 if (!props.Set(properties::ref, raw_ref)) {
374 SLOGE("Cannot save key reference");
375 return -1;
376 }
377
378 return 0;
379}
380
Paul Crowley93363482015-07-07 15:17:22 +0100381static ext4_encryption_key fill_key(const std::string &key)
Paul Crowleyf25a35a2015-05-06 13:38:53 +0100382{
Paul Lawrencefd7db732015-04-10 07:48:51 -0700383 // ext4enc:TODO Currently raw key is required to be of length
384 // sizeof(ext4_key.raw) == EXT4_MAX_KEY_SIZE, so zero pad to
385 // this length. Change when kernel bug is fixed.
386 ext4_encryption_key ext4_key = {EXT4_ENCRYPTION_MODE_AES_256_XTS,
387 {0},
388 sizeof(ext4_key.raw)};
389 memset(ext4_key.raw, 0, sizeof(ext4_key.raw));
390 static_assert(key_length / 8 <= sizeof(ext4_key.raw),
391 "Key too long!");
Paul Crowley95376d62015-05-06 15:04:43 +0100392 memcpy(ext4_key.raw, &key[0], key.size());
Paul Crowley93363482015-07-07 15:17:22 +0100393 return ext4_key;
394}
Paul Lawrence731a7a22015-04-28 22:14:15 +0000395
Paul Crowley93363482015-07-07 15:17:22 +0100396static std::string keyname(const std::string &raw_ref)
397{
Paul Lawrencefd7db732015-04-10 07:48:51 -0700398 std::ostringstream o;
Paul Crowley93363482015-07-07 15:17:22 +0100399 o << "ext4:";
Paul Lawrencefd7db732015-04-10 07:48:51 -0700400 for (auto i = raw_ref.begin(); i != raw_ref.end(); ++i) {
401 o << std::hex << std::setw(2) << std::setfill('0') << (int)*i;
402 }
Paul Crowley93363482015-07-07 15:17:22 +0100403 return o.str();
404}
Paul Lawrencefd7db732015-04-10 07:48:51 -0700405
Paul Crowley93363482015-07-07 15:17:22 +0100406// Get the keyring we store all keys in
407static key_serial_t e4crypt_keyring()
408{
409 return keyctl_search(KEY_SPEC_SESSION_KEYRING, "keyring", "e4crypt", 0);
410}
Paul Lawrence731a7a22015-04-28 22:14:15 +0000411
Paul Crowley93363482015-07-07 15:17:22 +0100412static int e4crypt_install_key(const ext4_encryption_key &ext4_key, const std::string &ref)
413{
414 key_serial_t device_keyring = e4crypt_keyring();
Paul Lawrence731a7a22015-04-28 22:14:15 +0000415 SLOGI("Found device_keyring - id is %d", device_keyring);
Paul Lawrencefd7db732015-04-10 07:48:51 -0700416 key_serial_t key_id = add_key("logon", ref.c_str(),
Paul Lawrence731a7a22015-04-28 22:14:15 +0000417 (void*)&ext4_key, sizeof(ext4_key),
418 device_keyring);
Paul Lawrence731a7a22015-04-28 22:14:15 +0000419 if (key_id == -1) {
420 SLOGE("Failed to insert key into keyring with error %s",
421 strerror(errno));
Paul Crowley93363482015-07-07 15:17:22 +0100422 return -1;
Paul Lawrence731a7a22015-04-28 22:14:15 +0000423 }
Paul Lawrencefd7db732015-04-10 07:48:51 -0700424 SLOGI("Added key %d (%s) to keyring %d in process %d",
425 key_id, ref.c_str(), device_keyring, getpid());
Paul Crowley93363482015-07-07 15:17:22 +0100426 return 0;
427}
Paul Lawrence731a7a22015-04-28 22:14:15 +0000428
Paul Crowley93363482015-07-07 15:17:22 +0100429// Install password into global keyring
430// Return raw key reference for use in policy
431static std::string e4crypt_install_key(const std::string &key)
432{
433 auto ext4_key = fill_key(key);
434 auto raw_ref = generate_key_ref(ext4_key.raw, ext4_key.size);
435 auto ref = keyname(raw_ref);
436 if (e4crypt_install_key(ext4_key, ref) == -1) {
437 return "";
438 }
Paul Crowleyf25a35a2015-05-06 13:38:53 +0100439 return raw_ref;
Paul Lawrence731a7a22015-04-28 22:14:15 +0000440}
441
442int e4crypt_restart(const char* path)
443{
444 SLOGI("e4crypt_restart");
445
446 int rc = 0;
447
448 SLOGI("ext4 restart called on %s", path);
449 property_set("vold.decrypt", "trigger_reset_main");
450 SLOGI("Just asked init to shut down class main");
451 sleep(2);
452
453 std::string tmp_path = std::string() + path + "/tmp_mnt";
454
Paul Lawrence2f32cda2015-05-05 14:28:25 -0700455 rc = wait_and_unmount(tmp_path.c_str(), true);
Paul Lawrence731a7a22015-04-28 22:14:15 +0000456 if (rc) {
457 SLOGE("umount %s failed with rc %d, msg %s",
458 tmp_path.c_str(), rc, strerror(errno));
459 return rc;
460 }
461
Paul Lawrence2f32cda2015-05-05 14:28:25 -0700462 rc = wait_and_unmount(path, true);
Paul Lawrence731a7a22015-04-28 22:14:15 +0000463 if (rc) {
464 SLOGE("umount %s failed with rc %d, msg %s",
465 path, rc, strerror(errno));
466 return rc;
467 }
468
469 return 0;
470}
471
Paul Lawrence731a7a22015-04-28 22:14:15 +0000472int e4crypt_get_password_type(const char* path)
473{
474 SLOGI("e4crypt_get_password_type");
475 return GetPropsOrAltProps(path).GetChild(properties::key)
476 .Get<int>(tag::crypt_type, CRYPT_TYPE_DEFAULT);
477}
Paul Lawrence368d7942015-04-15 14:12:00 -0700478
Paul Lawrence86c942a2015-05-06 13:53:43 -0700479const char* e4crypt_get_password(const char* path)
480{
481 SLOGI("e4crypt_get_password");
482
483 auto i = s_key_store.find(path);
484 if (i == s_key_store.end()) {
485 return 0;
486 }
487
488 struct timespec now;
489 clock_gettime(CLOCK_BOOTTIME, &now);
490 if (i->second.expiry_time < now.tv_sec) {
491 e4crypt_clear_password(path);
492 return 0;
493 }
494
495 return i->second.password.c_str();
496}
497
498void e4crypt_clear_password(const char* path)
499{
500 SLOGI("e4crypt_clear_password");
501
502 auto i = s_key_store.find(path);
503 if (i == s_key_store.end()) {
504 return;
505 }
506
507 memset(&i->second.password[0], 0, i->second.password.size());
508 i->second.password = std::string();
509}
510
Paul Lawrence368d7942015-04-15 14:12:00 -0700511int e4crypt_get_field(const char* path, const char* fieldname,
512 char* value, size_t len)
513{
514 auto v = GetPropsOrAltProps(path).GetChild(properties::props)
515 .Get<std::string>(fieldname);
516
517 if (v == "") {
518 return CRYPTO_GETFIELD_ERROR_NO_FIELD;
519 }
520
521 if (v.length() >= len) {
522 return CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
523 }
524
525 strlcpy(value, v.c_str(), len);
526 return 0;
527}
528
529int e4crypt_set_field(const char* path, const char* fieldname,
530 const char* value)
531{
532 return GetPropsOrAltProps(path).GetChild(properties::props)
533 .Set(fieldname, std::string(value)) ? 0 : -1;
534}
Paul Crowley95376d62015-05-06 15:04:43 +0100535
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800536static std::string get_key_path(const char *mount_path, userid_t user_id) {
Paul Crowley95376d62015-05-06 15:04:43 +0100537 // ext4enc:TODO get the path properly
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800538 auto key_dir = StringPrintf("%s/misc/vold/user_keys", mount_path);
539 if (fs_prepare_dir(key_dir.c_str(), 0700, AID_ROOT, AID_ROOT)) {
540 PLOG(ERROR) << "Failed to prepare " << key_dir;
Paul Crowley95376d62015-05-06 15:04:43 +0100541 return "";
542 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800543 return StringPrintf("%s/%d", key_dir.c_str(), user_id);
Paul Crowleyb33e8872015-05-19 12:34:09 +0100544}
545
546// ext4enc:TODO this can't be the only place keys are read from /dev/urandom
547// we should unite those places.
Paul Crowley93363482015-07-07 15:17:22 +0100548static std::string e4crypt_get_key(
549 const std::string &key_path,
Paul Crowleyb33e8872015-05-19 12:34:09 +0100550 bool create_if_absent)
551{
Paul Crowley95376d62015-05-06 15:04:43 +0100552 std::string content;
553 if (android::base::ReadFileToString(key_path, &content)) {
554 if (content.size() != key_length/8) {
555 SLOGE("Wrong size key %zu in %s", content.size(), key_path.c_str());
556 return "";
557 }
558 return content;
559 }
560 if (!create_if_absent) {
561 SLOGE("No key found in %s", key_path.c_str());
562 return "";
563 }
564 std::ifstream urandom("/dev/urandom");
565 if (!urandom) {
566 SLOGE("Unable to open /dev/urandom (%s)", strerror(errno));
567 return "";
568 }
569 char key_bytes[key_length / 8];
570 errno = 0;
571 urandom.read(key_bytes, sizeof(key_bytes));
572 if (!urandom) {
573 SLOGE("Unable to read key from /dev/urandom (%s)", strerror(errno));
574 return "";
575 }
Paul Crowley93363482015-07-07 15:17:22 +0100576 std::string key(key_bytes, sizeof(key_bytes));
577 if (!android::base::WriteStringToFile(key, key_path)) {
Paul Crowley95376d62015-05-06 15:04:43 +0100578 SLOGE("Unable to write key to %s (%s)",
579 key_path.c_str(), strerror(errno));
580 return "";
581 }
Paul Crowley93363482015-07-07 15:17:22 +0100582 return key;
Paul Crowley95376d62015-05-06 15:04:43 +0100583}
584
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800585static int e4crypt_set_user_policy(const char *mount_path, userid_t user_id,
586 const char *path, bool create_if_absent) {
587 SLOGD("e4crypt_set_user_policy for %d", user_id);
588 auto user_key = e4crypt_get_key(get_key_path(mount_path, user_id),
589 create_if_absent);
Paul Crowley95376d62015-05-06 15:04:43 +0100590 if (user_key.empty()) {
591 return -1;
592 }
593 auto raw_ref = e4crypt_install_key(user_key);
594 if (raw_ref.empty()) {
595 return -1;
596 }
597 return do_policy_set(path, raw_ref.c_str(), raw_ref.size());
598}
599
Paul Crowley95376d62015-05-06 15:04:43 +0100600static bool is_numeric(const char *name) {
601 for (const char *p = name; *p != '\0'; p++) {
602 if (!isdigit(*p))
603 return false;
604 }
605 return true;
606}
607
608int e4crypt_set_user_crypto_policies(const char *dir)
609{
610 if (e4crypt_crypto_complete(DATA_MNT_POINT) != 0) {
611 return 0;
612 }
613 SLOGD("e4crypt_set_user_crypto_policies");
614 std::unique_ptr<DIR, int(*)(DIR*)> dirp(opendir(dir), closedir);
615 if (!dirp) {
616 SLOGE("Unable to read directory %s, error %s\n",
617 dir, strerror(errno));
618 return -1;
619 }
620 for (;;) {
621 struct dirent *result = readdir(dirp.get());
622 if (!result) {
623 // ext4enc:TODO check errno
624 break;
625 }
626 if (result->d_type != DT_DIR || !is_numeric(result->d_name)) {
627 continue; // skips user 0, which is a symlink
628 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800629 auto user_id = atoi(result->d_name);
Paul Crowley95376d62015-05-06 15:04:43 +0100630 auto user_dir = std::string() + dir + "/" + result->d_name;
631 // ext4enc:TODO don't hardcode /data
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800632 if (e4crypt_set_user_policy("/data", user_id, user_dir.c_str(), false)) {
Paul Crowley95376d62015-05-06 15:04:43 +0100633 // ext4enc:TODO If this function fails, stop the boot: we must
634 // deliver on promised encryption.
635 SLOGE("Unable to set policy on %s\n", user_dir.c_str());
636 }
637 }
638 return 0;
639}
Paul Crowleyb33e8872015-05-19 12:34:09 +0100640
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800641int e4crypt_create_user_key(userid_t user_id) {
642 SLOGD("e4crypt_create_user_key(%d)", user_id);
643 // TODO: create second key for user_de data
644 if (e4crypt_get_key(get_key_path(DATA_MNT_POINT, user_id), true).empty()) {
645 return -1;
646 } else {
647 return 0;
648 }
649}
650
651int e4crypt_destroy_user_key(userid_t user_id) {
652 SLOGD("e4crypt_destroy_user_key(%d)", user_id);
653 // TODO: destroy second key for user_de data
654 auto key_path = get_key_path(DATA_MNT_POINT, user_id);
Paul Crowley93363482015-07-07 15:17:22 +0100655 auto key = e4crypt_get_key(key_path, false);
656 auto ext4_key = fill_key(key);
657 auto ref = keyname(generate_key_ref(ext4_key.raw, ext4_key.size));
658 auto key_serial = keyctl_search(e4crypt_keyring(), "logon", ref.c_str(), 0);
659 if (keyctl_revoke(key_serial) == 0) {
660 SLOGD("Revoked key with serial %ld ref %s\n", key_serial, ref.c_str());
661 } else {
662 SLOGE("Failed to revoke key with serial %ld ref %s: %s\n",
663 key_serial, ref.c_str(), strerror(errno));
664 }
Paul Crowleycd307b72015-05-19 17:31:39 +0100665 int pid = fork();
666 if (pid < 0) {
667 SLOGE("Unable to fork: %s", strerror(errno));
Paul Crowleyb33e8872015-05-19 12:34:09 +0100668 return -1;
669 }
Paul Crowleycd307b72015-05-19 17:31:39 +0100670 if (pid == 0) {
671 SLOGD("Forked for secdiscard");
672 execl("/system/bin/secdiscard",
673 "/system/bin/secdiscard",
Paul Crowley5ab73e92015-07-03 16:17:23 +0100674 "--",
Paul Crowleycd307b72015-05-19 17:31:39 +0100675 key_path.c_str(),
676 NULL);
677 SLOGE("Unable to launch secdiscard on %s: %s\n", key_path.c_str(),
678 strerror(errno));
679 exit(-1);
680 }
681 // ext4enc:TODO reap the zombie
Paul Crowleyb33e8872015-05-19 12:34:09 +0100682 return 0;
683}
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800684
685int e4crypt_unlock_user_key(userid_t user_id, const char* token) {
686 if (property_get_bool("vold.emulate_fbe", false)) {
687 // When in emulation mode, we just use chmod
688 if (chmod(android::vold::BuildDataSystemCePath(user_id).c_str(), 0771) ||
689 chmod(android::vold::BuildDataUserPath(nullptr, user_id).c_str(), 0771)) {
690 PLOG(ERROR) << "Failed to unlock user " << user_id;
691 return -1;
692 }
693 } else {
694 auto user_key = e4crypt_get_key(get_key_path(DATA_MNT_POINT, user_id), false);
695 if (user_key.empty()) {
696 return -1;
697 }
698 auto raw_ref = e4crypt_install_key(user_key);
699 if (raw_ref.empty()) {
700 return -1;
701 }
702 }
703 return 0;
704}
705
706int e4crypt_lock_user_key(userid_t user_id) {
707 if (property_get_bool("vold.emulate_fbe", false)) {
708 // When in emulation mode, we just use chmod
709 if (chmod(android::vold::BuildDataSystemCePath(user_id).c_str(), 0000) ||
710 chmod(android::vold::BuildDataUserPath(nullptr, user_id).c_str(), 0000)) {
711 PLOG(ERROR) << "Failed to lock user " << user_id;
712 return -1;
713 }
714 } else {
715 // TODO: remove from kernel keyring
716 }
717 return 0;
718}
719
720int e4crypt_prepare_user_storage(const char* volume_uuid, userid_t user_id) {
721 std::string system_ce_path(android::vold::BuildDataSystemCePath(user_id));
722 std::string user_ce_path(android::vold::BuildDataUserPath(volume_uuid, user_id));
723 std::string user_de_path(android::vold::BuildDataUserDePath(volume_uuid, user_id));
724
725 if (fs_prepare_dir(system_ce_path.c_str(), 0700, AID_SYSTEM, AID_SYSTEM)) {
726 PLOG(ERROR) << "Failed to prepare " << system_ce_path;
727 return -1;
728 }
729 if (fs_prepare_dir(user_ce_path.c_str(), 0771, AID_SYSTEM, AID_SYSTEM)) {
730 PLOG(ERROR) << "Failed to prepare " << user_ce_path;
731 return -1;
732 }
733 if (fs_prepare_dir(user_de_path.c_str(), 0771, AID_SYSTEM, AID_SYSTEM)) {
734 PLOG(ERROR) << "Failed to prepare " << user_de_path;
735 return -1;
736 }
737
738 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
739 if (e4crypt_set_user_policy(DATA_MNT_POINT, user_id, system_ce_path.c_str(), true)
740 || e4crypt_set_user_policy(DATA_MNT_POINT, user_id, user_ce_path.c_str(), true)) {
741 return -1;
742 }
743 }
744
745 return 0;
746}