blob: 1504367a120f1779c5d9d0c801e609c0705602a4 [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 */
bigbiffbbbfe172021-05-30 15:52:41 -0400163
bigbiff7ba75002020-04-11 20:47:09 -0400164 Keymaster keymaster;
165 if (pathExists(newKeyPath)) {
166 if (!android::base::ReadFileToString(newKeyPath, &sKey))
bigbiffa957f072021-03-07 18:20:29 -0500167 LOG(ERROR) << "Failed to read incomplete key: " << dir;
bigbiff7ba75002020-04-11 20:47:09 -0400168 else if (!keymaster.deleteKey(sKey))
bigbiffa957f072021-03-07 18:20:29 -0500169 LOG(ERROR) << "Incomplete key deletion failed, continuing anyway: " << dir;
bigbiff7ba75002020-04-11 20:47:09 -0400170 else
171 unlink(newKeyPath.c_str());
172 }
bigbiffa957f072021-03-07 18:20:29 -0500173 bool needs_cp = cp_needsCheckpoint();
bigbiffbbbfe172021-05-30 15:52:41 -0400174 if (!retrieveOrGenerateKey(dir, temp, kEmptyAuthentication, gen, key, true)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400175 if (needs_cp && pathExists(newKeyPath)) std::thread(commit_key, dir).detach();
176 return true;
177}
178
bigbiff7ba75002020-04-11 20:47:09 -0400179static bool get_number_of_sectors(const std::string& real_blkdev, uint64_t* nr_sec) {
bigbiffa957f072021-03-07 18:20:29 -0500180 if (::GetBlockDev512Sectors(real_blkdev, nr_sec) != android::OK) {
bigbiff7ba75002020-04-11 20:47:09 -0400181 PLOG(ERROR) << "Unable to measure size of " << real_blkdev;
182 return false;
183 }
184 return true;
185}
186
bigbiffa957f072021-03-07 18:20:29 -0500187static bool create_crypto_blk_dev(const std::string& dm_name, const std::string& blk_device,
188 const KeyBuffer& key, const CryptoOptions& options,
189 std::string* crypto_blkdev, uint64_t* nr_sec) {
190 if (!get_number_of_sectors(blk_device, nr_sec)) return false;
191 // TODO(paulcrowley): don't hardcode that DmTargetDefaultKey uses 4096-byte
192 // sectors
193 *nr_sec &= ~7;
194
195 KeyBuffer module_key;
196 if (options.use_hw_wrapped_key) {
197 if (!exportWrappedStorageKey(key, &module_key)) {
198 LOG(ERROR) << "Failed to get ephemeral wrapped key";
199 return false;
200 }
201 } else {
202 module_key = key;
bigbiff7ba75002020-04-11 20:47:09 -0400203 }
204
bigbiffa957f072021-03-07 18:20:29 -0500205 KeyBuffer hex_key_buffer;
206 if (::StrToHex(module_key, hex_key_buffer) != android::OK) {
207 LOG(ERROR) << "Failed to turn key to hex";
bigbiff7ba75002020-04-11 20:47:09 -0400208 return false;
209 }
bigbiffa957f072021-03-07 18:20:29 -0500210 std::string hex_key(hex_key_buffer.data(), hex_key_buffer.size());
bigbiff7ba75002020-04-11 20:47:09 -0400211
bigbiffa957f072021-03-07 18:20:29 -0500212 auto target = std::make_unique<DmTargetDefaultKey>(0, *nr_sec, options.cipher.get_kernel_name(),
213 hex_key, blk_device, 0);
214 if (options.use_legacy_options_format) target->SetUseLegacyOptionsFormat();
215 if (options.set_dun) target->SetSetDun();
216 if (options.use_hw_wrapped_key) target->SetWrappedKeyV0();
bigbiff7ba75002020-04-11 20:47:09 -0400217
bigbiffa957f072021-03-07 18:20:29 -0500218 DmTable table;
219 table.AddTarget(std::move(target));
bigbiff7ba75002020-04-11 20:47:09 -0400220
bigbiffa957f072021-03-07 18:20:29 -0500221 auto& dm = DeviceMapper::Instance();
bigbiff7ba75002020-04-11 20:47:09 -0400222 for (int i = 0;; i++) {
bigbiffa957f072021-03-07 18:20:29 -0500223 if (dm.CreateDevice(dm_name, table)) {
bigbiff7ba75002020-04-11 20:47:09 -0400224 break;
225 }
226 if (i + 1 >= TABLE_LOAD_RETRIES) {
bigbiffa957f072021-03-07 18:20:29 -0500227 PLOG(ERROR) << "Could not create default-key device " << dm_name;
bigbiff7ba75002020-04-11 20:47:09 -0400228 return false;
229 }
bigbiffa957f072021-03-07 18:20:29 -0500230 PLOG(INFO) << "Could not create default-key device, retrying";
bigbiff7ba75002020-04-11 20:47:09 -0400231 usleep(500000);
232 }
233
bigbiffa957f072021-03-07 18:20:29 -0500234 if (!dm.GetDmDevicePathByName(dm_name, crypto_blkdev)) {
235 LOG(ERROR) << "Cannot retrieve default-key device status " << dm_name;
bigbiff7ba75002020-04-11 20:47:09 -0400236 return false;
237 }
bigbiffa957f072021-03-07 18:20:29 -0500238 std::stringstream ss;
239 ss << *crypto_blkdev;
240 LOG(INFO) << "Created device: " << ss.str();
241 return true;
242}
243
244static const CryptoType& lookup_cipher(const std::string& cipher_name) {
245 if (cipher_name.empty()) return supported_crypto_types[0];
246 for (size_t i = 0; i < array_length(supported_crypto_types); i++) {
247 if (cipher_name == supported_crypto_types[i].get_config_name()) {
248 return supported_crypto_types[i];
249 }
250 }
251 return invalid_crypto_type;
252}
253
254static bool parse_options(const std::string& options_string, CryptoOptions* options) {
255 auto parts = android::base::Split(options_string, ":");
256 if (parts.size() < 1 || parts.size() > 2) {
257 LOG(ERROR) << "Invalid metadata encryption option: " << options_string;
258 return false;
259 }
260 std::string cipher_name = parts[0];
261 options->cipher = lookup_cipher(cipher_name);
262 if (options->cipher.get_kernel_name() == nullptr) {
263 LOG(ERROR) << "No metadata cipher named " << cipher_name << " found";
264 return false;
265 }
266
267 if (parts.size() == 2) {
268 if (parts[1] == "wrappedkey_v0") {
269 options->use_hw_wrapped_key = true;
270 } else {
271 LOG(ERROR) << "Invalid metadata encryption flag: " << parts[1];
272 return false;
273 }
274 }
bigbiff7ba75002020-04-11 20:47:09 -0400275 return true;
276}
277
278bool fscrypt_mount_metadata_encrypted(const std::string& blk_device, const std::string& mount_point,
279 bool needs_encrypt) {
bigbiffa957f072021-03-07 18:20:29 -0500280 LOG(INFO) << "fscrypt_mount_metadata_encrypted: " << mount_point << " " << needs_encrypt;
281 auto encrypted_state = android::base::GetProperty("ro.crypto.state", "");
282 if (encrypted_state != "" && encrypted_state != "encrypted") {
283 LOG(ERROR) << "fscrypt_enable_crypto got unexpected starting state: " << encrypted_state;
284 return false;
285 }
bigbiff7ba75002020-04-11 20:47:09 -0400286 if (!ReadDefaultFstab(&fstab_default)) {
287 PLOG(ERROR) << "Failed to open default fstab";
288 return -1;
289 }
bigbiff7ba75002020-04-11 20:47:09 -0400290 auto data_rec = GetEntryForMountPoint(&fstab_default, mount_point);
291 if (!data_rec) {
bigbiffa957f072021-03-07 18:20:29 -0500292 LOG(ERROR) << "Failed to get data_rec for " << mount_point;
bigbiff7ba75002020-04-11 20:47:09 -0400293 return false;
294 }
bigbiffa957f072021-03-07 18:20:29 -0500295
296 constexpr unsigned int pre_gki_level = 29;
297 unsigned int options_format_version = android::base::GetUintProperty<unsigned int>(
298 "ro.crypto.dm_default_key.options_format.version",
299 (GetFirstApiLevel() <= pre_gki_level ? 1 : 2));
300
301 CryptoOptions options;
302 if (options_format_version == 1) {
303 if (!data_rec->metadata_encryption.empty()) {
304 LOG(ERROR) << "metadata_encryption options cannot be set in legacy mode";
305 return false;
306 }
307 options.cipher = legacy_aes_256_xts;
308 options.use_legacy_options_format = true;
309 options.set_dun = android::base::GetBoolProperty("ro.crypto.set_dun", false);
310 if (!options.set_dun && data_rec->fs_mgr_flags.checkpoint_blk) {
311 LOG(ERROR)
312 << "Block checkpoints and metadata encryption require ro.crypto.set_dun option";
313 return false;
314 }
315 } else if (options_format_version == 2) {
316 if (!parse_options(data_rec->metadata_encryption, &options)) return false;
317 } else {
318 LOG(ERROR) << "Unknown options_format_version: " << options_format_version;
bigbiff7ba75002020-04-11 20:47:09 -0400319 return false;
bigbiffa957f072021-03-07 18:20:29 -0500320 }
321
322 auto gen = needs_encrypt ? makeGen(options) : neverGen();
323 KeyBuffer key;
324 if (!read_key(data_rec->metadata_key_dir, gen, &key)) return false;
325
326 std::string crypto_blkdev;
327 uint64_t nr_sec;
328 if (!create_crypto_blk_dev(kDmNameUserdata, blk_device, key, options, &crypto_blkdev, &nr_sec))
329 return false;
330
bigbiff7ba75002020-04-11 20:47:09 -0400331 // FIXME handle the corrupt case
332 if (needs_encrypt) {
333 LOG(INFO) << "Beginning inplace encryption, nr_sec: " << nr_sec;
334 off64_t size_already_done = 0;
335 auto rc = cryptfs_enable_inplace(crypto_blkdev.data(), blk_device.data(), nr_sec,
336 &size_already_done, nr_sec, 0, false);
337 if (rc != 0) {
338 LOG(ERROR) << "Inplace crypto failed with code: " << rc;
339 return false;
340 }
341 if (static_cast<uint64_t>(size_already_done) != nr_sec) {
342 LOG(ERROR) << "Inplace crypto only got up to sector: " << size_already_done;
343 return false;
344 }
345 LOG(INFO) << "Inplace encryption complete";
346 }
347
bigbiffa957f072021-03-07 18:20:29 -0500348 LOG(INFO) << "Mounting metadata-encrypted filesystem:" << mount_point;
349 mount_via_fs_mgr(mount_point.c_str(), crypto_blkdev.c_str());
bigbiff7ba75002020-04-11 20:47:09 -0400350 android::base::SetProperty("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
bigbiffa957f072021-03-07 18:20:29 -0500351
352 // Record that there's at least one fstab entry with metadata encryption
353 if (!android::base::SetProperty("ro.crypto.metadata.enabled", "true")) {
354 LOG(WARNING) << "failed to set ro.crypto.metadata.enabled"; // This isn't fatal
355 }
bigbiff7ba75002020-04-11 20:47:09 -0400356 return true;
357}
bigbiffa957f072021-03-07 18:20:29 -0500358
359static bool get_volume_options(CryptoOptions* options) {
360 return parse_options(android::base::GetProperty("ro.crypto.volume.metadata.encryption", ""),
361 options);
362}
363
364bool defaultkey_volume_keygen(KeyGeneration* gen) {
365 CryptoOptions options;
366 if (!get_volume_options(&options)) return false;
367 *gen = makeGen(options);
368 return true;
369}
370
371bool defaultkey_setup_ext_volume(const std::string& label, const std::string& blk_device,
372 const KeyBuffer& key, std::string* out_crypto_blkdev) {
373 LOG(ERROR) << "defaultkey_setup_ext_volume: " << label << " " << blk_device;
374
375 CryptoOptions options;
376 if (!get_volume_options(&options)) return false;
377 uint64_t nr_sec;
378 return create_crypto_blk_dev(label, blk_device, key, options, out_crypto_blkdev, &nr_sec);
379}