blob: d875ff040f0bfd724e2249be6682eff29a11b97f [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"
42#include "KeyStorage.h"
43#include "KeyUtil.h"
44#include "Keymaster.h"
45#include "Utils.h"
46#include "VoldUtil.h"
47
bigbiff7ba75002020-04-11 20:47:09 -040048#define TABLE_LOAD_RETRIES 10
bigbiffa957f072021-03-07 18:20:29 -050049
bigbiff7ba75002020-04-11 20:47:09 -040050
51using android::fs_mgr::FstabEntry;
52using android::fs_mgr::GetEntryForMountPoint;
bigbiffa957f072021-03-07 18:20:29 -050053using ::KeyBuffer;
54using namespace android::dm;
55
56// Parsed from metadata options
57struct CryptoOptions {
58 struct CryptoType cipher = invalid_crypto_type;
59 bool use_legacy_options_format = false;
60 bool set_dun = true; // Non-legacy driver always sets DUN
61 bool use_hw_wrapped_key = false;
62};
bigbiff7ba75002020-04-11 20:47:09 -040063
64static const std::string kDmNameUserdata = "userdata";
65
66static const char* kFn_keymaster_key_blob = "keymaster_key_blob";
67static const char* kFn_keymaster_key_blob_upgraded = "keymaster_key_blob_upgraded";
68
bigbiffa957f072021-03-07 18:20:29 -050069// The first entry in this table is the default crypto type.
70constexpr CryptoType supported_crypto_types[] = {aes_256_xts, adiantum};
71
72static_assert(validateSupportedCryptoTypes(64, supported_crypto_types,
73 array_length(supported_crypto_types)),
74 "We have a CryptoType which was incompletely constructed.");
75
76constexpr CryptoType legacy_aes_256_xts =
77 CryptoType().set_config_name("aes-256-xts").set_kernel_name("AES-256-XTS").set_keysize(64);
78
79static_assert(isValidCryptoType(64, legacy_aes_256_xts),
80 "We have a CryptoType which was incompletely constructed.");
81
82// Returns KeyGeneration suitable for key as described in CryptoOptions
83const KeyGeneration makeGen(const CryptoOptions& options) {
84 return KeyGeneration{options.cipher.get_keysize(), true, options.use_hw_wrapped_key};
85}
86
bigbiff7ba75002020-04-11 20:47:09 -040087static bool mount_via_fs_mgr(const char* mount_point, const char* blk_device) {
bigbiffa957f072021-03-07 18:20:29 -050088 // We're about to mount data not verified by verified boot. Tell Keymaster instances that early
89 // boot has ended.
90 ::Keymaster::earlyBootEnded();
91
bigbiff7ba75002020-04-11 20:47:09 -040092 // fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
93 // partitions in the fsck domain.
bigbiffa957f072021-03-07 18:20:29 -050094 if (setexeccon(::sFsckContext)) {
bigbiff7ba75002020-04-11 20:47:09 -040095 PLOG(ERROR) << "Failed to setexeccon";
96 return false;
97 }
bigbiffa957f072021-03-07 18:20:29 -050098
99 if (!ReadDefaultFstab(&fstab_default)) {
100 PLOG(ERROR) << "Failed to open default fstab";
101 return -1;
102 }
bigbiff7ba75002020-04-11 20:47:09 -0400103 auto mount_rc = fs_mgr_do_mount(&fstab_default, const_cast<char*>(mount_point),
104 const_cast<char*>(blk_device), nullptr,
bigbiffa957f072021-03-07 18:20:29 -0500105 ::cp_needsCheckpoint(), true);
bigbiff7ba75002020-04-11 20:47:09 -0400106 if (setexeccon(nullptr)) {
107 PLOG(ERROR) << "Failed to clear setexeccon";
108 return false;
109 }
110 if (mount_rc != 0) {
111 LOG(ERROR) << "fs_mgr_do_mount failed with rc " << mount_rc;
112 return false;
113 }
bigbiffa957f072021-03-07 18:20:29 -0500114 LOG(INFO) << "mount_via_fs_mgr::Mounted " << mount_point;
bigbiff7ba75002020-04-11 20:47:09 -0400115 return true;
116}
117
bigbiff7ba75002020-04-11 20:47:09 -0400118// Note: It is possible to orphan a key if it is removed before deleting
119// Update this once keymaster APIs change, and we have a proper commit.
120static void commit_key(const std::string& dir) {
121 while (!android::base::WaitForProperty("vold.checkpoint_committed", "1")) {
122 LOG(ERROR) << "Wait for boot timed out";
123 }
124 Keymaster keymaster;
125 auto keyPath = dir + "/" + kFn_keymaster_key_blob;
126 auto newKeyPath = dir + "/" + kFn_keymaster_key_blob_upgraded;
127 std::string key;
128
129 if (!android::base::ReadFileToString(keyPath, &key)) {
130 LOG(ERROR) << "Failed to read old key: " << dir;
131 return;
132 }
133 if (rename(newKeyPath.c_str(), keyPath.c_str()) != 0) {
134 PLOG(ERROR) << "Unable to move upgraded key to location: " << keyPath;
135 return;
136 }
137 if (!keymaster.deleteKey(key)) {
138 LOG(ERROR) << "Key deletion failed during upgrade, continuing anyway: " << dir;
139 }
140 LOG(INFO) << "Old Key deleted: " << dir;
141}
142
bigbiffa957f072021-03-07 18:20:29 -0500143static bool read_key(const std::string& metadata_key_dir, const KeyGeneration& gen,
144 KeyBuffer* key) {
145 if (metadata_key_dir.empty()) {
146 LOG(ERROR) << "Failed to get metadata_key_dir";
bigbiff7ba75002020-04-11 20:47:09 -0400147 return false;
148 }
bigbiff7ba75002020-04-11 20:47:09 -0400149 std::string sKey;
bigbiffa957f072021-03-07 18:20:29 -0500150 auto dir = metadata_key_dir + "/key";
151 LOG(INFO) << "metadata_key_dir/key: " << dir;
bigbiff7ba75002020-04-11 20:47:09 -0400152 if (fs_mkdirs(dir.c_str(), 0700)) {
153 PLOG(ERROR) << "Creating directories: " << dir;
154 return false;
155 }
bigbiffa957f072021-03-07 18:20:29 -0500156 auto temp = metadata_key_dir + "/tmp";
bigbiff7ba75002020-04-11 20:47:09 -0400157 auto newKeyPath = dir + "/" + kFn_keymaster_key_blob_upgraded;
158 /* If we have a leftover upgraded key, delete it.
159 * We either failed an update and must return to the old key,
160 * or we rebooted before commiting the keys in a freak accident.
161 * Either way, we can re-upgrade the key if we need to.
162 */
163 Keymaster keymaster;
164 if (pathExists(newKeyPath)) {
165 if (!android::base::ReadFileToString(newKeyPath, &sKey))
bigbiffa957f072021-03-07 18:20:29 -0500166 LOG(ERROR) << "Failed to read incomplete key: " << dir;
bigbiff7ba75002020-04-11 20:47:09 -0400167 else if (!keymaster.deleteKey(sKey))
bigbiffa957f072021-03-07 18:20:29 -0500168 LOG(ERROR) << "Incomplete key deletion failed, continuing anyway: " << dir;
bigbiff7ba75002020-04-11 20:47:09 -0400169 else
170 unlink(newKeyPath.c_str());
171 }
bigbiffa957f072021-03-07 18:20:29 -0500172 bool needs_cp = cp_needsCheckpoint();
173 if (!retrieveOrGenerateKey(dir, temp, kEmptyAuthentication, gen, key, needs_cp)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400174 if (needs_cp && pathExists(newKeyPath)) std::thread(commit_key, dir).detach();
175 return true;
176}
177
bigbiff7ba75002020-04-11 20:47:09 -0400178static bool get_number_of_sectors(const std::string& real_blkdev, uint64_t* nr_sec) {
bigbiffa957f072021-03-07 18:20:29 -0500179 if (::GetBlockDev512Sectors(real_blkdev, nr_sec) != android::OK) {
bigbiff7ba75002020-04-11 20:47:09 -0400180 PLOG(ERROR) << "Unable to measure size of " << real_blkdev;
181 return false;
182 }
183 return true;
184}
185
bigbiffa957f072021-03-07 18:20:29 -0500186static bool create_crypto_blk_dev(const std::string& dm_name, const std::string& blk_device,
187 const KeyBuffer& key, const CryptoOptions& options,
188 std::string* crypto_blkdev, uint64_t* nr_sec) {
189 if (!get_number_of_sectors(blk_device, nr_sec)) return false;
190 // TODO(paulcrowley): don't hardcode that DmTargetDefaultKey uses 4096-byte
191 // sectors
192 *nr_sec &= ~7;
193
194 KeyBuffer module_key;
195 if (options.use_hw_wrapped_key) {
196 if (!exportWrappedStorageKey(key, &module_key)) {
197 LOG(ERROR) << "Failed to get ephemeral wrapped key";
198 return false;
199 }
200 } else {
201 module_key = key;
bigbiff7ba75002020-04-11 20:47:09 -0400202 }
203
bigbiffa957f072021-03-07 18:20:29 -0500204 KeyBuffer hex_key_buffer;
205 if (::StrToHex(module_key, hex_key_buffer) != android::OK) {
206 LOG(ERROR) << "Failed to turn key to hex";
bigbiff7ba75002020-04-11 20:47:09 -0400207 return false;
208 }
bigbiffa957f072021-03-07 18:20:29 -0500209 std::string hex_key(hex_key_buffer.data(), hex_key_buffer.size());
bigbiff7ba75002020-04-11 20:47:09 -0400210
bigbiffa957f072021-03-07 18:20:29 -0500211 auto target = std::make_unique<DmTargetDefaultKey>(0, *nr_sec, options.cipher.get_kernel_name(),
212 hex_key, blk_device, 0);
213 if (options.use_legacy_options_format) target->SetUseLegacyOptionsFormat();
214 if (options.set_dun) target->SetSetDun();
215 if (options.use_hw_wrapped_key) target->SetWrappedKeyV0();
bigbiff7ba75002020-04-11 20:47:09 -0400216
bigbiffa957f072021-03-07 18:20:29 -0500217 DmTable table;
218 table.AddTarget(std::move(target));
bigbiff7ba75002020-04-11 20:47:09 -0400219
bigbiffa957f072021-03-07 18:20:29 -0500220 auto& dm = DeviceMapper::Instance();
bigbiff7ba75002020-04-11 20:47:09 -0400221 for (int i = 0;; i++) {
bigbiffa957f072021-03-07 18:20:29 -0500222 if (dm.CreateDevice(dm_name, table)) {
bigbiff7ba75002020-04-11 20:47:09 -0400223 break;
224 }
225 if (i + 1 >= TABLE_LOAD_RETRIES) {
bigbiffa957f072021-03-07 18:20:29 -0500226 PLOG(ERROR) << "Could not create default-key device " << dm_name;
bigbiff7ba75002020-04-11 20:47:09 -0400227 return false;
228 }
bigbiffa957f072021-03-07 18:20:29 -0500229 PLOG(INFO) << "Could not create default-key device, retrying";
bigbiff7ba75002020-04-11 20:47:09 -0400230 usleep(500000);
231 }
232
bigbiffa957f072021-03-07 18:20:29 -0500233 if (!dm.GetDmDevicePathByName(dm_name, crypto_blkdev)) {
234 LOG(ERROR) << "Cannot retrieve default-key device status " << dm_name;
bigbiff7ba75002020-04-11 20:47:09 -0400235 return false;
236 }
bigbiffa957f072021-03-07 18:20:29 -0500237 std::stringstream ss;
238 ss << *crypto_blkdev;
239 LOG(INFO) << "Created device: " << ss.str();
240 return true;
241}
242
243static const CryptoType& lookup_cipher(const std::string& cipher_name) {
244 if (cipher_name.empty()) return supported_crypto_types[0];
245 for (size_t i = 0; i < array_length(supported_crypto_types); i++) {
246 if (cipher_name == supported_crypto_types[i].get_config_name()) {
247 return supported_crypto_types[i];
248 }
249 }
250 return invalid_crypto_type;
251}
252
253static bool parse_options(const std::string& options_string, CryptoOptions* options) {
254 auto parts = android::base::Split(options_string, ":");
255 if (parts.size() < 1 || parts.size() > 2) {
256 LOG(ERROR) << "Invalid metadata encryption option: " << options_string;
257 return false;
258 }
259 std::string cipher_name = parts[0];
260 options->cipher = lookup_cipher(cipher_name);
261 if (options->cipher.get_kernel_name() == nullptr) {
262 LOG(ERROR) << "No metadata cipher named " << cipher_name << " found";
263 return false;
264 }
265
266 if (parts.size() == 2) {
267 if (parts[1] == "wrappedkey_v0") {
268 options->use_hw_wrapped_key = true;
269 } else {
270 LOG(ERROR) << "Invalid metadata encryption flag: " << parts[1];
271 return false;
272 }
273 }
bigbiff7ba75002020-04-11 20:47:09 -0400274 return true;
275}
276
277bool fscrypt_mount_metadata_encrypted(const std::string& blk_device, const std::string& mount_point,
278 bool needs_encrypt) {
bigbiffa957f072021-03-07 18:20:29 -0500279 LOG(INFO) << "fscrypt_mount_metadata_encrypted: " << mount_point << " " << needs_encrypt;
280 auto encrypted_state = android::base::GetProperty("ro.crypto.state", "");
281 if (encrypted_state != "" && encrypted_state != "encrypted") {
282 LOG(ERROR) << "fscrypt_enable_crypto got unexpected starting state: " << encrypted_state;
283 return false;
284 }
bigbiff7ba75002020-04-11 20:47:09 -0400285 if (!ReadDefaultFstab(&fstab_default)) {
286 PLOG(ERROR) << "Failed to open default fstab";
287 return -1;
288 }
bigbiff7ba75002020-04-11 20:47:09 -0400289 auto data_rec = GetEntryForMountPoint(&fstab_default, mount_point);
290 if (!data_rec) {
bigbiffa957f072021-03-07 18:20:29 -0500291 LOG(ERROR) << "Failed to get data_rec for " << mount_point;
bigbiff7ba75002020-04-11 20:47:09 -0400292 return false;
293 }
bigbiffa957f072021-03-07 18:20:29 -0500294
295 constexpr unsigned int pre_gki_level = 29;
296 unsigned int options_format_version = android::base::GetUintProperty<unsigned int>(
297 "ro.crypto.dm_default_key.options_format.version",
298 (GetFirstApiLevel() <= pre_gki_level ? 1 : 2));
299
300 CryptoOptions options;
301 if (options_format_version == 1) {
302 if (!data_rec->metadata_encryption.empty()) {
303 LOG(ERROR) << "metadata_encryption options cannot be set in legacy mode";
304 return false;
305 }
306 options.cipher = legacy_aes_256_xts;
307 options.use_legacy_options_format = true;
308 options.set_dun = android::base::GetBoolProperty("ro.crypto.set_dun", false);
309 if (!options.set_dun && data_rec->fs_mgr_flags.checkpoint_blk) {
310 LOG(ERROR)
311 << "Block checkpoints and metadata encryption require ro.crypto.set_dun option";
312 return false;
313 }
314 } else if (options_format_version == 2) {
315 if (!parse_options(data_rec->metadata_encryption, &options)) return false;
316 } else {
317 LOG(ERROR) << "Unknown options_format_version: " << options_format_version;
bigbiff7ba75002020-04-11 20:47:09 -0400318 return false;
bigbiffa957f072021-03-07 18:20:29 -0500319 }
320
321 auto gen = needs_encrypt ? makeGen(options) : neverGen();
322 KeyBuffer key;
323 if (!read_key(data_rec->metadata_key_dir, gen, &key)) return false;
324
325 std::string crypto_blkdev;
326 uint64_t nr_sec;
327 if (!create_crypto_blk_dev(kDmNameUserdata, blk_device, key, options, &crypto_blkdev, &nr_sec))
328 return false;
329
bigbiff7ba75002020-04-11 20:47:09 -0400330 // FIXME handle the corrupt case
331 if (needs_encrypt) {
332 LOG(INFO) << "Beginning inplace encryption, nr_sec: " << nr_sec;
333 off64_t size_already_done = 0;
334 auto rc = cryptfs_enable_inplace(crypto_blkdev.data(), blk_device.data(), nr_sec,
335 &size_already_done, nr_sec, 0, false);
336 if (rc != 0) {
337 LOG(ERROR) << "Inplace crypto failed with code: " << rc;
338 return false;
339 }
340 if (static_cast<uint64_t>(size_already_done) != nr_sec) {
341 LOG(ERROR) << "Inplace crypto only got up to sector: " << size_already_done;
342 return false;
343 }
344 LOG(INFO) << "Inplace encryption complete";
345 }
346
bigbiffa957f072021-03-07 18:20:29 -0500347 LOG(INFO) << "Mounting metadata-encrypted filesystem:" << mount_point;
348 mount_via_fs_mgr(mount_point.c_str(), crypto_blkdev.c_str());
bigbiff7ba75002020-04-11 20:47:09 -0400349 android::base::SetProperty("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
bigbiffa957f072021-03-07 18:20:29 -0500350
351 // Record that there's at least one fstab entry with metadata encryption
352 if (!android::base::SetProperty("ro.crypto.metadata.enabled", "true")) {
353 LOG(WARNING) << "failed to set ro.crypto.metadata.enabled"; // This isn't fatal
354 }
bigbiff7ba75002020-04-11 20:47:09 -0400355 return true;
356}
bigbiffa957f072021-03-07 18:20:29 -0500357
358static bool get_volume_options(CryptoOptions* options) {
359 return parse_options(android::base::GetProperty("ro.crypto.volume.metadata.encryption", ""),
360 options);
361}
362
363bool defaultkey_volume_keygen(KeyGeneration* gen) {
364 CryptoOptions options;
365 if (!get_volume_options(&options)) return false;
366 *gen = makeGen(options);
367 return true;
368}
369
370bool defaultkey_setup_ext_volume(const std::string& label, const std::string& blk_device,
371 const KeyBuffer& key, std::string* out_crypto_blkdev) {
372 LOG(ERROR) << "defaultkey_setup_ext_volume: " << label << " " << blk_device;
373
374 CryptoOptions options;
375 if (!get_volume_options(&options)) return false;
376 uint64_t nr_sec;
377 return create_crypto_blk_dev(label, blk_device, key, options, out_crypto_blkdev, &nr_sec);
378}