blob: 853e81ebf872e8ca793ab5ee1d889859e3ff9d04 [file] [log] [blame]
bigbiff7ba75002020-04-11 20:47:09 -04001/*
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>
bigbiff7ba75002020-04-11 20:47:09 -040026#include <sys/param.h>
27#include <sys/stat.h>
28#include <sys/types.h>
29
bigbiff7ba75002020-04-11 20:47:09 -040030#include <android-base/file.h>
31#include <android-base/logging.h>
32#include <android-base/properties.h>
bigbiffa957f072021-03-07 18:20:29 -050033#include <android-base/strings.h>
bigbiff7ba75002020-04-11 20:47:09 -040034#include <android-base/unique_fd.h>
35#include <cutils/fs.h>
36#include <fs_mgr.h>
bigbiffa957f072021-03-07 18:20:29 -050037#include <libdm/dm.h>
bigbiff7ba75002020-04-11 20:47:09 -040038
39#include "Checkpoint.h"
bigbiffa957f072021-03-07 18:20:29 -050040#include "CryptoType.h"
bigbiff7ba75002020-04-11 20:47:09 -040041#include "EncryptInplace.h"
bigbiffbcd23d32021-09-22 18:22:13 -040042#include "FsCrypt.h"
bigbiff7ba75002020-04-11 20:47:09 -040043#include "KeyStorage.h"
44#include "KeyUtil.h"
45#include "Keymaster.h"
46#include "Utils.h"
47#include "VoldUtil.h"
48
bigbiff7ba75002020-04-11 20:47:09 -040049#define TABLE_LOAD_RETRIES 10
bigbiffa957f072021-03-07 18:20:29 -050050
bigbiff7ba75002020-04-11 20:47:09 -040051
52using android::fs_mgr::FstabEntry;
53using android::fs_mgr::GetEntryForMountPoint;
bigbiffa957f072021-03-07 18:20:29 -050054using ::KeyBuffer;
55using namespace android::dm;
56
57// Parsed from metadata options
58struct CryptoOptions {
59 struct CryptoType cipher = invalid_crypto_type;
60 bool use_legacy_options_format = false;
61 bool set_dun = true; // Non-legacy driver always sets DUN
62 bool use_hw_wrapped_key = false;
63};
bigbiff7ba75002020-04-11 20:47:09 -040064
65static const std::string kDmNameUserdata = "userdata";
66
67static const char* kFn_keymaster_key_blob = "keymaster_key_blob";
68static const char* kFn_keymaster_key_blob_upgraded = "keymaster_key_blob_upgraded";
69
bigbiffa957f072021-03-07 18:20:29 -050070// The first entry in this table is the default crypto type.
71constexpr CryptoType supported_crypto_types[] = {aes_256_xts, adiantum};
72
73static_assert(validateSupportedCryptoTypes(64, supported_crypto_types,
74 array_length(supported_crypto_types)),
75 "We have a CryptoType which was incompletely constructed.");
76
77constexpr CryptoType legacy_aes_256_xts =
78 CryptoType().set_config_name("aes-256-xts").set_kernel_name("AES-256-XTS").set_keysize(64);
79
80static_assert(isValidCryptoType(64, legacy_aes_256_xts),
81 "We have a CryptoType which was incompletely constructed.");
82
83// Returns KeyGeneration suitable for key as described in CryptoOptions
84const KeyGeneration makeGen(const CryptoOptions& options) {
85 return KeyGeneration{options.cipher.get_keysize(), true, options.use_hw_wrapped_key};
86}
87
bigbiff7ba75002020-04-11 20:47:09 -040088static bool mount_via_fs_mgr(const char* mount_point, const char* blk_device) {
bigbiffa957f072021-03-07 18:20:29 -050089 // We're about to mount data not verified by verified boot. Tell Keymaster instances that early
90 // boot has ended.
91 ::Keymaster::earlyBootEnded();
92
bigbiff7ba75002020-04-11 20:47:09 -040093 // fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
94 // partitions in the fsck domain.
bigbiffa957f072021-03-07 18:20:29 -050095 if (setexeccon(::sFsckContext)) {
bigbiff7ba75002020-04-11 20:47:09 -040096 PLOG(ERROR) << "Failed to setexeccon";
97 return false;
98 }
bigbiffa957f072021-03-07 18:20:29 -050099
bigbiff543a9282021-10-02 09:50:58 -0400100 if (fstab_default.empty()) {
101 if (!ReadDefaultFstab(&fstab_default)) {
102 PLOG(ERROR) << "Failed to open default fstab";
103 return -1;
104 }
bigbiffa957f072021-03-07 18:20:29 -0500105 }
bigbiff7ba75002020-04-11 20:47:09 -0400106 auto mount_rc = fs_mgr_do_mount(&fstab_default, const_cast<char*>(mount_point),
107 const_cast<char*>(blk_device), nullptr,
bigbiffa957f072021-03-07 18:20:29 -0500108 ::cp_needsCheckpoint(), true);
bigbiff7ba75002020-04-11 20:47:09 -0400109 if (setexeccon(nullptr)) {
110 PLOG(ERROR) << "Failed to clear setexeccon";
111 return false;
112 }
113 if (mount_rc != 0) {
114 LOG(ERROR) << "fs_mgr_do_mount failed with rc " << mount_rc;
115 return false;
116 }
bigbiffa957f072021-03-07 18:20:29 -0500117 LOG(INFO) << "mount_via_fs_mgr::Mounted " << mount_point;
bigbiff7ba75002020-04-11 20:47:09 -0400118 return true;
119}
120
bigbiff7ba75002020-04-11 20:47:09 -0400121// Note: It is possible to orphan a key if it is removed before deleting
122// Update this once keymaster APIs change, and we have a proper commit.
123static void commit_key(const std::string& dir) {
124 while (!android::base::WaitForProperty("vold.checkpoint_committed", "1")) {
125 LOG(ERROR) << "Wait for boot timed out";
126 }
127 Keymaster keymaster;
128 auto keyPath = dir + "/" + kFn_keymaster_key_blob;
129 auto newKeyPath = dir + "/" + kFn_keymaster_key_blob_upgraded;
130 std::string key;
131
132 if (!android::base::ReadFileToString(keyPath, &key)) {
133 LOG(ERROR) << "Failed to read old key: " << dir;
134 return;
135 }
136 if (rename(newKeyPath.c_str(), keyPath.c_str()) != 0) {
137 PLOG(ERROR) << "Unable to move upgraded key to location: " << keyPath;
138 return;
139 }
140 if (!keymaster.deleteKey(key)) {
141 LOG(ERROR) << "Key deletion failed during upgrade, continuing anyway: " << dir;
142 }
143 LOG(INFO) << "Old Key deleted: " << dir;
144}
145
bigbiffa957f072021-03-07 18:20:29 -0500146static bool read_key(const std::string& metadata_key_dir, const KeyGeneration& gen,
147 KeyBuffer* key) {
148 if (metadata_key_dir.empty()) {
149 LOG(ERROR) << "Failed to get metadata_key_dir";
bigbiff7ba75002020-04-11 20:47:09 -0400150 return false;
151 }
bigbiff7ba75002020-04-11 20:47:09 -0400152 std::string sKey;
bigbiffa957f072021-03-07 18:20:29 -0500153 auto dir = metadata_key_dir + "/key";
154 LOG(INFO) << "metadata_key_dir/key: " << dir;
bigbiff7ba75002020-04-11 20:47:09 -0400155 if (fs_mkdirs(dir.c_str(), 0700)) {
156 PLOG(ERROR) << "Creating directories: " << dir;
157 return false;
158 }
bigbiffa957f072021-03-07 18:20:29 -0500159 auto temp = metadata_key_dir + "/tmp";
bigbiff7ba75002020-04-11 20:47:09 -0400160 auto newKeyPath = dir + "/" + kFn_keymaster_key_blob_upgraded;
161 /* If we have a leftover upgraded key, delete it.
162 * We either failed an update and must return to the old key,
163 * or we rebooted before commiting the keys in a freak accident.
164 * Either way, we can re-upgrade the key if we need to.
165 */
bigbiffbbbfe172021-05-30 15:52:41 -0400166
bigbiff7ba75002020-04-11 20:47:09 -0400167 Keymaster keymaster;
168 if (pathExists(newKeyPath)) {
169 if (!android::base::ReadFileToString(newKeyPath, &sKey))
bigbiffa957f072021-03-07 18:20:29 -0500170 LOG(ERROR) << "Failed to read incomplete key: " << dir;
bigbiff7ba75002020-04-11 20:47:09 -0400171 else if (!keymaster.deleteKey(sKey))
bigbiffa957f072021-03-07 18:20:29 -0500172 LOG(ERROR) << "Incomplete key deletion failed, continuing anyway: " << dir;
bigbiff7ba75002020-04-11 20:47:09 -0400173 else
174 unlink(newKeyPath.c_str());
175 }
bigbiffa957f072021-03-07 18:20:29 -0500176 bool needs_cp = cp_needsCheckpoint();
bigbiffaa8d5172021-11-05 18:58:37 +0000177 if (!retrieveOrGenerateKey(dir, temp, kEmptyAuthentication, gen, key, true)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400178 if (needs_cp && pathExists(newKeyPath)) std::thread(commit_key, dir).detach();
179 return true;
180}
181
bigbiff7ba75002020-04-11 20:47:09 -0400182static bool get_number_of_sectors(const std::string& real_blkdev, uint64_t* nr_sec) {
bigbiffa957f072021-03-07 18:20:29 -0500183 if (::GetBlockDev512Sectors(real_blkdev, nr_sec) != android::OK) {
bigbiff7ba75002020-04-11 20:47:09 -0400184 PLOG(ERROR) << "Unable to measure size of " << real_blkdev;
185 return false;
186 }
187 return true;
188}
189
bigbiffa957f072021-03-07 18:20:29 -0500190static bool create_crypto_blk_dev(const std::string& dm_name, const std::string& blk_device,
191 const KeyBuffer& key, const CryptoOptions& options,
192 std::string* crypto_blkdev, uint64_t* nr_sec) {
193 if (!get_number_of_sectors(blk_device, nr_sec)) return false;
194 // TODO(paulcrowley): don't hardcode that DmTargetDefaultKey uses 4096-byte
195 // sectors
196 *nr_sec &= ~7;
197
198 KeyBuffer module_key;
199 if (options.use_hw_wrapped_key) {
200 if (!exportWrappedStorageKey(key, &module_key)) {
201 LOG(ERROR) << "Failed to get ephemeral wrapped key";
202 return false;
203 }
204 } else {
205 module_key = key;
bigbiff7ba75002020-04-11 20:47:09 -0400206 }
207
bigbiffa957f072021-03-07 18:20:29 -0500208 KeyBuffer hex_key_buffer;
209 if (::StrToHex(module_key, hex_key_buffer) != android::OK) {
210 LOG(ERROR) << "Failed to turn key to hex";
bigbiff7ba75002020-04-11 20:47:09 -0400211 return false;
212 }
bigbiffa957f072021-03-07 18:20:29 -0500213 std::string hex_key(hex_key_buffer.data(), hex_key_buffer.size());
bigbiff7ba75002020-04-11 20:47:09 -0400214
bigbiffa957f072021-03-07 18:20:29 -0500215 auto target = std::make_unique<DmTargetDefaultKey>(0, *nr_sec, options.cipher.get_kernel_name(),
216 hex_key, blk_device, 0);
217 if (options.use_legacy_options_format) target->SetUseLegacyOptionsFormat();
218 if (options.set_dun) target->SetSetDun();
219 if (options.use_hw_wrapped_key) target->SetWrappedKeyV0();
bigbiff7ba75002020-04-11 20:47:09 -0400220
bigbiffa957f072021-03-07 18:20:29 -0500221 DmTable table;
222 table.AddTarget(std::move(target));
bigbiff7ba75002020-04-11 20:47:09 -0400223
bigbiffa957f072021-03-07 18:20:29 -0500224 auto& dm = DeviceMapper::Instance();
bigbiff7ba75002020-04-11 20:47:09 -0400225 for (int i = 0;; i++) {
bigbiffa957f072021-03-07 18:20:29 -0500226 if (dm.CreateDevice(dm_name, table)) {
bigbiff7ba75002020-04-11 20:47:09 -0400227 break;
228 }
229 if (i + 1 >= TABLE_LOAD_RETRIES) {
bigbiffa957f072021-03-07 18:20:29 -0500230 PLOG(ERROR) << "Could not create default-key device " << dm_name;
bigbiff7ba75002020-04-11 20:47:09 -0400231 return false;
232 }
bigbiffa957f072021-03-07 18:20:29 -0500233 PLOG(INFO) << "Could not create default-key device, retrying";
bigbiff7ba75002020-04-11 20:47:09 -0400234 usleep(500000);
235 }
236
bigbiffa957f072021-03-07 18:20:29 -0500237 if (!dm.GetDmDevicePathByName(dm_name, crypto_blkdev)) {
238 LOG(ERROR) << "Cannot retrieve default-key device status " << dm_name;
bigbiff7ba75002020-04-11 20:47:09 -0400239 return false;
240 }
bigbiffa957f072021-03-07 18:20:29 -0500241 std::stringstream ss;
242 ss << *crypto_blkdev;
243 LOG(INFO) << "Created device: " << ss.str();
244 return true;
245}
246
247static const CryptoType& lookup_cipher(const std::string& cipher_name) {
248 if (cipher_name.empty()) return supported_crypto_types[0];
249 for (size_t i = 0; i < array_length(supported_crypto_types); i++) {
250 if (cipher_name == supported_crypto_types[i].get_config_name()) {
251 return supported_crypto_types[i];
252 }
253 }
254 return invalid_crypto_type;
255}
256
257static bool parse_options(const std::string& options_string, CryptoOptions* options) {
258 auto parts = android::base::Split(options_string, ":");
259 if (parts.size() < 1 || parts.size() > 2) {
260 LOG(ERROR) << "Invalid metadata encryption option: " << options_string;
261 return false;
262 }
263 std::string cipher_name = parts[0];
264 options->cipher = lookup_cipher(cipher_name);
265 if (options->cipher.get_kernel_name() == nullptr) {
266 LOG(ERROR) << "No metadata cipher named " << cipher_name << " found";
267 return false;
268 }
269
270 if (parts.size() == 2) {
271 if (parts[1] == "wrappedkey_v0") {
272 options->use_hw_wrapped_key = true;
273 } else {
274 LOG(ERROR) << "Invalid metadata encryption flag: " << parts[1];
275 return false;
276 }
277 }
bigbiff7ba75002020-04-11 20:47:09 -0400278 return true;
279}
280
281bool fscrypt_mount_metadata_encrypted(const std::string& blk_device, const std::string& mount_point,
282 bool needs_encrypt) {
bigbiffa957f072021-03-07 18:20:29 -0500283 LOG(INFO) << "fscrypt_mount_metadata_encrypted: " << mount_point << " " << needs_encrypt;
284 auto encrypted_state = android::base::GetProperty("ro.crypto.state", "");
285 if (encrypted_state != "" && encrypted_state != "encrypted") {
286 LOG(ERROR) << "fscrypt_enable_crypto got unexpected starting state: " << encrypted_state;
287 return false;
288 }
bigbiff543a9282021-10-02 09:50:58 -0400289 if (fstab_default.empty()) {
290 if (!ReadDefaultFstab(&fstab_default)) {
291 PLOG(ERROR) << "Failed to open default fstab";
292 return -1;
293 }
bigbiff7ba75002020-04-11 20:47:09 -0400294 }
bigbiff7ba75002020-04-11 20:47:09 -0400295 auto data_rec = GetEntryForMountPoint(&fstab_default, mount_point);
296 if (!data_rec) {
bigbiffa957f072021-03-07 18:20:29 -0500297 LOG(ERROR) << "Failed to get data_rec for " << mount_point;
bigbiff7ba75002020-04-11 20:47:09 -0400298 return false;
299 }
bigbiffa957f072021-03-07 18:20:29 -0500300
301 constexpr unsigned int pre_gki_level = 29;
302 unsigned int options_format_version = android::base::GetUintProperty<unsigned int>(
303 "ro.crypto.dm_default_key.options_format.version",
304 (GetFirstApiLevel() <= pre_gki_level ? 1 : 2));
305
306 CryptoOptions options;
307 if (options_format_version == 1) {
308 if (!data_rec->metadata_encryption.empty()) {
309 LOG(ERROR) << "metadata_encryption options cannot be set in legacy mode";
310 return false;
311 }
312 options.cipher = legacy_aes_256_xts;
313 options.use_legacy_options_format = true;
bigbiffbcd23d32021-09-22 18:22:13 -0400314 if (is_metadata_wrapped_key_supported()) {
315 options.use_hw_wrapped_key = true;
316 LOG(INFO) << "metadata_wrapped_key_true";
317 }
bigbiffa957f072021-03-07 18:20:29 -0500318 options.set_dun = android::base::GetBoolProperty("ro.crypto.set_dun", false);
319 if (!options.set_dun && data_rec->fs_mgr_flags.checkpoint_blk) {
320 LOG(ERROR)
321 << "Block checkpoints and metadata encryption require ro.crypto.set_dun option";
322 return false;
323 }
324 } else if (options_format_version == 2) {
325 if (!parse_options(data_rec->metadata_encryption, &options)) return false;
326 } else {
327 LOG(ERROR) << "Unknown options_format_version: " << options_format_version;
bigbiff7ba75002020-04-11 20:47:09 -0400328 return false;
bigbiffa957f072021-03-07 18:20:29 -0500329 }
bigbiffa957f072021-03-07 18:20:29 -0500330 auto gen = needs_encrypt ? makeGen(options) : neverGen();
331 KeyBuffer key;
332 if (!read_key(data_rec->metadata_key_dir, gen, &key)) return false;
333
334 std::string crypto_blkdev;
335 uint64_t nr_sec;
336 if (!create_crypto_blk_dev(kDmNameUserdata, blk_device, key, options, &crypto_blkdev, &nr_sec))
337 return false;
338
bigbiff7ba75002020-04-11 20:47:09 -0400339 // FIXME handle the corrupt case
340 if (needs_encrypt) {
341 LOG(INFO) << "Beginning inplace encryption, nr_sec: " << nr_sec;
342 off64_t size_already_done = 0;
343 auto rc = cryptfs_enable_inplace(crypto_blkdev.data(), blk_device.data(), nr_sec,
344 &size_already_done, nr_sec, 0, false);
345 if (rc != 0) {
346 LOG(ERROR) << "Inplace crypto failed with code: " << rc;
347 return false;
348 }
349 if (static_cast<uint64_t>(size_already_done) != nr_sec) {
350 LOG(ERROR) << "Inplace crypto only got up to sector: " << size_already_done;
351 return false;
352 }
353 LOG(INFO) << "Inplace encryption complete";
354 }
355
bigbiffa957f072021-03-07 18:20:29 -0500356 LOG(INFO) << "Mounting metadata-encrypted filesystem:" << mount_point;
357 mount_via_fs_mgr(mount_point.c_str(), crypto_blkdev.c_str());
bigbiff7ba75002020-04-11 20:47:09 -0400358 android::base::SetProperty("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
bigbiffa957f072021-03-07 18:20:29 -0500359
360 // Record that there's at least one fstab entry with metadata encryption
361 if (!android::base::SetProperty("ro.crypto.metadata.enabled", "true")) {
362 LOG(WARNING) << "failed to set ro.crypto.metadata.enabled"; // This isn't fatal
363 }
bigbiff7ba75002020-04-11 20:47:09 -0400364 return true;
365}
bigbiffa957f072021-03-07 18:20:29 -0500366
367static bool get_volume_options(CryptoOptions* options) {
368 return parse_options(android::base::GetProperty("ro.crypto.volume.metadata.encryption", ""),
369 options);
370}
371
372bool defaultkey_volume_keygen(KeyGeneration* gen) {
373 CryptoOptions options;
374 if (!get_volume_options(&options)) return false;
375 *gen = makeGen(options);
376 return true;
377}
378
379bool defaultkey_setup_ext_volume(const std::string& label, const std::string& blk_device,
380 const KeyBuffer& key, std::string* out_crypto_blkdev) {
381 LOG(ERROR) << "defaultkey_setup_ext_volume: " << label << " " << blk_device;
382
383 CryptoOptions options;
384 if (!get_volume_options(&options)) return false;
385 uint64_t nr_sec;
386 return create_crypto_blk_dev(label, blk_device, key, options, out_crypto_blkdev, &nr_sec);
387}