1 /*
2 * Copyright (C) 2020 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 //
18 // Test that file contents encryption is working, via:
19 //
20 // - Correctness tests. These test the standard FBE settings supported by
21 // Android R and higher.
22 //
23 // - Randomness test. This runs on all devices that use FBE, even old ones.
24 //
25 // The correctness tests cover the following settings:
26 //
27 // fileencryption=aes-256-xts:aes-256-cts:v2
28 // fileencryption=aes-256-xts:aes-256-cts:v2+inlinecrypt_optimized
29 // fileencryption=aes-256-xts:aes-256-cts:v2+inlinecrypt_optimized+wrappedkey_v0
30 // fileencryption=aes-256-xts:aes-256-cts:v2+emmc_optimized
31 // fileencryption=aes-256-xts:aes-256-cts:v2+emmc_optimized+wrappedkey_v0
32 // fileencryption=adiantum:adiantum:v2
33 //
34 // On devices launching with R or higher those are equivalent to simply:
35 //
36 // fileencryption=
37 // fileencryption=::inlinecrypt_optimized
38 // fileencryption=::inlinecrypt_optimized+wrappedkey_v0
39 // fileencryption=::emmc_optimized
40 // fileencryption=::emmc_optimized+wrappedkey_v0
41 // fileencryption=adiantum
42 //
43 // The tests don't check which one of those settings, if any, the device is
44 // actually using; they just try to test everything they can.
45 // "fileencryption=aes-256-xts" is guaranteed to be available if the kernel
46 // supports any "fscrypt v2" features at all. The others may not be available,
47 // so the tests take that into account and skip testing them when unavailable.
48 //
49 // None of these tests should ever fail. In particular, vendors must not break
50 // any standard FBE settings, regardless of what the device actually uses. If
51 // any test fails, make sure to check things like the byte order of keys.
52 //
53
54 #include <android-base/file.h>
55 #include <android-base/properties.h>
56 #include <android-base/stringprintf.h>
57 #include <android-base/unique_fd.h>
58 #include <asm/byteorder.h>
59 #include <errno.h>
60 #include <fcntl.h>
61 #include <gtest/gtest.h>
62 #include <limits.h>
63 #include <linux/f2fs.h>
64 #include <linux/fiemap.h>
65 #include <linux/fs.h>
66 #include <linux/fscrypt.h>
67 #include <lz4.h>
68 #include <openssl/evp.h>
69 #include <openssl/hkdf.h>
70 #include <openssl/siphash.h>
71 #include <stdlib.h>
72 #include <string.h>
73 #include <sys/ioctl.h>
74 #include <unistd.h>
75
76 #include <chrono>
77 #include <thread>
78
79 #include "vts_kernel_encryption.h"
80
81 /* These values are missing from <linux/f2fs.h> */
82 enum f2fs_compress_algorithm {
83 F2FS_COMPRESS_LZO,
84 F2FS_COMPRESS_LZ4,
85 F2FS_COMPRESS_ZSTD,
86 F2FS_COMPRESS_LZORLE,
87 F2FS_COMPRESS_MAX,
88 };
89
90 namespace android {
91 namespace kernel {
92
93 // The main mountpoint of the filesystem the test will use to test FBE.
94 constexpr const char *kTestMountpoint = "/data";
95
96 // A directory on the kTestMountpoint filesystem that doesn't already have an
97 // encryption policy, and therefore allows the creation of subdirectories with
98 // custom encryption policies.
99 constexpr const char *kUnencryptedDir = "/data/unencrypted";
100
101 // A directory on the kTestMountpoint filesystem that already has an encryption
102 // policy. Any files created in this directory will be encrypted using the
103 // encryption settings that Android is configured to use.
104 constexpr const char *kTmpDir = "/data/local/tmp";
105
106 // Assumed size of filesystem blocks, in bytes
107 constexpr int kFilesystemBlockSize = 4096;
108
109 // Size of the test file in filesystem blocks
110 constexpr int kTestFileBlocks = 256;
111
112 // Size of the test file in bytes
113 constexpr int kTestFileBytes = kFilesystemBlockSize * kTestFileBlocks;
114
115 // fscrypt master key size in bytes
116 constexpr int kFscryptMasterKeySize = 64;
117
118 // fscrypt maximum IV size in bytes
119 constexpr int kFscryptMaxIVSize = 32;
120
121 // fscrypt per-file nonce size in bytes
122 constexpr int kFscryptFileNonceSize = 16;
123
124 // fscrypt HKDF context bytes, from kernel fs/crypto/fscrypt_private.h
125 enum FscryptHkdfContext {
126 HKDF_CONTEXT_KEY_IDENTIFIER = 1,
127 HKDF_CONTEXT_PER_FILE_ENC_KEY = 2,
128 HKDF_CONTEXT_DIRECT_KEY = 3,
129 HKDF_CONTEXT_IV_INO_LBLK_64_KEY = 4,
130 HKDF_CONTEXT_DIRHASH_KEY = 5,
131 HKDF_CONTEXT_IV_INO_LBLK_32_KEY = 6,
132 HKDF_CONTEXT_INODE_HASH_KEY = 7,
133 };
134
135 struct FscryptFileNonce {
136 uint8_t bytes[kFscryptFileNonceSize];
137 };
138
139 // Format of the initialization vector
140 union FscryptIV {
141 struct {
142 __le32 lblk_num; // file logical block number, starts at 0
143 __le32 inode_number; // only used for IV_INO_LBLK_64
144 uint8_t file_nonce[kFscryptFileNonceSize]; // only used for DIRECT_KEY
145 };
146 uint8_t bytes[kFscryptMaxIVSize];
147 };
148
149 struct TestFileInfo {
150 std::vector<uint8_t> plaintext;
151 std::vector<uint8_t> actual_ciphertext;
152 uint64_t inode_number;
153 FscryptFileNonce nonce;
154 };
155
GetInodeNumber(const std::string & path,uint64_t * inode_number)156 static bool GetInodeNumber(const std::string &path, uint64_t *inode_number) {
157 struct stat stbuf;
158 if (stat(path.c_str(), &stbuf) != 0) {
159 ADD_FAILURE() << "Failed to stat " << path << Errno();
160 return false;
161 }
162 *inode_number = stbuf.st_ino;
163 return true;
164 }
165
166 //
167 // Checks whether the kernel has support for the following fscrypt features:
168 //
169 // - Filesystem-level keyring (FS_IOC_ADD_ENCRYPTION_KEY and
170 // FS_IOC_REMOVE_ENCRYPTION_KEY)
171 // - v2 encryption policies
172 // - The IV_INO_LBLK_64 encryption policy flag
173 // - The FS_IOC_GET_ENCRYPTION_NONCE ioctl
174 // - The IV_INO_LBLK_32 encryption policy flag
175 //
176 // To do this it's sufficient to just check whether FS_IOC_ADD_ENCRYPTION_KEY is
177 // available, as the other features were added in the same AOSP release.
178 //
179 // The easiest way to do this is to just execute the ioctl with a NULL argument.
180 // If available it will fail with EFAULT; otherwise it will fail with ENOTTY (or
181 // EOPNOTSUPP if encryption isn't enabled on the filesystem; that happens on old
182 // devices that aren't using FBE and are upgraded to a new kernel).
183 //
IsFscryptV2Supported(const std::string & mountpoint)184 static bool IsFscryptV2Supported(const std::string &mountpoint) {
185 android::base::unique_fd fd(
186 open(mountpoint.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
187 if (fd < 0) {
188 ADD_FAILURE() << "Failed to open " << mountpoint << Errno();
189 return false;
190 }
191
192 if (ioctl(fd, FS_IOC_ADD_ENCRYPTION_KEY, nullptr) == 0) {
193 ADD_FAILURE()
194 << "FS_IOC_ADD_ENCRYPTION_KEY(nullptr) unexpectedly succeeded on "
195 << mountpoint;
196 return false;
197 }
198 switch (errno) {
199 case EFAULT:
200 return true;
201 case EOPNOTSUPP:
202 case ENOTTY:
203 GTEST_LOG_(INFO) << "No support for FS_IOC_ADD_ENCRYPTION_KEY on "
204 << mountpoint;
205 return false;
206 default:
207 ADD_FAILURE()
208 << "Unexpected error from FS_IOC_ADD_ENCRYPTION_KEY(nullptr) on "
209 << mountpoint << Errno();
210 return false;
211 }
212 }
213
214 // Helper class to freeze / unfreeze a filesystem, to prevent the filesystem
215 // from moving the file's blocks while the test is accessing them via the
216 // underlying device. ext4 doesn't need this, but f2fs does because f2fs does
217 // background garbage collection. We cannot use F2FS_IOC_SET_PIN_FILE because
218 // F2FS_IOC_SET_PIN_FILE doesn't support compressed files.
219 //
220 // The fd given can be any fd to a file or directory on the filesystem.
221 // FIFREEZE operates on the whole filesystem, not on the individual file given.
222 class ScopedFsFreezer {
223 public:
ScopedFsFreezer(int fd)224 explicit ScopedFsFreezer(int fd) {
225 auto start = std::chrono::steady_clock::now();
226 do {
227 if (ioctl(fd, FIFREEZE, NULL) == 0) {
228 fd_ = fd;
229 return;
230 }
231 if (errno == EBUSY || errno == EINVAL) {
232 // EBUSY means the filesystem is already frozen, perhaps by a concurrent
233 // execution of this same test. Since we don't have control over
234 // exactly when another process unfreezes the filesystem, we don't
235 // continue on with the test but rather just keep retrying the freeze
236 // until it works.
237 //
238 // Very rarely, on f2fs FIFREEZE fails with EINVAL (b/255800104).
239 // Unfortunately, the reason for this is still unknown. Enter the retry
240 // loop in this case too, in the hope that it helps.
241 //
242 // Both of these errors are rare, so this sleep should not normally be
243 // executed.
244 std::this_thread::sleep_for(std::chrono::milliseconds(100));
245 continue;
246 }
247 ADD_FAILURE() << "Failed to freeze filesystem" << Errno();
248 return;
249 } while (std::chrono::steady_clock::now() - start <
250 std::chrono::seconds(20));
251 ADD_FAILURE() << "Timed out while waiting to freeze filesystem";
252 }
253
~ScopedFsFreezer()254 ~ScopedFsFreezer() {
255 if (fd_ != -1 && ioctl(fd_, FITHAW, NULL) != 0) {
256 ADD_FAILURE() << "Failed to thaw filesystem" << Errno();
257 }
258 }
259
260 private:
261 int fd_ = -1;
262 };
263
264 // Reads the raw data of the file specified by |fd| from its underlying block
265 // device |blk_device|. The file has |expected_data_size| bytes of initialized
266 // data; this must be a multiple of the filesystem block size
267 // kFilesystemBlockSize. The file may contain holes, in which case only the
268 // non-holes are read; the holes are not counted in |expected_data_size|.
ReadRawDataOfFile(int fd,const std::string & blk_device,int expected_data_size,std::vector<uint8_t> * raw_data)269 static bool ReadRawDataOfFile(int fd, const std::string &blk_device,
270 int expected_data_size,
271 std::vector<uint8_t> *raw_data) {
272 int max_extents = expected_data_size / kFilesystemBlockSize;
273
274 EXPECT_TRUE(expected_data_size % kFilesystemBlockSize == 0);
275
276 if (fsync(fd) != 0) {
277 ADD_FAILURE() << "Failed to sync file" << Errno();
278 return false;
279 }
280
281 // Freeze the filesystem containing the file.
282 ScopedFsFreezer freezer(fd);
283
284 // Query the file's extents.
285 size_t allocsize = offsetof(struct fiemap, fm_extents[max_extents]);
286 std::unique_ptr<struct fiemap> map(
287 new (::operator new(allocsize)) struct fiemap);
288 memset(map.get(), 0, allocsize);
289 map->fm_flags = 0;
290 map->fm_length = UINT64_MAX;
291 map->fm_extent_count = max_extents;
292 if (ioctl(fd, FS_IOC_FIEMAP, map.get()) != 0) {
293 ADD_FAILURE() << "Failed to get extents of file" << Errno();
294 return false;
295 }
296
297 // Read the raw data, using direct I/O to avoid getting any stale cached data.
298 // Direct I/O requires using a block size aligned buffer.
299
300 std::unique_ptr<void, void (*)(void *)> buf_mem(
301 aligned_alloc(kFilesystemBlockSize, expected_data_size), free);
302 if (buf_mem == nullptr) {
303 ADD_FAILURE() << "Out of memory";
304 return false;
305 }
306 uint8_t *buf = static_cast<uint8_t *>(buf_mem.get());
307 int offset = 0;
308
309 android::base::unique_fd blk_fd(
310 open(blk_device.c_str(), O_RDONLY | O_DIRECT | O_CLOEXEC));
311 if (blk_fd < 0) {
312 ADD_FAILURE() << "Failed to open raw block device " << blk_device
313 << Errno();
314 return false;
315 }
316
317 for (int i = 0; i < map->fm_mapped_extents; i++) {
318 const struct fiemap_extent &extent = map->fm_extents[i];
319
320 GTEST_LOG_(INFO) << "Extent " << i + 1 << " of " << map->fm_mapped_extents
321 << " is logical offset " << extent.fe_logical
322 << ", physical offset " << extent.fe_physical
323 << ", length " << extent.fe_length << ", flags 0x"
324 << std::hex << extent.fe_flags << std::dec;
325 // Make sure the flags indicate that fe_physical is actually valid.
326 if (extent.fe_flags & (FIEMAP_EXTENT_UNKNOWN | FIEMAP_EXTENT_UNWRITTEN)) {
327 ADD_FAILURE() << "Unsupported extent flags: 0x" << std::hex
328 << extent.fe_flags << std::dec;
329 return false;
330 }
331 if (extent.fe_length % kFilesystemBlockSize != 0) {
332 ADD_FAILURE() << "Extent is not aligned to filesystem block size";
333 return false;
334 }
335 if (extent.fe_length > expected_data_size - offset) {
336 ADD_FAILURE() << "File is longer than expected";
337 return false;
338 }
339 if (pread(blk_fd, &buf[offset], extent.fe_length, extent.fe_physical) !=
340 extent.fe_length) {
341 ADD_FAILURE() << "Error reading raw data from block device" << Errno();
342 return false;
343 }
344 offset += extent.fe_length;
345 }
346 if (offset != expected_data_size) {
347 ADD_FAILURE() << "File is shorter than expected";
348 return false;
349 }
350 *raw_data = std::vector<uint8_t>(&buf[0], &buf[offset]);
351 return true;
352 }
353
354 // Writes |plaintext| to a file |path| located on the block device |blk_device|.
355 // Returns in |ciphertext| the file's raw ciphertext read from |blk_device|.
WriteTestFile(const std::vector<uint8_t> & plaintext,const std::string & path,const std::string & blk_device,const struct f2fs_comp_option * compress_options,std::vector<uint8_t> * ciphertext)356 static bool WriteTestFile(const std::vector<uint8_t> &plaintext,
357 const std::string &path,
358 const std::string &blk_device,
359 const struct f2fs_comp_option *compress_options,
360 std::vector<uint8_t> *ciphertext) {
361 GTEST_LOG_(INFO) << "Creating test file " << path << " containing "
362 << plaintext.size() << " bytes of data";
363 android::base::unique_fd fd(
364 open(path.c_str(), O_WRONLY | O_CREAT | O_CLOEXEC, 0600));
365 if (fd < 0) {
366 ADD_FAILURE() << "Failed to create " << path << Errno();
367 return false;
368 }
369
370 if (compress_options != nullptr) {
371 if (ioctl(fd, F2FS_IOC_SET_COMPRESS_OPTION, compress_options) != 0) {
372 ADD_FAILURE() << "Error setting compression options on " << path
373 << Errno();
374 return false;
375 }
376 }
377
378 if (!android::base::WriteFully(fd, plaintext.data(), plaintext.size())) {
379 ADD_FAILURE() << "Error writing to " << path << Errno();
380 return false;
381 }
382
383 if (compress_options != nullptr) {
384 // With compress_mode=user, files in a compressed directory inherit the
385 // compression flag but aren't actually compressed unless
386 // F2FS_IOC_COMPRESS_FILE is called. The ioctl compresses existing data
387 // only, so it must be called *after* writing the data. With
388 // compress_mode=fs, the ioctl is unnecessary and fails with EOPNOTSUPP.
389 if (ioctl(fd, F2FS_IOC_COMPRESS_FILE, NULL) != 0 && errno != EOPNOTSUPP) {
390 ADD_FAILURE() << "F2FS_IOC_COMPRESS_FILE failed on " << path << Errno();
391 return false;
392 }
393 }
394
395 GTEST_LOG_(INFO) << "Reading the raw ciphertext of " << path << " from disk";
396 if (!ReadRawDataOfFile(fd, blk_device, plaintext.size(), ciphertext)) {
397 ADD_FAILURE() << "Failed to read the raw ciphertext of " << path;
398 return false;
399 }
400 return true;
401 }
402
403 // See MakeSomeCompressibleClusters() for explanation.
IsCompressibleCluster(int cluster_num)404 static bool IsCompressibleCluster(int cluster_num) {
405 return cluster_num % 2 == 0;
406 }
407
408 // Given some random data that will be written to the test file, modifies every
409 // other compression cluster to be compressible by at least 1 filesystem block.
410 //
411 // This testing strategy is adapted from the xfstest "f2fs/002". We use some
412 // compressible clusters and some incompressible clusters because we want to
413 // test that the encryption works correctly with both. We also don't make the
414 // data *too* compressible, since we want to have enough compressed blocks in
415 // each cluster to see the IVs being incremented.
MakeSomeCompressibleClusters(std::vector<uint8_t> & bytes,int log_cluster_size)416 static bool MakeSomeCompressibleClusters(std::vector<uint8_t> &bytes,
417 int log_cluster_size) {
418 int cluster_bytes = kFilesystemBlockSize << log_cluster_size;
419 if (bytes.size() % cluster_bytes != 0) {
420 ADD_FAILURE() << "Test file size (" << bytes.size()
421 << " bytes) is not divisible by compression cluster size ("
422 << cluster_bytes << " bytes)";
423 return false;
424 }
425 int num_clusters = bytes.size() / cluster_bytes;
426 for (int i = 0; i < num_clusters; i++) {
427 if (IsCompressibleCluster(i)) {
428 memset(&bytes[i * cluster_bytes], 0, 2 * kFilesystemBlockSize);
429 }
430 }
431 return true;
432 }
433
434 // On-disk format of an f2fs compressed cluster
435 struct f2fs_compressed_cluster {
436 __le32 clen;
437 __le32 reserved[5];
438 uint8_t cdata[];
439 } __attribute__((packed));
440
DecompressLZ4Cluster(const uint8_t * in,uint8_t * out,int cluster_bytes)441 static bool DecompressLZ4Cluster(const uint8_t *in, uint8_t *out,
442 int cluster_bytes) {
443 const struct f2fs_compressed_cluster *cluster =
444 reinterpret_cast<const struct f2fs_compressed_cluster *>(in);
445 uint32_t clen = __le32_to_cpu(cluster->clen);
446
447 if (clen > cluster_bytes - kFilesystemBlockSize - sizeof(*cluster)) {
448 ADD_FAILURE() << "Invalid compressed cluster (bad compressed size)";
449 return false;
450 }
451 if (LZ4_decompress_safe(reinterpret_cast<const char *>(cluster->cdata),
452 reinterpret_cast<char *>(out), clen,
453 cluster_bytes) != cluster_bytes) {
454 ADD_FAILURE() << "Invalid compressed cluster (LZ4 decompression error)";
455 return false;
456 }
457
458 // As long as we're here, do a regression test for kernel commit 7fa6d59816e7
459 // ("f2fs: fix leaking uninitialized memory in compressed clusters").
460 // Note that if this fails, we can still continue with the rest of the test.
461 size_t full_clen = offsetof(struct f2fs_compressed_cluster, cdata[clen]);
462 if (full_clen % kFilesystemBlockSize != 0) {
463 size_t remainder =
464 kFilesystemBlockSize - (full_clen % kFilesystemBlockSize);
465 std::vector<uint8_t> zeroes(remainder, 0);
466 std::vector<uint8_t> actual(&cluster->cdata[clen],
467 &cluster->cdata[clen + remainder]);
468 EXPECT_EQ(zeroes, actual);
469 }
470 return true;
471 }
472
473 class FBEPolicyTest : public ::testing::Test {
474 protected:
475 void SetUp() override;
476 void TearDown() override;
477 bool SetMasterKey(const std::vector<uint8_t> &master_key, uint32_t flags = 0,
478 bool required = true);
479 bool CreateAndSetHwWrappedKey(std::vector<uint8_t> *enc_key,
480 std::vector<uint8_t> *sw_secret);
481 int GetSkipFlagsForInoBasedEncryption();
482 bool SetEncryptionPolicy(int contents_mode, int filenames_mode, int flags,
483 int skip_flags);
484 bool GenerateTestFile(
485 TestFileInfo *info,
486 const struct f2fs_comp_option *compress_options = nullptr);
487 bool VerifyKeyIdentifier(const std::vector<uint8_t> &master_key);
488 bool DerivePerModeEncryptionKey(const std::vector<uint8_t> &master_key,
489 int mode, FscryptHkdfContext context,
490 std::vector<uint8_t> &enc_key);
491 bool DerivePerFileEncryptionKey(const std::vector<uint8_t> &master_key,
492 const FscryptFileNonce &nonce,
493 std::vector<uint8_t> &enc_key);
494 void VerifyCiphertext(const std::vector<uint8_t> &enc_key,
495 const FscryptIV &starting_iv, const Cipher &cipher,
496 const TestFileInfo &file_info);
497 void TestEmmcOptimizedDunWraparound(const std::vector<uint8_t> &master_key,
498 const std::vector<uint8_t> &enc_key);
499 bool EnableF2fsCompressionOnTestDir();
500 bool F2fsCompressOptionsSupported(const struct f2fs_comp_option &opts);
501 std::string test_dir_;
502 std::string test_file_;
503 struct fscrypt_key_specifier master_key_specifier_;
504 bool skip_test_ = false;
505 bool key_added_ = false;
506 FilesystemInfo fs_info_;
507 };
508
509 // Test setup procedure. Creates a test directory test_dir_ and does other
510 // preparations. skip_test_ is set to true if the test should be skipped.
SetUp()511 void FBEPolicyTest::SetUp() {
512 if (!IsFscryptV2Supported(kTestMountpoint)) {
513 int first_api_level;
514 ASSERT_TRUE(GetFirstApiLevel(&first_api_level));
515 // Devices launching with R or higher must support fscrypt v2.
516 ASSERT_LE(first_api_level, __ANDROID_API_Q__);
517 GTEST_LOG_(INFO) << "Skipping test because fscrypt v2 is unsupported";
518 skip_test_ = true;
519 return;
520 }
521
522 // Make sure that if multiple test processes run simultaneously, they generate
523 // different encryption keys.
524 srand(getpid());
525
526 test_dir_ = android::base::StringPrintf("%s/FBEPolicyTest.%d",
527 kUnencryptedDir, getpid());
528 test_file_ = test_dir_ + "/file";
529
530 ASSERT_TRUE(GetFilesystemInfo(kTestMountpoint, &fs_info_));
531
532 DeleteRecursively(test_dir_);
533 if (mkdir(test_dir_.c_str(), 0700) != 0) {
534 FAIL() << "Failed to create " << test_dir_ << Errno();
535 }
536 }
537
TearDown()538 void FBEPolicyTest::TearDown() {
539 DeleteRecursively(test_dir_);
540
541 // Remove the test key from kTestMountpoint.
542 if (key_added_) {
543 android::base::unique_fd mntfd(
544 open(kTestMountpoint, O_RDONLY | O_DIRECTORY | O_CLOEXEC));
545 if (mntfd < 0) {
546 FAIL() << "Failed to open " << kTestMountpoint << Errno();
547 }
548 struct fscrypt_remove_key_arg arg;
549 memset(&arg, 0, sizeof(arg));
550 arg.key_spec = master_key_specifier_;
551
552 if (ioctl(mntfd, FS_IOC_REMOVE_ENCRYPTION_KEY, &arg) != 0) {
553 FAIL() << "FS_IOC_REMOVE_ENCRYPTION_KEY failed on " << kTestMountpoint
554 << Errno();
555 }
556 }
557 }
558
559 // Adds |master_key| to kTestMountpoint and places the resulting key identifier
560 // in master_key_specifier_.
SetMasterKey(const std::vector<uint8_t> & master_key,uint32_t flags,bool required)561 bool FBEPolicyTest::SetMasterKey(const std::vector<uint8_t> &master_key,
562 uint32_t flags, bool required) {
563 size_t allocsize = sizeof(struct fscrypt_add_key_arg) + master_key.size();
564 std::unique_ptr<struct fscrypt_add_key_arg> arg(
565 new (::operator new(allocsize)) struct fscrypt_add_key_arg);
566 memset(arg.get(), 0, allocsize);
567 arg->key_spec.type = FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER;
568 arg->__flags = flags;
569 arg->raw_size = master_key.size();
570 std::copy(master_key.begin(), master_key.end(), arg->raw);
571
572 GTEST_LOG_(INFO) << "Adding fscrypt master key, flags are 0x" << std::hex
573 << flags << std::dec << ", raw bytes are "
574 << BytesToHex(master_key);
575 android::base::unique_fd mntfd(
576 open(kTestMountpoint, O_RDONLY | O_DIRECTORY | O_CLOEXEC));
577 if (mntfd < 0) {
578 ADD_FAILURE() << "Failed to open " << kTestMountpoint << Errno();
579 return false;
580 }
581 if (ioctl(mntfd, FS_IOC_ADD_ENCRYPTION_KEY, arg.get()) != 0) {
582 if (required || (errno != EINVAL && errno != EOPNOTSUPP)) {
583 ADD_FAILURE() << "FS_IOC_ADD_ENCRYPTION_KEY failed on " << kTestMountpoint
584 << Errno();
585 }
586 return false;
587 }
588 master_key_specifier_ = arg->key_spec;
589 GTEST_LOG_(INFO) << "Master key identifier is "
590 << BytesToHex(master_key_specifier_.u.identifier);
591 key_added_ = true;
592 if (!(flags & __FSCRYPT_ADD_KEY_FLAG_HW_WRAPPED) &&
593 !VerifyKeyIdentifier(master_key))
594 return false;
595 return true;
596 }
597
598 // Creates a hardware-wrapped key, adds it to the filesystem, and derives the
599 // corresponding inline encryption key |enc_key| and software secret
600 // |sw_secret|. Returns false if unsuccessful (either the test failed, or the
601 // device doesn't support hardware-wrapped keys so the test should be skipped).
CreateAndSetHwWrappedKey(std::vector<uint8_t> * enc_key,std::vector<uint8_t> * sw_secret)602 bool FBEPolicyTest::CreateAndSetHwWrappedKey(std::vector<uint8_t> *enc_key,
603 std::vector<uint8_t> *sw_secret) {
604 std::vector<uint8_t> master_key, exported_key;
605 if (!CreateHwWrappedKey(&master_key, &exported_key)) return false;
606
607 if (!SetMasterKey(exported_key, __FSCRYPT_ADD_KEY_FLAG_HW_WRAPPED, false)) {
608 if (!HasFailure()) {
609 GTEST_LOG_(INFO) << "Skipping test because kernel doesn't support "
610 "hardware-wrapped keys";
611 }
612 return false;
613 }
614
615 if (!DeriveHwWrappedEncryptionKey(master_key, enc_key)) return false;
616 if (!DeriveHwWrappedRawSecret(master_key, sw_secret)) return false;
617
618 if (!VerifyKeyIdentifier(*sw_secret)) return false;
619
620 return true;
621 }
622
623 enum {
624 kSkipIfNoPolicySupport = 1 << 0,
625 kSkipIfNoCryptoAPISupport = 1 << 1,
626 kSkipIfNoHardwareSupport = 1 << 2,
627 };
628
629 // Returns 0 if encryption policies that include the inode number in the IVs
630 // (e.g. IV_INO_LBLK_64) are guaranteed to be settable on the test filesystem.
631 // Else returns kSkipIfNoPolicySupport.
632 //
633 // On f2fs, they're always settable. On ext4, they're only settable if the
634 // filesystem has the 'stable_inodes' feature flag. Android only sets
635 // 'stable_inodes' if the device uses one of these encryption policies "for
636 // real", e.g. "fileencryption=::inlinecrypt_optimized" in fstab. Since the
637 // fstab could contain something else, we have to allow the tests for these
638 // encryption policies to be skipped on ext4.
GetSkipFlagsForInoBasedEncryption()639 int FBEPolicyTest::GetSkipFlagsForInoBasedEncryption() {
640 if (fs_info_.type == "ext4") return kSkipIfNoPolicySupport;
641 return 0;
642 }
643
644 // Sets a v2 encryption policy on the test directory. The policy will use the
645 // test key and the specified encryption modes and flags. If the kernel doesn't
646 // support setting or using the encryption policy, then a failure will be added,
647 // unless the reason is covered by a bit set in |skip_flags|.
SetEncryptionPolicy(int contents_mode,int filenames_mode,int flags,int skip_flags)648 bool FBEPolicyTest::SetEncryptionPolicy(int contents_mode, int filenames_mode,
649 int flags, int skip_flags) {
650 if (!key_added_) {
651 ADD_FAILURE() << "SetEncryptionPolicy called but no key added";
652 return false;
653 }
654
655 struct fscrypt_policy_v2 policy;
656 memset(&policy, 0, sizeof(policy));
657 policy.version = FSCRYPT_POLICY_V2;
658 policy.contents_encryption_mode = contents_mode;
659 policy.filenames_encryption_mode = filenames_mode;
660 // Always give PAD_16, to match the policies that Android sets for real.
661 // It doesn't affect contents encryption, though.
662 policy.flags = flags | FSCRYPT_POLICY_FLAGS_PAD_16;
663 memcpy(policy.master_key_identifier, master_key_specifier_.u.identifier,
664 FSCRYPT_KEY_IDENTIFIER_SIZE);
665
666 android::base::unique_fd dirfd(
667 open(test_dir_.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
668 if (dirfd < 0) {
669 ADD_FAILURE() << "Failed to open " << test_dir_ << Errno();
670 return false;
671 }
672 GTEST_LOG_(INFO) << "Setting encryption policy on " << test_dir_;
673 if (ioctl(dirfd, FS_IOC_SET_ENCRYPTION_POLICY, &policy) != 0) {
674 if (errno == EINVAL && (skip_flags & kSkipIfNoPolicySupport)) {
675 GTEST_LOG_(INFO) << "Skipping test because encryption policy is "
676 "unsupported on this filesystem / kernel";
677 return false;
678 }
679 ADD_FAILURE() << "FS_IOC_SET_ENCRYPTION_POLICY failed on " << test_dir_
680 << " using contents_mode=" << contents_mode
681 << ", filenames_mode=" << filenames_mode << ", flags=0x"
682 << std::hex << flags << std::dec << Errno();
683 return false;
684 }
685 if (skip_flags & (kSkipIfNoCryptoAPISupport | kSkipIfNoHardwareSupport)) {
686 android::base::unique_fd fd(
687 open(test_file_.c_str(), O_WRONLY | O_CREAT | O_CLOEXEC, 0600));
688 if (fd < 0) {
689 // Setting an encryption policy that uses modes that aren't enabled in the
690 // kernel's crypto API (e.g. FSCRYPT_MODE_ADIANTUM when the kernel lacks
691 // CONFIG_CRYPTO_ADIANTUM) will still succeed, but actually creating a
692 // file will fail with ENOPKG. Make sure to check for this case.
693 if (errno == ENOPKG && (skip_flags & kSkipIfNoCryptoAPISupport)) {
694 GTEST_LOG_(INFO)
695 << "Skipping test because encryption policy is "
696 "unsupported on this kernel, due to missing crypto API support";
697 return false;
698 }
699 // We get EINVAL here when using a hardware-wrapped key and the inline
700 // encryption hardware supports wrapped keys but doesn't support the
701 // number of DUN bytes that the file contents encryption requires.
702 if (errno == EINVAL && (skip_flags & kSkipIfNoHardwareSupport)) {
703 GTEST_LOG_(INFO)
704 << "Skipping test because encryption policy is not compatible with "
705 "this device's inline encryption hardware";
706 return false;
707 }
708 }
709 unlink(test_file_.c_str());
710 }
711 return true;
712 }
713
714 // Generates some test data, writes it to a file in the test directory, and
715 // returns in |info| the file's plaintext, the file's raw ciphertext read from
716 // disk, and other information about the file.
GenerateTestFile(TestFileInfo * info,const struct f2fs_comp_option * compress_options)717 bool FBEPolicyTest::GenerateTestFile(
718 TestFileInfo *info, const struct f2fs_comp_option *compress_options) {
719 info->plaintext.resize(kTestFileBytes);
720 RandomBytesForTesting(info->plaintext);
721
722 if (compress_options != nullptr &&
723 !MakeSomeCompressibleClusters(info->plaintext,
724 compress_options->log_cluster_size))
725 return false;
726
727 if (!WriteTestFile(info->plaintext, test_file_, fs_info_.raw_blk_device,
728 compress_options, &info->actual_ciphertext))
729 return false;
730
731 android::base::unique_fd fd(open(test_file_.c_str(), O_RDONLY | O_CLOEXEC));
732 if (fd < 0) {
733 ADD_FAILURE() << "Failed to open " << test_file_ << Errno();
734 return false;
735 }
736
737 // Get the file's inode number.
738 if (!GetInodeNumber(test_file_, &info->inode_number)) return false;
739 GTEST_LOG_(INFO) << "Inode number: " << info->inode_number;
740
741 // Get the file's nonce.
742 if (ioctl(fd, FS_IOC_GET_ENCRYPTION_NONCE, info->nonce.bytes) != 0) {
743 ADD_FAILURE() << "FS_IOC_GET_ENCRYPTION_NONCE failed on " << test_file_
744 << Errno();
745 return false;
746 }
747 GTEST_LOG_(INFO) << "File nonce: " << BytesToHex(info->nonce.bytes);
748 return true;
749 }
750
InitHkdfInfo(FscryptHkdfContext context)751 static std::vector<uint8_t> InitHkdfInfo(FscryptHkdfContext context) {
752 return {
753 'f', 's', 'c', 'r', 'y', 'p', 't', '\0', static_cast<uint8_t>(context)};
754 }
755
DeriveKey(const std::vector<uint8_t> & master_key,const std::vector<uint8_t> & hkdf_info,std::vector<uint8_t> & out)756 static bool DeriveKey(const std::vector<uint8_t> &master_key,
757 const std::vector<uint8_t> &hkdf_info,
758 std::vector<uint8_t> &out) {
759 if (HKDF(out.data(), out.size(), EVP_sha512(), master_key.data(),
760 master_key.size(), nullptr, 0, hkdf_info.data(),
761 hkdf_info.size()) != 1) {
762 ADD_FAILURE() << "BoringSSL HKDF-SHA512 call failed";
763 return false;
764 }
765 GTEST_LOG_(INFO) << "Derived subkey " << BytesToHex(out)
766 << " using HKDF info " << BytesToHex(hkdf_info);
767 return true;
768 }
769
770 // Derives the key identifier from |master_key| and verifies that it matches the
771 // value the kernel returned in |master_key_specifier_|.
VerifyKeyIdentifier(const std::vector<uint8_t> & master_key)772 bool FBEPolicyTest::VerifyKeyIdentifier(
773 const std::vector<uint8_t> &master_key) {
774 std::vector<uint8_t> hkdf_info = InitHkdfInfo(HKDF_CONTEXT_KEY_IDENTIFIER);
775 std::vector<uint8_t> computed_key_identifier(FSCRYPT_KEY_IDENTIFIER_SIZE);
776 if (!DeriveKey(master_key, hkdf_info, computed_key_identifier)) return false;
777
778 std::vector<uint8_t> actual_key_identifier(
779 std::begin(master_key_specifier_.u.identifier),
780 std::end(master_key_specifier_.u.identifier));
781 EXPECT_EQ(actual_key_identifier, computed_key_identifier);
782 return actual_key_identifier == computed_key_identifier;
783 }
784
785 // Derives a per-mode encryption key from |master_key|, |mode|, |context|, and
786 // (if needed for the context) the filesystem UUID.
DerivePerModeEncryptionKey(const std::vector<uint8_t> & master_key,int mode,FscryptHkdfContext context,std::vector<uint8_t> & enc_key)787 bool FBEPolicyTest::DerivePerModeEncryptionKey(
788 const std::vector<uint8_t> &master_key, int mode,
789 FscryptHkdfContext context, std::vector<uint8_t> &enc_key) {
790 std::vector<uint8_t> hkdf_info = InitHkdfInfo(context);
791
792 hkdf_info.push_back(mode);
793 if (context == HKDF_CONTEXT_IV_INO_LBLK_64_KEY ||
794 context == HKDF_CONTEXT_IV_INO_LBLK_32_KEY)
795 hkdf_info.insert(hkdf_info.end(), fs_info_.uuid.bytes,
796 std::end(fs_info_.uuid.bytes));
797
798 return DeriveKey(master_key, hkdf_info, enc_key);
799 }
800
801 // Derives a per-file encryption key from |master_key| and |nonce|.
DerivePerFileEncryptionKey(const std::vector<uint8_t> & master_key,const FscryptFileNonce & nonce,std::vector<uint8_t> & enc_key)802 bool FBEPolicyTest::DerivePerFileEncryptionKey(
803 const std::vector<uint8_t> &master_key, const FscryptFileNonce &nonce,
804 std::vector<uint8_t> &enc_key) {
805 std::vector<uint8_t> hkdf_info = InitHkdfInfo(HKDF_CONTEXT_PER_FILE_ENC_KEY);
806
807 hkdf_info.insert(hkdf_info.end(), nonce.bytes, std::end(nonce.bytes));
808
809 return DeriveKey(master_key, hkdf_info, enc_key);
810 }
811
812 // For IV_INO_LBLK_32: Hashes the |inode_number| using the SipHash key derived
813 // from |master_key|. Returns the resulting hash in |hash|.
HashInodeNumber(const std::vector<uint8_t> & master_key,uint64_t inode_number,uint32_t * hash)814 static bool HashInodeNumber(const std::vector<uint8_t> &master_key,
815 uint64_t inode_number, uint32_t *hash) {
816 union {
817 uint64_t words[2];
818 __le64 le_words[2];
819 } siphash_key;
820 union {
821 __le64 inode_number;
822 uint8_t bytes[8];
823 } input;
824
825 std::vector<uint8_t> hkdf_info = InitHkdfInfo(HKDF_CONTEXT_INODE_HASH_KEY);
826 std::vector<uint8_t> ino_hash_key(sizeof(siphash_key));
827 if (!DeriveKey(master_key, hkdf_info, ino_hash_key)) return false;
828
829 memcpy(&siphash_key, &ino_hash_key[0], sizeof(siphash_key));
830 siphash_key.words[0] = __le64_to_cpu(siphash_key.le_words[0]);
831 siphash_key.words[1] = __le64_to_cpu(siphash_key.le_words[1]);
832
833 GTEST_LOG_(INFO) << "Inode hash key is {" << std::hex << "0x"
834 << siphash_key.words[0] << ", 0x" << siphash_key.words[1]
835 << "}" << std::dec;
836
837 input.inode_number = __cpu_to_le64(inode_number);
838
839 *hash = SIPHASH_24(siphash_key.words, input.bytes, sizeof(input));
840 GTEST_LOG_(INFO) << "Hashed inode number " << inode_number << " to 0x"
841 << std::hex << *hash << std::dec;
842 return true;
843 }
844
VerifyCiphertext(const std::vector<uint8_t> & enc_key,const FscryptIV & starting_iv,const Cipher & cipher,const TestFileInfo & file_info)845 void FBEPolicyTest::VerifyCiphertext(const std::vector<uint8_t> &enc_key,
846 const FscryptIV &starting_iv,
847 const Cipher &cipher,
848 const TestFileInfo &file_info) {
849 const std::vector<uint8_t> &plaintext = file_info.plaintext;
850
851 GTEST_LOG_(INFO) << "Verifying correctness of encrypted data";
852 FscryptIV iv = starting_iv;
853
854 std::vector<uint8_t> computed_ciphertext(plaintext.size());
855
856 // Encrypt each filesystem block of file contents.
857 for (size_t i = 0; i < plaintext.size(); i += kFilesystemBlockSize) {
858 int block_size =
859 std::min<size_t>(kFilesystemBlockSize, plaintext.size() - i);
860
861 ASSERT_GE(sizeof(iv.bytes), cipher.ivsize());
862 ASSERT_TRUE(cipher.Encrypt(enc_key, iv.bytes, &plaintext[i],
863 &computed_ciphertext[i], block_size));
864
865 // Update the IV by incrementing the file logical block number.
866 iv.lblk_num = __cpu_to_le32(__le32_to_cpu(iv.lblk_num) + 1);
867 }
868
869 ASSERT_EQ(file_info.actual_ciphertext, computed_ciphertext);
870 }
871
InitIVForPerFileKey(FscryptIV * iv)872 static bool InitIVForPerFileKey(FscryptIV *iv) {
873 memset(iv, 0, kFscryptMaxIVSize);
874 return true;
875 }
876
InitIVForDirectKey(const FscryptFileNonce & nonce,FscryptIV * iv)877 static bool InitIVForDirectKey(const FscryptFileNonce &nonce, FscryptIV *iv) {
878 memset(iv, 0, kFscryptMaxIVSize);
879 memcpy(iv->file_nonce, nonce.bytes, kFscryptFileNonceSize);
880 return true;
881 }
882
InitIVForInoLblk64(uint64_t inode_number,FscryptIV * iv)883 static bool InitIVForInoLblk64(uint64_t inode_number, FscryptIV *iv) {
884 if (inode_number > UINT32_MAX) {
885 ADD_FAILURE() << "inode number doesn't fit in 32 bits";
886 return false;
887 }
888 memset(iv, 0, kFscryptMaxIVSize);
889 iv->inode_number = __cpu_to_le32(inode_number);
890 return true;
891 }
892
InitIVForInoLblk32(const std::vector<uint8_t> & master_key,uint64_t inode_number,FscryptIV * iv)893 static bool InitIVForInoLblk32(const std::vector<uint8_t> &master_key,
894 uint64_t inode_number, FscryptIV *iv) {
895 uint32_t hash;
896 if (!HashInodeNumber(master_key, inode_number, &hash)) return false;
897 memset(iv, 0, kFscryptMaxIVSize);
898 iv->lblk_num = __cpu_to_le32(hash);
899 return true;
900 }
901
902 // Tests a policy matching "fileencryption=aes-256-xts:aes-256-cts:v2"
903 // (or simply "fileencryption=" on devices launched with R or higher)
TEST_F(FBEPolicyTest,TestAesPerFileKeysPolicy)904 TEST_F(FBEPolicyTest, TestAesPerFileKeysPolicy) {
905 if (skip_test_) return;
906
907 auto master_key = GenerateTestKey(kFscryptMasterKeySize);
908 ASSERT_TRUE(SetMasterKey(master_key));
909
910 if (!SetEncryptionPolicy(FSCRYPT_MODE_AES_256_XTS, FSCRYPT_MODE_AES_256_CTS,
911 0, 0))
912 return;
913
914 TestFileInfo file_info;
915 ASSERT_TRUE(GenerateTestFile(&file_info));
916
917 std::vector<uint8_t> enc_key(kAes256XtsKeySize);
918 ASSERT_TRUE(DerivePerFileEncryptionKey(master_key, file_info.nonce, enc_key));
919
920 FscryptIV iv;
921 ASSERT_TRUE(InitIVForPerFileKey(&iv));
922 VerifyCiphertext(enc_key, iv, Aes256XtsCipher(), file_info);
923 }
924
925 // Tests a policy matching
926 // "fileencryption=aes-256-xts:aes-256-cts:v2+inlinecrypt_optimized"
927 // (or simply "fileencryption=::inlinecrypt_optimized" on devices launched with
928 // R or higher)
TEST_F(FBEPolicyTest,TestAesInlineCryptOptimizedPolicy)929 TEST_F(FBEPolicyTest, TestAesInlineCryptOptimizedPolicy) {
930 if (skip_test_) return;
931
932 auto master_key = GenerateTestKey(kFscryptMasterKeySize);
933 ASSERT_TRUE(SetMasterKey(master_key));
934
935 if (!SetEncryptionPolicy(FSCRYPT_MODE_AES_256_XTS, FSCRYPT_MODE_AES_256_CTS,
936 FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64,
937 GetSkipFlagsForInoBasedEncryption()))
938 return;
939
940 TestFileInfo file_info;
941 ASSERT_TRUE(GenerateTestFile(&file_info));
942
943 std::vector<uint8_t> enc_key(kAes256XtsKeySize);
944 ASSERT_TRUE(DerivePerModeEncryptionKey(master_key, FSCRYPT_MODE_AES_256_XTS,
945 HKDF_CONTEXT_IV_INO_LBLK_64_KEY,
946 enc_key));
947
948 FscryptIV iv;
949 ASSERT_TRUE(InitIVForInoLblk64(file_info.inode_number, &iv));
950 VerifyCiphertext(enc_key, iv, Aes256XtsCipher(), file_info);
951 }
952
953 // Tests a policy matching
954 // "fileencryption=aes-256-xts:aes-256-cts:v2+inlinecrypt_optimized+wrappedkey_v0"
955 // (or simply "fileencryption=::inlinecrypt_optimized+wrappedkey_v0" on devices
956 // launched with R or higher)
TEST_F(FBEPolicyTest,TestAesInlineCryptOptimizedHwWrappedKeyPolicy)957 TEST_F(FBEPolicyTest, TestAesInlineCryptOptimizedHwWrappedKeyPolicy) {
958 if (skip_test_) return;
959
960 std::vector<uint8_t> enc_key, sw_secret;
961 if (!CreateAndSetHwWrappedKey(&enc_key, &sw_secret)) return;
962
963 if (!SetEncryptionPolicy(
964 FSCRYPT_MODE_AES_256_XTS, FSCRYPT_MODE_AES_256_CTS,
965 FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64,
966 // 64-bit DUN support is not guaranteed.
967 kSkipIfNoHardwareSupport | GetSkipFlagsForInoBasedEncryption()))
968 return;
969
970 TestFileInfo file_info;
971 ASSERT_TRUE(GenerateTestFile(&file_info));
972
973 FscryptIV iv;
974 ASSERT_TRUE(InitIVForInoLblk64(file_info.inode_number, &iv));
975 VerifyCiphertext(enc_key, iv, Aes256XtsCipher(), file_info);
976 }
977
978 // With IV_INO_LBLK_32, the DUN (IV) can wrap from UINT32_MAX to 0 in the middle
979 // of the file. This method tests that this case appears to be handled
980 // correctly, by doing I/O across the place where the DUN wraps around. Assumes
981 // that test_dir_ has already been set up with an IV_INO_LBLK_32 policy.
TestEmmcOptimizedDunWraparound(const std::vector<uint8_t> & master_key,const std::vector<uint8_t> & enc_key)982 void FBEPolicyTest::TestEmmcOptimizedDunWraparound(
983 const std::vector<uint8_t> &master_key,
984 const std::vector<uint8_t> &enc_key) {
985 // We'll test writing 'block_count' filesystem blocks. The first
986 // 'block_count_1' blocks will have DUNs [..., UINT32_MAX - 1, UINT32_MAX].
987 // The remaining 'block_count_2' blocks will have DUNs [0, 1, ...].
988 constexpr uint32_t block_count_1 = 3;
989 constexpr uint32_t block_count_2 = 7;
990 constexpr uint32_t block_count = block_count_1 + block_count_2;
991 constexpr size_t data_size = block_count * kFilesystemBlockSize;
992
993 // Assumed maximum file size. Unfortunately there isn't a syscall to get
994 // this. ext4 allows ~16TB and f2fs allows ~4TB. However, an underestimate
995 // works fine for our purposes, so just go with 1TB.
996 constexpr off_t max_file_size = 1000000000000;
997 constexpr off_t max_file_blocks = max_file_size / kFilesystemBlockSize;
998
999 // Repeatedly create empty files until we find one that can be used for DUN
1000 // wraparound testing, due to SipHash(inode_number) being almost UINT32_MAX.
1001 std::string path;
1002 TestFileInfo file_info;
1003 uint32_t lblk_with_dun_0;
1004 for (int i = 0;; i++) {
1005 // The probability of finding a usable file is about 'max_file_blocks /
1006 // UINT32_MAX', or about 5.6%. So on average we'll need about 18 tries.
1007 // The probability we'll need over 1000 tries is less than 1e-25.
1008 ASSERT_LT(i, 1000) << "Tried too many times to find a usable test file";
1009
1010 path = android::base::StringPrintf("%s/file%d", test_dir_.c_str(), i);
1011 android::base::unique_fd fd(
1012 open(path.c_str(), O_WRONLY | O_CREAT | O_CLOEXEC, 0600));
1013 ASSERT_GE(fd, 0) << "Failed to create " << path << Errno();
1014
1015 ASSERT_TRUE(GetInodeNumber(path, &file_info.inode_number));
1016 uint32_t hash;
1017 ASSERT_TRUE(HashInodeNumber(master_key, file_info.inode_number, &hash));
1018 // Negating the hash gives the distance to DUN 0, and hence the 0-based
1019 // logical block number of the block which has DUN 0.
1020 lblk_with_dun_0 = -hash;
1021 if (lblk_with_dun_0 >= block_count_1 &&
1022 static_cast<off_t>(lblk_with_dun_0) + block_count_2 < max_file_blocks)
1023 break;
1024 }
1025
1026 GTEST_LOG_(INFO) << "DUN wraparound test: path=" << path
1027 << ", inode_number=" << file_info.inode_number
1028 << ", lblk_with_dun_0=" << lblk_with_dun_0;
1029
1030 // Write some data across the DUN wraparound boundary and verify that the
1031 // resulting on-disk ciphertext is as expected. Note that we don't actually
1032 // have to fill the file until the boundary; we can just write to the needed
1033 // part and leave a hole before it.
1034 for (int i = 0; i < 2; i++) {
1035 // Try both buffered I/O and direct I/O.
1036 int open_flags = O_RDWR | O_CLOEXEC;
1037 if (i == 1) open_flags |= O_DIRECT;
1038
1039 android::base::unique_fd fd(open(path.c_str(), open_flags));
1040 ASSERT_GE(fd, 0) << "Failed to open " << path << Errno();
1041
1042 // Generate some test data.
1043 file_info.plaintext.resize(data_size);
1044 RandomBytesForTesting(file_info.plaintext);
1045
1046 // Write the test data. To support O_DIRECT, use a block-aligned buffer.
1047 std::unique_ptr<void, void (*)(void *)> buf_mem(
1048 aligned_alloc(kFilesystemBlockSize, data_size), free);
1049 ASSERT_TRUE(buf_mem != nullptr);
1050 memcpy(buf_mem.get(), &file_info.plaintext[0], data_size);
1051 off_t pos = static_cast<off_t>(lblk_with_dun_0 - block_count_1) *
1052 kFilesystemBlockSize;
1053 ASSERT_EQ(data_size, pwrite(fd, buf_mem.get(), data_size, pos))
1054 << "Error writing data to " << path << Errno();
1055
1056 // Verify the ciphertext.
1057 ASSERT_TRUE(ReadRawDataOfFile(fd, fs_info_.raw_blk_device, data_size,
1058 &file_info.actual_ciphertext));
1059 FscryptIV iv;
1060 memset(&iv, 0, sizeof(iv));
1061 iv.lblk_num = __cpu_to_le32(-block_count_1);
1062 VerifyCiphertext(enc_key, iv, Aes256XtsCipher(), file_info);
1063 }
1064 }
1065
1066 // Tests a policy matching
1067 // "fileencryption=aes-256-xts:aes-256-cts:v2+emmc_optimized" (or simply
1068 // "fileencryption=::emmc_optimized" on devices launched with R or higher)
TEST_F(FBEPolicyTest,TestAesEmmcOptimizedPolicy)1069 TEST_F(FBEPolicyTest, TestAesEmmcOptimizedPolicy) {
1070 if (skip_test_) return;
1071
1072 auto master_key = GenerateTestKey(kFscryptMasterKeySize);
1073 ASSERT_TRUE(SetMasterKey(master_key));
1074
1075 if (!SetEncryptionPolicy(FSCRYPT_MODE_AES_256_XTS, FSCRYPT_MODE_AES_256_CTS,
1076 FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32,
1077 GetSkipFlagsForInoBasedEncryption()))
1078 return;
1079
1080 TestFileInfo file_info;
1081 ASSERT_TRUE(GenerateTestFile(&file_info));
1082
1083 std::vector<uint8_t> enc_key(kAes256XtsKeySize);
1084 ASSERT_TRUE(DerivePerModeEncryptionKey(master_key, FSCRYPT_MODE_AES_256_XTS,
1085 HKDF_CONTEXT_IV_INO_LBLK_32_KEY,
1086 enc_key));
1087
1088 FscryptIV iv;
1089 ASSERT_TRUE(InitIVForInoLblk32(master_key, file_info.inode_number, &iv));
1090 VerifyCiphertext(enc_key, iv, Aes256XtsCipher(), file_info);
1091
1092 TestEmmcOptimizedDunWraparound(master_key, enc_key);
1093 }
1094
1095 // Tests a policy matching
1096 // "fileencryption=aes-256-xts:aes-256-cts:v2+emmc_optimized+wrappedkey_v0"
1097 // (or simply "fileencryption=::emmc_optimized+wrappedkey_v0" on devices
1098 // launched with R or higher)
TEST_F(FBEPolicyTest,TestAesEmmcOptimizedHwWrappedKeyPolicy)1099 TEST_F(FBEPolicyTest, TestAesEmmcOptimizedHwWrappedKeyPolicy) {
1100 if (skip_test_) return;
1101
1102 std::vector<uint8_t> enc_key, sw_secret;
1103 if (!CreateAndSetHwWrappedKey(&enc_key, &sw_secret)) return;
1104
1105 if (!SetEncryptionPolicy(FSCRYPT_MODE_AES_256_XTS, FSCRYPT_MODE_AES_256_CTS,
1106 FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32,
1107 GetSkipFlagsForInoBasedEncryption()))
1108 return;
1109
1110 TestFileInfo file_info;
1111 ASSERT_TRUE(GenerateTestFile(&file_info));
1112
1113 FscryptIV iv;
1114 ASSERT_TRUE(InitIVForInoLblk32(sw_secret, file_info.inode_number, &iv));
1115 VerifyCiphertext(enc_key, iv, Aes256XtsCipher(), file_info);
1116
1117 TestEmmcOptimizedDunWraparound(sw_secret, enc_key);
1118 }
1119
1120 // Tests a policy matching "fileencryption=adiantum:adiantum:v2" (or simply
1121 // "fileencryption=adiantum" on devices launched with R or higher)
TEST_F(FBEPolicyTest,TestAdiantumPolicy)1122 TEST_F(FBEPolicyTest, TestAdiantumPolicy) {
1123 if (skip_test_) return;
1124
1125 auto master_key = GenerateTestKey(kFscryptMasterKeySize);
1126 ASSERT_TRUE(SetMasterKey(master_key));
1127
1128 // Adiantum support isn't required (since CONFIG_CRYPTO_ADIANTUM can be unset
1129 // in the kernel config), so we may skip the test here.
1130 //
1131 // We don't need to use GetSkipFlagsForInoBasedEncryption() here, since the
1132 // "DIRECT_KEY" IV generation method doesn't include inode numbers in the IVs.
1133 if (!SetEncryptionPolicy(FSCRYPT_MODE_ADIANTUM, FSCRYPT_MODE_ADIANTUM,
1134 FSCRYPT_POLICY_FLAG_DIRECT_KEY,
1135 kSkipIfNoCryptoAPISupport))
1136 return;
1137
1138 TestFileInfo file_info;
1139 ASSERT_TRUE(GenerateTestFile(&file_info));
1140
1141 std::vector<uint8_t> enc_key(kAdiantumKeySize);
1142 ASSERT_TRUE(DerivePerModeEncryptionKey(master_key, FSCRYPT_MODE_ADIANTUM,
1143 HKDF_CONTEXT_DIRECT_KEY, enc_key));
1144
1145 FscryptIV iv;
1146 ASSERT_TRUE(InitIVForDirectKey(file_info.nonce, &iv));
1147 VerifyCiphertext(enc_key, iv, AdiantumCipher(), file_info);
1148 }
1149
1150 // Tests adding a corrupted wrapped key to fscrypt keyring.
1151 // If wrapped key is corrupted, fscrypt should return a failure.
TEST_F(FBEPolicyTest,TestHwWrappedKeyCorruption)1152 TEST_F(FBEPolicyTest, TestHwWrappedKeyCorruption) {
1153 if (skip_test_) return;
1154
1155 std::vector<uint8_t> master_key, exported_key;
1156 if (!CreateHwWrappedKey(&master_key, &exported_key)) return;
1157
1158 for (int i = 0; i < exported_key.size(); i++) {
1159 std::vector<uint8_t> corrupt_key(exported_key.begin(), exported_key.end());
1160 corrupt_key[i] = ~corrupt_key[i];
1161 ASSERT_FALSE(
1162 SetMasterKey(corrupt_key, __FSCRYPT_ADD_KEY_FLAG_HW_WRAPPED, false));
1163 }
1164 }
1165
EnableF2fsCompressionOnTestDir()1166 bool FBEPolicyTest::EnableF2fsCompressionOnTestDir() {
1167 android::base::unique_fd fd(open(test_dir_.c_str(), O_RDONLY | O_CLOEXEC));
1168 if (fd < 0) {
1169 ADD_FAILURE() << "Failed to open " << test_dir_ << Errno();
1170 return false;
1171 }
1172
1173 int flags;
1174 if (ioctl(fd, FS_IOC_GETFLAGS, &flags) != 0) {
1175 ADD_FAILURE() << "Unexpected error getting flags of " << test_dir_
1176 << Errno();
1177 return false;
1178 }
1179 flags |= FS_COMPR_FL;
1180 if (ioctl(fd, FS_IOC_SETFLAGS, &flags) != 0) {
1181 if (errno == EOPNOTSUPP) {
1182 GTEST_LOG_(INFO)
1183 << "Skipping test because f2fs compression is not supported on "
1184 << kTestMountpoint;
1185 return false;
1186 }
1187 ADD_FAILURE() << "Unexpected error enabling compression on " << test_dir_
1188 << Errno();
1189 return false;
1190 }
1191 return true;
1192 }
1193
F2fsCompressAlgorithmName(int algorithm)1194 static std::string F2fsCompressAlgorithmName(int algorithm) {
1195 switch (algorithm) {
1196 case F2FS_COMPRESS_LZO:
1197 return "LZO";
1198 case F2FS_COMPRESS_LZ4:
1199 return "LZ4";
1200 case F2FS_COMPRESS_ZSTD:
1201 return "ZSTD";
1202 case F2FS_COMPRESS_LZORLE:
1203 return "LZORLE";
1204 default:
1205 return android::base::StringPrintf("%d", algorithm);
1206 }
1207 }
1208
F2fsCompressOptionsSupported(const struct f2fs_comp_option & opts)1209 bool FBEPolicyTest::F2fsCompressOptionsSupported(
1210 const struct f2fs_comp_option &opts) {
1211 android::base::unique_fd fd(
1212 open(test_file_.c_str(), O_WRONLY | O_CREAT, 0600));
1213 if (fd < 0) {
1214 // If the filesystem has the compression feature flag enabled but f2fs
1215 // compression support was compiled out of the kernel, then setting
1216 // FS_COMPR_FL on the directory will succeed, but creating a file in the
1217 // directory will fail with EOPNOTSUPP.
1218 if (errno == EOPNOTSUPP) {
1219 GTEST_LOG_(INFO)
1220 << "Skipping test because kernel doesn't support f2fs compression";
1221 return false;
1222 }
1223 ADD_FAILURE() << "Unexpected error creating " << test_file_
1224 << " after enabling f2fs compression on parent directory"
1225 << Errno();
1226 return false;
1227 }
1228
1229 if (ioctl(fd, F2FS_IOC_SET_COMPRESS_OPTION, &opts) != 0) {
1230 if (errno == ENOTTY || errno == EOPNOTSUPP) {
1231 GTEST_LOG_(INFO) << "Skipping test because kernel doesn't support "
1232 "F2FS_IOC_SET_COMPRESS_OPTION on "
1233 << kTestMountpoint;
1234 return false;
1235 }
1236 ADD_FAILURE() << "Unexpected error from F2FS_IOC_SET_COMPRESS_OPTION"
1237 << Errno();
1238 return false;
1239 }
1240 // Unsupported compression algorithms aren't detected until the file is
1241 // reopened.
1242 fd.reset(open(test_file_.c_str(), O_WRONLY));
1243 if (fd < 0) {
1244 if (errno == EOPNOTSUPP || errno == ENOPKG) {
1245 GTEST_LOG_(INFO) << "Skipping test because kernel doesn't support "
1246 << F2fsCompressAlgorithmName(opts.algorithm)
1247 << " compression";
1248 return false;
1249 }
1250 ADD_FAILURE() << "Unexpected error when reopening file after "
1251 "F2FS_IOC_SET_COMPRESS_OPTION"
1252 << Errno();
1253 return false;
1254 }
1255 unlink(test_file_.c_str());
1256 return true;
1257 }
1258
1259 // Tests that encryption is done correctly on compressed files.
1260 //
1261 // This works by creating a compressed+encrypted file, then decrypting the
1262 // file's on-disk data, then decompressing it, then comparing the result to the
1263 // original data. We don't do it the other way around (compress+encrypt the
1264 // original data and compare to the on-disk data) because different
1265 // implementations of a compression algorithm can produce different results.
1266 //
1267 // This is adapted from the xfstest "f2fs/002"; see there for some more details.
1268 //
1269 // This test will skip itself if any of the following is true:
1270 // - f2fs compression isn't enabled on /data
1271 // - f2fs compression isn't enabled in the kernel (CONFIG_F2FS_FS_COMPRESSION)
1272 // - The kernel doesn't support the needed algorithm (CONFIG_F2FS_FS_LZ4)
1273 // - The kernel doesn't support the F2FS_IOC_SET_COMPRESS_OPTION ioctl
1274 //
1275 // Note, this test will be flaky if the kernel is missing commit 093f0bac32b
1276 // ("f2fs: change fiemap way in printing compression chunk").
TEST_F(FBEPolicyTest,TestF2fsCompression)1277 TEST_F(FBEPolicyTest, TestF2fsCompression) {
1278 if (skip_test_) return;
1279
1280 // Currently, only f2fs supports compression+encryption.
1281 if (fs_info_.type != "f2fs") {
1282 GTEST_LOG_(INFO) << "Skipping test because device uses " << fs_info_.type
1283 << ", not f2fs";
1284 return;
1285 }
1286
1287 // Enable compression and encryption on the test directory. Afterwards, both
1288 // of these features will be inherited by any file created in this directory.
1289 //
1290 // If compression is not supported, skip the test. Use the default encryption
1291 // settings, which should always be supported.
1292 if (!EnableF2fsCompressionOnTestDir()) return;
1293 auto master_key = GenerateTestKey(kFscryptMasterKeySize);
1294 ASSERT_TRUE(SetMasterKey(master_key));
1295 ASSERT_TRUE(SetEncryptionPolicy(FSCRYPT_MODE_AES_256_XTS,
1296 FSCRYPT_MODE_AES_256_CTS, 0, 0));
1297
1298 // This test will use LZ4 compression with a cluster size of 2^2 = 4 blocks.
1299 // Check that this setting is supported.
1300 //
1301 // Note that the precise choice of algorithm and cluster size isn't too
1302 // important for this test. We just (somewhat arbitrarily) chose a setting
1303 // which is commonly used and for which a decompression library is available.
1304 const int log_cluster_size = 2;
1305 const int cluster_bytes = kFilesystemBlockSize << log_cluster_size;
1306 struct f2fs_comp_option comp_opt;
1307 memset(&comp_opt, 0, sizeof(comp_opt));
1308 comp_opt.algorithm = F2FS_COMPRESS_LZ4;
1309 comp_opt.log_cluster_size = log_cluster_size;
1310 if (!F2fsCompressOptionsSupported(comp_opt)) return;
1311
1312 // Generate the test file and retrieve its on-disk data. Note: despite being
1313 // compressed, the on-disk data here will still be |kTestFileBytes| long.
1314 // This is because FS_IOC_FIEMAP doesn't natively support compression, and the
1315 // way that f2fs handles it on compressed files results in us reading extra
1316 // blocks appended to the compressed clusters. It works out in the end
1317 // though, since these extra blocks get ignored during decompression.
1318 TestFileInfo file_info;
1319 ASSERT_TRUE(GenerateTestFile(&file_info, &comp_opt));
1320
1321 GTEST_LOG_(INFO) << "Decrypting the blocks of the compressed file";
1322 std::vector<uint8_t> enc_key(kAes256XtsKeySize);
1323 ASSERT_TRUE(DerivePerFileEncryptionKey(master_key, file_info.nonce, enc_key));
1324 std::vector<uint8_t> decrypted_data(kTestFileBytes);
1325 FscryptIV iv;
1326 memset(&iv, 0, sizeof(iv));
1327 ASSERT_EQ(0, kTestFileBytes % kFilesystemBlockSize);
1328 for (int i = 0; i < kTestFileBytes; i += kFilesystemBlockSize) {
1329 int block_num = i / kFilesystemBlockSize;
1330 int cluster_num = i / cluster_bytes;
1331
1332 // In compressed clusters, IVs start at 1 higher than the expected value.
1333 // Fortunately, due to the compression there is no overlap...
1334 if (IsCompressibleCluster(cluster_num)) block_num++;
1335
1336 iv.lblk_num = __cpu_to_le32(block_num);
1337 ASSERT_TRUE(Aes256XtsCipher().Decrypt(
1338 enc_key, iv.bytes, &file_info.actual_ciphertext[i], &decrypted_data[i],
1339 kFilesystemBlockSize));
1340 }
1341
1342 GTEST_LOG_(INFO) << "Decompressing the decrypted blocks of the file";
1343 std::vector<uint8_t> decompressed_data(kTestFileBytes);
1344 ASSERT_EQ(0, kTestFileBytes % cluster_bytes);
1345 for (int i = 0; i < kTestFileBytes; i += cluster_bytes) {
1346 int cluster_num = i / cluster_bytes;
1347 if (IsCompressibleCluster(cluster_num)) {
1348 // We had filled this cluster with compressible data, so it should have
1349 // been stored compressed.
1350 ASSERT_TRUE(DecompressLZ4Cluster(&decrypted_data[i],
1351 &decompressed_data[i], cluster_bytes));
1352 } else {
1353 // We had filled this cluster with random data, so it should have been
1354 // incompressible and thus stored uncompressed.
1355 memcpy(&decompressed_data[i], &decrypted_data[i], cluster_bytes);
1356 }
1357 }
1358
1359 // Finally do the actual test. The data we got after decryption+decompression
1360 // should match the original file contents.
1361 GTEST_LOG_(INFO) << "Comparing the result to the original data";
1362 ASSERT_EQ(file_info.plaintext, decompressed_data);
1363 }
1364
DeviceUsesFBE()1365 static bool DeviceUsesFBE() {
1366 if (android::base::GetProperty("ro.crypto.type", "") == "file") return true;
1367 // FBE has been required since Android Q.
1368 int first_api_level;
1369 if (!GetFirstApiLevel(&first_api_level)) return true;
1370 if (first_api_level >= __ANDROID_API_Q__) {
1371 ADD_FAILURE() << "File-based encryption is required";
1372 } else {
1373 GTEST_LOG_(INFO)
1374 << "Skipping test because device doesn't use file-based encryption";
1375 }
1376 return false;
1377 }
1378
1379 // Retrieves the encryption key specifier used in the file-based encryption
1380 // policy of |dir|. This isn't the key itself, but rather a "name" for the key.
1381 // If the key specifier cannot be retrieved, e.g. due to the directory being
1382 // unencrypted, then false is returned and a failure is added.
GetKeyUsedByDir(const std::string & dir,std::string * key_specifier)1383 static bool GetKeyUsedByDir(const std::string &dir,
1384 std::string *key_specifier) {
1385 android::base::unique_fd fd(open(dir.c_str(), O_RDONLY));
1386 if (fd < 0) {
1387 ADD_FAILURE() << "Failed to open " << dir << Errno();
1388 return false;
1389 }
1390 struct fscrypt_get_policy_ex_arg arg = {.policy_size = sizeof(arg.policy)};
1391 int res = ioctl(fd, FS_IOC_GET_ENCRYPTION_POLICY_EX, &arg);
1392 if (res != 0 && errno == ENOTTY) {
1393 // Handle old kernels that don't support FS_IOC_GET_ENCRYPTION_POLICY_EX.
1394 res = ioctl(fd, FS_IOC_GET_ENCRYPTION_POLICY, &arg.policy.v1);
1395 }
1396 if (res != 0) {
1397 if (errno == ENODATA) {
1398 ADD_FAILURE() << "Directory " << dir << " is not encrypted!";
1399 } else {
1400 ADD_FAILURE() << "Failed to get encryption policy of " << dir << Errno();
1401 }
1402 return false;
1403 }
1404 switch (arg.policy.version) {
1405 case FSCRYPT_POLICY_V1:
1406 *key_specifier = BytesToHex(arg.policy.v1.master_key_descriptor);
1407 return true;
1408 case FSCRYPT_POLICY_V2:
1409 *key_specifier = BytesToHex(arg.policy.v2.master_key_identifier);
1410 return true;
1411 default:
1412 ADD_FAILURE() << dir << " uses unknown encryption policy version ("
1413 << arg.policy.version << ")";
1414 return false;
1415 }
1416 }
1417
1418 // Tests that if the device uses FBE, then the ciphertext for file contents in
1419 // encrypted directories seems to be random.
1420 //
1421 // This isn't as strong a test as the correctness tests, but it's useful because
1422 // it applies regardless of the encryption format and key. Thus it runs even on
1423 // old devices, including ones that used a vendor-specific encryption format.
TEST(FBETest,TestFileContentsRandomness)1424 TEST(FBETest, TestFileContentsRandomness) {
1425 const std::string path_1 =
1426 android::base::StringPrintf("%s/FBETest-1.%d", kTmpDir, getpid());
1427 const std::string path_2 =
1428 android::base::StringPrintf("%s/FBETest-2.%d", kTmpDir, getpid());
1429
1430 if (!DeviceUsesFBE()) return;
1431
1432 FilesystemInfo fs_info;
1433 ASSERT_TRUE(GetFilesystemInfo(kTestMountpoint, &fs_info));
1434
1435 std::vector<uint8_t> zeroes(kTestFileBytes, 0);
1436 std::vector<uint8_t> ciphertext_1;
1437 std::vector<uint8_t> ciphertext_2;
1438 ASSERT_TRUE(WriteTestFile(zeroes, path_1, fs_info.raw_blk_device, nullptr,
1439 &ciphertext_1));
1440 ASSERT_TRUE(WriteTestFile(zeroes, path_2, fs_info.raw_blk_device, nullptr,
1441 &ciphertext_2));
1442
1443 GTEST_LOG_(INFO) << "Verifying randomness of ciphertext";
1444
1445 // Each individual file's ciphertext should be random.
1446 ASSERT_TRUE(VerifyDataRandomness(ciphertext_1));
1447 ASSERT_TRUE(VerifyDataRandomness(ciphertext_2));
1448
1449 // The files' ciphertext concatenated should also be random.
1450 // I.e., each file should be encrypted differently.
1451 std::vector<uint8_t> concatenated_ciphertext;
1452 concatenated_ciphertext.insert(concatenated_ciphertext.end(),
1453 ciphertext_1.begin(), ciphertext_1.end());
1454 concatenated_ciphertext.insert(concatenated_ciphertext.end(),
1455 ciphertext_2.begin(), ciphertext_2.end());
1456 ASSERT_TRUE(VerifyDataRandomness(concatenated_ciphertext));
1457
1458 ASSERT_EQ(unlink(path_1.c_str()), 0);
1459 ASSERT_EQ(unlink(path_2.c_str()), 0);
1460 }
1461
1462 // Tests that all of user 0's directories that should be encrypted actually are,
1463 // and that user 0's CE and DE keys are different.
TEST(FBETest,TestUserDirectoryPolicies)1464 TEST(FBETest, TestUserDirectoryPolicies) {
1465 if (!DeviceUsesFBE()) return;
1466
1467 std::string user0_ce_key, user0_de_key;
1468 EXPECT_TRUE(GetKeyUsedByDir("/data/user/0", &user0_ce_key));
1469 EXPECT_TRUE(GetKeyUsedByDir("/data/user_de/0", &user0_de_key));
1470 EXPECT_NE(user0_ce_key, user0_de_key) << "CE and DE keys must differ";
1471
1472 // Check the CE directories other than /data/user/0.
1473 for (const std::string &dir : {"/data/media/0", "/data/misc_ce/0",
1474 "/data/system_ce/0", "/data/vendor_ce/0"}) {
1475 std::string key;
1476 EXPECT_TRUE(GetKeyUsedByDir(dir, &key));
1477 EXPECT_EQ(key, user0_ce_key) << dir << " must be encrypted with CE key";
1478 }
1479
1480 // Check the DE directories other than /data/user_de/0.
1481 for (const std::string &dir :
1482 {"/data/misc_de/0", "/data/system_de/0", "/data/vendor_de/0"}) {
1483 std::string key;
1484 EXPECT_TRUE(GetKeyUsedByDir(dir, &key));
1485 EXPECT_EQ(key, user0_de_key) << dir << " must be encrypted with DE key";
1486 }
1487 }
1488
1489 } // namespace kernel
1490 } // namespace android
1491