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