FsCrypt.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848
  1. /*
  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. #include "FsCrypt.h"
  17. #include "KeyStorage.h"
  18. #include "KeyUtil.h"
  19. #include "Utils.h"
  20. #include "VoldUtil.h"
  21. #include <algorithm>
  22. #include <map>
  23. #include <set>
  24. #include <sstream>
  25. #include <string>
  26. #include <vector>
  27. #include <dirent.h>
  28. #include <errno.h>
  29. #include <fcntl.h>
  30. #include <limits.h>
  31. #include <selinux/android.h>
  32. #include <sys/mount.h>
  33. #include <sys/stat.h>
  34. #include <sys/types.h>
  35. #include <unistd.h>
  36. #include <private/android_filesystem_config.h>
  37. #include "android/os/IVold.h"
  38. #include "cryptfs.h"
  39. #define EMULATED_USES_SELINUX 0
  40. #define MANAGE_MISC_DIRS 0
  41. #include <cutils/fs.h>
  42. #include <cutils/properties.h>
  43. #include <fscrypt/fscrypt.h>
  44. #include <keyutils.h>
  45. #include <android-base/file.h>
  46. #include <android-base/logging.h>
  47. #include <android-base/properties.h>
  48. #include <android-base/stringprintf.h>
  49. #include <android-base/unique_fd.h>
  50. using android::base::StringPrintf;
  51. using android::fs_mgr::GetEntryForMountPoint;
  52. using android::vold::kEmptyAuthentication;
  53. using android::vold::KeyBuffer;
  54. using android::vold::writeStringToFile;
  55. namespace {
  56. struct PolicyKeyRef {
  57. std::string contents_mode;
  58. std::string filenames_mode;
  59. std::string key_raw_ref;
  60. };
  61. const std::string device_key_dir = std::string() + DATA_MNT_POINT + fscrypt_unencrypted_folder;
  62. const std::string device_key_path = device_key_dir + "/key";
  63. const std::string device_key_temp = device_key_dir + "/temp";
  64. const std::string user_key_dir = std::string() + DATA_MNT_POINT + "/misc/vold/user_keys";
  65. const std::string user_key_temp = user_key_dir + "/temp";
  66. const std::string prepare_subdirs_path = "/system/bin/vold_prepare_subdirs";
  67. const std::string systemwide_volume_key_dir =
  68. std::string() + DATA_MNT_POINT + "/misc/vold/volume_keys";
  69. bool s_systemwide_keys_initialized = false;
  70. // Some users are ephemeral, don't try to wipe their keys from disk
  71. std::set<userid_t> s_ephemeral_users;
  72. // Map user ids to key references
  73. std::map<userid_t, std::string> s_de_key_raw_refs;
  74. std::map<userid_t, std::string> s_ce_key_raw_refs;
  75. // TODO abolish this map, per b/26948053
  76. std::map<userid_t, KeyBuffer> s_ce_keys;
  77. } // namespace
  78. static bool fscrypt_is_emulated() {
  79. return property_get_bool("persist.sys.emulate_fbe", false);
  80. }
  81. static const char* escape_empty(const std::string& value) {
  82. return value.empty() ? "null" : value.c_str();
  83. }
  84. static std::string get_de_key_path(userid_t user_id) {
  85. return StringPrintf("%s/de/%d", user_key_dir.c_str(), user_id);
  86. }
  87. static std::string get_ce_key_directory_path(userid_t user_id) {
  88. return StringPrintf("%s/ce/%d", user_key_dir.c_str(), user_id);
  89. }
  90. // Returns the keys newest first
  91. static std::vector<std::string> get_ce_key_paths(const std::string& directory_path) {
  92. auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(directory_path.c_str()), closedir);
  93. if (!dirp) {
  94. PLOG(ERROR) << "Unable to open ce key directory: " + directory_path;
  95. return std::vector<std::string>();
  96. }
  97. std::vector<std::string> result;
  98. for (;;) {
  99. errno = 0;
  100. auto const entry = readdir(dirp.get());
  101. if (!entry) {
  102. if (errno) {
  103. PLOG(ERROR) << "Unable to read ce key directory: " + directory_path;
  104. return std::vector<std::string>();
  105. }
  106. break;
  107. }
  108. if (entry->d_type != DT_DIR || entry->d_name[0] != 'c') {
  109. LOG(DEBUG) << "Skipping non-key " << entry->d_name;
  110. continue;
  111. }
  112. result.emplace_back(directory_path + "/" + entry->d_name);
  113. }
  114. std::sort(result.begin(), result.end());
  115. std::reverse(result.begin(), result.end());
  116. return result;
  117. }
  118. static std::string get_ce_key_current_path(const std::string& directory_path) {
  119. return directory_path + "/current";
  120. }
  121. static bool get_ce_key_new_path(const std::string& directory_path,
  122. const std::vector<std::string>& paths, std::string* ce_key_path) {
  123. if (paths.empty()) {
  124. *ce_key_path = get_ce_key_current_path(directory_path);
  125. return true;
  126. }
  127. for (unsigned int i = 0; i < UINT_MAX; i++) {
  128. auto const candidate = StringPrintf("%s/cx%010u", directory_path.c_str(), i);
  129. if (paths[0] < candidate) {
  130. *ce_key_path = candidate;
  131. return true;
  132. }
  133. }
  134. return false;
  135. }
  136. // Discard all keys but the named one; rename it to canonical name.
  137. // No point in acting on errors in this; ignore them.
  138. static void fixate_user_ce_key(const std::string& directory_path, const std::string& to_fix,
  139. const std::vector<std::string>& paths) {
  140. for (auto const other_path : paths) {
  141. if (other_path != to_fix) {
  142. android::vold::destroyKey(other_path);
  143. }
  144. }
  145. auto const current_path = get_ce_key_current_path(directory_path);
  146. if (to_fix != current_path) {
  147. LOG(DEBUG) << "Renaming " << to_fix << " to " << current_path;
  148. if (rename(to_fix.c_str(), current_path.c_str()) != 0) {
  149. PLOG(WARNING) << "Unable to rename " << to_fix << " to " << current_path;
  150. return;
  151. }
  152. }
  153. android::vold::FsyncDirectory(directory_path);
  154. }
  155. static bool read_and_fixate_user_ce_key(userid_t user_id,
  156. const android::vold::KeyAuthentication& auth,
  157. KeyBuffer* ce_key) {
  158. auto const directory_path = get_ce_key_directory_path(user_id);
  159. auto const paths = get_ce_key_paths(directory_path);
  160. for (auto const ce_key_path : paths) {
  161. LOG(DEBUG) << "Trying user CE key " << ce_key_path;
  162. if (android::vold::retrieveKey(ce_key_path, auth, ce_key)) {
  163. LOG(DEBUG) << "Successfully retrieved key";
  164. fixate_user_ce_key(directory_path, ce_key_path, paths);
  165. return true;
  166. }
  167. }
  168. LOG(ERROR) << "Failed to find working ce key for user " << user_id;
  169. return false;
  170. }
  171. static bool read_and_install_user_ce_key(userid_t user_id,
  172. const android::vold::KeyAuthentication& auth) {
  173. if (s_ce_key_raw_refs.count(user_id) != 0) return true;
  174. KeyBuffer ce_key;
  175. if (!read_and_fixate_user_ce_key(user_id, auth, &ce_key)) return false;
  176. std::string ce_raw_ref;
  177. if (!android::vold::installKey(ce_key, &ce_raw_ref)) return false;
  178. s_ce_keys[user_id] = std::move(ce_key);
  179. s_ce_key_raw_refs[user_id] = ce_raw_ref;
  180. LOG(DEBUG) << "Installed ce key for user " << user_id;
  181. return true;
  182. }
  183. static bool prepare_dir(const std::string& dir, mode_t mode, uid_t uid, gid_t gid) {
  184. LOG(DEBUG) << "Preparing: " << dir;
  185. if (fs_prepare_dir(dir.c_str(), mode, uid, gid) != 0) {
  186. PLOG(ERROR) << "Failed to prepare " << dir;
  187. return false;
  188. }
  189. return true;
  190. }
  191. static bool destroy_dir(const std::string& dir) {
  192. LOG(DEBUG) << "Destroying: " << dir;
  193. if (rmdir(dir.c_str()) != 0 && errno != ENOENT) {
  194. PLOG(ERROR) << "Failed to destroy " << dir;
  195. return false;
  196. }
  197. return true;
  198. }
  199. // NB this assumes that there is only one thread listening for crypt commands, because
  200. // it creates keys in a fixed location.
  201. static bool create_and_install_user_keys(userid_t user_id, bool create_ephemeral) {
  202. KeyBuffer de_key, ce_key;
  203. if (!android::vold::randomKey(&de_key)) return false;
  204. if (!android::vold::randomKey(&ce_key)) return false;
  205. if (create_ephemeral) {
  206. // If the key should be created as ephemeral, don't store it.
  207. s_ephemeral_users.insert(user_id);
  208. } else {
  209. auto const directory_path = get_ce_key_directory_path(user_id);
  210. if (!prepare_dir(directory_path, 0700, AID_ROOT, AID_ROOT)) return false;
  211. auto const paths = get_ce_key_paths(directory_path);
  212. std::string ce_key_path;
  213. if (!get_ce_key_new_path(directory_path, paths, &ce_key_path)) return false;
  214. if (!android::vold::storeKeyAtomically(ce_key_path, user_key_temp, kEmptyAuthentication,
  215. ce_key))
  216. return false;
  217. fixate_user_ce_key(directory_path, ce_key_path, paths);
  218. // Write DE key second; once this is written, all is good.
  219. if (!android::vold::storeKeyAtomically(get_de_key_path(user_id), user_key_temp,
  220. kEmptyAuthentication, de_key))
  221. return false;
  222. }
  223. std::string de_raw_ref;
  224. if (!android::vold::installKey(de_key, &de_raw_ref)) return false;
  225. s_de_key_raw_refs[user_id] = de_raw_ref;
  226. std::string ce_raw_ref;
  227. if (!android::vold::installKey(ce_key, &ce_raw_ref)) return false;
  228. s_ce_keys[user_id] = ce_key;
  229. s_ce_key_raw_refs[user_id] = ce_raw_ref;
  230. LOG(DEBUG) << "Created keys for user " << user_id;
  231. return true;
  232. }
  233. static bool lookup_key_ref(const std::map<userid_t, std::string>& key_map, userid_t user_id,
  234. std::string* raw_ref) {
  235. auto refi = key_map.find(user_id);
  236. if (refi == key_map.end()) {
  237. LOG(DEBUG) << "Cannot find key for " << user_id;
  238. return false;
  239. }
  240. *raw_ref = refi->second;
  241. return true;
  242. }
  243. static void get_data_file_encryption_modes(PolicyKeyRef* key_ref) {
  244. auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
  245. if (entry == nullptr) {
  246. return;
  247. }
  248. key_ref->contents_mode = entry->file_contents_mode;
  249. key_ref->filenames_mode = entry->file_names_mode;
  250. }
  251. static bool ensure_policy(const PolicyKeyRef& key_ref, const std::string& path) {
  252. return fscrypt_policy_ensure(path.c_str(), key_ref.key_raw_ref.data(),
  253. key_ref.key_raw_ref.size(), key_ref.contents_mode.c_str(),
  254. key_ref.filenames_mode.c_str()) == 0;
  255. }
  256. static bool is_numeric(const char* name) {
  257. for (const char* p = name; *p != '\0'; p++) {
  258. if (!isdigit(*p)) return false;
  259. }
  260. return true;
  261. }
  262. static bool load_all_de_keys() {
  263. auto de_dir = user_key_dir + "/de";
  264. auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(de_dir.c_str()), closedir);
  265. if (!dirp) {
  266. PLOG(ERROR) << "Unable to read de key directory";
  267. return false;
  268. }
  269. for (;;) {
  270. errno = 0;
  271. auto entry = readdir(dirp.get());
  272. if (!entry) {
  273. if (errno) {
  274. PLOG(ERROR) << "Unable to read de key directory";
  275. return false;
  276. }
  277. break;
  278. }
  279. if (entry->d_type != DT_DIR || !is_numeric(entry->d_name)) {
  280. LOG(DEBUG) << "Skipping non-de-key " << entry->d_name;
  281. continue;
  282. }
  283. userid_t user_id = std::stoi(entry->d_name);
  284. if (s_de_key_raw_refs.count(user_id) == 0) {
  285. auto key_path = de_dir + "/" + entry->d_name;
  286. KeyBuffer key;
  287. if (!android::vold::retrieveKey(key_path, kEmptyAuthentication, &key)) return false;
  288. std::string raw_ref;
  289. if (!android::vold::installKey(key, &raw_ref)) return false;
  290. s_de_key_raw_refs[user_id] = raw_ref;
  291. LOG(DEBUG) << "Installed de key for user " << user_id;
  292. }
  293. }
  294. // fscrypt:TODO: go through all DE directories, ensure that all user dirs have the
  295. // correct policy set on them, and that no rogue ones exist.
  296. return true;
  297. }
  298. bool fscrypt_initialize_systemwide_keys() {
  299. LOG(INFO) << "fscrypt_initialize_systemwide_keys";
  300. if (s_systemwide_keys_initialized) {
  301. LOG(INFO) << "Already initialized";
  302. return true;
  303. }
  304. PolicyKeyRef device_ref;
  305. if (!android::vold::retrieveAndInstallKey(true, kEmptyAuthentication, device_key_path,
  306. device_key_temp, &device_ref.key_raw_ref))
  307. return false;
  308. get_data_file_encryption_modes(&device_ref);
  309. std::string modestring = device_ref.contents_mode + ":" + device_ref.filenames_mode;
  310. std::string mode_filename = std::string("/data") + fscrypt_key_mode;
  311. if (!android::vold::writeStringToFile(modestring, mode_filename)) return false;
  312. std::string ref_filename = std::string("/data") + fscrypt_key_ref;
  313. if (!android::vold::writeStringToFile(device_ref.key_raw_ref, ref_filename)) return false;
  314. LOG(INFO) << "Wrote system DE key reference to:" << ref_filename;
  315. KeyBuffer per_boot_key;
  316. if (!android::vold::randomKey(&per_boot_key)) return false;
  317. std::string per_boot_raw_ref;
  318. if (!android::vold::installKey(per_boot_key, &per_boot_raw_ref)) return false;
  319. std::string per_boot_ref_filename = std::string("/data") + fscrypt_key_per_boot_ref;
  320. if (!android::vold::writeStringToFile(per_boot_raw_ref, per_boot_ref_filename)) return false;
  321. LOG(INFO) << "Wrote per boot key reference to:" << per_boot_ref_filename;
  322. if (!android::vold::FsyncDirectory(device_key_dir)) return false;
  323. s_systemwide_keys_initialized = true;
  324. return true;
  325. }
  326. bool fscrypt_init_user0() {
  327. LOG(DEBUG) << "fscrypt_init_user0";
  328. if (fscrypt_is_native()) {
  329. if (!prepare_dir(user_key_dir, 0700, AID_ROOT, AID_ROOT)) return false;
  330. if (!prepare_dir(user_key_dir + "/ce", 0700, AID_ROOT, AID_ROOT)) return false;
  331. if (!prepare_dir(user_key_dir + "/de", 0700, AID_ROOT, AID_ROOT)) return false;
  332. if (!android::vold::pathExists(get_de_key_path(0))) {
  333. if (!create_and_install_user_keys(0, false)) return false;
  334. }
  335. // TODO: switch to loading only DE_0 here once framework makes
  336. // explicit calls to install DE keys for secondary users
  337. if (!load_all_de_keys()) return false;
  338. }
  339. // We can only safely prepare DE storage here, since CE keys are probably
  340. // entangled with user credentials. The framework will always prepare CE
  341. // storage once CE keys are installed.
  342. if (!fscrypt_prepare_user_storage("", 0, 0, android::os::IVold::STORAGE_FLAG_DE)) {
  343. LOG(ERROR) << "Failed to prepare user 0 storage";
  344. return false;
  345. }
  346. // If this is a non-FBE device that recently left an emulated mode,
  347. // restore user data directories to known-good state.
  348. if (!fscrypt_is_native() && !fscrypt_is_emulated()) {
  349. fscrypt_unlock_user_key(0, 0, "!", "!");
  350. }
  351. return true;
  352. }
  353. bool fscrypt_vold_create_user_key(userid_t user_id, int serial, bool ephemeral) {
  354. LOG(DEBUG) << "fscrypt_vold_create_user_key for " << user_id << " serial " << serial;
  355. if (!fscrypt_is_native()) {
  356. return true;
  357. }
  358. // FIXME test for existence of key that is not loaded yet
  359. if (s_ce_key_raw_refs.count(user_id) != 0) {
  360. LOG(ERROR) << "Already exists, can't fscrypt_vold_create_user_key for " << user_id
  361. << " serial " << serial;
  362. // FIXME should we fail the command?
  363. return true;
  364. }
  365. if (!create_and_install_user_keys(user_id, ephemeral)) {
  366. return false;
  367. }
  368. return true;
  369. }
  370. static void drop_caches() {
  371. // Clean any dirty pages (otherwise they won't be dropped).
  372. sync();
  373. // Drop inode and page caches.
  374. if (!writeStringToFile("3", "/proc/sys/vm/drop_caches")) {
  375. PLOG(ERROR) << "Failed to drop caches during key eviction";
  376. }
  377. }
  378. static bool evict_ce_key(userid_t user_id) {
  379. s_ce_keys.erase(user_id);
  380. bool success = true;
  381. std::string raw_ref;
  382. // If we haven't loaded the CE key, no need to evict it.
  383. if (lookup_key_ref(s_ce_key_raw_refs, user_id, &raw_ref)) {
  384. success &= android::vold::evictKey(raw_ref);
  385. drop_caches();
  386. }
  387. s_ce_key_raw_refs.erase(user_id);
  388. return success;
  389. }
  390. bool fscrypt_destroy_user_key(userid_t user_id) {
  391. LOG(DEBUG) << "fscrypt_destroy_user_key(" << user_id << ")";
  392. if (!fscrypt_is_native()) {
  393. return true;
  394. }
  395. bool success = true;
  396. std::string raw_ref;
  397. success &= evict_ce_key(user_id);
  398. success &=
  399. lookup_key_ref(s_de_key_raw_refs, user_id, &raw_ref) && android::vold::evictKey(raw_ref);
  400. s_de_key_raw_refs.erase(user_id);
  401. auto it = s_ephemeral_users.find(user_id);
  402. if (it != s_ephemeral_users.end()) {
  403. s_ephemeral_users.erase(it);
  404. } else {
  405. for (auto const path : get_ce_key_paths(get_ce_key_directory_path(user_id))) {
  406. success &= android::vold::destroyKey(path);
  407. }
  408. auto de_key_path = get_de_key_path(user_id);
  409. if (android::vold::pathExists(de_key_path)) {
  410. success &= android::vold::destroyKey(de_key_path);
  411. } else {
  412. LOG(INFO) << "Not present so not erasing: " << de_key_path;
  413. }
  414. }
  415. return success;
  416. }
  417. static bool emulated_lock(const std::string& path) {
  418. if (chmod(path.c_str(), 0000) != 0) {
  419. PLOG(ERROR) << "Failed to chmod " << path;
  420. return false;
  421. }
  422. #if EMULATED_USES_SELINUX
  423. if (setfilecon(path.c_str(), "u:object_r:storage_stub_file:s0") != 0) {
  424. PLOG(WARNING) << "Failed to setfilecon " << path;
  425. return false;
  426. }
  427. #endif
  428. return true;
  429. }
  430. static bool emulated_unlock(const std::string& path, mode_t mode) {
  431. if (chmod(path.c_str(), mode) != 0) {
  432. PLOG(ERROR) << "Failed to chmod " << path;
  433. // FIXME temporary workaround for b/26713622
  434. if (fscrypt_is_emulated()) return false;
  435. }
  436. #if EMULATED_USES_SELINUX
  437. if (selinux_android_restorecon(path.c_str(), SELINUX_ANDROID_RESTORECON_FORCE) != 0) {
  438. PLOG(WARNING) << "Failed to restorecon " << path;
  439. // FIXME temporary workaround for b/26713622
  440. if (fscrypt_is_emulated()) return false;
  441. }
  442. #endif
  443. return true;
  444. }
  445. static bool parse_hex(const std::string& hex, std::string* result) {
  446. if (hex == "!") {
  447. *result = "";
  448. return true;
  449. }
  450. if (android::vold::HexToStr(hex, *result) != 0) {
  451. LOG(ERROR) << "Invalid FBE hex string"; // Don't log the string for security reasons
  452. return false;
  453. }
  454. return true;
  455. }
  456. static std::string volkey_path(const std::string& misc_path, const std::string& volume_uuid) {
  457. return misc_path + "/vold/volume_keys/" + volume_uuid + "/default";
  458. }
  459. static std::string volume_secdiscardable_path(const std::string& volume_uuid) {
  460. return systemwide_volume_key_dir + "/" + volume_uuid + "/secdiscardable";
  461. }
  462. static bool read_or_create_volkey(const std::string& misc_path, const std::string& volume_uuid,
  463. PolicyKeyRef* key_ref) {
  464. auto secdiscardable_path = volume_secdiscardable_path(volume_uuid);
  465. std::string secdiscardable_hash;
  466. if (android::vold::pathExists(secdiscardable_path)) {
  467. if (!android::vold::readSecdiscardable(secdiscardable_path, &secdiscardable_hash))
  468. return false;
  469. } else {
  470. if (fs_mkdirs(secdiscardable_path.c_str(), 0700) != 0) {
  471. PLOG(ERROR) << "Creating directories for: " << secdiscardable_path;
  472. return false;
  473. }
  474. if (!android::vold::createSecdiscardable(secdiscardable_path, &secdiscardable_hash))
  475. return false;
  476. }
  477. auto key_path = volkey_path(misc_path, volume_uuid);
  478. if (fs_mkdirs(key_path.c_str(), 0700) != 0) {
  479. PLOG(ERROR) << "Creating directories for: " << key_path;
  480. return false;
  481. }
  482. android::vold::KeyAuthentication auth("", secdiscardable_hash);
  483. if (!android::vold::retrieveAndInstallKey(true, auth, key_path, key_path + "_tmp",
  484. &key_ref->key_raw_ref))
  485. return false;
  486. key_ref->contents_mode =
  487. android::base::GetProperty("ro.crypto.volume.contents_mode", "aes-256-xts");
  488. key_ref->filenames_mode =
  489. android::base::GetProperty("ro.crypto.volume.filenames_mode", "aes-256-heh");
  490. return true;
  491. }
  492. static bool destroy_volkey(const std::string& misc_path, const std::string& volume_uuid) {
  493. auto path = volkey_path(misc_path, volume_uuid);
  494. if (!android::vold::pathExists(path)) return true;
  495. return android::vold::destroyKey(path);
  496. }
  497. bool fscrypt_add_user_key_auth(userid_t user_id, int serial, const std::string& token_hex,
  498. const std::string& secret_hex) {
  499. LOG(DEBUG) << "fscrypt_add_user_key_auth " << user_id << " serial=" << serial
  500. << " token_present=" << (token_hex != "!");
  501. if (!fscrypt_is_native()) return true;
  502. if (s_ephemeral_users.count(user_id) != 0) return true;
  503. std::string token, secret;
  504. if (!parse_hex(token_hex, &token)) return false;
  505. if (!parse_hex(secret_hex, &secret)) return false;
  506. auto auth =
  507. secret.empty() ? kEmptyAuthentication : android::vold::KeyAuthentication(token, secret);
  508. auto it = s_ce_keys.find(user_id);
  509. if (it == s_ce_keys.end()) {
  510. LOG(ERROR) << "Key not loaded into memory, can't change for user " << user_id;
  511. return false;
  512. }
  513. const auto& ce_key = it->second;
  514. auto const directory_path = get_ce_key_directory_path(user_id);
  515. auto const paths = get_ce_key_paths(directory_path);
  516. std::string ce_key_path;
  517. if (!get_ce_key_new_path(directory_path, paths, &ce_key_path)) return false;
  518. if (!android::vold::storeKeyAtomically(ce_key_path, user_key_temp, auth, ce_key)) return false;
  519. if (!android::vold::FsyncDirectory(directory_path)) return false;
  520. return true;
  521. }
  522. bool fscrypt_fixate_newest_user_key_auth(userid_t user_id) {
  523. LOG(DEBUG) << "fscrypt_fixate_newest_user_key_auth " << user_id;
  524. if (!fscrypt_is_native()) return true;
  525. if (s_ephemeral_users.count(user_id) != 0) return true;
  526. auto const directory_path = get_ce_key_directory_path(user_id);
  527. auto const paths = get_ce_key_paths(directory_path);
  528. if (paths.empty()) {
  529. LOG(ERROR) << "No ce keys present, cannot fixate for user " << user_id;
  530. return false;
  531. }
  532. fixate_user_ce_key(directory_path, paths[0], paths);
  533. return true;
  534. }
  535. // TODO: rename to 'install' for consistency, and take flags to know which keys to install
  536. bool fscrypt_unlock_user_key(userid_t user_id, int serial, const std::string& token_hex,
  537. const std::string& secret_hex) {
  538. LOG(DEBUG) << "fscrypt_unlock_user_key " << user_id << " serial=" << serial
  539. << " token_present=" << (token_hex != "!");
  540. if (fscrypt_is_native()) {
  541. if (s_ce_key_raw_refs.count(user_id) != 0) {
  542. LOG(WARNING) << "Tried to unlock already-unlocked key for user " << user_id;
  543. return true;
  544. }
  545. std::string token, secret;
  546. if (!parse_hex(token_hex, &token)) return false;
  547. if (!parse_hex(secret_hex, &secret)) return false;
  548. android::vold::KeyAuthentication auth(token, secret);
  549. if (!read_and_install_user_ce_key(user_id, auth)) {
  550. LOG(ERROR) << "Couldn't read key for " << user_id;
  551. return false;
  552. }
  553. } else {
  554. // When in emulation mode, we just use chmod. However, we also
  555. // unlock directories when not in emulation mode, to bring devices
  556. // back into a known-good state.
  557. if (!emulated_unlock(android::vold::BuildDataSystemCePath(user_id), 0771) ||
  558. !emulated_unlock(android::vold::BuildDataMiscCePath(user_id), 01771) ||
  559. !emulated_unlock(android::vold::BuildDataMediaCePath("", user_id), 0770) ||
  560. !emulated_unlock(android::vold::BuildDataUserCePath("", user_id), 0771)) {
  561. LOG(ERROR) << "Failed to unlock user " << user_id;
  562. return false;
  563. }
  564. }
  565. return true;
  566. }
  567. // TODO: rename to 'evict' for consistency
  568. bool fscrypt_lock_user_key(userid_t user_id) {
  569. LOG(DEBUG) << "fscrypt_lock_user_key " << user_id;
  570. if (fscrypt_is_native()) {
  571. return evict_ce_key(user_id);
  572. } else if (fscrypt_is_emulated()) {
  573. // When in emulation mode, we just use chmod
  574. if (!emulated_lock(android::vold::BuildDataSystemCePath(user_id)) ||
  575. !emulated_lock(android::vold::BuildDataMiscCePath(user_id)) ||
  576. !emulated_lock(android::vold::BuildDataMediaCePath("", user_id)) ||
  577. !emulated_lock(android::vold::BuildDataUserCePath("", user_id))) {
  578. LOG(ERROR) << "Failed to lock user " << user_id;
  579. return false;
  580. }
  581. }
  582. return true;
  583. }
  584. static bool prepare_subdirs(const std::string& action, const std::string& volume_uuid,
  585. userid_t user_id, int flags) {
  586. if (0 != android::vold::ForkExecvp(
  587. std::vector<std::string>{prepare_subdirs_path, action, volume_uuid,
  588. std::to_string(user_id), std::to_string(flags)})) {
  589. LOG(ERROR) << "vold_prepare_subdirs failed";
  590. return false;
  591. }
  592. return true;
  593. }
  594. bool fscrypt_prepare_user_storage(const std::string& volume_uuid, userid_t user_id, int serial,
  595. int flags) {
  596. LOG(DEBUG) << "fscrypt_prepare_user_storage for volume " << escape_empty(volume_uuid)
  597. << ", user " << user_id << ", serial " << serial << ", flags " << flags;
  598. if (flags & android::os::IVold::STORAGE_FLAG_DE) {
  599. // DE_sys key
  600. auto system_legacy_path = android::vold::BuildDataSystemLegacyPath(user_id);
  601. auto misc_legacy_path = android::vold::BuildDataMiscLegacyPath(user_id);
  602. auto profiles_de_path = android::vold::BuildDataProfilesDePath(user_id);
  603. // DE_n key
  604. auto system_de_path = android::vold::BuildDataSystemDePath(user_id);
  605. auto misc_de_path = android::vold::BuildDataMiscDePath(user_id);
  606. auto vendor_de_path = android::vold::BuildDataVendorDePath(user_id);
  607. auto user_de_path = android::vold::BuildDataUserDePath(volume_uuid, user_id);
  608. if (volume_uuid.empty()) {
  609. if (!prepare_dir(system_legacy_path, 0700, AID_SYSTEM, AID_SYSTEM)) return false;
  610. #if MANAGE_MISC_DIRS
  611. if (!prepare_dir(misc_legacy_path, 0750, multiuser_get_uid(user_id, AID_SYSTEM),
  612. multiuser_get_uid(user_id, AID_EVERYBODY)))
  613. return false;
  614. #endif
  615. if (!prepare_dir(profiles_de_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
  616. if (!prepare_dir(system_de_path, 0770, AID_SYSTEM, AID_SYSTEM)) return false;
  617. if (!prepare_dir(misc_de_path, 01771, AID_SYSTEM, AID_MISC)) return false;
  618. if (!prepare_dir(vendor_de_path, 0771, AID_ROOT, AID_ROOT)) return false;
  619. }
  620. if (!prepare_dir(user_de_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
  621. if (fscrypt_is_native()) {
  622. PolicyKeyRef de_ref;
  623. if (volume_uuid.empty()) {
  624. if (!lookup_key_ref(s_de_key_raw_refs, user_id, &de_ref.key_raw_ref)) return false;
  625. get_data_file_encryption_modes(&de_ref);
  626. if (!ensure_policy(de_ref, system_de_path)) return false;
  627. if (!ensure_policy(de_ref, misc_de_path)) return false;
  628. if (!ensure_policy(de_ref, vendor_de_path)) return false;
  629. } else {
  630. if (!read_or_create_volkey(misc_de_path, volume_uuid, &de_ref)) return false;
  631. }
  632. if (!ensure_policy(de_ref, user_de_path)) return false;
  633. }
  634. }
  635. if (flags & android::os::IVold::STORAGE_FLAG_CE) {
  636. // CE_n key
  637. auto system_ce_path = android::vold::BuildDataSystemCePath(user_id);
  638. auto misc_ce_path = android::vold::BuildDataMiscCePath(user_id);
  639. auto vendor_ce_path = android::vold::BuildDataVendorCePath(user_id);
  640. auto media_ce_path = android::vold::BuildDataMediaCePath(volume_uuid, user_id);
  641. auto user_ce_path = android::vold::BuildDataUserCePath(volume_uuid, user_id);
  642. if (volume_uuid.empty()) {
  643. if (!prepare_dir(system_ce_path, 0770, AID_SYSTEM, AID_SYSTEM)) return false;
  644. if (!prepare_dir(misc_ce_path, 01771, AID_SYSTEM, AID_MISC)) return false;
  645. if (!prepare_dir(vendor_ce_path, 0771, AID_ROOT, AID_ROOT)) return false;
  646. }
  647. if (!prepare_dir(media_ce_path, 0770, AID_MEDIA_RW, AID_MEDIA_RW)) return false;
  648. if (!prepare_dir(user_ce_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
  649. if (fscrypt_is_native()) {
  650. PolicyKeyRef ce_ref;
  651. if (volume_uuid.empty()) {
  652. if (!lookup_key_ref(s_ce_key_raw_refs, user_id, &ce_ref.key_raw_ref)) return false;
  653. get_data_file_encryption_modes(&ce_ref);
  654. if (!ensure_policy(ce_ref, system_ce_path)) return false;
  655. if (!ensure_policy(ce_ref, misc_ce_path)) return false;
  656. if (!ensure_policy(ce_ref, vendor_ce_path)) return false;
  657. } else {
  658. if (!read_or_create_volkey(misc_ce_path, volume_uuid, &ce_ref)) return false;
  659. }
  660. if (!ensure_policy(ce_ref, media_ce_path)) return false;
  661. if (!ensure_policy(ce_ref, user_ce_path)) return false;
  662. }
  663. if (volume_uuid.empty()) {
  664. // Now that credentials have been installed, we can run restorecon
  665. // over these paths
  666. // NOTE: these paths need to be kept in sync with libselinux
  667. android::vold::RestoreconRecursive(system_ce_path);
  668. android::vold::RestoreconRecursive(vendor_ce_path);
  669. android::vold::RestoreconRecursive(misc_ce_path);
  670. }
  671. }
  672. if (!prepare_subdirs("prepare", volume_uuid, user_id, flags)) return false;
  673. return true;
  674. }
  675. bool fscrypt_destroy_user_storage(const std::string& volume_uuid, userid_t user_id, int flags) {
  676. LOG(DEBUG) << "fscrypt_destroy_user_storage for volume " << escape_empty(volume_uuid)
  677. << ", user " << user_id << ", flags " << flags;
  678. bool res = true;
  679. res &= prepare_subdirs("destroy", volume_uuid, user_id, flags);
  680. if (flags & android::os::IVold::STORAGE_FLAG_CE) {
  681. // CE_n key
  682. auto system_ce_path = android::vold::BuildDataSystemCePath(user_id);
  683. auto misc_ce_path = android::vold::BuildDataMiscCePath(user_id);
  684. auto vendor_ce_path = android::vold::BuildDataVendorCePath(user_id);
  685. auto media_ce_path = android::vold::BuildDataMediaCePath(volume_uuid, user_id);
  686. auto user_ce_path = android::vold::BuildDataUserCePath(volume_uuid, user_id);
  687. res &= destroy_dir(media_ce_path);
  688. res &= destroy_dir(user_ce_path);
  689. if (volume_uuid.empty()) {
  690. res &= destroy_dir(system_ce_path);
  691. res &= destroy_dir(misc_ce_path);
  692. res &= destroy_dir(vendor_ce_path);
  693. } else {
  694. if (fscrypt_is_native()) {
  695. res &= destroy_volkey(misc_ce_path, volume_uuid);
  696. }
  697. }
  698. }
  699. if (flags & android::os::IVold::STORAGE_FLAG_DE) {
  700. // DE_sys key
  701. auto system_legacy_path = android::vold::BuildDataSystemLegacyPath(user_id);
  702. auto misc_legacy_path = android::vold::BuildDataMiscLegacyPath(user_id);
  703. auto profiles_de_path = android::vold::BuildDataProfilesDePath(user_id);
  704. // DE_n key
  705. auto system_de_path = android::vold::BuildDataSystemDePath(user_id);
  706. auto misc_de_path = android::vold::BuildDataMiscDePath(user_id);
  707. auto vendor_de_path = android::vold::BuildDataVendorDePath(user_id);
  708. auto user_de_path = android::vold::BuildDataUserDePath(volume_uuid, user_id);
  709. res &= destroy_dir(user_de_path);
  710. if (volume_uuid.empty()) {
  711. res &= destroy_dir(system_legacy_path);
  712. #if MANAGE_MISC_DIRS
  713. res &= destroy_dir(misc_legacy_path);
  714. #endif
  715. res &= destroy_dir(profiles_de_path);
  716. res &= destroy_dir(system_de_path);
  717. res &= destroy_dir(misc_de_path);
  718. res &= destroy_dir(vendor_de_path);
  719. } else {
  720. if (fscrypt_is_native()) {
  721. res &= destroy_volkey(misc_de_path, volume_uuid);
  722. }
  723. }
  724. }
  725. return res;
  726. }
  727. static bool destroy_volume_keys(const std::string& directory_path, const std::string& volume_uuid) {
  728. auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(directory_path.c_str()), closedir);
  729. if (!dirp) {
  730. PLOG(ERROR) << "Unable to open directory: " + directory_path;
  731. return false;
  732. }
  733. bool res = true;
  734. for (;;) {
  735. errno = 0;
  736. auto const entry = readdir(dirp.get());
  737. if (!entry) {
  738. if (errno) {
  739. PLOG(ERROR) << "Unable to read directory: " + directory_path;
  740. return false;
  741. }
  742. break;
  743. }
  744. if (entry->d_type != DT_DIR || entry->d_name[0] == '.') {
  745. LOG(DEBUG) << "Skipping non-user " << entry->d_name;
  746. continue;
  747. }
  748. res &= destroy_volkey(directory_path + "/" + entry->d_name, volume_uuid);
  749. }
  750. return res;
  751. }
  752. bool fscrypt_destroy_volume_keys(const std::string& volume_uuid) {
  753. bool res = true;
  754. LOG(DEBUG) << "fscrypt_destroy_volume_keys for volume " << escape_empty(volume_uuid);
  755. auto secdiscardable_path = volume_secdiscardable_path(volume_uuid);
  756. res &= android::vold::runSecdiscardSingle(secdiscardable_path);
  757. res &= destroy_volume_keys("/data/misc_ce", volume_uuid);
  758. res &= destroy_volume_keys("/data/misc_de", volume_uuid);
  759. return res;
  760. }