blob: b707549206ab8a20909537a4a72895b8d2bed63a [file] [log] [blame]
Paul Crowleyd5759812016-06-02 11:04:27 -07001/*
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
19#include <string>
20#include <thread>
21#include <vector>
22
23#include <fcntl.h>
24#include <sys/ioctl.h>
25#include <sys/param.h>
26#include <sys/stat.h>
27#include <sys/types.h>
28
29#include <linux/dm-ioctl.h>
30
31#include <android-base/logging.h>
32#include <cutils/properties.h>
33#include <fs_mgr.h>
34
35#include "AutoCloseFD.h"
36#include "EncryptInplace.h"
37#include "KeyStorage.h"
38#include "KeyUtil.h"
39#include "secontext.h"
40#include "Utils.h"
41#include "VoldUtil.h"
42
43extern struct fstab *fstab;
44#define DM_CRYPT_BUF_SIZE 4096
45#define TABLE_LOAD_RETRIES 10
46#define DEFAULT_KEY_TARGET_TYPE "default-key"
47
48static const std::string kDmNameUserdata = "userdata";
49
50static 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(secontextFsck())) {
54 PLOG(ERROR) << "Failed to setexeccon";
55 return false;
56 }
57 auto mount_rc = fs_mgr_do_mount(fstab, const_cast<char*>(mount_point),
58 const_cast<char*>(blk_device), nullptr);
59 if (setexeccon(nullptr)) {
60 PLOG(ERROR) << "Failed to clear setexeccon";
61 return false;
62 }
63 if (mount_rc != 0) {
64 LOG(ERROR) << "fs_mgr_do_mount failed with rc " << mount_rc;
65 return false;
66 }
67 LOG(DEBUG) << "Mounted " << mount_point;
68 return true;
69}
70
71static bool read_key(bool create_if_absent, std::string* key) {
72 auto data_rec = fs_mgr_get_crypt_entry(fstab);
73 if (!data_rec) {
74 LOG(ERROR) << "Failed to get data_rec";
75 return false;
76 }
77 if (!data_rec->key_dir) {
78 LOG(ERROR) << "Failed to get key_dir";
79 return false;
80 }
81 LOG(DEBUG) << "key_dir: " << data_rec->key_dir;
82 if (!android::vold::pathExists(data_rec->key_dir)) {
83 if (mkdir(data_rec->key_dir, 0777) != 0) {
84 PLOG(ERROR) << "Unable to create: " << data_rec->key_dir;
85 return false;
86 }
87 LOG(DEBUG) << "Created: " << data_rec->key_dir;
88 }
89 std::string key_dir = data_rec->key_dir;
90 auto dir = key_dir + "/key";
91 auto temp = key_dir + "/tmp";
92 if (!android::vold::retrieveKey(create_if_absent, dir, temp, key)) return false;
93 return true;
94}
95
96static std::string default_key_params(const std::string& real_blkdev, const std::string& key) {
97 std::string hex_key;
98 if (android::vold::StrToHex(key, hex_key) != android::OK) {
99 LOG(ERROR) << "Failed to turn key to hex";
100 return "";
101 }
102 auto res = std::string() + "AES-256-XTS " + hex_key + " " + real_blkdev + " 0";
103 LOG(DEBUG) << "crypt_params: " << res;
104 return res;
105}
106
107static bool get_number_of_sectors(const std::string& real_blkdev, uint64_t *nr_sec) {
108 AutoCloseFD dev_fd(real_blkdev, O_RDONLY);
109 if (!dev_fd) {
110 PLOG(ERROR) << "Unable to open " << real_blkdev << " to measure size";
111 return false;
112 }
113 unsigned long res;
114 // TODO: should use BLKGETSIZE64
115 get_blkdev_size(dev_fd.get(), &res);
116 if (res == 0) {
117 PLOG(ERROR) << "Unable to measure size of " << real_blkdev;
118 return false;
119 }
120 *nr_sec = res;
121 return true;
122}
123
124static struct dm_ioctl* dm_ioctl_init(char *buffer, size_t buffer_size,
125 const std::string& dm_name) {
126 if (buffer_size < sizeof(dm_ioctl)) {
127 LOG(ERROR) << "dm_ioctl buffer too small";
128 return nullptr;
129 }
130
131 memset(buffer, 0, buffer_size);
132 struct dm_ioctl* io = (struct dm_ioctl*) buffer;
133 io->data_size = buffer_size;
134 io->data_start = sizeof(struct dm_ioctl);
135 io->version[0] = 4;
136 io->version[1] = 0;
137 io->version[2] = 0;
138 io->flags = 0;
139 dm_name.copy(io->name, sizeof(io->name));
140 return io;
141}
142
143static bool create_crypto_blk_dev(const std::string& dm_name, uint64_t nr_sec,
144 const std::string& target_type, const std::string& crypt_params,
145 std::string* crypto_blkdev) {
146 AutoCloseFD dm_fd("/dev/device-mapper", O_RDWR);
147 if (!dm_fd) {
148 PLOG(ERROR) << "Cannot open device-mapper";
149 return false;
150 }
151 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
152 auto io = dm_ioctl_init(buffer, sizeof(buffer), dm_name);
153 if (!io || ioctl(dm_fd.get(), DM_DEV_CREATE, io) != 0) {
154 PLOG(ERROR) << "Cannot create dm-crypt device " << dm_name;
155 return false;
156 }
157
158 // Get the device status, in particular, the name of its device file
159 io = dm_ioctl_init(buffer, sizeof(buffer), dm_name);
160 if (ioctl(dm_fd.get(), DM_DEV_STATUS, io) != 0) {
161 PLOG(ERROR) << "Cannot retrieve dm-crypt device status " << dm_name;
162 return false;
163 }
164 *crypto_blkdev = std::string() + "/dev/block/dm-" + std::to_string(
165 (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00));
166
167 io = dm_ioctl_init(buffer, sizeof(buffer), dm_name);
168 unsigned long paramix = io->data_start + sizeof(struct dm_target_spec);
169 unsigned long nullix = paramix + crypt_params.size();
170 unsigned long endix = (nullix + 1 + 7) & 8; // Add room for \0 and align to 8 byte boundary
171
172 if (endix > sizeof(buffer)) {
173 LOG(ERROR) << "crypt_params too big for DM_CRYPT_BUF_SIZE";
174 return false;
175 }
176
177 io->target_count = 1;
178 auto tgt = (struct dm_target_spec *) (buffer + io->data_start);
179 tgt->status = 0;
180 tgt->sector_start = 0;
181 tgt->length = nr_sec;
182 target_type.copy(tgt->target_type, sizeof(tgt->target_type));
183 crypt_params.copy(buffer + paramix, sizeof(buffer) - paramix);
184 buffer[nullix] = '\0';
185 tgt->next = endix;
186
187 for (int i = 0; ; i++) {
188 if (ioctl(dm_fd.get(), DM_TABLE_LOAD, io) == 0) {
189 break;
190 }
191 if (i+1 >= TABLE_LOAD_RETRIES) {
192 PLOG(ERROR) << "DM_TABLE_LOAD ioctl failed";
193 return false;
194 }
195 PLOG(INFO) << "DM_TABLE_LOAD ioctl failed, retrying";
196 usleep(500000);
197 }
198
199 // Resume this device to activate it
200 io = dm_ioctl_init(buffer, sizeof(buffer), dm_name);
201 if (ioctl(dm_fd.get(), DM_DEV_SUSPEND, io)) {
202 PLOG(ERROR) << "Cannot resume dm-crypt device " << dm_name;
203 return false;
204 }
205 return true;
206}
207
208#define DATA_PREP_TIMEOUT 1000
209static bool prep_data_fs(void)
210{
211 // NOTE: post_fs_data results in init calling back around to vold, so all
212 // callers to this method must be async
213
214 /* Do the prep of the /data filesystem */
Guang Zhu5b6c6a22017-04-28 23:56:45 +0000215 property_set("vold.post_fs_data_done", "0");
Paul Crowleyd5759812016-06-02 11:04:27 -0700216 property_set("vold.decrypt", "trigger_post_fs_data");
Guang Zhu5b6c6a22017-04-28 23:56:45 +0000217 LOG(DEBUG) << "Waiting for post_fs_data_done";
218
219 /* Wait a max of 50 seconds, hopefully it takes much less */
220 for (int i = 0; ; i++) {
221 char p[PROPERTY_VALUE_MAX];
222
223 property_get("vold.post_fs_data_done", p, "0");
224 if (*p == '1') {
225 LOG(INFO) << "Successful data prep";
226 return true;
227 }
228 if (i + 1 == DATA_PREP_TIMEOUT) {
229 LOG(ERROR) << "post_fs_data timed out";
230 return false;
231 }
232 usleep(50000);
233 }
Paul Crowleyd5759812016-06-02 11:04:27 -0700234}
235
236static void async_kick_off() {
237 LOG(DEBUG) << "Asynchronously restarting framework";
Guang Zhu5b6c6a22017-04-28 23:56:45 +0000238 sleep(2); // TODO: this mirrors cryptfs, but can it be made shorter?
239 property_set("vold.decrypt", "trigger_load_persist_props");
Paul Crowleyd5759812016-06-02 11:04:27 -0700240 if (!prep_data_fs()) return;
Guang Zhu5b6c6a22017-04-28 23:56:45 +0000241 /* startup service classes main and late_start */
242 property_set("vold.decrypt", "trigger_restart_framework");
Paul Crowleyd5759812016-06-02 11:04:27 -0700243}
244
245bool e4crypt_mount_metadata_encrypted() {
246 LOG(DEBUG) << "e4crypt_mount_default_encrypted";
247 std::string key;
248 if (!read_key(false, &key)) return false;
249 auto data_rec = fs_mgr_get_crypt_entry(fstab);
250 if (!data_rec) {
251 LOG(ERROR) << "Failed to get data_rec";
252 return false;
253 }
254 uint64_t nr_sec;
255 if (!get_number_of_sectors(data_rec->blk_device, &nr_sec)) return false;
256 std::string crypto_blkdev;
257 if (!create_crypto_blk_dev(kDmNameUserdata, nr_sec, DEFAULT_KEY_TARGET_TYPE,
258 default_key_params(data_rec->blk_device, key), &crypto_blkdev)) return false;
259 // FIXME handle the corrupt case
260
261 LOG(DEBUG) << "Restarting filesystem for metadata encryption";
262 mount_via_fs_mgr(data_rec->mount_point, crypto_blkdev.c_str());
263 std::thread(&async_kick_off).detach();
264 return true;
265}
266
267bool e4crypt_enable_crypto() {
268 LOG(DEBUG) << "e4crypt_enable_crypto";
269 char encrypted_state[PROPERTY_VALUE_MAX];
270 property_get("ro.crypto.state", encrypted_state, "");
271 if (strcmp(encrypted_state, "")) {
272 LOG(DEBUG) << "e4crypt_enable_crypto got unexpected starting state: " << encrypted_state;
273 return false;
274 }
275
276 std::string key_ref;
277 if (!read_key(true, &key_ref)) return false;
278
279 auto data_rec = fs_mgr_get_crypt_entry(fstab);
280 if (!data_rec) {
281 LOG(ERROR) << "Failed to get data_rec";
282 return false;
283 }
284 uint64_t nr_sec;
285 if (!get_number_of_sectors(data_rec->blk_device, &nr_sec)) return false;
286
287 std::string crypto_blkdev;
288 if (!create_crypto_blk_dev(kDmNameUserdata, nr_sec, DEFAULT_KEY_TARGET_TYPE,
289 default_key_params(data_rec->blk_device, key_ref), &crypto_blkdev)) return false;
290
291 LOG(INFO) << "Beginning inplace encryption, nr_sec: " << nr_sec;
292 off64_t size_already_done = 0;
293 auto rc = cryptfs_enable_inplace(const_cast<char *>(crypto_blkdev.c_str()),
294 data_rec->blk_device, nr_sec, &size_already_done, nr_sec, 0);
295 if (rc != 0) {
296 LOG(ERROR) << "Inplace crypto failed with code: " << rc;
297 return false;
298 }
299 if (static_cast<uint64_t>(size_already_done) != nr_sec) {
300 LOG(ERROR) << "Inplace crypto only got up to sector: " << size_already_done;
301 return false;
302 }
303 LOG(INFO) << "Inplace encryption complete";
304
305 property_set("ro.crypto.state", "encrypted");
306 property_set("ro.crypto.type", "file");
307
308 mount_via_fs_mgr(data_rec->mount_point, crypto_blkdev.c_str());
Guang Zhu5b6c6a22017-04-28 23:56:45 +0000309 property_set("vold.decrypt", "trigger_reset_main");
Paul Crowleyd5759812016-06-02 11:04:27 -0700310 std::thread(&async_kick_off).detach();
311 return true;
312}