xref: /aosp_15_r20/system/vold/MetadataCrypt.cpp (revision f40fafd4c6c2594924d919feffc1a1fd6e3b30f3)
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 <fstream>
21 #include <string>
22 
23 #include <fcntl.h>
24 #include <sys/param.h>
25 #include <sys/stat.h>
26 #include <sys/types.h>
27 
28 #include <android-base/logging.h>
29 #include <android-base/properties.h>
30 #include <android-base/strings.h>
31 #include <android-base/unique_fd.h>
32 #include <cutils/fs.h>
33 #include <fs_mgr.h>
34 #include <libdm/dm.h>
35 #include <libgsi/libgsi.h>
36 
37 #include "Checkpoint.h"
38 #include "CryptoType.h"
39 #include "EncryptInplace.h"
40 #include "KeyStorage.h"
41 #include "KeyUtil.h"
42 #include "Keystore.h"
43 #include "Utils.h"
44 #include "VoldUtil.h"
45 #include "fs/Ext4.h"
46 #include "fs/F2fs.h"
47 
48 namespace android {
49 namespace vold {
50 
51 using android::base::Basename;
52 using android::fs_mgr::FstabEntry;
53 using android::fs_mgr::GetEntryForMountPoint;
54 using android::fscrypt::GetFirstApiLevel;
55 using android::vold::KeyBuffer;
56 using namespace android::dm;
57 using namespace std::chrono_literals;
58 
59 // Parsed from metadata options
60 struct CryptoOptions {
61     struct CryptoType cipher = invalid_crypto_type;
62     bool use_legacy_options_format = false;
63     bool set_dun = true;  // Non-legacy driver always sets DUN
64     bool use_hw_wrapped_key = false;
65 };
66 
67 static const std::string kDmNameUserdata = "userdata";
68 
69 // The first entry in this table is the default crypto type.
70 constexpr CryptoType supported_crypto_types[] = {aes_256_xts, adiantum};
71 
72 static_assert(validateSupportedCryptoTypes(64, supported_crypto_types,
73                                            array_length(supported_crypto_types)),
74               "We have a CryptoType which was incompletely constructed.");
75 
76 constexpr CryptoType legacy_aes_256_xts =
77         CryptoType().set_config_name("aes-256-xts").set_kernel_name("AES-256-XTS").set_keysize(64);
78 
79 static_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
makeGen(const CryptoOptions & options)83 const KeyGeneration makeGen(const CryptoOptions& options) {
84     return KeyGeneration{options.cipher.get_keysize(), true, options.use_hw_wrapped_key};
85 }
86 
defaultkey_precreate_dm_device()87 void defaultkey_precreate_dm_device() {
88     auto& dm = DeviceMapper::Instance();
89     if (dm.GetState(kDmNameUserdata) != DmDeviceState::INVALID) {
90         LOG(INFO) << "Not pre-creating userdata encryption device; device already exists";
91         return;
92     }
93 
94     if (!dm.CreatePlaceholderDevice(kDmNameUserdata)) {
95         LOG(ERROR) << "Failed to pre-create userdata metadata encryption device";
96     }
97 }
98 
mount_via_fs_mgr(const char * mount_point,const char * blk_device,bool needs_encrypt)99 static bool mount_via_fs_mgr(const char* mount_point, const char* blk_device, bool needs_encrypt) {
100     // fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
101     // partitions in the fsck domain.
102     if (setexeccon(android::vold::sFsckContext)) {
103         PLOG(ERROR) << "Failed to setexeccon";
104         return false;
105     }
106     auto mount_rc = fs_mgr_do_mount(&fstab_default, mount_point, blk_device,
107                                     android::vold::cp_needsCheckpoint(), needs_encrypt);
108     if (setexeccon(nullptr)) {
109         PLOG(ERROR) << "Failed to clear setexeccon";
110         return false;
111     }
112     if (mount_rc != 0) {
113         LOG(ERROR) << "fs_mgr_do_mount failed with rc " << mount_rc;
114         return false;
115     }
116     LOG(DEBUG) << "Mounted " << mount_point;
117     return true;
118 }
119 
read_key(const std::string & metadata_key_dir,const KeyGeneration & gen,bool first_key,KeyBuffer * key)120 static bool read_key(const std::string& metadata_key_dir, const KeyGeneration& gen, bool first_key,
121                      KeyBuffer* key) {
122     if (metadata_key_dir.empty()) {
123         LOG(ERROR) << "Failed to get metadata_key_dir";
124         return false;
125     }
126     std::string sKey;
127     auto dir = metadata_key_dir + "/key";
128     LOG(DEBUG) << "metadata_key_dir/key: " << dir;
129     if (!MkdirsSync(dir, 0700)) return false;
130     auto in_dsu = android::base::GetBoolProperty("ro.gsid.image_running", false);
131     // !pathExists(dir) does not imply there's a factory reset when in DSU mode.
132     if (!pathExists(dir) && !in_dsu && first_key) {
133         auto delete_all = android::base::GetBoolProperty(
134                 "ro.crypto.metadata_init_delete_all_keys.enabled", false);
135         if (delete_all) {
136             LOG(INFO) << "Metadata key does not exist, calling deleteAllKeys";
137             Keystore::deleteAllKeys();
138         } else {
139             LOG(DEBUG) << "Metadata key does not exist but "
140                           "ro.crypto.metadata_init_delete_all_keys.enabled is false";
141         }
142     }
143     auto temp = metadata_key_dir + "/tmp";
144     return retrieveOrGenerateKey(dir, temp, kEmptyAuthentication, gen, key);
145 }
146 
get_number_of_sectors(const std::string & real_blkdev,uint64_t * nr_sec)147 static bool get_number_of_sectors(const std::string& real_blkdev, uint64_t* nr_sec) {
148     if (android::vold::GetBlockDev512Sectors(real_blkdev, nr_sec) != android::OK) {
149         PLOG(ERROR) << "Unable to measure size of " << real_blkdev;
150         return false;
151     }
152     return true;
153 }
154 
create_crypto_blk_dev(const std::string & dm_name,const std::string & blk_device,const KeyBuffer & key,const CryptoOptions & options,std::string * crypto_blkdev,uint64_t * nr_sec,bool is_userdata)155 static bool create_crypto_blk_dev(const std::string& dm_name, const std::string& blk_device,
156                                   const KeyBuffer& key, const CryptoOptions& options,
157                                   std::string* crypto_blkdev, uint64_t* nr_sec, bool is_userdata) {
158     if (!get_number_of_sectors(blk_device, nr_sec)) return false;
159     // TODO(paulcrowley): don't hardcode that DmTargetDefaultKey uses 4096-byte
160     // sectors
161     *nr_sec &= ~7;
162 
163     KeyBuffer module_key;
164     if (options.use_hw_wrapped_key) {
165         if (!exportWrappedStorageKey(key, &module_key)) {
166             LOG(ERROR) << "Failed to get ephemeral wrapped key";
167             return false;
168         }
169     } else {
170         module_key = key;
171     }
172 
173     KeyBuffer hex_key_buffer;
174     if (android::vold::StrToHex(module_key, hex_key_buffer) != android::OK) {
175         LOG(ERROR) << "Failed to turn key to hex";
176         return false;
177     }
178     std::string hex_key(hex_key_buffer.data(), hex_key_buffer.size());
179 
180     auto target = std::make_unique<DmTargetDefaultKey>(0, *nr_sec, options.cipher.get_kernel_name(),
181                                                        hex_key, blk_device, 0);
182     if (options.use_legacy_options_format) target->SetUseLegacyOptionsFormat();
183     if (options.set_dun) target->SetSetDun();
184     if (options.use_hw_wrapped_key) target->SetWrappedKeyV0();
185 
186     DmTable table;
187     table.AddTarget(std::move(target));
188 
189     auto& dm = DeviceMapper::Instance();
190     if (dm_name == kDmNameUserdata && dm.GetState(dm_name) == DmDeviceState::SUSPENDED) {
191         // The device was created in advance, populate it now.
192         if (!dm.LoadTableAndActivate(dm_name, table)) {
193             LOG(ERROR) << "Failed to populate default-key device " << dm_name;
194             return false;
195         }
196         if (!dm.WaitForDevice(dm_name, 20s, crypto_blkdev)) {
197             LOG(ERROR) << "Failed to wait for default-key device " << dm_name;
198             return false;
199         }
200     } else if (!dm.CreateDevice(dm_name, table, crypto_blkdev, 5s)) {
201         LOG(ERROR) << "Could not create default-key device " << dm_name;
202         return false;
203     }
204 
205     // If there are multiple partitions used for a single mount, F2FS stores
206     // their partition paths in superblock. If the paths are dm targets, we
207     // cannot guarantee them across device boots. Let's use the logical paths.
208     if (is_userdata) {
209         *crypto_blkdev = "/dev/block/mapper/" + dm_name;
210     }
211     return true;
212 }
213 
lookup_cipher(const std::string & cipher_name)214 static const CryptoType& lookup_cipher(const std::string& cipher_name) {
215     if (cipher_name.empty()) return supported_crypto_types[0];
216     for (size_t i = 0; i < array_length(supported_crypto_types); i++) {
217         if (cipher_name == supported_crypto_types[i].get_config_name()) {
218             return supported_crypto_types[i];
219         }
220     }
221     return invalid_crypto_type;
222 }
223 
parse_options(const std::string & options_string,CryptoOptions * options)224 static bool parse_options(const std::string& options_string, CryptoOptions* options) {
225     auto parts = android::base::Split(options_string, ":");
226     if (parts.size() < 1 || parts.size() > 2) {
227         LOG(ERROR) << "Invalid metadata encryption option: " << options_string;
228         return false;
229     }
230     std::string cipher_name = parts[0];
231     options->cipher = lookup_cipher(cipher_name);
232     if (options->cipher.get_kernel_name() == nullptr) {
233         LOG(ERROR) << "No metadata cipher named " << cipher_name << " found";
234         return false;
235     }
236 
237     if (parts.size() == 2) {
238         if (parts[1] == "wrappedkey_v0") {
239             options->use_hw_wrapped_key = true;
240         } else {
241             LOG(ERROR) << "Invalid metadata encryption flag: " << parts[1];
242             return false;
243         }
244     }
245     return true;
246 }
247 
248 class EncryptionInProgress {
249   private:
250     std::string file_path_;
251     bool need_cleanup_ = false;
252 
253   public:
EncryptionInProgress(const FstabEntry & entry)254     EncryptionInProgress(const FstabEntry& entry) {
255         file_path_ = fs_mgr_metadata_encryption_in_progress_file_name(entry);
256     }
257 
Mark()258     [[nodiscard]] bool Mark() {
259         {
260             std::ofstream touch(file_path_);
261             if (!touch.is_open()) {
262                 PLOG(ERROR) << "Failed to mark metadata encryption in progress " << file_path_;
263                 return false;
264             }
265             need_cleanup_ = true;
266         }
267         if (!android::vold::FsyncParentDirectory(file_path_)) return false;
268 
269         LOG(INFO) << "Marked metadata encryption in progress (" << file_path_ << ")";
270         return true;
271     }
272 
Remove()273     [[nodiscard]] bool Remove() {
274         need_cleanup_ = false;
275         if (unlink(file_path_.c_str()) != 0) {
276             PLOG(ERROR) << "Failed to clear metadata encryption in progress (" << file_path_ << ")";
277             return false;
278         }
279         if (!android::vold::FsyncParentDirectory(file_path_)) return false;
280 
281         LOG(INFO) << "Cleared metadata encryption in progress (" << file_path_ << ")";
282         return true;
283     }
284 
~EncryptionInProgress()285     ~EncryptionInProgress() {
286         if (need_cleanup_) (void)Remove();
287     }
288 };
289 
fscrypt_mount_metadata_encrypted(const std::string & blk_device,const std::string & mount_point,bool needs_encrypt,bool should_format,const std::string & fs_type,bool is_zoned,const std::vector<std::string> & user_devices,const std::vector<bool> & device_aliased,int64_t length)290 bool fscrypt_mount_metadata_encrypted(const std::string& blk_device, const std::string& mount_point,
291                                       bool needs_encrypt, bool should_format,
292                                       const std::string& fs_type, bool is_zoned,
293                                       const std::vector<std::string>& user_devices,
294                                       const std::vector<bool>& device_aliased, int64_t length) {
295     LOG(DEBUG) << "fscrypt_mount_metadata_encrypted: " << mount_point
296                << " encrypt: " << needs_encrypt << " format: " << should_format << " with "
297                << fs_type << " block device: " << blk_device << " with zoned " << is_zoned
298                << " length: " << length;
299 
300     for (auto& device : user_devices) {
301         LOG(DEBUG) << " - user devices: " << device;
302     }
303 
304     auto encrypted_state = android::base::GetProperty("ro.crypto.state", "");
305     if (encrypted_state != "" && encrypted_state != "encrypted") {
306         LOG(ERROR) << "fscrypt_mount_metadata_encrypted got unexpected starting state: "
307                    << encrypted_state;
308         return false;
309     }
310 
311     auto data_rec = GetEntryForMountPoint(&fstab_default, mount_point);
312     if (!data_rec) {
313         LOG(ERROR) << "Failed to get data_rec for " << mount_point;
314         return false;
315     }
316 
317     unsigned int options_format_version = android::base::GetUintProperty<unsigned int>(
318             "ro.crypto.dm_default_key.options_format.version",
319             (GetFirstApiLevel() <= __ANDROID_API_Q__ ? 1 : 2));
320 
321     CryptoOptions options;
322     if (options_format_version == 1) {
323         if (!data_rec->metadata_encryption_options.empty()) {
324             LOG(ERROR) << "metadata_encryption options cannot be set in legacy mode";
325             return false;
326         }
327         options.cipher = legacy_aes_256_xts;
328         options.use_legacy_options_format = true;
329         options.set_dun = android::base::GetBoolProperty("ro.crypto.set_dun", false);
330         if (!options.set_dun && data_rec->fs_mgr_flags.checkpoint_blk) {
331             LOG(ERROR)
332                     << "Block checkpoints and metadata encryption require ro.crypto.set_dun option";
333             return false;
334         }
335     } else if (options_format_version == 2) {
336         if (!parse_options(data_rec->metadata_encryption_options, &options)) return false;
337     } else {
338         LOG(ERROR) << "Unknown options_format_version: " << options_format_version;
339         return false;
340     }
341 
342     auto default_metadata_key_dir = data_rec->metadata_key_dir;
343     if (!user_devices.empty()) {
344         default_metadata_key_dir = default_metadata_key_dir + "/default";
345     }
346     auto gen = needs_encrypt ? makeGen(options) : neverGen();
347     KeyBuffer key;
348     if (!read_key(default_metadata_key_dir, gen, true, &key)) {
349         LOG(ERROR) << "read_key failed in mountFstab";
350         return false;
351     }
352 
353     std::string crypto_blkdev;
354     uint64_t nr_sec;
355     if (!create_crypto_blk_dev(kDmNameUserdata, blk_device, key, options, &crypto_blkdev, &nr_sec,
356                                true)) {
357         LOG(ERROR) << "create_crypto_blk_dev failed in mountFstab";
358         return false;
359     }
360 
361     // create dm-default-key for user devices
362     std::vector<std::string> crypto_user_blkdev;
363     for (auto& device : user_devices) {
364         std::string name = Basename(device);
365         auto metadata_key_dir = data_rec->metadata_key_dir + "/" + name;
366 
367         if (!read_key(metadata_key_dir, gen, false, &key)) {
368             LOG(ERROR) << "read_key failed with zoned device: " << device;
369             return false;
370         }
371         std::string crypto_blkdev_arg;
372         if (!create_crypto_blk_dev(name, device, key, options, &crypto_blkdev_arg, &nr_sec, true)) {
373             LOG(ERROR) << "fscrypt_mount_metadata_encrypted: failed with device: " << device;
374             return false;
375         }
376         crypto_user_blkdev.push_back(crypto_blkdev_arg.c_str());
377     }
378 
379     if (needs_encrypt) {
380         EncryptionInProgress marker(*data_rec);
381         if (!marker.Mark()) return false;
382         if (should_format) {
383             status_t error;
384 
385             if (fs_type == "ext4") {
386                 error = ext4::Format(crypto_blkdev, 0, mount_point);
387             } else if (fs_type == "f2fs") {
388                 error = f2fs::Format(crypto_blkdev, is_zoned, crypto_user_blkdev, device_aliased,
389                                      length);
390             } else {
391                 LOG(ERROR) << "Unknown filesystem type: " << fs_type;
392                 return false;
393             }
394             if (error != 0) {
395                 LOG(ERROR) << "Format of " << crypto_blkdev << " for " << mount_point
396                            << " failed (err=" << error << ").";
397                 return false;
398             }
399             LOG(DEBUG) << "Format of " << crypto_blkdev << " for " << mount_point << " succeeded.";
400         } else {
401             if (!user_devices.empty()) {
402                 LOG(ERROR) << "encrypt_inplace cannot support zoned or userdata_exp device; should "
403                               "format it.";
404                 return false;
405             }
406             if (!encrypt_inplace(crypto_blkdev, blk_device, nr_sec)) {
407                 LOG(ERROR) << "encrypt_inplace failed in mountFstab";
408                 return false;
409             }
410         }
411         if (!marker.Remove()) return false;
412     }
413 
414     LOG(DEBUG) << "Mounting metadata-encrypted filesystem:" << mount_point;
415     mount_via_fs_mgr(mount_point.c_str(), crypto_blkdev.c_str(), needs_encrypt);
416 
417     // Record that there's at least one fstab entry with metadata encryption
418     if (!android::base::SetProperty("ro.crypto.metadata.enabled", "true")) {
419         LOG(WARNING) << "failed to set ro.crypto.metadata.enabled";  // This isn't fatal
420     }
421     return true;
422 }
423 
get_volume_options(CryptoOptions * options)424 static bool get_volume_options(CryptoOptions* options) {
425     return parse_options(android::base::GetProperty("ro.crypto.volume.metadata.encryption", ""),
426                          options);
427 }
428 
defaultkey_volume_keygen(KeyGeneration * gen)429 bool defaultkey_volume_keygen(KeyGeneration* gen) {
430     CryptoOptions options;
431     if (!get_volume_options(&options)) return false;
432     *gen = makeGen(options);
433     return true;
434 }
435 
defaultkey_setup_ext_volume(const std::string & label,const std::string & blk_device,const KeyBuffer & key,std::string * out_crypto_blkdev)436 bool defaultkey_setup_ext_volume(const std::string& label, const std::string& blk_device,
437                                  const KeyBuffer& key, std::string* out_crypto_blkdev) {
438     LOG(DEBUG) << "defaultkey_setup_ext_volume: " << label << " " << blk_device;
439 
440     CryptoOptions options;
441     if (!get_volume_options(&options)) return false;
442     uint64_t nr_sec;
443     return create_crypto_blk_dev(label, blk_device, key, options, out_crypto_blkdev, &nr_sec,
444                                  false);
445 }
446 
destroy_dsu_metadata_key(const std::string & dsu_slot)447 bool destroy_dsu_metadata_key(const std::string& dsu_slot) {
448     LOG(DEBUG) << "destroy_dsu_metadata_key: " << dsu_slot;
449 
450     const auto dsu_metadata_key_dir = android::gsi::GetDsuMetadataKeyDir(dsu_slot);
451     if (!pathExists(dsu_metadata_key_dir)) {
452         LOG(DEBUG) << "DSU metadata_key_dir doesn't exist, nothing to remove: "
453                    << dsu_metadata_key_dir;
454         return true;
455     }
456 
457     // Ensure that the DSU key directory is different from the host OS'.
458     // Under normal circumstances, this should never happen, but handle it just in case.
459     if (auto data_rec = GetEntryForMountPoint(&fstab_default, "/data")) {
460         if (dsu_metadata_key_dir == data_rec->metadata_key_dir) {
461             LOG(ERROR) << "DSU metadata_key_dir is same as host OS: " << dsu_metadata_key_dir;
462             return false;
463         }
464     }
465 
466     bool ok = true;
467     for (auto suffix : {"/key", "/tmp"}) {
468         const auto key_path = dsu_metadata_key_dir + suffix;
469         if (pathExists(key_path)) {
470             LOG(DEBUG) << "Destroy key: " << key_path;
471             if (!android::vold::destroyKey(key_path)) {
472                 LOG(ERROR) << "Failed to destroyKey(): " << key_path;
473                 ok = false;
474             }
475         }
476     }
477     if (!ok) {
478         return false;
479     }
480 
481     LOG(DEBUG) << "Remove DSU metadata_key_dir: " << dsu_metadata_key_dir;
482     // DeleteDirContentsAndDir() already logged any error, so don't log repeatedly.
483     return android::vold::DeleteDirContentsAndDir(dsu_metadata_key_dir) == android::OK;
484 }
485 
486 }  // namespace vold
487 }  // namespace android
488