blob: f90ba561c1a327c08b308da7ff0eec6c0b981b0f [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;
81
Paul Lawrencefd7db732015-04-10 07:48:51 -070082 // ext4enc:TODO get these consts from somewhere good
83 const int SHA512_LENGTH = 64;
84 const int EXT4_KEY_DESCRIPTOR_SIZE = 8;
85
Paul Lawrence731a7a22015-04-28 22:14:15 +000086 // ext4enc:TODO Include structure from somewhere sensible
87 // MUST be in sync with ext4_crypto.c in kernel
Paul Lawrencefd7db732015-04-10 07:48:51 -070088 const int EXT4_MAX_KEY_SIZE = 64;
89 const int EXT4_ENCRYPTION_MODE_AES_256_XTS = 1;
Paul Lawrence731a7a22015-04-28 22:14:15 +000090 struct ext4_encryption_key {
Paul Lawrencefd7db732015-04-10 07:48:51 -070091 uint32_t mode;
92 char raw[EXT4_MAX_KEY_SIZE];
93 uint32_t size;
Paul Lawrence731a7a22015-04-28 22:14:15 +000094 };
95
96 namespace tag {
97 const char* magic = "magic";
98 const char* major_version = "major_version";
99 const char* minor_version = "minor_version";
100 const char* flags = "flags";
101 const char* crypt_type = "crypt_type";
102 const char* failed_decrypt_count = "failed_decrypt_count";
103 const char* crypto_type_name = "crypto_type_name";
104 const char* master_key = "master_key";
105 const char* salt = "salt";
106 const char* kdf_type = "kdf_type";
107 const char* N_factor = "N_factor";
108 const char* r_factor = "r_factor";
109 const char* p_factor = "p_factor";
110 const char* keymaster_blob = "keymaster_blob";
111 const char* scrypted_intermediate_key = "scrypted_intermediate_key";
112 }
113}
114
Paul Crowley95376d62015-05-06 15:04:43 +0100115static std::string e4crypt_install_key(const std::string &key);
Paul Crowleyf25a35a2015-05-06 13:38:53 +0100116
Paul Lawrence731a7a22015-04-28 22:14:15 +0000117static int put_crypt_ftr_and_key(const crypt_mnt_ftr& crypt_ftr,
118 UnencryptedProperties& props)
119{
120 SLOGI("Putting crypt footer");
121
122 bool success = props.Set<int>(tag::magic, crypt_ftr.magic)
123 && props.Set<int>(tag::major_version, crypt_ftr.major_version)
124 && props.Set<int>(tag::minor_version, crypt_ftr.minor_version)
125 && props.Set<int>(tag::flags, crypt_ftr.flags)
126 && props.Set<int>(tag::crypt_type, crypt_ftr.crypt_type)
127 && props.Set<int>(tag::failed_decrypt_count,
128 crypt_ftr.failed_decrypt_count)
129 && props.Set<std::string>(tag::crypto_type_name,
130 std::string(reinterpret_cast<const char*>(crypt_ftr.crypto_type_name)))
131 && props.Set<std::string>(tag::master_key,
132 std::string((const char*) crypt_ftr.master_key,
133 crypt_ftr.keysize))
134 && props.Set<std::string>(tag::salt,
135 std::string((const char*) crypt_ftr.salt,
136 SALT_LEN))
137 && props.Set<int>(tag::kdf_type, crypt_ftr.kdf_type)
138 && props.Set<int>(tag::N_factor, crypt_ftr.N_factor)
139 && props.Set<int>(tag::r_factor, crypt_ftr.r_factor)
140 && props.Set<int>(tag::p_factor, crypt_ftr.p_factor)
141 && props.Set<std::string>(tag::keymaster_blob,
142 std::string((const char*) crypt_ftr.keymaster_blob,
143 crypt_ftr.keymaster_blob_size))
144 && props.Set<std::string>(tag::scrypted_intermediate_key,
145 std::string((const char*) crypt_ftr.scrypted_intermediate_key,
146 SCRYPT_LEN));
147 return success ? 0 : -1;
148}
149
150static int get_crypt_ftr_and_key(crypt_mnt_ftr& crypt_ftr,
151 const UnencryptedProperties& props)
152{
153 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
154 crypt_ftr.magic = props.Get<int>(tag::magic);
155 crypt_ftr.major_version = props.Get<int>(tag::major_version);
156 crypt_ftr.minor_version = props.Get<int>(tag::minor_version);
Paul Lawrence0d9cd9e2015-05-05 15:58:27 -0700157 crypt_ftr.ftr_size = sizeof(crypt_ftr);
Paul Lawrence731a7a22015-04-28 22:14:15 +0000158 crypt_ftr.flags = props.Get<int>(tag::flags);
159 crypt_ftr.crypt_type = props.Get<int>(tag::crypt_type);
160 crypt_ftr.failed_decrypt_count = props.Get<int>(tag::failed_decrypt_count);
161 std::string crypto_type_name = props.Get<std::string>(tag::crypto_type_name);
162 strlcpy(reinterpret_cast<char*>(crypt_ftr.crypto_type_name),
163 crypto_type_name.c_str(),
164 sizeof(crypt_ftr.crypto_type_name));
165 std::string master_key = props.Get<std::string>(tag::master_key);
166 crypt_ftr.keysize = master_key.size();
167 if (crypt_ftr.keysize > sizeof(crypt_ftr.master_key)) {
168 SLOGE("Master key size too long");
169 return -1;
170 }
171 memcpy(crypt_ftr.master_key, &master_key[0], crypt_ftr.keysize);
172 std::string salt = props.Get<std::string>(tag::salt);
173 if (salt.size() != SALT_LEN) {
174 SLOGE("Salt wrong length");
175 return -1;
176 }
177 memcpy(crypt_ftr.salt, &salt[0], SALT_LEN);
178 crypt_ftr.kdf_type = props.Get<int>(tag::kdf_type);
179 crypt_ftr.N_factor = props.Get<int>(tag::N_factor);
180 crypt_ftr.r_factor = props.Get<int>(tag::r_factor);
181 crypt_ftr.p_factor = props.Get<int>(tag::p_factor);
182 std::string keymaster_blob = props.Get<std::string>(tag::keymaster_blob);
183 crypt_ftr.keymaster_blob_size = keymaster_blob.size();
184 if (crypt_ftr.keymaster_blob_size > sizeof(crypt_ftr.keymaster_blob)) {
185 SLOGE("Keymaster blob too long");
186 return -1;
187 }
188 memcpy(crypt_ftr.keymaster_blob, &keymaster_blob[0],
189 crypt_ftr.keymaster_blob_size);
190 std::string scrypted_intermediate_key = props.Get<std::string>(tag::scrypted_intermediate_key);
191 if (scrypted_intermediate_key.size() != SCRYPT_LEN) {
192 SLOGE("scrypted intermediate key wrong length");
193 return -1;
194 }
195 memcpy(crypt_ftr.scrypted_intermediate_key, &scrypted_intermediate_key[0],
196 SCRYPT_LEN);
197
198 return 0;
199}
200
201static UnencryptedProperties GetProps(const char* path)
202{
203 return UnencryptedProperties(path);
204}
205
206static UnencryptedProperties GetAltProps(const char* path)
207{
208 return UnencryptedProperties((std::string() + path + "/tmp_mnt").c_str());
209}
210
211static UnencryptedProperties GetPropsOrAltProps(const char* path)
212{
213 UnencryptedProperties props = GetProps(path);
214 if (props.OK()) {
215 return props;
216 }
217 return GetAltProps(path);
218}
219
220int e4crypt_enable(const char* path)
221{
222 // Already enabled?
223 if (s_key_store.find(path) != s_key_store.end()) {
224 return 0;
225 }
226
227 // Not an encryptable device?
228 UnencryptedProperties key_props = GetProps(path).GetChild(properties::key);
229 if (!key_props.OK()) {
230 return 0;
231 }
232
233 if (key_props.Get<std::string>(tag::master_key).empty()) {
234 crypt_mnt_ftr ftr;
235 if (cryptfs_create_default_ftr(&ftr, key_length)) {
236 SLOGE("Failed to create crypto footer");
237 return -1;
238 }
239
Paul Lawrence0d9cd9e2015-05-05 15:58:27 -0700240 // Scrub fields not used by ext4enc
241 ftr.persist_data_offset[0] = 0;
242 ftr.persist_data_offset[1] = 0;
243 ftr.persist_data_size = 0;
244
Paul Lawrence731a7a22015-04-28 22:14:15 +0000245 if (put_crypt_ftr_and_key(ftr, key_props)) {
246 SLOGE("Failed to write crypto footer");
247 return -1;
248 }
249
250 crypt_mnt_ftr ftr2;
251 if (get_crypt_ftr_and_key(ftr2, key_props)) {
252 SLOGE("Failed to read crypto footer back");
253 return -1;
254 }
255
256 if (memcmp(&ftr, &ftr2, sizeof(ftr)) != 0) {
257 SLOGE("Crypto footer not correctly written");
Paul Lawrence0d9cd9e2015-05-05 15:58:27 -0700258 return -1;
Paul Lawrence731a7a22015-04-28 22:14:15 +0000259 }
260 }
261
262 if (!UnencryptedProperties(path).Remove(properties::ref)) {
263 SLOGE("Failed to remove key ref");
264 return -1;
265 }
266
267 return e4crypt_check_passwd(path, "");
268}
269
270int e4crypt_change_password(const char* path, int crypt_type,
271 const char* password)
272{
273 SLOGI("e4crypt_change_password");
Paul Lawrencea56d3132015-05-04 15:48:24 -0700274 auto key_props = GetProps(path).GetChild(properties::key);
Paul Lawrence731a7a22015-04-28 22:14:15 +0000275
276 crypt_mnt_ftr ftr;
277 if (get_crypt_ftr_and_key(ftr, key_props)) {
278 SLOGE("Failed to read crypto footer back");
279 return -1;
280 }
281
282 auto mki = s_key_store.find(path);
283 if (mki == s_key_store.end()) {
284 SLOGE("No stored master key - can't change password");
285 return -1;
286 }
287
Paul Crowley95376d62015-05-06 15:04:43 +0100288 const unsigned char* master_key_bytes
Paul Lawrence731a7a22015-04-28 22:14:15 +0000289 = reinterpret_cast<const unsigned char*>(&mki->second.master_key[0]);
290
Paul Crowley95376d62015-05-06 15:04:43 +0100291 if (cryptfs_set_password(&ftr, password, master_key_bytes)) {
Paul Lawrence731a7a22015-04-28 22:14:15 +0000292 SLOGE("Failed to set password");
293 return -1;
294 }
295
296 ftr.crypt_type = crypt_type;
297
298 if (put_crypt_ftr_and_key(ftr, key_props)) {
299 SLOGE("Failed to write crypto footer");
300 return -1;
301 }
302
303 if (!UnencryptedProperties(path).Set(properties::is_default,
304 crypt_type == CRYPT_TYPE_DEFAULT)) {
305 SLOGE("Failed to update default flag");
306 return -1;
307 }
308
309 return 0;
310}
311
312int e4crypt_crypto_complete(const char* path)
313{
314 SLOGI("ext4 crypto complete called on %s", path);
Paul Lawrencea56d3132015-05-04 15:48:24 -0700315 auto key_props = GetPropsOrAltProps(path).GetChild(properties::key);
Paul Lawrence731a7a22015-04-28 22:14:15 +0000316 if (key_props.Get<std::string>(tag::master_key).empty()) {
317 SLOGI("No master key, so not ext4enc");
318 return -1;
319 }
320
321 return 0;
322}
323
Paul Crowley93363482015-07-07 15:17:22 +0100324// Get raw keyref - used to make keyname and to pass to ioctl
Paul Lawrencefd7db732015-04-10 07:48:51 -0700325static std::string generate_key_ref(const char* key, int length)
326{
327 SHA512_CTX c;
328
329 SHA512_Init(&c);
330 SHA512_Update(&c, key, length);
331 unsigned char key_ref1[SHA512_LENGTH];
332 SHA512_Final(key_ref1, &c);
333
334 SHA512_Init(&c);
335 SHA512_Update(&c, key_ref1, SHA512_LENGTH);
336 unsigned char key_ref2[SHA512_LENGTH];
337 SHA512_Final(key_ref2, &c);
338
339 return std::string((char*)key_ref2, EXT4_KEY_DESCRIPTOR_SIZE);
340}
341
Paul Lawrence731a7a22015-04-28 22:14:15 +0000342int e4crypt_check_passwd(const char* path, const char* password)
343{
344 SLOGI("e4crypt_check_password");
Paul Lawrencea56d3132015-05-04 15:48:24 -0700345 auto props = GetPropsOrAltProps(path);
346 auto key_props = props.GetChild(properties::key);
Paul Lawrence731a7a22015-04-28 22:14:15 +0000347
348 crypt_mnt_ftr ftr;
349 if (get_crypt_ftr_and_key(ftr, key_props)) {
350 SLOGE("Failed to read crypto footer back");
351 return -1;
352 }
353
Paul Crowley95376d62015-05-06 15:04:43 +0100354 unsigned char master_key_bytes[key_length / 8];
355 if (cryptfs_get_master_key (&ftr, password, master_key_bytes)){
Paul Lawrence731a7a22015-04-28 22:14:15 +0000356 SLOGI("Incorrect password");
Paul Lawrencec78c71b2015-04-14 15:26:29 -0700357 ftr.failed_decrypt_count++;
358 if (put_crypt_ftr_and_key(ftr, key_props)) {
359 SLOGW("Failed to update failed_decrypt_count");
360 }
361 return ftr.failed_decrypt_count;
362 }
363
364 if (ftr.failed_decrypt_count) {
365 ftr.failed_decrypt_count = 0;
366 if (put_crypt_ftr_and_key(ftr, key_props)) {
367 SLOGW("Failed to reset failed_decrypt_count");
368 }
Paul Lawrence731a7a22015-04-28 22:14:15 +0000369 }
Paul Crowley95376d62015-05-06 15:04:43 +0100370 std::string master_key(reinterpret_cast<char*>(master_key_bytes),
371 sizeof(master_key_bytes));
Paul Lawrence731a7a22015-04-28 22:14:15 +0000372
Paul Lawrence86c942a2015-05-06 13:53:43 -0700373 struct timespec now;
374 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Crowley95376d62015-05-06 15:04:43 +0100375 s_key_store[path] = keys{master_key, password,
Paul Lawrence86c942a2015-05-06 13:53:43 -0700376 now.tv_sec + password_max_age_seconds};
Paul Crowleyf25a35a2015-05-06 13:38:53 +0100377 auto raw_ref = e4crypt_install_key(master_key);
378 if (raw_ref.empty()) {
379 return -1;
380 }
Paul Lawrence731a7a22015-04-28 22:14:15 +0000381
Paul Crowleyf25a35a2015-05-06 13:38:53 +0100382 // Save reference to key so we can set policy later
383 if (!props.Set(properties::ref, raw_ref)) {
384 SLOGE("Cannot save key reference");
385 return -1;
386 }
387
388 return 0;
389}
390
Paul Crowley93363482015-07-07 15:17:22 +0100391static ext4_encryption_key fill_key(const std::string &key)
Paul Crowleyf25a35a2015-05-06 13:38:53 +0100392{
Paul Lawrencefd7db732015-04-10 07:48:51 -0700393 // ext4enc:TODO Currently raw key is required to be of length
394 // sizeof(ext4_key.raw) == EXT4_MAX_KEY_SIZE, so zero pad to
395 // this length. Change when kernel bug is fixed.
396 ext4_encryption_key ext4_key = {EXT4_ENCRYPTION_MODE_AES_256_XTS,
397 {0},
398 sizeof(ext4_key.raw)};
399 memset(ext4_key.raw, 0, sizeof(ext4_key.raw));
400 static_assert(key_length / 8 <= sizeof(ext4_key.raw),
401 "Key too long!");
Paul Crowley95376d62015-05-06 15:04:43 +0100402 memcpy(ext4_key.raw, &key[0], key.size());
Paul Crowley93363482015-07-07 15:17:22 +0100403 return ext4_key;
404}
Paul Lawrence731a7a22015-04-28 22:14:15 +0000405
Paul Crowley93363482015-07-07 15:17:22 +0100406static std::string keyname(const std::string &raw_ref)
407{
Paul Lawrencefd7db732015-04-10 07:48:51 -0700408 std::ostringstream o;
Paul Crowley93363482015-07-07 15:17:22 +0100409 o << "ext4:";
Paul Lawrencefd7db732015-04-10 07:48:51 -0700410 for (auto i = raw_ref.begin(); i != raw_ref.end(); ++i) {
411 o << std::hex << std::setw(2) << std::setfill('0') << (int)*i;
412 }
Paul Crowley93363482015-07-07 15:17:22 +0100413 return o.str();
414}
Paul Lawrencefd7db732015-04-10 07:48:51 -0700415
Paul Crowley93363482015-07-07 15:17:22 +0100416// Get the keyring we store all keys in
417static key_serial_t e4crypt_keyring()
418{
419 return keyctl_search(KEY_SPEC_SESSION_KEYRING, "keyring", "e4crypt", 0);
420}
Paul Lawrence731a7a22015-04-28 22:14:15 +0000421
Paul Crowley93363482015-07-07 15:17:22 +0100422static int e4crypt_install_key(const ext4_encryption_key &ext4_key, const std::string &ref)
423{
424 key_serial_t device_keyring = e4crypt_keyring();
Paul Lawrence731a7a22015-04-28 22:14:15 +0000425 SLOGI("Found device_keyring - id is %d", device_keyring);
Paul Lawrencefd7db732015-04-10 07:48:51 -0700426 key_serial_t key_id = add_key("logon", ref.c_str(),
Paul Lawrence731a7a22015-04-28 22:14:15 +0000427 (void*)&ext4_key, sizeof(ext4_key),
428 device_keyring);
Paul Lawrence731a7a22015-04-28 22:14:15 +0000429 if (key_id == -1) {
430 SLOGE("Failed to insert key into keyring with error %s",
431 strerror(errno));
Paul Crowley93363482015-07-07 15:17:22 +0100432 return -1;
Paul Lawrence731a7a22015-04-28 22:14:15 +0000433 }
Paul Lawrencefd7db732015-04-10 07:48:51 -0700434 SLOGI("Added key %d (%s) to keyring %d in process %d",
435 key_id, ref.c_str(), device_keyring, getpid());
Paul Crowley93363482015-07-07 15:17:22 +0100436 return 0;
437}
Paul Lawrence731a7a22015-04-28 22:14:15 +0000438
Paul Crowley93363482015-07-07 15:17:22 +0100439// Install password into global keyring
440// Return raw key reference for use in policy
441static std::string e4crypt_install_key(const std::string &key)
442{
443 auto ext4_key = fill_key(key);
444 auto raw_ref = generate_key_ref(ext4_key.raw, ext4_key.size);
445 auto ref = keyname(raw_ref);
446 if (e4crypt_install_key(ext4_key, ref) == -1) {
447 return "";
448 }
Paul Crowleyf25a35a2015-05-06 13:38:53 +0100449 return raw_ref;
Paul Lawrence731a7a22015-04-28 22:14:15 +0000450}
451
452int e4crypt_restart(const char* path)
453{
454 SLOGI("e4crypt_restart");
455
456 int rc = 0;
457
458 SLOGI("ext4 restart called on %s", path);
459 property_set("vold.decrypt", "trigger_reset_main");
460 SLOGI("Just asked init to shut down class main");
461 sleep(2);
462
463 std::string tmp_path = std::string() + path + "/tmp_mnt";
464
Paul Lawrence2f32cda2015-05-05 14:28:25 -0700465 rc = wait_and_unmount(tmp_path.c_str(), true);
Paul Lawrence731a7a22015-04-28 22:14:15 +0000466 if (rc) {
467 SLOGE("umount %s failed with rc %d, msg %s",
468 tmp_path.c_str(), rc, strerror(errno));
469 return rc;
470 }
471
Paul Lawrence2f32cda2015-05-05 14:28:25 -0700472 rc = wait_and_unmount(path, true);
Paul Lawrence731a7a22015-04-28 22:14:15 +0000473 if (rc) {
474 SLOGE("umount %s failed with rc %d, msg %s",
475 path, rc, strerror(errno));
476 return rc;
477 }
478
479 return 0;
480}
481
Paul Lawrence731a7a22015-04-28 22:14:15 +0000482int e4crypt_get_password_type(const char* path)
483{
484 SLOGI("e4crypt_get_password_type");
485 return GetPropsOrAltProps(path).GetChild(properties::key)
486 .Get<int>(tag::crypt_type, CRYPT_TYPE_DEFAULT);
487}
Paul Lawrence368d7942015-04-15 14:12:00 -0700488
Paul Lawrence86c942a2015-05-06 13:53:43 -0700489const char* e4crypt_get_password(const char* path)
490{
491 SLOGI("e4crypt_get_password");
492
493 auto i = s_key_store.find(path);
494 if (i == s_key_store.end()) {
495 return 0;
496 }
497
498 struct timespec now;
499 clock_gettime(CLOCK_BOOTTIME, &now);
500 if (i->second.expiry_time < now.tv_sec) {
501 e4crypt_clear_password(path);
502 return 0;
503 }
504
505 return i->second.password.c_str();
506}
507
508void e4crypt_clear_password(const char* path)
509{
510 SLOGI("e4crypt_clear_password");
511
512 auto i = s_key_store.find(path);
513 if (i == s_key_store.end()) {
514 return;
515 }
516
517 memset(&i->second.password[0], 0, i->second.password.size());
518 i->second.password = std::string();
519}
520
Paul Lawrence368d7942015-04-15 14:12:00 -0700521int e4crypt_get_field(const char* path, const char* fieldname,
522 char* value, size_t len)
523{
524 auto v = GetPropsOrAltProps(path).GetChild(properties::props)
525 .Get<std::string>(fieldname);
526
527 if (v == "") {
528 return CRYPTO_GETFIELD_ERROR_NO_FIELD;
529 }
530
531 if (v.length() >= len) {
532 return CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
533 }
534
535 strlcpy(value, v.c_str(), len);
536 return 0;
537}
538
539int e4crypt_set_field(const char* path, const char* fieldname,
540 const char* value)
541{
542 return GetPropsOrAltProps(path).GetChild(properties::props)
543 .Set(fieldname, std::string(value)) ? 0 : -1;
544}
Paul Crowley95376d62015-05-06 15:04:43 +0100545
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800546static std::string get_key_path(const char *mount_path, userid_t user_id) {
Paul Crowley95376d62015-05-06 15:04:43 +0100547 // ext4enc:TODO get the path properly
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800548 auto key_dir = StringPrintf("%s/misc/vold/user_keys", mount_path);
549 if (fs_prepare_dir(key_dir.c_str(), 0700, AID_ROOT, AID_ROOT)) {
550 PLOG(ERROR) << "Failed to prepare " << key_dir;
Paul Crowley95376d62015-05-06 15:04:43 +0100551 return "";
552 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800553 return StringPrintf("%s/%d", key_dir.c_str(), user_id);
Paul Crowleyb33e8872015-05-19 12:34:09 +0100554}
555
556// ext4enc:TODO this can't be the only place keys are read from /dev/urandom
557// we should unite those places.
Paul Crowley93363482015-07-07 15:17:22 +0100558static std::string e4crypt_get_key(
559 const std::string &key_path,
Paul Crowleyb33e8872015-05-19 12:34:09 +0100560 bool create_if_absent)
561{
Paul Crowley95376d62015-05-06 15:04:43 +0100562 std::string content;
563 if (android::base::ReadFileToString(key_path, &content)) {
564 if (content.size() != key_length/8) {
565 SLOGE("Wrong size key %zu in %s", content.size(), key_path.c_str());
566 return "";
567 }
568 return content;
569 }
570 if (!create_if_absent) {
571 SLOGE("No key found in %s", key_path.c_str());
572 return "";
573 }
574 std::ifstream urandom("/dev/urandom");
575 if (!urandom) {
576 SLOGE("Unable to open /dev/urandom (%s)", strerror(errno));
577 return "";
578 }
579 char key_bytes[key_length / 8];
580 errno = 0;
581 urandom.read(key_bytes, sizeof(key_bytes));
582 if (!urandom) {
583 SLOGE("Unable to read key from /dev/urandom (%s)", strerror(errno));
584 return "";
585 }
Paul Crowley93363482015-07-07 15:17:22 +0100586 std::string key(key_bytes, sizeof(key_bytes));
587 if (!android::base::WriteStringToFile(key, key_path)) {
Paul Crowley95376d62015-05-06 15:04:43 +0100588 SLOGE("Unable to write key to %s (%s)",
589 key_path.c_str(), strerror(errno));
590 return "";
591 }
Paul Crowley93363482015-07-07 15:17:22 +0100592 return key;
Paul Crowley95376d62015-05-06 15:04:43 +0100593}
594
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800595static int e4crypt_set_user_policy(const char *mount_path, userid_t user_id,
596 const char *path, bool create_if_absent) {
597 SLOGD("e4crypt_set_user_policy for %d", user_id);
598 auto user_key = e4crypt_get_key(get_key_path(mount_path, user_id),
599 create_if_absent);
Paul Crowley95376d62015-05-06 15:04:43 +0100600 if (user_key.empty()) {
601 return -1;
602 }
603 auto raw_ref = e4crypt_install_key(user_key);
604 if (raw_ref.empty()) {
605 return -1;
606 }
607 return do_policy_set(path, raw_ref.c_str(), raw_ref.size());
608}
609
Paul Crowley95376d62015-05-06 15:04:43 +0100610static bool is_numeric(const char *name) {
611 for (const char *p = name; *p != '\0'; p++) {
612 if (!isdigit(*p))
613 return false;
614 }
615 return true;
616}
617
618int e4crypt_set_user_crypto_policies(const char *dir)
619{
620 if (e4crypt_crypto_complete(DATA_MNT_POINT) != 0) {
621 return 0;
622 }
623 SLOGD("e4crypt_set_user_crypto_policies");
624 std::unique_ptr<DIR, int(*)(DIR*)> dirp(opendir(dir), closedir);
625 if (!dirp) {
626 SLOGE("Unable to read directory %s, error %s\n",
627 dir, strerror(errno));
628 return -1;
629 }
630 for (;;) {
631 struct dirent *result = readdir(dirp.get());
632 if (!result) {
633 // ext4enc:TODO check errno
634 break;
635 }
636 if (result->d_type != DT_DIR || !is_numeric(result->d_name)) {
637 continue; // skips user 0, which is a symlink
638 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800639 auto user_id = atoi(result->d_name);
Paul Crowley95376d62015-05-06 15:04:43 +0100640 auto user_dir = std::string() + dir + "/" + result->d_name;
641 // ext4enc:TODO don't hardcode /data
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800642 if (e4crypt_set_user_policy("/data", user_id, user_dir.c_str(), false)) {
Paul Crowley95376d62015-05-06 15:04:43 +0100643 // ext4enc:TODO If this function fails, stop the boot: we must
644 // deliver on promised encryption.
645 SLOGE("Unable to set policy on %s\n", user_dir.c_str());
646 }
647 }
648 return 0;
649}
Paul Crowleyb33e8872015-05-19 12:34:09 +0100650
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800651int e4crypt_create_user_key(userid_t user_id) {
652 SLOGD("e4crypt_create_user_key(%d)", user_id);
653 // TODO: create second key for user_de data
654 if (e4crypt_get_key(get_key_path(DATA_MNT_POINT, user_id), true).empty()) {
655 return -1;
656 } else {
657 return 0;
658 }
659}
660
661int e4crypt_destroy_user_key(userid_t user_id) {
662 SLOGD("e4crypt_destroy_user_key(%d)", user_id);
663 // TODO: destroy second key for user_de data
664 auto key_path = get_key_path(DATA_MNT_POINT, user_id);
Paul Crowley93363482015-07-07 15:17:22 +0100665 auto key = e4crypt_get_key(key_path, false);
666 auto ext4_key = fill_key(key);
667 auto ref = keyname(generate_key_ref(ext4_key.raw, ext4_key.size));
668 auto key_serial = keyctl_search(e4crypt_keyring(), "logon", ref.c_str(), 0);
669 if (keyctl_revoke(key_serial) == 0) {
670 SLOGD("Revoked key with serial %ld ref %s\n", key_serial, ref.c_str());
671 } else {
672 SLOGE("Failed to revoke key with serial %ld ref %s: %s\n",
673 key_serial, ref.c_str(), strerror(errno));
674 }
Paul Crowleycd307b72015-05-19 17:31:39 +0100675 int pid = fork();
676 if (pid < 0) {
677 SLOGE("Unable to fork: %s", strerror(errno));
Paul Crowleyb33e8872015-05-19 12:34:09 +0100678 return -1;
679 }
Paul Crowleycd307b72015-05-19 17:31:39 +0100680 if (pid == 0) {
681 SLOGD("Forked for secdiscard");
682 execl("/system/bin/secdiscard",
683 "/system/bin/secdiscard",
Paul Crowley5ab73e92015-07-03 16:17:23 +0100684 "--",
Paul Crowleycd307b72015-05-19 17:31:39 +0100685 key_path.c_str(),
686 NULL);
687 SLOGE("Unable to launch secdiscard on %s: %s\n", key_path.c_str(),
688 strerror(errno));
689 exit(-1);
690 }
691 // ext4enc:TODO reap the zombie
Paul Crowleyb33e8872015-05-19 12:34:09 +0100692 return 0;
693}
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800694
695int e4crypt_unlock_user_key(userid_t user_id, const char* token) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -0700696 if (e4crypt_is_native()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800697 auto user_key = e4crypt_get_key(get_key_path(DATA_MNT_POINT, user_id), false);
698 if (user_key.empty()) {
699 return -1;
700 }
701 auto raw_ref = e4crypt_install_key(user_key);
702 if (raw_ref.empty()) {
703 return -1;
704 }
Jeff Sharkeyfc505c32015-12-07 17:27:01 -0700705 } else {
706 // When in emulation mode, we just use chmod. However, we also
707 // unlock directories when not in emulation mode, to bring devices
708 // back into a known-good state.
709 if (chmod(android::vold::BuildDataSystemCePath(user_id).c_str(), 0771) ||
710 chmod(android::vold::BuildDataMediaPath(nullptr, user_id).c_str(), 0770) ||
711 chmod(android::vold::BuildDataUserPath(nullptr, user_id).c_str(), 0771)) {
712 PLOG(ERROR) << "Failed to unlock user " << user_id;
713 return -1;
714 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800715 }
Jeff Sharkeyfc505c32015-12-07 17:27:01 -0700716
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800717 return 0;
718}
719
720int e4crypt_lock_user_key(userid_t user_id) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -0700721 if (e4crypt_is_native()) {
722 // TODO: remove from kernel keyring
723 } else if (e4crypt_is_emulated()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800724 // When in emulation mode, we just use chmod
725 if (chmod(android::vold::BuildDataSystemCePath(user_id).c_str(), 0000) ||
Jeff Sharkeyfc505c32015-12-07 17:27:01 -0700726 chmod(android::vold::BuildDataMediaPath(nullptr, user_id).c_str(), 0000) ||
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800727 chmod(android::vold::BuildDataUserPath(nullptr, user_id).c_str(), 0000)) {
728 PLOG(ERROR) << "Failed to lock user " << user_id;
729 return -1;
730 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800731 }
Jeff Sharkeyfc505c32015-12-07 17:27:01 -0700732
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800733 return 0;
734}
735
736int e4crypt_prepare_user_storage(const char* volume_uuid, userid_t user_id) {
737 std::string system_ce_path(android::vold::BuildDataSystemCePath(user_id));
738 std::string user_ce_path(android::vold::BuildDataUserPath(volume_uuid, user_id));
739 std::string user_de_path(android::vold::BuildDataUserDePath(volume_uuid, user_id));
740
741 if (fs_prepare_dir(system_ce_path.c_str(), 0700, AID_SYSTEM, AID_SYSTEM)) {
742 PLOG(ERROR) << "Failed to prepare " << system_ce_path;
743 return -1;
744 }
745 if (fs_prepare_dir(user_ce_path.c_str(), 0771, AID_SYSTEM, AID_SYSTEM)) {
746 PLOG(ERROR) << "Failed to prepare " << user_ce_path;
747 return -1;
748 }
749 if (fs_prepare_dir(user_de_path.c_str(), 0771, AID_SYSTEM, AID_SYSTEM)) {
750 PLOG(ERROR) << "Failed to prepare " << user_de_path;
751 return -1;
752 }
753
754 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
755 if (e4crypt_set_user_policy(DATA_MNT_POINT, user_id, system_ce_path.c_str(), true)
756 || e4crypt_set_user_policy(DATA_MNT_POINT, user_id, user_ce_path.c_str(), true)) {
757 return -1;
758 }
759 }
760
761 return 0;
762}