MetadataCrypt.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. /*
  2. * Copyright (C) 2016 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 "MetadataCrypt.h"
  17. #include "KeyBuffer.h"
  18. #include <algorithm>
  19. #include <string>
  20. #include <thread>
  21. #include <vector>
  22. #include <fcntl.h>
  23. #include <sys/ioctl.h>
  24. #include <sys/param.h>
  25. #include <sys/stat.h>
  26. #include <sys/types.h>
  27. #include <linux/dm-ioctl.h>
  28. #include <android-base/file.h>
  29. #include <android-base/logging.h>
  30. #include <android-base/properties.h>
  31. #include <android-base/unique_fd.h>
  32. #include <cutils/fs.h>
  33. #include <fs_mgr.h>
  34. #include "Checkpoint.h"
  35. #include "EncryptInplace.h"
  36. #include "KeyStorage.h"
  37. #include "KeyUtil.h"
  38. #include "Keymaster.h"
  39. #include "Utils.h"
  40. #include "VoldUtil.h"
  41. #define DM_CRYPT_BUF_SIZE 4096
  42. #define TABLE_LOAD_RETRIES 10
  43. #define DEFAULT_KEY_TARGET_TYPE "default-key"
  44. using android::fs_mgr::FstabEntry;
  45. using android::fs_mgr::GetEntryForMountPoint;
  46. using android::vold::KeyBuffer;
  47. static const std::string kDmNameUserdata = "userdata";
  48. static const char* kFn_keymaster_key_blob = "keymaster_key_blob";
  49. static const char* kFn_keymaster_key_blob_upgraded = "keymaster_key_blob_upgraded";
  50. static bool mount_via_fs_mgr(const char* mount_point, const char* blk_device) {
  51. // fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
  52. // partitions in the fsck domain.
  53. if (setexeccon(android::vold::sFsckContext)) {
  54. PLOG(ERROR) << "Failed to setexeccon";
  55. return false;
  56. }
  57. auto mount_rc = fs_mgr_do_mount(&fstab_default, const_cast<char*>(mount_point),
  58. const_cast<char*>(blk_device), nullptr,
  59. android::vold::cp_needsCheckpoint());
  60. if (setexeccon(nullptr)) {
  61. PLOG(ERROR) << "Failed to clear setexeccon";
  62. return false;
  63. }
  64. if (mount_rc != 0) {
  65. LOG(ERROR) << "fs_mgr_do_mount failed with rc " << mount_rc;
  66. return false;
  67. }
  68. LOG(DEBUG) << "Mounted " << mount_point;
  69. return true;
  70. }
  71. namespace android {
  72. namespace vold {
  73. // Note: It is possible to orphan a key if it is removed before deleting
  74. // Update this once keymaster APIs change, and we have a proper commit.
  75. static void commit_key(const std::string& dir) {
  76. while (!android::base::WaitForProperty("vold.checkpoint_committed", "1")) {
  77. LOG(ERROR) << "Wait for boot timed out";
  78. }
  79. Keymaster keymaster;
  80. auto keyPath = dir + "/" + kFn_keymaster_key_blob;
  81. auto newKeyPath = dir + "/" + kFn_keymaster_key_blob_upgraded;
  82. std::string key;
  83. if (!android::base::ReadFileToString(keyPath, &key)) {
  84. LOG(ERROR) << "Failed to read old key: " << dir;
  85. return;
  86. }
  87. if (rename(newKeyPath.c_str(), keyPath.c_str()) != 0) {
  88. PLOG(ERROR) << "Unable to move upgraded key to location: " << keyPath;
  89. return;
  90. }
  91. if (!keymaster.deleteKey(key)) {
  92. LOG(ERROR) << "Key deletion failed during upgrade, continuing anyway: " << dir;
  93. }
  94. LOG(INFO) << "Old Key deleted: " << dir;
  95. }
  96. static bool read_key(const FstabEntry& data_rec, bool create_if_absent, KeyBuffer* key) {
  97. if (data_rec.key_dir.empty()) {
  98. LOG(ERROR) << "Failed to get key_dir";
  99. return false;
  100. }
  101. std::string key_dir = data_rec.key_dir;
  102. std::string sKey;
  103. auto dir = key_dir + "/key";
  104. LOG(DEBUG) << "key_dir/key: " << dir;
  105. if (fs_mkdirs(dir.c_str(), 0700)) {
  106. PLOG(ERROR) << "Creating directories: " << dir;
  107. return false;
  108. }
  109. auto temp = key_dir + "/tmp";
  110. auto newKeyPath = dir + "/" + kFn_keymaster_key_blob_upgraded;
  111. /* If we have a leftover upgraded key, delete it.
  112. * We either failed an update and must return to the old key,
  113. * or we rebooted before commiting the keys in a freak accident.
  114. * Either way, we can re-upgrade the key if we need to.
  115. */
  116. Keymaster keymaster;
  117. if (pathExists(newKeyPath)) {
  118. if (!android::base::ReadFileToString(newKeyPath, &sKey))
  119. LOG(ERROR) << "Failed to read old key: " << dir;
  120. else if (!keymaster.deleteKey(sKey))
  121. LOG(ERROR) << "Old key deletion failed, continuing anyway: " << dir;
  122. else
  123. unlink(newKeyPath.c_str());
  124. }
  125. bool needs_cp = cp_needsCheckpoint();
  126. if (!android::vold::retrieveKey(create_if_absent, dir, temp, key, needs_cp)) return false;
  127. if (needs_cp && pathExists(newKeyPath)) std::thread(commit_key, dir).detach();
  128. return true;
  129. }
  130. } // namespace vold
  131. } // namespace android
  132. static KeyBuffer default_key_params(const std::string& real_blkdev, const KeyBuffer& key) {
  133. KeyBuffer hex_key;
  134. if (android::vold::StrToHex(key, hex_key) != android::OK) {
  135. LOG(ERROR) << "Failed to turn key to hex";
  136. return KeyBuffer();
  137. }
  138. auto res = KeyBuffer() + "AES-256-XTS " + hex_key + " " + real_blkdev.c_str() + " 0";
  139. return res;
  140. }
  141. static bool get_number_of_sectors(const std::string& real_blkdev, uint64_t* nr_sec) {
  142. if (android::vold::GetBlockDev512Sectors(real_blkdev, nr_sec) != android::OK) {
  143. PLOG(ERROR) << "Unable to measure size of " << real_blkdev;
  144. return false;
  145. }
  146. return true;
  147. }
  148. static struct dm_ioctl* dm_ioctl_init(char* buffer, size_t buffer_size, const std::string& dm_name) {
  149. if (buffer_size < sizeof(dm_ioctl)) {
  150. LOG(ERROR) << "dm_ioctl buffer too small";
  151. return nullptr;
  152. }
  153. memset(buffer, 0, buffer_size);
  154. struct dm_ioctl* io = (struct dm_ioctl*)buffer;
  155. io->data_size = buffer_size;
  156. io->data_start = sizeof(struct dm_ioctl);
  157. io->version[0] = 4;
  158. io->version[1] = 0;
  159. io->version[2] = 0;
  160. io->flags = 0;
  161. dm_name.copy(io->name, sizeof(io->name));
  162. return io;
  163. }
  164. static bool create_crypto_blk_dev(const std::string& dm_name, uint64_t nr_sec,
  165. const std::string& target_type, const KeyBuffer& crypt_params,
  166. std::string* crypto_blkdev) {
  167. android::base::unique_fd dm_fd(
  168. TEMP_FAILURE_RETRY(open("/dev/device-mapper", O_RDWR | O_CLOEXEC, 0)));
  169. if (dm_fd == -1) {
  170. PLOG(ERROR) << "Cannot open device-mapper";
  171. return false;
  172. }
  173. alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
  174. auto io = dm_ioctl_init(buffer, sizeof(buffer), dm_name);
  175. if (!io || ioctl(dm_fd.get(), DM_DEV_CREATE, io) != 0) {
  176. PLOG(ERROR) << "Cannot create dm-crypt device " << dm_name;
  177. return false;
  178. }
  179. // Get the device status, in particular, the name of its device file
  180. io = dm_ioctl_init(buffer, sizeof(buffer), dm_name);
  181. if (ioctl(dm_fd.get(), DM_DEV_STATUS, io) != 0) {
  182. PLOG(ERROR) << "Cannot retrieve dm-crypt device status " << dm_name;
  183. return false;
  184. }
  185. *crypto_blkdev = std::string() + "/dev/block/dm-" +
  186. std::to_string((io->dev & 0xff) | ((io->dev >> 12) & 0xfff00));
  187. io = dm_ioctl_init(buffer, sizeof(buffer), dm_name);
  188. size_t paramix = io->data_start + sizeof(struct dm_target_spec);
  189. size_t nullix = paramix + crypt_params.size();
  190. size_t endix = (nullix + 1 + 7) & 8; // Add room for \0 and align to 8 byte boundary
  191. if (endix > sizeof(buffer)) {
  192. LOG(ERROR) << "crypt_params too big for DM_CRYPT_BUF_SIZE";
  193. return false;
  194. }
  195. io->target_count = 1;
  196. auto tgt = (struct dm_target_spec*)(buffer + io->data_start);
  197. tgt->status = 0;
  198. tgt->sector_start = 0;
  199. tgt->length = nr_sec;
  200. target_type.copy(tgt->target_type, sizeof(tgt->target_type));
  201. memcpy(buffer + paramix, crypt_params.data(),
  202. std::min(crypt_params.size(), sizeof(buffer) - paramix));
  203. buffer[nullix] = '\0';
  204. tgt->next = endix;
  205. for (int i = 0;; i++) {
  206. if (ioctl(dm_fd.get(), DM_TABLE_LOAD, io) == 0) {
  207. break;
  208. }
  209. if (i + 1 >= TABLE_LOAD_RETRIES) {
  210. PLOG(ERROR) << "DM_TABLE_LOAD ioctl failed";
  211. return false;
  212. }
  213. PLOG(INFO) << "DM_TABLE_LOAD ioctl failed, retrying";
  214. usleep(500000);
  215. }
  216. // Resume this device to activate it
  217. io = dm_ioctl_init(buffer, sizeof(buffer), dm_name);
  218. if (ioctl(dm_fd.get(), DM_DEV_SUSPEND, io)) {
  219. PLOG(ERROR) << "Cannot resume dm-crypt device " << dm_name;
  220. return false;
  221. }
  222. return true;
  223. }
  224. bool fscrypt_mount_metadata_encrypted(const std::string& blk_device, const std::string& mount_point,
  225. bool needs_encrypt) {
  226. LOG(DEBUG) << "fscrypt_mount_metadata_encrypted: " << mount_point << " " << needs_encrypt;
  227. auto encrypted_state = android::base::GetProperty("ro.crypto.state", "");
  228. if (encrypted_state != "") {
  229. LOG(DEBUG) << "fscrypt_enable_crypto got unexpected starting state: " << encrypted_state;
  230. return false;
  231. }
  232. auto data_rec = GetEntryForMountPoint(&fstab_default, mount_point);
  233. if (!data_rec) {
  234. LOG(ERROR) << "Failed to get data_rec";
  235. return false;
  236. }
  237. KeyBuffer key;
  238. if (!read_key(*data_rec, needs_encrypt, &key)) return false;
  239. uint64_t nr_sec;
  240. if (!get_number_of_sectors(data_rec->blk_device, &nr_sec)) return false;
  241. std::string crypto_blkdev;
  242. if (!create_crypto_blk_dev(kDmNameUserdata, nr_sec, DEFAULT_KEY_TARGET_TYPE,
  243. default_key_params(blk_device, key), &crypto_blkdev))
  244. return false;
  245. // FIXME handle the corrupt case
  246. if (needs_encrypt) {
  247. LOG(INFO) << "Beginning inplace encryption, nr_sec: " << nr_sec;
  248. off64_t size_already_done = 0;
  249. auto rc = cryptfs_enable_inplace(crypto_blkdev.data(), blk_device.data(), nr_sec,
  250. &size_already_done, nr_sec, 0, false);
  251. if (rc != 0) {
  252. LOG(ERROR) << "Inplace crypto failed with code: " << rc;
  253. return false;
  254. }
  255. if (static_cast<uint64_t>(size_already_done) != nr_sec) {
  256. LOG(ERROR) << "Inplace crypto only got up to sector: " << size_already_done;
  257. return false;
  258. }
  259. LOG(INFO) << "Inplace encryption complete";
  260. }
  261. LOG(DEBUG) << "Mounting metadata-encrypted filesystem:" << mount_point;
  262. mount_via_fs_mgr(data_rec->mount_point.c_str(), crypto_blkdev.c_str());
  263. return true;
  264. }