blob: 7470ff9c059b6c5b205741fbeb2dd8dd88f1b29a [file] [log] [blame]
Paul Lawrence707fd6c2015-04-28 22:14:15 +00001#include "Ext4Crypt.h"
2
Paul Lawrence5e7f0042015-04-10 07:48:51 -07003#include <iomanip>
Paul Lawrence707fd6c2015-04-28 22:14:15 +00004#include <map>
Paul Lawrence5e7f0042015-04-10 07:48:51 -07005#include <fstream>
6#include <string>
7#include <sstream>
Paul Lawrence707fd6c2015-04-28 22:14:15 +00008
9#include <errno.h>
Paul Crowley75a52022015-05-06 15:04:43 +010010#include <dirent.h>
Paul Lawrence707fd6c2015-04-28 22:14:15 +000011#include <sys/mount.h>
Paul Crowley75a52022015-05-06 15:04:43 +010012#include <sys/types.h>
13#include <sys/stat.h>
14#include <fcntl.h>
Paul Lawrence707fd6c2015-04-28 22:14:15 +000015#include <cutils/properties.h>
Paul Lawrence5e7f0042015-04-10 07:48:51 -070016#include <openssl/sha.h>
Paul Lawrence707fd6c2015-04-28 22:14:15 +000017
18#include "unencrypted_properties.h"
19#include "key_control.h"
20#include "cryptfs.h"
Paul Crowley75a52022015-05-06 15:04:43 +010021#include "ext4_crypt_init_extensions.h"
Paul Lawrence707fd6c2015-04-28 22:14:15 +000022
23#define LOG_TAG "Ext4Crypt"
24#include "cutils/log.h"
25#include <cutils/klog.h>
Paul Crowley75a52022015-05-06 15:04:43 +010026#include <base/file.h>
27#include <base/stringprintf.h>
Paul Lawrence707fd6c2015-04-28 22:14:15 +000028
29namespace {
30 // Key length in bits
31 const int key_length = 128;
Paul Lawrence5e7f0042015-04-10 07:48:51 -070032 static_assert(key_length % 8 == 0,
33 "Key length must be multiple of 8 bits");
Paul Lawrence707fd6c2015-04-28 22:14:15 +000034
Paul Lawrence00f4aad2015-05-06 13:53:43 -070035 // How long do we store passwords for?
36 const int password_max_age_seconds = 60;
37
Paul Lawrence707fd6c2015-04-28 22:14:15 +000038 // How is device encrypted
39 struct keys {
40 std::string master_key;
41 std::string password;
Paul Lawrence00f4aad2015-05-06 13:53:43 -070042 time_t expiry_time;
Paul Lawrence707fd6c2015-04-28 22:14:15 +000043 };
44 std::map<std::string, keys> s_key_store;
45
Paul Lawrence5e7f0042015-04-10 07:48:51 -070046 // ext4enc:TODO get these consts from somewhere good
47 const int SHA512_LENGTH = 64;
48 const int EXT4_KEY_DESCRIPTOR_SIZE = 8;
49
Paul Lawrence707fd6c2015-04-28 22:14:15 +000050 // ext4enc:TODO Include structure from somewhere sensible
51 // MUST be in sync with ext4_crypto.c in kernel
Paul Lawrence5e7f0042015-04-10 07:48:51 -070052 const int EXT4_MAX_KEY_SIZE = 64;
53 const int EXT4_ENCRYPTION_MODE_AES_256_XTS = 1;
Paul Lawrence707fd6c2015-04-28 22:14:15 +000054 struct ext4_encryption_key {
Paul Lawrence5e7f0042015-04-10 07:48:51 -070055 uint32_t mode;
56 char raw[EXT4_MAX_KEY_SIZE];
57 uint32_t size;
Paul Lawrence707fd6c2015-04-28 22:14:15 +000058 };
59
60 namespace tag {
61 const char* magic = "magic";
62 const char* major_version = "major_version";
63 const char* minor_version = "minor_version";
64 const char* flags = "flags";
65 const char* crypt_type = "crypt_type";
66 const char* failed_decrypt_count = "failed_decrypt_count";
67 const char* crypto_type_name = "crypto_type_name";
68 const char* master_key = "master_key";
69 const char* salt = "salt";
70 const char* kdf_type = "kdf_type";
71 const char* N_factor = "N_factor";
72 const char* r_factor = "r_factor";
73 const char* p_factor = "p_factor";
74 const char* keymaster_blob = "keymaster_blob";
75 const char* scrypted_intermediate_key = "scrypted_intermediate_key";
76 }
77}
78
Paul Crowley75a52022015-05-06 15:04:43 +010079static std::string e4crypt_install_key(const std::string &key);
Paul Crowley1da96dc2015-05-06 13:38:53 +010080
Paul Lawrence707fd6c2015-04-28 22:14:15 +000081static int put_crypt_ftr_and_key(const crypt_mnt_ftr& crypt_ftr,
82 UnencryptedProperties& props)
83{
84 SLOGI("Putting crypt footer");
85
86 bool success = props.Set<int>(tag::magic, crypt_ftr.magic)
87 && props.Set<int>(tag::major_version, crypt_ftr.major_version)
88 && props.Set<int>(tag::minor_version, crypt_ftr.minor_version)
89 && props.Set<int>(tag::flags, crypt_ftr.flags)
90 && props.Set<int>(tag::crypt_type, crypt_ftr.crypt_type)
91 && props.Set<int>(tag::failed_decrypt_count,
92 crypt_ftr.failed_decrypt_count)
93 && props.Set<std::string>(tag::crypto_type_name,
94 std::string(reinterpret_cast<const char*>(crypt_ftr.crypto_type_name)))
95 && props.Set<std::string>(tag::master_key,
96 std::string((const char*) crypt_ftr.master_key,
97 crypt_ftr.keysize))
98 && props.Set<std::string>(tag::salt,
99 std::string((const char*) crypt_ftr.salt,
100 SALT_LEN))
101 && props.Set<int>(tag::kdf_type, crypt_ftr.kdf_type)
102 && props.Set<int>(tag::N_factor, crypt_ftr.N_factor)
103 && props.Set<int>(tag::r_factor, crypt_ftr.r_factor)
104 && props.Set<int>(tag::p_factor, crypt_ftr.p_factor)
105 && props.Set<std::string>(tag::keymaster_blob,
106 std::string((const char*) crypt_ftr.keymaster_blob,
107 crypt_ftr.keymaster_blob_size))
108 && props.Set<std::string>(tag::scrypted_intermediate_key,
109 std::string((const char*) crypt_ftr.scrypted_intermediate_key,
110 SCRYPT_LEN));
111 return success ? 0 : -1;
112}
113
114static int get_crypt_ftr_and_key(crypt_mnt_ftr& crypt_ftr,
115 const UnencryptedProperties& props)
116{
117 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
118 crypt_ftr.magic = props.Get<int>(tag::magic);
119 crypt_ftr.major_version = props.Get<int>(tag::major_version);
120 crypt_ftr.minor_version = props.Get<int>(tag::minor_version);
Paul Lawrence75c922f2015-05-05 15:58:27 -0700121 crypt_ftr.ftr_size = sizeof(crypt_ftr);
Paul Lawrence707fd6c2015-04-28 22:14:15 +0000122 crypt_ftr.flags = props.Get<int>(tag::flags);
123 crypt_ftr.crypt_type = props.Get<int>(tag::crypt_type);
124 crypt_ftr.failed_decrypt_count = props.Get<int>(tag::failed_decrypt_count);
125 std::string crypto_type_name = props.Get<std::string>(tag::crypto_type_name);
126 strlcpy(reinterpret_cast<char*>(crypt_ftr.crypto_type_name),
127 crypto_type_name.c_str(),
128 sizeof(crypt_ftr.crypto_type_name));
129 std::string master_key = props.Get<std::string>(tag::master_key);
130 crypt_ftr.keysize = master_key.size();
131 if (crypt_ftr.keysize > sizeof(crypt_ftr.master_key)) {
132 SLOGE("Master key size too long");
133 return -1;
134 }
135 memcpy(crypt_ftr.master_key, &master_key[0], crypt_ftr.keysize);
136 std::string salt = props.Get<std::string>(tag::salt);
137 if (salt.size() != SALT_LEN) {
138 SLOGE("Salt wrong length");
139 return -1;
140 }
141 memcpy(crypt_ftr.salt, &salt[0], SALT_LEN);
142 crypt_ftr.kdf_type = props.Get<int>(tag::kdf_type);
143 crypt_ftr.N_factor = props.Get<int>(tag::N_factor);
144 crypt_ftr.r_factor = props.Get<int>(tag::r_factor);
145 crypt_ftr.p_factor = props.Get<int>(tag::p_factor);
146 std::string keymaster_blob = props.Get<std::string>(tag::keymaster_blob);
147 crypt_ftr.keymaster_blob_size = keymaster_blob.size();
148 if (crypt_ftr.keymaster_blob_size > sizeof(crypt_ftr.keymaster_blob)) {
149 SLOGE("Keymaster blob too long");
150 return -1;
151 }
152 memcpy(crypt_ftr.keymaster_blob, &keymaster_blob[0],
153 crypt_ftr.keymaster_blob_size);
154 std::string scrypted_intermediate_key = props.Get<std::string>(tag::scrypted_intermediate_key);
155 if (scrypted_intermediate_key.size() != SCRYPT_LEN) {
156 SLOGE("scrypted intermediate key wrong length");
157 return -1;
158 }
159 memcpy(crypt_ftr.scrypted_intermediate_key, &scrypted_intermediate_key[0],
160 SCRYPT_LEN);
161
162 return 0;
163}
164
165static UnencryptedProperties GetProps(const char* path)
166{
167 return UnencryptedProperties(path);
168}
169
170static UnencryptedProperties GetAltProps(const char* path)
171{
172 return UnencryptedProperties((std::string() + path + "/tmp_mnt").c_str());
173}
174
175static UnencryptedProperties GetPropsOrAltProps(const char* path)
176{
177 UnencryptedProperties props = GetProps(path);
178 if (props.OK()) {
179 return props;
180 }
181 return GetAltProps(path);
182}
183
184int e4crypt_enable(const char* path)
185{
186 // Already enabled?
187 if (s_key_store.find(path) != s_key_store.end()) {
188 return 0;
189 }
190
191 // Not an encryptable device?
192 UnencryptedProperties key_props = GetProps(path).GetChild(properties::key);
193 if (!key_props.OK()) {
194 return 0;
195 }
196
197 if (key_props.Get<std::string>(tag::master_key).empty()) {
198 crypt_mnt_ftr ftr;
199 if (cryptfs_create_default_ftr(&ftr, key_length)) {
200 SLOGE("Failed to create crypto footer");
201 return -1;
202 }
203
Paul Lawrence75c922f2015-05-05 15:58:27 -0700204 // Scrub fields not used by ext4enc
205 ftr.persist_data_offset[0] = 0;
206 ftr.persist_data_offset[1] = 0;
207 ftr.persist_data_size = 0;
208
Paul Lawrence707fd6c2015-04-28 22:14:15 +0000209 if (put_crypt_ftr_and_key(ftr, key_props)) {
210 SLOGE("Failed to write crypto footer");
211 return -1;
212 }
213
214 crypt_mnt_ftr ftr2;
215 if (get_crypt_ftr_and_key(ftr2, key_props)) {
216 SLOGE("Failed to read crypto footer back");
217 return -1;
218 }
219
220 if (memcmp(&ftr, &ftr2, sizeof(ftr)) != 0) {
221 SLOGE("Crypto footer not correctly written");
Paul Lawrence75c922f2015-05-05 15:58:27 -0700222 return -1;
Paul Lawrence707fd6c2015-04-28 22:14:15 +0000223 }
224 }
225
226 if (!UnencryptedProperties(path).Remove(properties::ref)) {
227 SLOGE("Failed to remove key ref");
228 return -1;
229 }
230
231 return e4crypt_check_passwd(path, "");
232}
233
234int e4crypt_change_password(const char* path, int crypt_type,
235 const char* password)
236{
237 SLOGI("e4crypt_change_password");
Paul Lawrenceaaccfac2015-05-04 15:48:24 -0700238 auto key_props = GetProps(path).GetChild(properties::key);
Paul Lawrence707fd6c2015-04-28 22:14:15 +0000239
240 crypt_mnt_ftr ftr;
241 if (get_crypt_ftr_and_key(ftr, key_props)) {
242 SLOGE("Failed to read crypto footer back");
243 return -1;
244 }
245
246 auto mki = s_key_store.find(path);
247 if (mki == s_key_store.end()) {
248 SLOGE("No stored master key - can't change password");
249 return -1;
250 }
251
Paul Crowley75a52022015-05-06 15:04:43 +0100252 const unsigned char* master_key_bytes
Paul Lawrence707fd6c2015-04-28 22:14:15 +0000253 = reinterpret_cast<const unsigned char*>(&mki->second.master_key[0]);
254
Paul Crowley75a52022015-05-06 15:04:43 +0100255 if (cryptfs_set_password(&ftr, password, master_key_bytes)) {
Paul Lawrence707fd6c2015-04-28 22:14:15 +0000256 SLOGE("Failed to set password");
257 return -1;
258 }
259
260 ftr.crypt_type = crypt_type;
261
262 if (put_crypt_ftr_and_key(ftr, key_props)) {
263 SLOGE("Failed to write crypto footer");
264 return -1;
265 }
266
267 if (!UnencryptedProperties(path).Set(properties::is_default,
268 crypt_type == CRYPT_TYPE_DEFAULT)) {
269 SLOGE("Failed to update default flag");
270 return -1;
271 }
272
273 return 0;
274}
275
276int e4crypt_crypto_complete(const char* path)
277{
278 SLOGI("ext4 crypto complete called on %s", path);
Paul Lawrenceaaccfac2015-05-04 15:48:24 -0700279 auto key_props = GetPropsOrAltProps(path).GetChild(properties::key);
Paul Lawrence707fd6c2015-04-28 22:14:15 +0000280 if (key_props.Get<std::string>(tag::master_key).empty()) {
281 SLOGI("No master key, so not ext4enc");
282 return -1;
283 }
284
285 return 0;
286}
287
Paul Lawrence5e7f0042015-04-10 07:48:51 -0700288static std::string generate_key_ref(const char* key, int length)
289{
290 SHA512_CTX c;
291
292 SHA512_Init(&c);
293 SHA512_Update(&c, key, length);
294 unsigned char key_ref1[SHA512_LENGTH];
295 SHA512_Final(key_ref1, &c);
296
297 SHA512_Init(&c);
298 SHA512_Update(&c, key_ref1, SHA512_LENGTH);
299 unsigned char key_ref2[SHA512_LENGTH];
300 SHA512_Final(key_ref2, &c);
301
302 return std::string((char*)key_ref2, EXT4_KEY_DESCRIPTOR_SIZE);
303}
304
Paul Lawrence707fd6c2015-04-28 22:14:15 +0000305int e4crypt_check_passwd(const char* path, const char* password)
306{
307 SLOGI("e4crypt_check_password");
Paul Lawrenceaaccfac2015-05-04 15:48:24 -0700308 auto props = GetPropsOrAltProps(path);
309 auto key_props = props.GetChild(properties::key);
Paul Lawrence707fd6c2015-04-28 22:14:15 +0000310
311 crypt_mnt_ftr ftr;
312 if (get_crypt_ftr_and_key(ftr, key_props)) {
313 SLOGE("Failed to read crypto footer back");
314 return -1;
315 }
316
Paul Crowley75a52022015-05-06 15:04:43 +0100317 unsigned char master_key_bytes[key_length / 8];
318 if (cryptfs_get_master_key (&ftr, password, master_key_bytes)){
Paul Lawrence707fd6c2015-04-28 22:14:15 +0000319 SLOGI("Incorrect password");
Paul Lawrence3ca21e22015-04-14 15:26:29 -0700320 ftr.failed_decrypt_count++;
321 if (put_crypt_ftr_and_key(ftr, key_props)) {
322 SLOGW("Failed to update failed_decrypt_count");
323 }
324 return ftr.failed_decrypt_count;
325 }
326
327 if (ftr.failed_decrypt_count) {
328 ftr.failed_decrypt_count = 0;
329 if (put_crypt_ftr_and_key(ftr, key_props)) {
330 SLOGW("Failed to reset failed_decrypt_count");
331 }
Paul Lawrence707fd6c2015-04-28 22:14:15 +0000332 }
Paul Crowley75a52022015-05-06 15:04:43 +0100333 std::string master_key(reinterpret_cast<char*>(master_key_bytes),
334 sizeof(master_key_bytes));
Paul Lawrence707fd6c2015-04-28 22:14:15 +0000335
Paul Lawrence00f4aad2015-05-06 13:53:43 -0700336 struct timespec now;
337 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Crowley75a52022015-05-06 15:04:43 +0100338 s_key_store[path] = keys{master_key, password,
Paul Lawrence00f4aad2015-05-06 13:53:43 -0700339 now.tv_sec + password_max_age_seconds};
Paul Crowley1da96dc2015-05-06 13:38:53 +0100340 auto raw_ref = e4crypt_install_key(master_key);
341 if (raw_ref.empty()) {
342 return -1;
343 }
Paul Lawrence707fd6c2015-04-28 22:14:15 +0000344
Paul Crowley1da96dc2015-05-06 13:38:53 +0100345 // Save reference to key so we can set policy later
346 if (!props.Set(properties::ref, raw_ref)) {
347 SLOGE("Cannot save key reference");
348 return -1;
349 }
350
351 return 0;
352}
353
354// Install password into global keyring
355// Return raw key reference for use in policy
Paul Crowley75a52022015-05-06 15:04:43 +0100356static std::string e4crypt_install_key(const std::string &key)
Paul Crowley1da96dc2015-05-06 13:38:53 +0100357{
Paul Lawrence5e7f0042015-04-10 07:48:51 -0700358 // ext4enc:TODO Currently raw key is required to be of length
359 // sizeof(ext4_key.raw) == EXT4_MAX_KEY_SIZE, so zero pad to
360 // this length. Change when kernel bug is fixed.
361 ext4_encryption_key ext4_key = {EXT4_ENCRYPTION_MODE_AES_256_XTS,
362 {0},
363 sizeof(ext4_key.raw)};
364 memset(ext4_key.raw, 0, sizeof(ext4_key.raw));
365 static_assert(key_length / 8 <= sizeof(ext4_key.raw),
366 "Key too long!");
Paul Crowley75a52022015-05-06 15:04:43 +0100367 memcpy(ext4_key.raw, &key[0], key.size());
Paul Lawrence707fd6c2015-04-28 22:14:15 +0000368
Paul Lawrence5e7f0042015-04-10 07:48:51 -0700369 // Get raw keyref - used to make keyname and to pass to ioctl
370 auto raw_ref = generate_key_ref(ext4_key.raw, ext4_key.size);
371
372 // Generate keyname
373 std::ostringstream o;
374 for (auto i = raw_ref.begin(); i != raw_ref.end(); ++i) {
375 o << std::hex << std::setw(2) << std::setfill('0') << (int)*i;
376 }
377 auto ref = std::string("ext4:") + o.str();
378
379 // Find existing keyring
Paul Lawrence707fd6c2015-04-28 22:14:15 +0000380 key_serial_t device_keyring = keyctl_search(KEY_SPEC_SESSION_KEYRING,
381 "keyring", "e4crypt", 0);
382
383 SLOGI("Found device_keyring - id is %d", device_keyring);
384
Paul Lawrence5e7f0042015-04-10 07:48:51 -0700385 // Add key ...
386 key_serial_t key_id = add_key("logon", ref.c_str(),
Paul Lawrence707fd6c2015-04-28 22:14:15 +0000387 (void*)&ext4_key, sizeof(ext4_key),
388 device_keyring);
389
390 if (key_id == -1) {
391 SLOGE("Failed to insert key into keyring with error %s",
392 strerror(errno));
Paul Crowley75a52022015-05-06 15:04:43 +0100393 return "";
Paul Lawrence707fd6c2015-04-28 22:14:15 +0000394 }
395
Paul Lawrence5e7f0042015-04-10 07:48:51 -0700396 SLOGI("Added key %d (%s) to keyring %d in process %d",
397 key_id, ref.c_str(), device_keyring, getpid());
Paul Lawrence707fd6c2015-04-28 22:14:15 +0000398
Paul Crowley1da96dc2015-05-06 13:38:53 +0100399 return raw_ref;
Paul Lawrence707fd6c2015-04-28 22:14:15 +0000400}
401
402int e4crypt_restart(const char* path)
403{
404 SLOGI("e4crypt_restart");
405
406 int rc = 0;
407
408 SLOGI("ext4 restart called on %s", path);
409 property_set("vold.decrypt", "trigger_reset_main");
410 SLOGI("Just asked init to shut down class main");
411 sleep(2);
412
413 std::string tmp_path = std::string() + path + "/tmp_mnt";
414
Paul Lawrence29b54aa2015-05-05 14:28:25 -0700415 rc = wait_and_unmount(tmp_path.c_str(), true);
Paul Lawrence707fd6c2015-04-28 22:14:15 +0000416 if (rc) {
417 SLOGE("umount %s failed with rc %d, msg %s",
418 tmp_path.c_str(), rc, strerror(errno));
419 return rc;
420 }
421
Paul Lawrence29b54aa2015-05-05 14:28:25 -0700422 rc = wait_and_unmount(path, true);
Paul Lawrence707fd6c2015-04-28 22:14:15 +0000423 if (rc) {
424 SLOGE("umount %s failed with rc %d, msg %s",
425 path, rc, strerror(errno));
426 return rc;
427 }
428
429 return 0;
430}
431
Paul Lawrence707fd6c2015-04-28 22:14:15 +0000432int e4crypt_get_password_type(const char* path)
433{
434 SLOGI("e4crypt_get_password_type");
435 return GetPropsOrAltProps(path).GetChild(properties::key)
436 .Get<int>(tag::crypt_type, CRYPT_TYPE_DEFAULT);
437}
Paul Lawrence4e727452015-04-15 14:12:00 -0700438
Paul Lawrence00f4aad2015-05-06 13:53:43 -0700439const char* e4crypt_get_password(const char* path)
440{
441 SLOGI("e4crypt_get_password");
442
443 auto i = s_key_store.find(path);
444 if (i == s_key_store.end()) {
445 return 0;
446 }
447
448 struct timespec now;
449 clock_gettime(CLOCK_BOOTTIME, &now);
450 if (i->second.expiry_time < now.tv_sec) {
451 e4crypt_clear_password(path);
452 return 0;
453 }
454
455 return i->second.password.c_str();
456}
457
458void e4crypt_clear_password(const char* path)
459{
460 SLOGI("e4crypt_clear_password");
461
462 auto i = s_key_store.find(path);
463 if (i == s_key_store.end()) {
464 return;
465 }
466
467 memset(&i->second.password[0], 0, i->second.password.size());
468 i->second.password = std::string();
469}
470
Paul Lawrence4e727452015-04-15 14:12:00 -0700471int e4crypt_get_field(const char* path, const char* fieldname,
472 char* value, size_t len)
473{
474 auto v = GetPropsOrAltProps(path).GetChild(properties::props)
475 .Get<std::string>(fieldname);
476
477 if (v == "") {
478 return CRYPTO_GETFIELD_ERROR_NO_FIELD;
479 }
480
481 if (v.length() >= len) {
482 return CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
483 }
484
485 strlcpy(value, v.c_str(), len);
486 return 0;
487}
488
489int e4crypt_set_field(const char* path, const char* fieldname,
490 const char* value)
491{
492 return GetPropsOrAltProps(path).GetChild(properties::props)
493 .Set(fieldname, std::string(value)) ? 0 : -1;
494}
Paul Crowley75a52022015-05-06 15:04:43 +0100495
496// ext4enc:TODO this can't be the only place keys are read from /dev/urandom
497// we should unite those places.
498static std::string e4crypt_get_user_key(
499 const char *mount_path,
500 const char *user_handle,
501 bool create_if_absent)
502{
503 // ext4enc:TODO get the path properly
504 auto key_dir = android::base::StringPrintf("%s/misc/vold/user_keys",
505 mount_path);
506 if (mkdir(key_dir.c_str(), 0700) < 0 && errno != EEXIST) {
507 SLOGE("Unable to create %s (%s)", key_dir.c_str(), strerror(errno));
508 return "";
509 }
510 auto key_path = key_dir + "/" + user_handle;
511 std::string content;
512 if (android::base::ReadFileToString(key_path, &content)) {
513 if (content.size() != key_length/8) {
514 SLOGE("Wrong size key %zu in %s", content.size(), key_path.c_str());
515 return "";
516 }
517 return content;
518 }
519 if (!create_if_absent) {
520 SLOGE("No key found in %s", key_path.c_str());
521 return "";
522 }
523 std::ifstream urandom("/dev/urandom");
524 if (!urandom) {
525 SLOGE("Unable to open /dev/urandom (%s)", strerror(errno));
526 return "";
527 }
528 char key_bytes[key_length / 8];
529 errno = 0;
530 urandom.read(key_bytes, sizeof(key_bytes));
531 if (!urandom) {
532 SLOGE("Unable to read key from /dev/urandom (%s)", strerror(errno));
533 return "";
534 }
535 std::string user_key(key_bytes, sizeof(key_bytes));
536 if (!android::base::WriteStringToFile(user_key, key_path)) {
537 SLOGE("Unable to write key to %s (%s)",
538 key_path.c_str(), strerror(errno));
539 return "";
540 }
541 return user_key;
542}
543
544static int e4crypt_set_user_policy(const char *mount_path, const char *user_handle,
545 const char *path, bool create_if_absent)
546{
547 SLOGD("e4crypt_set_user_policy for %s", user_handle);
548 auto user_key = e4crypt_get_user_key(mount_path, user_handle,
549 create_if_absent);
550 if (user_key.empty()) {
551 return -1;
552 }
553 auto raw_ref = e4crypt_install_key(user_key);
554 if (raw_ref.empty()) {
555 return -1;
556 }
557 return do_policy_set(path, raw_ref.c_str(), raw_ref.size());
558}
559
560int e4crypt_create_new_user_dir(const char *user_handle, const char *path) {
561 SLOGD("e4crypt_create_new_user_dir(\"%s\", \"%s\")", user_handle, path);
562 if (mkdir(path, S_IRWXU | S_IRWXG | S_IXOTH) < 0) {
563 return -1;
564 }
565 if (chmod(path, S_IRWXU | S_IRWXG | S_IXOTH) < 0) {
566 return -1;
567 }
568 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
569 // ext4enc:TODO handle errors from this.
570 e4crypt_set_user_policy(DATA_MNT_POINT, user_handle, path, true);
571 }
572 return 0;
573}
574
575static bool is_numeric(const char *name) {
576 for (const char *p = name; *p != '\0'; p++) {
577 if (!isdigit(*p))
578 return false;
579 }
580 return true;
581}
582
583int e4crypt_set_user_crypto_policies(const char *dir)
584{
585 if (e4crypt_crypto_complete(DATA_MNT_POINT) != 0) {
586 return 0;
587 }
588 SLOGD("e4crypt_set_user_crypto_policies");
589 std::unique_ptr<DIR, int(*)(DIR*)> dirp(opendir(dir), closedir);
590 if (!dirp) {
591 SLOGE("Unable to read directory %s, error %s\n",
592 dir, strerror(errno));
593 return -1;
594 }
595 for (;;) {
596 struct dirent *result = readdir(dirp.get());
597 if (!result) {
598 // ext4enc:TODO check errno
599 break;
600 }
601 if (result->d_type != DT_DIR || !is_numeric(result->d_name)) {
602 continue; // skips user 0, which is a symlink
603 }
604 auto user_dir = std::string() + dir + "/" + result->d_name;
605 // ext4enc:TODO don't hardcode /data
606 if (e4crypt_set_user_policy("/data", result->d_name,
607 user_dir.c_str(), false)) {
608 // ext4enc:TODO If this function fails, stop the boot: we must
609 // deliver on promised encryption.
610 SLOGE("Unable to set policy on %s\n", user_dir.c_str());
611 }
612 }
613 return 0;
614}