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