blob: 38dc27d7183cb733c4f7c4243c4913ca039c3efa [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
Elliott Hughes7e128fb2015-12-04 15:50:53 -080049#include <android-base/file.h>
Elliott Hughes6bf05472015-12-04 17:55:33 -080050#include <android-base/logging.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080051#include <android-base/stringprintf.h>
Paul Lawrence731a7a22015-04-28 22:14:15 +000052
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -080053using android::base::StringPrintf;
54
Jeff Sharkeyfc505c32015-12-07 17:27:01 -070055static bool e4crypt_is_native() {
56 char value[PROPERTY_VALUE_MAX];
57 property_get("ro.crypto.type", value, "none");
58 return !strcmp(value, "file");
59}
60
61static bool e4crypt_is_emulated() {
62 return property_get_bool("persist.sys.emulate_fbe", false);
63}
Jeff Sharkeyc79fb892015-11-12 20:18:02 -080064
Paul Lawrence731a7a22015-04-28 22:14:15 +000065namespace {
66 // Key length in bits
67 const int key_length = 128;
Paul Lawrencefd7db732015-04-10 07:48:51 -070068 static_assert(key_length % 8 == 0,
69 "Key length must be multiple of 8 bits");
Paul Lawrence731a7a22015-04-28 22:14:15 +000070
Paul Lawrence86c942a2015-05-06 13:53:43 -070071 // How long do we store passwords for?
72 const int password_max_age_seconds = 60;
73
Paul Lawrence731a7a22015-04-28 22:14:15 +000074 // How is device encrypted
75 struct keys {
76 std::string master_key;
77 std::string password;
Paul Lawrence86c942a2015-05-06 13:53:43 -070078 time_t expiry_time;
Paul Lawrence731a7a22015-04-28 22:14:15 +000079 };
80 std::map<std::string, keys> s_key_store;
Lenka Trochtova395039f2015-11-25 10:13:03 +010081 // Maps the key paths of ephemeral keys to the keys
82 std::map<std::string, std::string> s_ephemeral_user_keys;
Paul Lawrence731a7a22015-04-28 22:14:15 +000083
Paul Lawrencefd7db732015-04-10 07:48:51 -070084 // ext4enc:TODO get these consts from somewhere good
85 const int SHA512_LENGTH = 64;
86 const int EXT4_KEY_DESCRIPTOR_SIZE = 8;
87
Paul Lawrence731a7a22015-04-28 22:14:15 +000088 // ext4enc:TODO Include structure from somewhere sensible
89 // MUST be in sync with ext4_crypto.c in kernel
Paul Lawrencefd7db732015-04-10 07:48:51 -070090 const int EXT4_MAX_KEY_SIZE = 64;
91 const int EXT4_ENCRYPTION_MODE_AES_256_XTS = 1;
Paul Lawrence731a7a22015-04-28 22:14:15 +000092 struct ext4_encryption_key {
Paul Lawrencefd7db732015-04-10 07:48:51 -070093 uint32_t mode;
94 char raw[EXT4_MAX_KEY_SIZE];
95 uint32_t size;
Paul Lawrence731a7a22015-04-28 22:14:15 +000096 };
97
98 namespace tag {
99 const char* magic = "magic";
100 const char* major_version = "major_version";
101 const char* minor_version = "minor_version";
102 const char* flags = "flags";
103 const char* crypt_type = "crypt_type";
104 const char* failed_decrypt_count = "failed_decrypt_count";
105 const char* crypto_type_name = "crypto_type_name";
106 const char* master_key = "master_key";
107 const char* salt = "salt";
108 const char* kdf_type = "kdf_type";
109 const char* N_factor = "N_factor";
110 const char* r_factor = "r_factor";
111 const char* p_factor = "p_factor";
112 const char* keymaster_blob = "keymaster_blob";
113 const char* scrypted_intermediate_key = "scrypted_intermediate_key";
114 }
115}
116
Paul Crowley95376d62015-05-06 15:04:43 +0100117static std::string e4crypt_install_key(const std::string &key);
Paul Crowleyf25a35a2015-05-06 13:38:53 +0100118
Paul Lawrence731a7a22015-04-28 22:14:15 +0000119static int put_crypt_ftr_and_key(const crypt_mnt_ftr& crypt_ftr,
120 UnencryptedProperties& props)
121{
122 SLOGI("Putting crypt footer");
123
124 bool success = props.Set<int>(tag::magic, crypt_ftr.magic)
125 && props.Set<int>(tag::major_version, crypt_ftr.major_version)
126 && props.Set<int>(tag::minor_version, crypt_ftr.minor_version)
127 && props.Set<int>(tag::flags, crypt_ftr.flags)
128 && props.Set<int>(tag::crypt_type, crypt_ftr.crypt_type)
129 && props.Set<int>(tag::failed_decrypt_count,
130 crypt_ftr.failed_decrypt_count)
131 && props.Set<std::string>(tag::crypto_type_name,
132 std::string(reinterpret_cast<const char*>(crypt_ftr.crypto_type_name)))
133 && props.Set<std::string>(tag::master_key,
134 std::string((const char*) crypt_ftr.master_key,
135 crypt_ftr.keysize))
136 && props.Set<std::string>(tag::salt,
137 std::string((const char*) crypt_ftr.salt,
138 SALT_LEN))
139 && props.Set<int>(tag::kdf_type, crypt_ftr.kdf_type)
140 && props.Set<int>(tag::N_factor, crypt_ftr.N_factor)
141 && props.Set<int>(tag::r_factor, crypt_ftr.r_factor)
142 && props.Set<int>(tag::p_factor, crypt_ftr.p_factor)
143 && props.Set<std::string>(tag::keymaster_blob,
144 std::string((const char*) crypt_ftr.keymaster_blob,
145 crypt_ftr.keymaster_blob_size))
146 && props.Set<std::string>(tag::scrypted_intermediate_key,
147 std::string((const char*) crypt_ftr.scrypted_intermediate_key,
148 SCRYPT_LEN));
149 return success ? 0 : -1;
150}
151
152static int get_crypt_ftr_and_key(crypt_mnt_ftr& crypt_ftr,
153 const UnencryptedProperties& props)
154{
155 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
156 crypt_ftr.magic = props.Get<int>(tag::magic);
157 crypt_ftr.major_version = props.Get<int>(tag::major_version);
158 crypt_ftr.minor_version = props.Get<int>(tag::minor_version);
Paul Lawrence0d9cd9e2015-05-05 15:58:27 -0700159 crypt_ftr.ftr_size = sizeof(crypt_ftr);
Paul Lawrence731a7a22015-04-28 22:14:15 +0000160 crypt_ftr.flags = props.Get<int>(tag::flags);
161 crypt_ftr.crypt_type = props.Get<int>(tag::crypt_type);
162 crypt_ftr.failed_decrypt_count = props.Get<int>(tag::failed_decrypt_count);
163 std::string crypto_type_name = props.Get<std::string>(tag::crypto_type_name);
164 strlcpy(reinterpret_cast<char*>(crypt_ftr.crypto_type_name),
165 crypto_type_name.c_str(),
166 sizeof(crypt_ftr.crypto_type_name));
167 std::string master_key = props.Get<std::string>(tag::master_key);
168 crypt_ftr.keysize = master_key.size();
169 if (crypt_ftr.keysize > sizeof(crypt_ftr.master_key)) {
170 SLOGE("Master key size too long");
171 return -1;
172 }
173 memcpy(crypt_ftr.master_key, &master_key[0], crypt_ftr.keysize);
174 std::string salt = props.Get<std::string>(tag::salt);
175 if (salt.size() != SALT_LEN) {
176 SLOGE("Salt wrong length");
177 return -1;
178 }
179 memcpy(crypt_ftr.salt, &salt[0], SALT_LEN);
180 crypt_ftr.kdf_type = props.Get<int>(tag::kdf_type);
181 crypt_ftr.N_factor = props.Get<int>(tag::N_factor);
182 crypt_ftr.r_factor = props.Get<int>(tag::r_factor);
183 crypt_ftr.p_factor = props.Get<int>(tag::p_factor);
184 std::string keymaster_blob = props.Get<std::string>(tag::keymaster_blob);
185 crypt_ftr.keymaster_blob_size = keymaster_blob.size();
186 if (crypt_ftr.keymaster_blob_size > sizeof(crypt_ftr.keymaster_blob)) {
187 SLOGE("Keymaster blob too long");
188 return -1;
189 }
190 memcpy(crypt_ftr.keymaster_blob, &keymaster_blob[0],
191 crypt_ftr.keymaster_blob_size);
192 std::string scrypted_intermediate_key = props.Get<std::string>(tag::scrypted_intermediate_key);
193 if (scrypted_intermediate_key.size() != SCRYPT_LEN) {
194 SLOGE("scrypted intermediate key wrong length");
195 return -1;
196 }
197 memcpy(crypt_ftr.scrypted_intermediate_key, &scrypted_intermediate_key[0],
198 SCRYPT_LEN);
199
200 return 0;
201}
202
203static UnencryptedProperties GetProps(const char* path)
204{
205 return UnencryptedProperties(path);
206}
207
208static UnencryptedProperties GetAltProps(const char* path)
209{
210 return UnencryptedProperties((std::string() + path + "/tmp_mnt").c_str());
211}
212
213static UnencryptedProperties GetPropsOrAltProps(const char* path)
214{
215 UnencryptedProperties props = GetProps(path);
216 if (props.OK()) {
217 return props;
218 }
219 return GetAltProps(path);
220}
221
222int e4crypt_enable(const char* path)
223{
224 // Already enabled?
225 if (s_key_store.find(path) != s_key_store.end()) {
226 return 0;
227 }
228
229 // Not an encryptable device?
230 UnencryptedProperties key_props = GetProps(path).GetChild(properties::key);
231 if (!key_props.OK()) {
232 return 0;
233 }
234
235 if (key_props.Get<std::string>(tag::master_key).empty()) {
236 crypt_mnt_ftr ftr;
237 if (cryptfs_create_default_ftr(&ftr, key_length)) {
238 SLOGE("Failed to create crypto footer");
239 return -1;
240 }
241
Paul Lawrence0d9cd9e2015-05-05 15:58:27 -0700242 // Scrub fields not used by ext4enc
243 ftr.persist_data_offset[0] = 0;
244 ftr.persist_data_offset[1] = 0;
245 ftr.persist_data_size = 0;
246
Paul Lawrence731a7a22015-04-28 22:14:15 +0000247 if (put_crypt_ftr_and_key(ftr, key_props)) {
248 SLOGE("Failed to write crypto footer");
249 return -1;
250 }
251
252 crypt_mnt_ftr ftr2;
253 if (get_crypt_ftr_and_key(ftr2, key_props)) {
254 SLOGE("Failed to read crypto footer back");
255 return -1;
256 }
257
258 if (memcmp(&ftr, &ftr2, sizeof(ftr)) != 0) {
259 SLOGE("Crypto footer not correctly written");
Paul Lawrence0d9cd9e2015-05-05 15:58:27 -0700260 return -1;
Paul Lawrence731a7a22015-04-28 22:14:15 +0000261 }
262 }
263
264 if (!UnencryptedProperties(path).Remove(properties::ref)) {
265 SLOGE("Failed to remove key ref");
266 return -1;
267 }
268
269 return e4crypt_check_passwd(path, "");
270}
271
272int e4crypt_change_password(const char* path, int crypt_type,
273 const char* password)
274{
275 SLOGI("e4crypt_change_password");
Paul Lawrencea56d3132015-05-04 15:48:24 -0700276 auto key_props = GetProps(path).GetChild(properties::key);
Paul Lawrence731a7a22015-04-28 22:14:15 +0000277
278 crypt_mnt_ftr ftr;
279 if (get_crypt_ftr_and_key(ftr, key_props)) {
280 SLOGE("Failed to read crypto footer back");
281 return -1;
282 }
283
284 auto mki = s_key_store.find(path);
285 if (mki == s_key_store.end()) {
286 SLOGE("No stored master key - can't change password");
287 return -1;
288 }
289
Paul Crowley95376d62015-05-06 15:04:43 +0100290 const unsigned char* master_key_bytes
Paul Lawrence731a7a22015-04-28 22:14:15 +0000291 = reinterpret_cast<const unsigned char*>(&mki->second.master_key[0]);
292
Paul Crowley95376d62015-05-06 15:04:43 +0100293 if (cryptfs_set_password(&ftr, password, master_key_bytes)) {
Paul Lawrence731a7a22015-04-28 22:14:15 +0000294 SLOGE("Failed to set password");
295 return -1;
296 }
297
298 ftr.crypt_type = crypt_type;
299
300 if (put_crypt_ftr_and_key(ftr, key_props)) {
301 SLOGE("Failed to write crypto footer");
302 return -1;
303 }
304
305 if (!UnencryptedProperties(path).Set(properties::is_default,
306 crypt_type == CRYPT_TYPE_DEFAULT)) {
307 SLOGE("Failed to update default flag");
308 return -1;
309 }
310
311 return 0;
312}
313
314int e4crypt_crypto_complete(const char* path)
315{
316 SLOGI("ext4 crypto complete called on %s", path);
Paul Lawrencea56d3132015-05-04 15:48:24 -0700317 auto key_props = GetPropsOrAltProps(path).GetChild(properties::key);
Paul Lawrence731a7a22015-04-28 22:14:15 +0000318 if (key_props.Get<std::string>(tag::master_key).empty()) {
319 SLOGI("No master key, so not ext4enc");
320 return -1;
321 }
322
323 return 0;
324}
325
Paul Crowley93363482015-07-07 15:17:22 +0100326// Get raw keyref - used to make keyname and to pass to ioctl
Paul Lawrencefd7db732015-04-10 07:48:51 -0700327static std::string generate_key_ref(const char* key, int length)
328{
329 SHA512_CTX c;
330
331 SHA512_Init(&c);
332 SHA512_Update(&c, key, length);
333 unsigned char key_ref1[SHA512_LENGTH];
334 SHA512_Final(key_ref1, &c);
335
336 SHA512_Init(&c);
337 SHA512_Update(&c, key_ref1, SHA512_LENGTH);
338 unsigned char key_ref2[SHA512_LENGTH];
339 SHA512_Final(key_ref2, &c);
340
341 return std::string((char*)key_ref2, EXT4_KEY_DESCRIPTOR_SIZE);
342}
343
Paul Lawrence731a7a22015-04-28 22:14:15 +0000344int e4crypt_check_passwd(const char* path, const char* password)
345{
346 SLOGI("e4crypt_check_password");
Paul Lawrencea56d3132015-05-04 15:48:24 -0700347 auto props = GetPropsOrAltProps(path);
348 auto key_props = props.GetChild(properties::key);
Paul Lawrence731a7a22015-04-28 22:14:15 +0000349
350 crypt_mnt_ftr ftr;
351 if (get_crypt_ftr_and_key(ftr, key_props)) {
352 SLOGE("Failed to read crypto footer back");
353 return -1;
354 }
355
Paul Crowley95376d62015-05-06 15:04:43 +0100356 unsigned char master_key_bytes[key_length / 8];
357 if (cryptfs_get_master_key (&ftr, password, master_key_bytes)){
Paul Lawrence731a7a22015-04-28 22:14:15 +0000358 SLOGI("Incorrect password");
Paul Lawrencec78c71b2015-04-14 15:26:29 -0700359 ftr.failed_decrypt_count++;
360 if (put_crypt_ftr_and_key(ftr, key_props)) {
361 SLOGW("Failed to update failed_decrypt_count");
362 }
363 return ftr.failed_decrypt_count;
364 }
365
366 if (ftr.failed_decrypt_count) {
367 ftr.failed_decrypt_count = 0;
368 if (put_crypt_ftr_and_key(ftr, key_props)) {
369 SLOGW("Failed to reset failed_decrypt_count");
370 }
Paul Lawrence731a7a22015-04-28 22:14:15 +0000371 }
Paul Crowley95376d62015-05-06 15:04:43 +0100372 std::string master_key(reinterpret_cast<char*>(master_key_bytes),
373 sizeof(master_key_bytes));
Paul Lawrence731a7a22015-04-28 22:14:15 +0000374
Paul Lawrence86c942a2015-05-06 13:53:43 -0700375 struct timespec now;
376 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Crowley95376d62015-05-06 15:04:43 +0100377 s_key_store[path] = keys{master_key, password,
Paul Lawrence86c942a2015-05-06 13:53:43 -0700378 now.tv_sec + password_max_age_seconds};
Paul Crowleyf25a35a2015-05-06 13:38:53 +0100379 auto raw_ref = e4crypt_install_key(master_key);
380 if (raw_ref.empty()) {
381 return -1;
382 }
Paul Lawrence731a7a22015-04-28 22:14:15 +0000383
Paul Crowleyf25a35a2015-05-06 13:38:53 +0100384 // Save reference to key so we can set policy later
385 if (!props.Set(properties::ref, raw_ref)) {
386 SLOGE("Cannot save key reference");
387 return -1;
388 }
389
390 return 0;
391}
392
Paul Crowley93363482015-07-07 15:17:22 +0100393static ext4_encryption_key fill_key(const std::string &key)
Paul Crowleyf25a35a2015-05-06 13:38:53 +0100394{
Paul Lawrencefd7db732015-04-10 07:48:51 -0700395 // ext4enc:TODO Currently raw key is required to be of length
396 // sizeof(ext4_key.raw) == EXT4_MAX_KEY_SIZE, so zero pad to
397 // this length. Change when kernel bug is fixed.
398 ext4_encryption_key ext4_key = {EXT4_ENCRYPTION_MODE_AES_256_XTS,
399 {0},
400 sizeof(ext4_key.raw)};
401 memset(ext4_key.raw, 0, sizeof(ext4_key.raw));
402 static_assert(key_length / 8 <= sizeof(ext4_key.raw),
403 "Key too long!");
Paul Crowley95376d62015-05-06 15:04:43 +0100404 memcpy(ext4_key.raw, &key[0], key.size());
Paul Crowley93363482015-07-07 15:17:22 +0100405 return ext4_key;
406}
Paul Lawrence731a7a22015-04-28 22:14:15 +0000407
Paul Crowley93363482015-07-07 15:17:22 +0100408static std::string keyname(const std::string &raw_ref)
409{
Paul Lawrencefd7db732015-04-10 07:48:51 -0700410 std::ostringstream o;
Paul Crowley93363482015-07-07 15:17:22 +0100411 o << "ext4:";
Paul Lawrencefd7db732015-04-10 07:48:51 -0700412 for (auto i = raw_ref.begin(); i != raw_ref.end(); ++i) {
413 o << std::hex << std::setw(2) << std::setfill('0') << (int)*i;
414 }
Paul Crowley93363482015-07-07 15:17:22 +0100415 return o.str();
416}
Paul Lawrencefd7db732015-04-10 07:48:51 -0700417
Paul Crowley93363482015-07-07 15:17:22 +0100418// Get the keyring we store all keys in
419static key_serial_t e4crypt_keyring()
420{
421 return keyctl_search(KEY_SPEC_SESSION_KEYRING, "keyring", "e4crypt", 0);
422}
Paul Lawrence731a7a22015-04-28 22:14:15 +0000423
Paul Crowley93363482015-07-07 15:17:22 +0100424static int e4crypt_install_key(const ext4_encryption_key &ext4_key, const std::string &ref)
425{
426 key_serial_t device_keyring = e4crypt_keyring();
Paul Lawrence731a7a22015-04-28 22:14:15 +0000427 SLOGI("Found device_keyring - id is %d", device_keyring);
Paul Lawrencefd7db732015-04-10 07:48:51 -0700428 key_serial_t key_id = add_key("logon", ref.c_str(),
Paul Lawrence731a7a22015-04-28 22:14:15 +0000429 (void*)&ext4_key, sizeof(ext4_key),
430 device_keyring);
Paul Lawrence731a7a22015-04-28 22:14:15 +0000431 if (key_id == -1) {
432 SLOGE("Failed to insert key into keyring with error %s",
433 strerror(errno));
Paul Crowley93363482015-07-07 15:17:22 +0100434 return -1;
Paul Lawrence731a7a22015-04-28 22:14:15 +0000435 }
Paul Lawrencefd7db732015-04-10 07:48:51 -0700436 SLOGI("Added key %d (%s) to keyring %d in process %d",
437 key_id, ref.c_str(), device_keyring, getpid());
Paul Crowley93363482015-07-07 15:17:22 +0100438 return 0;
439}
Paul Lawrence731a7a22015-04-28 22:14:15 +0000440
Paul Crowley93363482015-07-07 15:17:22 +0100441// Install password into global keyring
442// Return raw key reference for use in policy
443static std::string e4crypt_install_key(const std::string &key)
444{
445 auto ext4_key = fill_key(key);
446 auto raw_ref = generate_key_ref(ext4_key.raw, ext4_key.size);
447 auto ref = keyname(raw_ref);
448 if (e4crypt_install_key(ext4_key, ref) == -1) {
449 return "";
450 }
Paul Crowleyf25a35a2015-05-06 13:38:53 +0100451 return raw_ref;
Paul Lawrence731a7a22015-04-28 22:14:15 +0000452}
453
454int e4crypt_restart(const char* path)
455{
456 SLOGI("e4crypt_restart");
457
458 int rc = 0;
459
460 SLOGI("ext4 restart called on %s", path);
461 property_set("vold.decrypt", "trigger_reset_main");
462 SLOGI("Just asked init to shut down class main");
463 sleep(2);
464
465 std::string tmp_path = std::string() + path + "/tmp_mnt";
466
Paul Lawrence2f32cda2015-05-05 14:28:25 -0700467 rc = wait_and_unmount(tmp_path.c_str(), true);
Paul Lawrence731a7a22015-04-28 22:14:15 +0000468 if (rc) {
469 SLOGE("umount %s failed with rc %d, msg %s",
470 tmp_path.c_str(), rc, strerror(errno));
471 return rc;
472 }
473
Paul Lawrence2f32cda2015-05-05 14:28:25 -0700474 rc = wait_and_unmount(path, true);
Paul Lawrence731a7a22015-04-28 22:14:15 +0000475 if (rc) {
476 SLOGE("umount %s failed with rc %d, msg %s",
477 path, rc, strerror(errno));
478 return rc;
479 }
480
481 return 0;
482}
483
Paul Lawrence731a7a22015-04-28 22:14:15 +0000484int e4crypt_get_password_type(const char* path)
485{
486 SLOGI("e4crypt_get_password_type");
487 return GetPropsOrAltProps(path).GetChild(properties::key)
488 .Get<int>(tag::crypt_type, CRYPT_TYPE_DEFAULT);
489}
Paul Lawrence368d7942015-04-15 14:12:00 -0700490
Paul Lawrence86c942a2015-05-06 13:53:43 -0700491const char* e4crypt_get_password(const char* path)
492{
493 SLOGI("e4crypt_get_password");
494
495 auto i = s_key_store.find(path);
496 if (i == s_key_store.end()) {
497 return 0;
498 }
499
500 struct timespec now;
501 clock_gettime(CLOCK_BOOTTIME, &now);
502 if (i->second.expiry_time < now.tv_sec) {
503 e4crypt_clear_password(path);
504 return 0;
505 }
506
507 return i->second.password.c_str();
508}
509
510void e4crypt_clear_password(const char* path)
511{
512 SLOGI("e4crypt_clear_password");
513
514 auto i = s_key_store.find(path);
515 if (i == s_key_store.end()) {
516 return;
517 }
518
519 memset(&i->second.password[0], 0, i->second.password.size());
520 i->second.password = std::string();
521}
522
Paul Lawrence368d7942015-04-15 14:12:00 -0700523int e4crypt_get_field(const char* path, const char* fieldname,
524 char* value, size_t len)
525{
526 auto v = GetPropsOrAltProps(path).GetChild(properties::props)
527 .Get<std::string>(fieldname);
528
529 if (v == "") {
530 return CRYPTO_GETFIELD_ERROR_NO_FIELD;
531 }
532
533 if (v.length() >= len) {
534 return CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
535 }
536
537 strlcpy(value, v.c_str(), len);
538 return 0;
539}
540
541int e4crypt_set_field(const char* path, const char* fieldname,
542 const char* value)
543{
544 return GetPropsOrAltProps(path).GetChild(properties::props)
545 .Set(fieldname, std::string(value)) ? 0 : -1;
546}
Paul Crowley95376d62015-05-06 15:04:43 +0100547
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800548static std::string get_key_path(const char *mount_path, userid_t user_id) {
Paul Crowley95376d62015-05-06 15:04:43 +0100549 // ext4enc:TODO get the path properly
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800550 auto key_dir = StringPrintf("%s/misc/vold/user_keys", mount_path);
551 if (fs_prepare_dir(key_dir.c_str(), 0700, AID_ROOT, AID_ROOT)) {
552 PLOG(ERROR) << "Failed to prepare " << key_dir;
Paul Crowley95376d62015-05-06 15:04:43 +0100553 return "";
554 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800555 return StringPrintf("%s/%d", key_dir.c_str(), user_id);
Paul Crowleyb33e8872015-05-19 12:34:09 +0100556}
557
Lenka Trochtova395039f2015-11-25 10:13:03 +0100558static bool e4crypt_is_key_ephemeral(const std::string &key_path) {
559 return s_ephemeral_user_keys.find(key_path) != s_ephemeral_user_keys.end();
560}
561
Paul Crowleyb33e8872015-05-19 12:34:09 +0100562// ext4enc:TODO this can't be the only place keys are read from /dev/urandom
563// we should unite those places.
Paul Crowley93363482015-07-07 15:17:22 +0100564static std::string e4crypt_get_key(
565 const std::string &key_path,
Lenka Trochtova395039f2015-11-25 10:13:03 +0100566 bool create_if_absent,
567 bool create_ephemeral)
Paul Crowleyb33e8872015-05-19 12:34:09 +0100568{
Lenka Trochtova395039f2015-11-25 10:13:03 +0100569 const auto ephemeral_key_it = s_ephemeral_user_keys.find(key_path);
570 if (ephemeral_key_it != s_ephemeral_user_keys.end()) {
571 return ephemeral_key_it->second;
572 }
573
Paul Crowley95376d62015-05-06 15:04:43 +0100574 std::string content;
575 if (android::base::ReadFileToString(key_path, &content)) {
576 if (content.size() != key_length/8) {
577 SLOGE("Wrong size key %zu in %s", content.size(), key_path.c_str());
578 return "";
579 }
580 return content;
581 }
582 if (!create_if_absent) {
583 SLOGE("No key found in %s", key_path.c_str());
584 return "";
585 }
586 std::ifstream urandom("/dev/urandom");
587 if (!urandom) {
588 SLOGE("Unable to open /dev/urandom (%s)", strerror(errno));
589 return "";
590 }
591 char key_bytes[key_length / 8];
592 errno = 0;
593 urandom.read(key_bytes, sizeof(key_bytes));
594 if (!urandom) {
595 SLOGE("Unable to read key from /dev/urandom (%s)", strerror(errno));
596 return "";
597 }
Paul Crowley93363482015-07-07 15:17:22 +0100598 std::string key(key_bytes, sizeof(key_bytes));
Lenka Trochtova395039f2015-11-25 10:13:03 +0100599 if (create_ephemeral) {
600 // If the key should be created as ephemeral, store it in memory only.
601 s_ephemeral_user_keys[key_path] = key;
602 } else if (!android::base::WriteStringToFile(key, key_path)) {
Paul Crowley95376d62015-05-06 15:04:43 +0100603 SLOGE("Unable to write key to %s (%s)",
604 key_path.c_str(), strerror(errno));
605 return "";
606 }
Paul Crowley93363482015-07-07 15:17:22 +0100607 return key;
Paul Crowley95376d62015-05-06 15:04:43 +0100608}
609
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800610static int e4crypt_set_user_policy(const char *mount_path, userid_t user_id,
Lenka Trochtova395039f2015-11-25 10:13:03 +0100611 const char *path, bool create_if_absent, bool create_ephemeral) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800612 SLOGD("e4crypt_set_user_policy for %d", user_id);
613 auto user_key = e4crypt_get_key(get_key_path(mount_path, user_id),
Lenka Trochtova395039f2015-11-25 10:13:03 +0100614 create_if_absent, create_ephemeral);
Paul Crowley95376d62015-05-06 15:04:43 +0100615 if (user_key.empty()) {
616 return -1;
617 }
618 auto raw_ref = e4crypt_install_key(user_key);
619 if (raw_ref.empty()) {
620 return -1;
621 }
622 return do_policy_set(path, raw_ref.c_str(), raw_ref.size());
623}
624
Paul Crowley95376d62015-05-06 15:04:43 +0100625static bool is_numeric(const char *name) {
626 for (const char *p = name; *p != '\0'; p++) {
627 if (!isdigit(*p))
628 return false;
629 }
630 return true;
631}
632
Paul Crowley27cbce92015-12-10 14:51:30 +0000633int e4crypt_vold_set_user_crypto_policies(const char *dir)
Paul Crowley95376d62015-05-06 15:04:43 +0100634{
635 if (e4crypt_crypto_complete(DATA_MNT_POINT) != 0) {
636 return 0;
637 }
Paul Crowley27cbce92015-12-10 14:51:30 +0000638 SLOGD("e4crypt_vold_set_user_crypto_policies");
Paul Crowley95376d62015-05-06 15:04:43 +0100639 std::unique_ptr<DIR, int(*)(DIR*)> dirp(opendir(dir), closedir);
640 if (!dirp) {
641 SLOGE("Unable to read directory %s, error %s\n",
642 dir, strerror(errno));
643 return -1;
644 }
645 for (;;) {
646 struct dirent *result = readdir(dirp.get());
647 if (!result) {
648 // ext4enc:TODO check errno
649 break;
650 }
651 if (result->d_type != DT_DIR || !is_numeric(result->d_name)) {
652 continue; // skips user 0, which is a symlink
653 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800654 auto user_id = atoi(result->d_name);
Paul Crowley95376d62015-05-06 15:04:43 +0100655 auto user_dir = std::string() + dir + "/" + result->d_name;
656 // ext4enc:TODO don't hardcode /data
Lenka Trochtova395039f2015-11-25 10:13:03 +0100657 if (e4crypt_set_user_policy("/data", user_id, user_dir.c_str(), false, false)) {
Paul Crowley95376d62015-05-06 15:04:43 +0100658 // ext4enc:TODO If this function fails, stop the boot: we must
659 // deliver on promised encryption.
660 SLOGE("Unable to set policy on %s\n", user_dir.c_str());
661 }
662 }
663 return 0;
664}
Paul Crowleyb33e8872015-05-19 12:34:09 +0100665
Paul Crowley27cbce92015-12-10 14:51:30 +0000666int e4crypt_vold_create_user_key(userid_t user_id, int serial, bool ephemeral) {
667 SLOGD("e4crypt_vold_create_user_key(%d)", user_id);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800668 // TODO: create second key for user_de data
Lenka Trochtova395039f2015-11-25 10:13:03 +0100669 if (e4crypt_get_key(
670 get_key_path(DATA_MNT_POINT, user_id), true, ephemeral).empty()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800671 return -1;
672 } else {
673 return 0;
674 }
675}
676
677int e4crypt_destroy_user_key(userid_t user_id) {
678 SLOGD("e4crypt_destroy_user_key(%d)", user_id);
679 // TODO: destroy second key for user_de data
680 auto key_path = get_key_path(DATA_MNT_POINT, user_id);
Lenka Trochtova395039f2015-11-25 10:13:03 +0100681 auto key = e4crypt_get_key(key_path, false, false);
Paul Crowley93363482015-07-07 15:17:22 +0100682 auto ext4_key = fill_key(key);
683 auto ref = keyname(generate_key_ref(ext4_key.raw, ext4_key.size));
684 auto key_serial = keyctl_search(e4crypt_keyring(), "logon", ref.c_str(), 0);
685 if (keyctl_revoke(key_serial) == 0) {
686 SLOGD("Revoked key with serial %ld ref %s\n", key_serial, ref.c_str());
687 } else {
688 SLOGE("Failed to revoke key with serial %ld ref %s: %s\n",
689 key_serial, ref.c_str(), strerror(errno));
690 }
Lenka Trochtova395039f2015-11-25 10:13:03 +0100691 if (e4crypt_is_key_ephemeral(key_path)) {
692 s_ephemeral_user_keys.erase(key_path);
693 return 0;
694 }
Paul Crowleycd307b72015-05-19 17:31:39 +0100695 int pid = fork();
696 if (pid < 0) {
697 SLOGE("Unable to fork: %s", strerror(errno));
Paul Crowleyb33e8872015-05-19 12:34:09 +0100698 return -1;
699 }
Paul Crowleycd307b72015-05-19 17:31:39 +0100700 if (pid == 0) {
701 SLOGD("Forked for secdiscard");
702 execl("/system/bin/secdiscard",
703 "/system/bin/secdiscard",
Paul Crowley5ab73e92015-07-03 16:17:23 +0100704 "--",
Paul Crowleycd307b72015-05-19 17:31:39 +0100705 key_path.c_str(),
706 NULL);
707 SLOGE("Unable to launch secdiscard on %s: %s\n", key_path.c_str(),
708 strerror(errno));
709 exit(-1);
710 }
711 // ext4enc:TODO reap the zombie
Paul Crowleyb33e8872015-05-19 12:34:09 +0100712 return 0;
713}
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800714
715int e4crypt_unlock_user_key(userid_t user_id, const char* token) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -0700716 if (e4crypt_is_native()) {
Lenka Trochtova395039f2015-11-25 10:13:03 +0100717 auto user_key = e4crypt_get_key(get_key_path(DATA_MNT_POINT, user_id), false, false);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800718 if (user_key.empty()) {
719 return -1;
720 }
721 auto raw_ref = e4crypt_install_key(user_key);
722 if (raw_ref.empty()) {
723 return -1;
724 }
Jeff Sharkeyfc505c32015-12-07 17:27:01 -0700725 } else {
726 // When in emulation mode, we just use chmod. However, we also
727 // unlock directories when not in emulation mode, to bring devices
728 // back into a known-good state.
729 if (chmod(android::vold::BuildDataSystemCePath(user_id).c_str(), 0771) ||
730 chmod(android::vold::BuildDataMediaPath(nullptr, user_id).c_str(), 0770) ||
731 chmod(android::vold::BuildDataUserPath(nullptr, user_id).c_str(), 0771)) {
732 PLOG(ERROR) << "Failed to unlock user " << user_id;
733 return -1;
734 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800735 }
Jeff Sharkeyfc505c32015-12-07 17:27:01 -0700736
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800737 return 0;
738}
739
740int e4crypt_lock_user_key(userid_t user_id) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -0700741 if (e4crypt_is_native()) {
742 // TODO: remove from kernel keyring
743 } else if (e4crypt_is_emulated()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800744 // When in emulation mode, we just use chmod
745 if (chmod(android::vold::BuildDataSystemCePath(user_id).c_str(), 0000) ||
Jeff Sharkeyfc505c32015-12-07 17:27:01 -0700746 chmod(android::vold::BuildDataMediaPath(nullptr, user_id).c_str(), 0000) ||
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800747 chmod(android::vold::BuildDataUserPath(nullptr, user_id).c_str(), 0000)) {
748 PLOG(ERROR) << "Failed to lock user " << user_id;
749 return -1;
750 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800751 }
Jeff Sharkeyfc505c32015-12-07 17:27:01 -0700752
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800753 return 0;
754}
755
Lenka Trochtova395039f2015-11-25 10:13:03 +0100756int e4crypt_prepare_user_storage(const char* volume_uuid, userid_t user_id, bool ephemeral) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800757 std::string system_ce_path(android::vold::BuildDataSystemCePath(user_id));
758 std::string user_ce_path(android::vold::BuildDataUserPath(volume_uuid, user_id));
759 std::string user_de_path(android::vold::BuildDataUserDePath(volume_uuid, user_id));
760
761 if (fs_prepare_dir(system_ce_path.c_str(), 0700, AID_SYSTEM, AID_SYSTEM)) {
762 PLOG(ERROR) << "Failed to prepare " << system_ce_path;
763 return -1;
764 }
765 if (fs_prepare_dir(user_ce_path.c_str(), 0771, AID_SYSTEM, AID_SYSTEM)) {
766 PLOG(ERROR) << "Failed to prepare " << user_ce_path;
767 return -1;
768 }
769 if (fs_prepare_dir(user_de_path.c_str(), 0771, AID_SYSTEM, AID_SYSTEM)) {
770 PLOG(ERROR) << "Failed to prepare " << user_de_path;
771 return -1;
772 }
773
774 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
Lenka Trochtova395039f2015-11-25 10:13:03 +0100775 if (e4crypt_set_user_policy(DATA_MNT_POINT,
776 user_id,
777 system_ce_path.c_str(),
778 true,
779 ephemeral)
780 || e4crypt_set_user_policy(DATA_MNT_POINT,
781 user_id,
782 user_ce_path.c_str(),
783 true,
784 ephemeral)) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800785 return -1;
786 }
787 }
788
789 return 0;
790}