blob: 028c12c6b58d315dcb4ba9daee9bab139442d7d1 [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
Jeff Sharkeyc79fb892015-11-12 20:18:02 -080055static const char* kPropEmulateFbe = "persist.vold.emulate_fbe";
56
Paul Lawrence731a7a22015-04-28 22:14:15 +000057namespace {
58 // Key length in bits
59 const int key_length = 128;
Paul Lawrencefd7db732015-04-10 07:48:51 -070060 static_assert(key_length % 8 == 0,
61 "Key length must be multiple of 8 bits");
Paul Lawrence731a7a22015-04-28 22:14:15 +000062
Paul Lawrence86c942a2015-05-06 13:53:43 -070063 // How long do we store passwords for?
64 const int password_max_age_seconds = 60;
65
Paul Lawrence731a7a22015-04-28 22:14:15 +000066 // How is device encrypted
67 struct keys {
68 std::string master_key;
69 std::string password;
Paul Lawrence86c942a2015-05-06 13:53:43 -070070 time_t expiry_time;
Paul Lawrence731a7a22015-04-28 22:14:15 +000071 };
72 std::map<std::string, keys> s_key_store;
73
Paul Lawrencefd7db732015-04-10 07:48:51 -070074 // ext4enc:TODO get these consts from somewhere good
75 const int SHA512_LENGTH = 64;
76 const int EXT4_KEY_DESCRIPTOR_SIZE = 8;
77
Paul Lawrence731a7a22015-04-28 22:14:15 +000078 // ext4enc:TODO Include structure from somewhere sensible
79 // MUST be in sync with ext4_crypto.c in kernel
Paul Lawrencefd7db732015-04-10 07:48:51 -070080 const int EXT4_MAX_KEY_SIZE = 64;
81 const int EXT4_ENCRYPTION_MODE_AES_256_XTS = 1;
Paul Lawrence731a7a22015-04-28 22:14:15 +000082 struct ext4_encryption_key {
Paul Lawrencefd7db732015-04-10 07:48:51 -070083 uint32_t mode;
84 char raw[EXT4_MAX_KEY_SIZE];
85 uint32_t size;
Paul Lawrence731a7a22015-04-28 22:14:15 +000086 };
87
88 namespace tag {
89 const char* magic = "magic";
90 const char* major_version = "major_version";
91 const char* minor_version = "minor_version";
92 const char* flags = "flags";
93 const char* crypt_type = "crypt_type";
94 const char* failed_decrypt_count = "failed_decrypt_count";
95 const char* crypto_type_name = "crypto_type_name";
96 const char* master_key = "master_key";
97 const char* salt = "salt";
98 const char* kdf_type = "kdf_type";
99 const char* N_factor = "N_factor";
100 const char* r_factor = "r_factor";
101 const char* p_factor = "p_factor";
102 const char* keymaster_blob = "keymaster_blob";
103 const char* scrypted_intermediate_key = "scrypted_intermediate_key";
104 }
105}
106
Paul Crowley95376d62015-05-06 15:04:43 +0100107static std::string e4crypt_install_key(const std::string &key);
Paul Crowleyf25a35a2015-05-06 13:38:53 +0100108
Paul Lawrence731a7a22015-04-28 22:14:15 +0000109static int put_crypt_ftr_and_key(const crypt_mnt_ftr& crypt_ftr,
110 UnencryptedProperties& props)
111{
112 SLOGI("Putting crypt footer");
113
114 bool success = props.Set<int>(tag::magic, crypt_ftr.magic)
115 && props.Set<int>(tag::major_version, crypt_ftr.major_version)
116 && props.Set<int>(tag::minor_version, crypt_ftr.minor_version)
117 && props.Set<int>(tag::flags, crypt_ftr.flags)
118 && props.Set<int>(tag::crypt_type, crypt_ftr.crypt_type)
119 && props.Set<int>(tag::failed_decrypt_count,
120 crypt_ftr.failed_decrypt_count)
121 && props.Set<std::string>(tag::crypto_type_name,
122 std::string(reinterpret_cast<const char*>(crypt_ftr.crypto_type_name)))
123 && props.Set<std::string>(tag::master_key,
124 std::string((const char*) crypt_ftr.master_key,
125 crypt_ftr.keysize))
126 && props.Set<std::string>(tag::salt,
127 std::string((const char*) crypt_ftr.salt,
128 SALT_LEN))
129 && props.Set<int>(tag::kdf_type, crypt_ftr.kdf_type)
130 && props.Set<int>(tag::N_factor, crypt_ftr.N_factor)
131 && props.Set<int>(tag::r_factor, crypt_ftr.r_factor)
132 && props.Set<int>(tag::p_factor, crypt_ftr.p_factor)
133 && props.Set<std::string>(tag::keymaster_blob,
134 std::string((const char*) crypt_ftr.keymaster_blob,
135 crypt_ftr.keymaster_blob_size))
136 && props.Set<std::string>(tag::scrypted_intermediate_key,
137 std::string((const char*) crypt_ftr.scrypted_intermediate_key,
138 SCRYPT_LEN));
139 return success ? 0 : -1;
140}
141
142static int get_crypt_ftr_and_key(crypt_mnt_ftr& crypt_ftr,
143 const UnencryptedProperties& props)
144{
145 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
146 crypt_ftr.magic = props.Get<int>(tag::magic);
147 crypt_ftr.major_version = props.Get<int>(tag::major_version);
148 crypt_ftr.minor_version = props.Get<int>(tag::minor_version);
Paul Lawrence0d9cd9e2015-05-05 15:58:27 -0700149 crypt_ftr.ftr_size = sizeof(crypt_ftr);
Paul Lawrence731a7a22015-04-28 22:14:15 +0000150 crypt_ftr.flags = props.Get<int>(tag::flags);
151 crypt_ftr.crypt_type = props.Get<int>(tag::crypt_type);
152 crypt_ftr.failed_decrypt_count = props.Get<int>(tag::failed_decrypt_count);
153 std::string crypto_type_name = props.Get<std::string>(tag::crypto_type_name);
154 strlcpy(reinterpret_cast<char*>(crypt_ftr.crypto_type_name),
155 crypto_type_name.c_str(),
156 sizeof(crypt_ftr.crypto_type_name));
157 std::string master_key = props.Get<std::string>(tag::master_key);
158 crypt_ftr.keysize = master_key.size();
159 if (crypt_ftr.keysize > sizeof(crypt_ftr.master_key)) {
160 SLOGE("Master key size too long");
161 return -1;
162 }
163 memcpy(crypt_ftr.master_key, &master_key[0], crypt_ftr.keysize);
164 std::string salt = props.Get<std::string>(tag::salt);
165 if (salt.size() != SALT_LEN) {
166 SLOGE("Salt wrong length");
167 return -1;
168 }
169 memcpy(crypt_ftr.salt, &salt[0], SALT_LEN);
170 crypt_ftr.kdf_type = props.Get<int>(tag::kdf_type);
171 crypt_ftr.N_factor = props.Get<int>(tag::N_factor);
172 crypt_ftr.r_factor = props.Get<int>(tag::r_factor);
173 crypt_ftr.p_factor = props.Get<int>(tag::p_factor);
174 std::string keymaster_blob = props.Get<std::string>(tag::keymaster_blob);
175 crypt_ftr.keymaster_blob_size = keymaster_blob.size();
176 if (crypt_ftr.keymaster_blob_size > sizeof(crypt_ftr.keymaster_blob)) {
177 SLOGE("Keymaster blob too long");
178 return -1;
179 }
180 memcpy(crypt_ftr.keymaster_blob, &keymaster_blob[0],
181 crypt_ftr.keymaster_blob_size);
182 std::string scrypted_intermediate_key = props.Get<std::string>(tag::scrypted_intermediate_key);
183 if (scrypted_intermediate_key.size() != SCRYPT_LEN) {
184 SLOGE("scrypted intermediate key wrong length");
185 return -1;
186 }
187 memcpy(crypt_ftr.scrypted_intermediate_key, &scrypted_intermediate_key[0],
188 SCRYPT_LEN);
189
190 return 0;
191}
192
193static UnencryptedProperties GetProps(const char* path)
194{
195 return UnencryptedProperties(path);
196}
197
198static UnencryptedProperties GetAltProps(const char* path)
199{
200 return UnencryptedProperties((std::string() + path + "/tmp_mnt").c_str());
201}
202
203static UnencryptedProperties GetPropsOrAltProps(const char* path)
204{
205 UnencryptedProperties props = GetProps(path);
206 if (props.OK()) {
207 return props;
208 }
209 return GetAltProps(path);
210}
211
212int e4crypt_enable(const char* path)
213{
214 // Already enabled?
215 if (s_key_store.find(path) != s_key_store.end()) {
216 return 0;
217 }
218
219 // Not an encryptable device?
220 UnencryptedProperties key_props = GetProps(path).GetChild(properties::key);
221 if (!key_props.OK()) {
222 return 0;
223 }
224
225 if (key_props.Get<std::string>(tag::master_key).empty()) {
226 crypt_mnt_ftr ftr;
227 if (cryptfs_create_default_ftr(&ftr, key_length)) {
228 SLOGE("Failed to create crypto footer");
229 return -1;
230 }
231
Paul Lawrence0d9cd9e2015-05-05 15:58:27 -0700232 // Scrub fields not used by ext4enc
233 ftr.persist_data_offset[0] = 0;
234 ftr.persist_data_offset[1] = 0;
235 ftr.persist_data_size = 0;
236
Paul Lawrence731a7a22015-04-28 22:14:15 +0000237 if (put_crypt_ftr_and_key(ftr, key_props)) {
238 SLOGE("Failed to write crypto footer");
239 return -1;
240 }
241
242 crypt_mnt_ftr ftr2;
243 if (get_crypt_ftr_and_key(ftr2, key_props)) {
244 SLOGE("Failed to read crypto footer back");
245 return -1;
246 }
247
248 if (memcmp(&ftr, &ftr2, sizeof(ftr)) != 0) {
249 SLOGE("Crypto footer not correctly written");
Paul Lawrence0d9cd9e2015-05-05 15:58:27 -0700250 return -1;
Paul Lawrence731a7a22015-04-28 22:14:15 +0000251 }
252 }
253
254 if (!UnencryptedProperties(path).Remove(properties::ref)) {
255 SLOGE("Failed to remove key ref");
256 return -1;
257 }
258
259 return e4crypt_check_passwd(path, "");
260}
261
262int e4crypt_change_password(const char* path, int crypt_type,
263 const char* password)
264{
265 SLOGI("e4crypt_change_password");
Paul Lawrencea56d3132015-05-04 15:48:24 -0700266 auto key_props = GetProps(path).GetChild(properties::key);
Paul Lawrence731a7a22015-04-28 22:14:15 +0000267
268 crypt_mnt_ftr ftr;
269 if (get_crypt_ftr_and_key(ftr, key_props)) {
270 SLOGE("Failed to read crypto footer back");
271 return -1;
272 }
273
274 auto mki = s_key_store.find(path);
275 if (mki == s_key_store.end()) {
276 SLOGE("No stored master key - can't change password");
277 return -1;
278 }
279
Paul Crowley95376d62015-05-06 15:04:43 +0100280 const unsigned char* master_key_bytes
Paul Lawrence731a7a22015-04-28 22:14:15 +0000281 = reinterpret_cast<const unsigned char*>(&mki->second.master_key[0]);
282
Paul Crowley95376d62015-05-06 15:04:43 +0100283 if (cryptfs_set_password(&ftr, password, master_key_bytes)) {
Paul Lawrence731a7a22015-04-28 22:14:15 +0000284 SLOGE("Failed to set password");
285 return -1;
286 }
287
288 ftr.crypt_type = crypt_type;
289
290 if (put_crypt_ftr_and_key(ftr, key_props)) {
291 SLOGE("Failed to write crypto footer");
292 return -1;
293 }
294
295 if (!UnencryptedProperties(path).Set(properties::is_default,
296 crypt_type == CRYPT_TYPE_DEFAULT)) {
297 SLOGE("Failed to update default flag");
298 return -1;
299 }
300
301 return 0;
302}
303
304int e4crypt_crypto_complete(const char* path)
305{
306 SLOGI("ext4 crypto complete called on %s", path);
Paul Lawrencea56d3132015-05-04 15:48:24 -0700307 auto key_props = GetPropsOrAltProps(path).GetChild(properties::key);
Paul Lawrence731a7a22015-04-28 22:14:15 +0000308 if (key_props.Get<std::string>(tag::master_key).empty()) {
309 SLOGI("No master key, so not ext4enc");
310 return -1;
311 }
312
313 return 0;
314}
315
Paul Crowley93363482015-07-07 15:17:22 +0100316// Get raw keyref - used to make keyname and to pass to ioctl
Paul Lawrencefd7db732015-04-10 07:48:51 -0700317static std::string generate_key_ref(const char* key, int length)
318{
319 SHA512_CTX c;
320
321 SHA512_Init(&c);
322 SHA512_Update(&c, key, length);
323 unsigned char key_ref1[SHA512_LENGTH];
324 SHA512_Final(key_ref1, &c);
325
326 SHA512_Init(&c);
327 SHA512_Update(&c, key_ref1, SHA512_LENGTH);
328 unsigned char key_ref2[SHA512_LENGTH];
329 SHA512_Final(key_ref2, &c);
330
331 return std::string((char*)key_ref2, EXT4_KEY_DESCRIPTOR_SIZE);
332}
333
Paul Lawrence731a7a22015-04-28 22:14:15 +0000334int e4crypt_check_passwd(const char* path, const char* password)
335{
336 SLOGI("e4crypt_check_password");
Paul Lawrencea56d3132015-05-04 15:48:24 -0700337 auto props = GetPropsOrAltProps(path);
338 auto key_props = props.GetChild(properties::key);
Paul Lawrence731a7a22015-04-28 22:14:15 +0000339
340 crypt_mnt_ftr ftr;
341 if (get_crypt_ftr_and_key(ftr, key_props)) {
342 SLOGE("Failed to read crypto footer back");
343 return -1;
344 }
345
Paul Crowley95376d62015-05-06 15:04:43 +0100346 unsigned char master_key_bytes[key_length / 8];
347 if (cryptfs_get_master_key (&ftr, password, master_key_bytes)){
Paul Lawrence731a7a22015-04-28 22:14:15 +0000348 SLOGI("Incorrect password");
Paul Lawrencec78c71b2015-04-14 15:26:29 -0700349 ftr.failed_decrypt_count++;
350 if (put_crypt_ftr_and_key(ftr, key_props)) {
351 SLOGW("Failed to update failed_decrypt_count");
352 }
353 return ftr.failed_decrypt_count;
354 }
355
356 if (ftr.failed_decrypt_count) {
357 ftr.failed_decrypt_count = 0;
358 if (put_crypt_ftr_and_key(ftr, key_props)) {
359 SLOGW("Failed to reset failed_decrypt_count");
360 }
Paul Lawrence731a7a22015-04-28 22:14:15 +0000361 }
Paul Crowley95376d62015-05-06 15:04:43 +0100362 std::string master_key(reinterpret_cast<char*>(master_key_bytes),
363 sizeof(master_key_bytes));
Paul Lawrence731a7a22015-04-28 22:14:15 +0000364
Paul Lawrence86c942a2015-05-06 13:53:43 -0700365 struct timespec now;
366 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Crowley95376d62015-05-06 15:04:43 +0100367 s_key_store[path] = keys{master_key, password,
Paul Lawrence86c942a2015-05-06 13:53:43 -0700368 now.tv_sec + password_max_age_seconds};
Paul Crowleyf25a35a2015-05-06 13:38:53 +0100369 auto raw_ref = e4crypt_install_key(master_key);
370 if (raw_ref.empty()) {
371 return -1;
372 }
Paul Lawrence731a7a22015-04-28 22:14:15 +0000373
Paul Crowleyf25a35a2015-05-06 13:38:53 +0100374 // Save reference to key so we can set policy later
375 if (!props.Set(properties::ref, raw_ref)) {
376 SLOGE("Cannot save key reference");
377 return -1;
378 }
379
380 return 0;
381}
382
Paul Crowley93363482015-07-07 15:17:22 +0100383static ext4_encryption_key fill_key(const std::string &key)
Paul Crowleyf25a35a2015-05-06 13:38:53 +0100384{
Paul Lawrencefd7db732015-04-10 07:48:51 -0700385 // ext4enc:TODO Currently raw key is required to be of length
386 // sizeof(ext4_key.raw) == EXT4_MAX_KEY_SIZE, so zero pad to
387 // this length. Change when kernel bug is fixed.
388 ext4_encryption_key ext4_key = {EXT4_ENCRYPTION_MODE_AES_256_XTS,
389 {0},
390 sizeof(ext4_key.raw)};
391 memset(ext4_key.raw, 0, sizeof(ext4_key.raw));
392 static_assert(key_length / 8 <= sizeof(ext4_key.raw),
393 "Key too long!");
Paul Crowley95376d62015-05-06 15:04:43 +0100394 memcpy(ext4_key.raw, &key[0], key.size());
Paul Crowley93363482015-07-07 15:17:22 +0100395 return ext4_key;
396}
Paul Lawrence731a7a22015-04-28 22:14:15 +0000397
Paul Crowley93363482015-07-07 15:17:22 +0100398static std::string keyname(const std::string &raw_ref)
399{
Paul Lawrencefd7db732015-04-10 07:48:51 -0700400 std::ostringstream o;
Paul Crowley93363482015-07-07 15:17:22 +0100401 o << "ext4:";
Paul Lawrencefd7db732015-04-10 07:48:51 -0700402 for (auto i = raw_ref.begin(); i != raw_ref.end(); ++i) {
403 o << std::hex << std::setw(2) << std::setfill('0') << (int)*i;
404 }
Paul Crowley93363482015-07-07 15:17:22 +0100405 return o.str();
406}
Paul Lawrencefd7db732015-04-10 07:48:51 -0700407
Paul Crowley93363482015-07-07 15:17:22 +0100408// Get the keyring we store all keys in
409static key_serial_t e4crypt_keyring()
410{
411 return keyctl_search(KEY_SPEC_SESSION_KEYRING, "keyring", "e4crypt", 0);
412}
Paul Lawrence731a7a22015-04-28 22:14:15 +0000413
Paul Crowley93363482015-07-07 15:17:22 +0100414static int e4crypt_install_key(const ext4_encryption_key &ext4_key, const std::string &ref)
415{
416 key_serial_t device_keyring = e4crypt_keyring();
Paul Lawrence731a7a22015-04-28 22:14:15 +0000417 SLOGI("Found device_keyring - id is %d", device_keyring);
Paul Lawrencefd7db732015-04-10 07:48:51 -0700418 key_serial_t key_id = add_key("logon", ref.c_str(),
Paul Lawrence731a7a22015-04-28 22:14:15 +0000419 (void*)&ext4_key, sizeof(ext4_key),
420 device_keyring);
Paul Lawrence731a7a22015-04-28 22:14:15 +0000421 if (key_id == -1) {
422 SLOGE("Failed to insert key into keyring with error %s",
423 strerror(errno));
Paul Crowley93363482015-07-07 15:17:22 +0100424 return -1;
Paul Lawrence731a7a22015-04-28 22:14:15 +0000425 }
Paul Lawrencefd7db732015-04-10 07:48:51 -0700426 SLOGI("Added key %d (%s) to keyring %d in process %d",
427 key_id, ref.c_str(), device_keyring, getpid());
Paul Crowley93363482015-07-07 15:17:22 +0100428 return 0;
429}
Paul Lawrence731a7a22015-04-28 22:14:15 +0000430
Paul Crowley93363482015-07-07 15:17:22 +0100431// Install password into global keyring
432// Return raw key reference for use in policy
433static std::string e4crypt_install_key(const std::string &key)
434{
435 auto ext4_key = fill_key(key);
436 auto raw_ref = generate_key_ref(ext4_key.raw, ext4_key.size);
437 auto ref = keyname(raw_ref);
438 if (e4crypt_install_key(ext4_key, ref) == -1) {
439 return "";
440 }
Paul Crowleyf25a35a2015-05-06 13:38:53 +0100441 return raw_ref;
Paul Lawrence731a7a22015-04-28 22:14:15 +0000442}
443
444int e4crypt_restart(const char* path)
445{
446 SLOGI("e4crypt_restart");
447
448 int rc = 0;
449
450 SLOGI("ext4 restart called on %s", path);
451 property_set("vold.decrypt", "trigger_reset_main");
452 SLOGI("Just asked init to shut down class main");
453 sleep(2);
454
455 std::string tmp_path = std::string() + path + "/tmp_mnt";
456
Paul Lawrence2f32cda2015-05-05 14:28:25 -0700457 rc = wait_and_unmount(tmp_path.c_str(), true);
Paul Lawrence731a7a22015-04-28 22:14:15 +0000458 if (rc) {
459 SLOGE("umount %s failed with rc %d, msg %s",
460 tmp_path.c_str(), rc, strerror(errno));
461 return rc;
462 }
463
Paul Lawrence2f32cda2015-05-05 14:28:25 -0700464 rc = wait_and_unmount(path, true);
Paul Lawrence731a7a22015-04-28 22:14:15 +0000465 if (rc) {
466 SLOGE("umount %s failed with rc %d, msg %s",
467 path, rc, strerror(errno));
468 return rc;
469 }
470
471 return 0;
472}
473
Paul Lawrence731a7a22015-04-28 22:14:15 +0000474int e4crypt_get_password_type(const char* path)
475{
476 SLOGI("e4crypt_get_password_type");
477 return GetPropsOrAltProps(path).GetChild(properties::key)
478 .Get<int>(tag::crypt_type, CRYPT_TYPE_DEFAULT);
479}
Paul Lawrence368d7942015-04-15 14:12:00 -0700480
Paul Lawrence86c942a2015-05-06 13:53:43 -0700481const char* e4crypt_get_password(const char* path)
482{
483 SLOGI("e4crypt_get_password");
484
485 auto i = s_key_store.find(path);
486 if (i == s_key_store.end()) {
487 return 0;
488 }
489
490 struct timespec now;
491 clock_gettime(CLOCK_BOOTTIME, &now);
492 if (i->second.expiry_time < now.tv_sec) {
493 e4crypt_clear_password(path);
494 return 0;
495 }
496
497 return i->second.password.c_str();
498}
499
500void e4crypt_clear_password(const char* path)
501{
502 SLOGI("e4crypt_clear_password");
503
504 auto i = s_key_store.find(path);
505 if (i == s_key_store.end()) {
506 return;
507 }
508
509 memset(&i->second.password[0], 0, i->second.password.size());
510 i->second.password = std::string();
511}
512
Paul Lawrence368d7942015-04-15 14:12:00 -0700513int e4crypt_get_field(const char* path, const char* fieldname,
514 char* value, size_t len)
515{
516 auto v = GetPropsOrAltProps(path).GetChild(properties::props)
517 .Get<std::string>(fieldname);
518
519 if (v == "") {
520 return CRYPTO_GETFIELD_ERROR_NO_FIELD;
521 }
522
523 if (v.length() >= len) {
524 return CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
525 }
526
527 strlcpy(value, v.c_str(), len);
528 return 0;
529}
530
531int e4crypt_set_field(const char* path, const char* fieldname,
532 const char* value)
533{
534 return GetPropsOrAltProps(path).GetChild(properties::props)
535 .Set(fieldname, std::string(value)) ? 0 : -1;
536}
Paul Crowley95376d62015-05-06 15:04:43 +0100537
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800538static std::string get_key_path(const char *mount_path, userid_t user_id) {
Paul Crowley95376d62015-05-06 15:04:43 +0100539 // ext4enc:TODO get the path properly
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800540 auto key_dir = StringPrintf("%s/misc/vold/user_keys", mount_path);
541 if (fs_prepare_dir(key_dir.c_str(), 0700, AID_ROOT, AID_ROOT)) {
542 PLOG(ERROR) << "Failed to prepare " << key_dir;
Paul Crowley95376d62015-05-06 15:04:43 +0100543 return "";
544 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800545 return StringPrintf("%s/%d", key_dir.c_str(), user_id);
Paul Crowleyb33e8872015-05-19 12:34:09 +0100546}
547
548// ext4enc:TODO this can't be the only place keys are read from /dev/urandom
549// we should unite those places.
Paul Crowley93363482015-07-07 15:17:22 +0100550static std::string e4crypt_get_key(
551 const std::string &key_path,
Paul Crowleyb33e8872015-05-19 12:34:09 +0100552 bool create_if_absent)
553{
Paul Crowley95376d62015-05-06 15:04:43 +0100554 std::string content;
555 if (android::base::ReadFileToString(key_path, &content)) {
556 if (content.size() != key_length/8) {
557 SLOGE("Wrong size key %zu in %s", content.size(), key_path.c_str());
558 return "";
559 }
560 return content;
561 }
562 if (!create_if_absent) {
563 SLOGE("No key found in %s", key_path.c_str());
564 return "";
565 }
566 std::ifstream urandom("/dev/urandom");
567 if (!urandom) {
568 SLOGE("Unable to open /dev/urandom (%s)", strerror(errno));
569 return "";
570 }
571 char key_bytes[key_length / 8];
572 errno = 0;
573 urandom.read(key_bytes, sizeof(key_bytes));
574 if (!urandom) {
575 SLOGE("Unable to read key from /dev/urandom (%s)", strerror(errno));
576 return "";
577 }
Paul Crowley93363482015-07-07 15:17:22 +0100578 std::string key(key_bytes, sizeof(key_bytes));
579 if (!android::base::WriteStringToFile(key, key_path)) {
Paul Crowley95376d62015-05-06 15:04:43 +0100580 SLOGE("Unable to write key to %s (%s)",
581 key_path.c_str(), strerror(errno));
582 return "";
583 }
Paul Crowley93363482015-07-07 15:17:22 +0100584 return key;
Paul Crowley95376d62015-05-06 15:04:43 +0100585}
586
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800587static int e4crypt_set_user_policy(const char *mount_path, userid_t user_id,
588 const char *path, bool create_if_absent) {
589 SLOGD("e4crypt_set_user_policy for %d", user_id);
590 auto user_key = e4crypt_get_key(get_key_path(mount_path, user_id),
591 create_if_absent);
Paul Crowley95376d62015-05-06 15:04:43 +0100592 if (user_key.empty()) {
593 return -1;
594 }
595 auto raw_ref = e4crypt_install_key(user_key);
596 if (raw_ref.empty()) {
597 return -1;
598 }
599 return do_policy_set(path, raw_ref.c_str(), raw_ref.size());
600}
601
Paul Crowley95376d62015-05-06 15:04:43 +0100602static bool is_numeric(const char *name) {
603 for (const char *p = name; *p != '\0'; p++) {
604 if (!isdigit(*p))
605 return false;
606 }
607 return true;
608}
609
610int e4crypt_set_user_crypto_policies(const char *dir)
611{
612 if (e4crypt_crypto_complete(DATA_MNT_POINT) != 0) {
613 return 0;
614 }
615 SLOGD("e4crypt_set_user_crypto_policies");
616 std::unique_ptr<DIR, int(*)(DIR*)> dirp(opendir(dir), closedir);
617 if (!dirp) {
618 SLOGE("Unable to read directory %s, error %s\n",
619 dir, strerror(errno));
620 return -1;
621 }
622 for (;;) {
623 struct dirent *result = readdir(dirp.get());
624 if (!result) {
625 // ext4enc:TODO check errno
626 break;
627 }
628 if (result->d_type != DT_DIR || !is_numeric(result->d_name)) {
629 continue; // skips user 0, which is a symlink
630 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800631 auto user_id = atoi(result->d_name);
Paul Crowley95376d62015-05-06 15:04:43 +0100632 auto user_dir = std::string() + dir + "/" + result->d_name;
633 // ext4enc:TODO don't hardcode /data
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800634 if (e4crypt_set_user_policy("/data", user_id, user_dir.c_str(), false)) {
Paul Crowley95376d62015-05-06 15:04:43 +0100635 // ext4enc:TODO If this function fails, stop the boot: we must
636 // deliver on promised encryption.
637 SLOGE("Unable to set policy on %s\n", user_dir.c_str());
638 }
639 }
640 return 0;
641}
Paul Crowleyb33e8872015-05-19 12:34:09 +0100642
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800643int e4crypt_create_user_key(userid_t user_id) {
644 SLOGD("e4crypt_create_user_key(%d)", user_id);
645 // TODO: create second key for user_de data
646 if (e4crypt_get_key(get_key_path(DATA_MNT_POINT, user_id), true).empty()) {
647 return -1;
648 } else {
649 return 0;
650 }
651}
652
653int e4crypt_destroy_user_key(userid_t user_id) {
654 SLOGD("e4crypt_destroy_user_key(%d)", user_id);
655 // TODO: destroy second key for user_de data
656 auto key_path = get_key_path(DATA_MNT_POINT, user_id);
Paul Crowley93363482015-07-07 15:17:22 +0100657 auto key = e4crypt_get_key(key_path, false);
658 auto ext4_key = fill_key(key);
659 auto ref = keyname(generate_key_ref(ext4_key.raw, ext4_key.size));
660 auto key_serial = keyctl_search(e4crypt_keyring(), "logon", ref.c_str(), 0);
661 if (keyctl_revoke(key_serial) == 0) {
662 SLOGD("Revoked key with serial %ld ref %s\n", key_serial, ref.c_str());
663 } else {
664 SLOGE("Failed to revoke key with serial %ld ref %s: %s\n",
665 key_serial, ref.c_str(), strerror(errno));
666 }
Paul Crowleycd307b72015-05-19 17:31:39 +0100667 int pid = fork();
668 if (pid < 0) {
669 SLOGE("Unable to fork: %s", strerror(errno));
Paul Crowleyb33e8872015-05-19 12:34:09 +0100670 return -1;
671 }
Paul Crowleycd307b72015-05-19 17:31:39 +0100672 if (pid == 0) {
673 SLOGD("Forked for secdiscard");
674 execl("/system/bin/secdiscard",
675 "/system/bin/secdiscard",
Paul Crowley5ab73e92015-07-03 16:17:23 +0100676 "--",
Paul Crowleycd307b72015-05-19 17:31:39 +0100677 key_path.c_str(),
678 NULL);
679 SLOGE("Unable to launch secdiscard on %s: %s\n", key_path.c_str(),
680 strerror(errno));
681 exit(-1);
682 }
683 // ext4enc:TODO reap the zombie
Paul Crowleyb33e8872015-05-19 12:34:09 +0100684 return 0;
685}
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800686
687int e4crypt_unlock_user_key(userid_t user_id, const char* token) {
Jeff Sharkeyc79fb892015-11-12 20:18:02 -0800688 if (property_get_bool(kPropEmulateFbe, false)) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800689 // When in emulation mode, we just use chmod
690 if (chmod(android::vold::BuildDataSystemCePath(user_id).c_str(), 0771) ||
691 chmod(android::vold::BuildDataUserPath(nullptr, user_id).c_str(), 0771)) {
692 PLOG(ERROR) << "Failed to unlock user " << user_id;
693 return -1;
694 }
695 } else {
696 auto user_key = e4crypt_get_key(get_key_path(DATA_MNT_POINT, user_id), false);
697 if (user_key.empty()) {
698 return -1;
699 }
700 auto raw_ref = e4crypt_install_key(user_key);
701 if (raw_ref.empty()) {
702 return -1;
703 }
704 }
705 return 0;
706}
707
708int e4crypt_lock_user_key(userid_t user_id) {
Jeff Sharkeyc79fb892015-11-12 20:18:02 -0800709 if (property_get_bool(kPropEmulateFbe, false)) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800710 // When in emulation mode, we just use chmod
711 if (chmod(android::vold::BuildDataSystemCePath(user_id).c_str(), 0000) ||
712 chmod(android::vold::BuildDataUserPath(nullptr, user_id).c_str(), 0000)) {
713 PLOG(ERROR) << "Failed to lock user " << user_id;
714 return -1;
715 }
716 } else {
717 // TODO: remove from kernel keyring
718 }
719 return 0;
720}
721
722int e4crypt_prepare_user_storage(const char* volume_uuid, userid_t user_id) {
723 std::string system_ce_path(android::vold::BuildDataSystemCePath(user_id));
724 std::string user_ce_path(android::vold::BuildDataUserPath(volume_uuid, user_id));
725 std::string user_de_path(android::vold::BuildDataUserDePath(volume_uuid, user_id));
726
727 if (fs_prepare_dir(system_ce_path.c_str(), 0700, AID_SYSTEM, AID_SYSTEM)) {
728 PLOG(ERROR) << "Failed to prepare " << system_ce_path;
729 return -1;
730 }
731 if (fs_prepare_dir(user_ce_path.c_str(), 0771, AID_SYSTEM, AID_SYSTEM)) {
732 PLOG(ERROR) << "Failed to prepare " << user_ce_path;
733 return -1;
734 }
735 if (fs_prepare_dir(user_de_path.c_str(), 0771, AID_SYSTEM, AID_SYSTEM)) {
736 PLOG(ERROR) << "Failed to prepare " << user_de_path;
737 return -1;
738 }
739
740 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
741 if (e4crypt_set_user_policy(DATA_MNT_POINT, user_id, system_ce_path.c_str(), true)
742 || e4crypt_set_user_policy(DATA_MNT_POINT, user_id, user_ce_path.c_str(), true)) {
743 return -1;
744 }
745 }
746
747 return 0;
748}