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/fiemap.h>
64 #include <linux/fs.h>
65 #include <linux/fscrypt.h>
66 #include <openssl/evp.h>
67 #include <openssl/hkdf.h>
68 #include <openssl/siphash.h>
69 #include <stdlib.h>
70 #include <string.h>
71 #include <sys/ioctl.h>
72 #include <unistd.h>
73 
74 #include "vts_kernel_encryption.h"
75 
76 #ifndef F2FS_IOCTL_MAGIC
77 #define F2FS_IOCTL_MAGIC 0xf5
78 #endif
79 #ifndef F2FS_IOC_SET_PIN_FILE
80 #define F2FS_IOC_SET_PIN_FILE _IOW(F2FS_IOCTL_MAGIC, 13, __u32)
81 #endif
82 
83 namespace android {
84 namespace kernel {
85 
86 // Assumed size of filesystem blocks, in bytes
87 constexpr int kFilesystemBlockSize = 4096;
88 
89 // Size of the test file in filesystem blocks
90 constexpr int kTestFileBlocks = 256;
91 
92 // Size of the test file in bytes
93 constexpr int kTestFileBytes = kFilesystemBlockSize * kTestFileBlocks;
94 
95 // fscrypt master key size in bytes
96 constexpr int kFscryptMasterKeySize = 64;
97 
98 // fscrypt maximum IV size in bytes
99 constexpr int kFscryptMaxIVSize = 32;
100 
101 // fscrypt per-file nonce size in bytes
102 constexpr int kFscryptFileNonceSize = 16;
103 
104 // fscrypt HKDF context bytes, from kernel fs/crypto/fscrypt_private.h
105 enum FscryptHkdfContext {
106   HKDF_CONTEXT_KEY_IDENTIFIER = 1,
107   HKDF_CONTEXT_PER_FILE_ENC_KEY = 2,
108   HKDF_CONTEXT_DIRECT_KEY = 3,
109   HKDF_CONTEXT_IV_INO_LBLK_64_KEY = 4,
110   HKDF_CONTEXT_DIRHASH_KEY = 5,
111   HKDF_CONTEXT_IV_INO_LBLK_32_KEY = 6,
112   HKDF_CONTEXT_INODE_HASH_KEY = 7,
113 };
114 
115 struct FscryptFileNonce {
116   uint8_t bytes[kFscryptFileNonceSize];
117 };
118 
119 // Format of the initialization vector
120 union FscryptIV {
121   struct {
122     __le32 lblk_num;      // file logical block number, starts at 0
123     __le32 inode_number;  // only used for IV_INO_LBLK_64
124     uint8_t file_nonce[kFscryptFileNonceSize];  // only used for DIRECT_KEY
125   };
126   uint8_t bytes[kFscryptMaxIVSize];
127 };
128 
129 struct TestFileInfo {
130   std::vector<uint8_t> plaintext;
131   std::vector<uint8_t> actual_ciphertext;
132   uint64_t inode_number;
133   FscryptFileNonce nonce;
134 };
135 
GetInodeNumber(const std::string & path,uint64_t * inode_number)136 static bool GetInodeNumber(const std::string &path, uint64_t *inode_number) {
137   struct stat stbuf;
138   if (stat(path.c_str(), &stbuf) != 0) {
139     ADD_FAILURE() << "Failed to stat " << path << Errno();
140     return false;
141   }
142   *inode_number = stbuf.st_ino;
143   return true;
144 }
145 
146 //
147 // Checks whether the kernel has support for the following fscrypt features:
148 //
149 // - Filesystem-level keyring (FS_IOC_ADD_ENCRYPTION_KEY and
150 //   FS_IOC_REMOVE_ENCRYPTION_KEY)
151 // - v2 encryption policies
152 // - The IV_INO_LBLK_64 encryption policy flag
153 // - The FS_IOC_GET_ENCRYPTION_NONCE ioctl
154 // - The IV_INO_LBLK_32 encryption policy flag
155 //
156 // To do this it's sufficient to just check whether FS_IOC_ADD_ENCRYPTION_KEY is
157 // available, as the other features were added in the same AOSP release.
158 //
159 // The easiest way to do this is to just execute the ioctl with a NULL argument.
160 // If available it will fail with EFAULT; otherwise it will fail with ENOTTY.
161 //
IsFscryptV2Supported(const std::string & mountpoint)162 static bool IsFscryptV2Supported(const std::string &mountpoint) {
163   android::base::unique_fd fd(
164       open(mountpoint.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
165   if (fd < 0) {
166     ADD_FAILURE() << "Failed to open " << mountpoint << Errno();
167     return false;
168   }
169 
170   if (ioctl(fd, FS_IOC_ADD_ENCRYPTION_KEY, nullptr) == 0) {
171     ADD_FAILURE()
172         << "FS_IOC_ADD_ENCRYPTION_KEY(nullptr) unexpectedly succeeded on "
173         << mountpoint;
174     return false;
175   }
176   switch (errno) {
177     case EFAULT:
178       return true;
179     case ENOTTY:
180       GTEST_LOG_(INFO) << "No support for FS_IOC_ADD_ENCRYPTION_KEY on "
181                        << mountpoint;
182       return false;
183     default:
184       ADD_FAILURE()
185           << "Unexpected error from FS_IOC_ADD_ENCRYPTION_KEY(nullptr) on "
186           << mountpoint << Errno();
187       return false;
188   }
189 }
190 
191 // Helper class to pin / unpin a file on f2fs, to prevent f2fs from moving the
192 // file's blocks while the test is accessing them via the underlying device.
193 //
194 // This can be used without checking the filesystem type, since on other
195 // filesystem types F2FS_IOC_SET_PIN_FILE will just fail and do nothing.
196 class ScopedF2fsFilePinning {
197  public:
ScopedF2fsFilePinning(int fd)198   explicit ScopedF2fsFilePinning(int fd) : fd_(fd) {
199     __u32 set = 1;
200     ioctl(fd_, F2FS_IOC_SET_PIN_FILE, &set);
201   }
202 
~ScopedF2fsFilePinning()203   ~ScopedF2fsFilePinning() {
204     __u32 set = 0;
205     ioctl(fd_, F2FS_IOC_SET_PIN_FILE, &set);
206   }
207 
208  private:
209   int fd_;
210 };
211 
212 // Reads the raw data of the file specified by |fd| from its underlying block
213 // device |blk_device|.  The file has |expected_data_size| bytes of initialized
214 // data; this must be a multiple of the filesystem block size
215 // kFilesystemBlockSize.  The file may contain holes, in which case only the
216 // 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)217 static bool ReadRawDataOfFile(int fd, const std::string &blk_device,
218                               int expected_data_size,
219                               std::vector<uint8_t> *raw_data) {
220   int max_extents = expected_data_size / kFilesystemBlockSize;
221 
222   EXPECT_TRUE(expected_data_size % kFilesystemBlockSize == 0);
223 
224   // It's not entirely clear how F2FS_IOC_SET_PIN_FILE interacts with dirty
225   // data, so do an extra sync here and don't just rely on FIEMAP_FLAG_SYNC.
226   if (fsync(fd) != 0) {
227     ADD_FAILURE() << "Failed to sync file" << Errno();
228     return false;
229   }
230 
231   ScopedF2fsFilePinning pinned_file(fd);  // no-op on non-f2fs
232 
233   // Query the file's extents.
234   size_t allocsize = offsetof(struct fiemap, fm_extents[max_extents]);
235   std::unique_ptr<struct fiemap> map(
236       new (::operator new(allocsize)) struct fiemap);
237   memset(map.get(), 0, allocsize);
238   map->fm_flags = FIEMAP_FLAG_SYNC;
239   map->fm_length = UINT64_MAX;
240   map->fm_extent_count = max_extents;
241   if (ioctl(fd, FS_IOC_FIEMAP, map.get()) != 0) {
242     ADD_FAILURE() << "Failed to get extents of file" << Errno();
243     return false;
244   }
245 
246   // Read the raw data, using direct I/O to avoid getting any stale cached data.
247   // Direct I/O requires using a block size aligned buffer.
248 
249   std::unique_ptr<void, void (*)(void *)> buf_mem(
250       aligned_alloc(kFilesystemBlockSize, expected_data_size), free);
251   if (buf_mem == nullptr) {
252     ADD_FAILURE() << "Out of memory";
253     return false;
254   }
255   uint8_t *buf = static_cast<uint8_t *>(buf_mem.get());
256   int offset = 0;
257 
258   android::base::unique_fd blk_fd(
259       open(blk_device.c_str(), O_RDONLY | O_DIRECT | O_CLOEXEC));
260   if (blk_fd < 0) {
261     ADD_FAILURE() << "Failed to open raw block device " << blk_device
262                   << Errno();
263     return false;
264   }
265 
266   for (int i = 0; i < map->fm_mapped_extents; i++) {
267     const struct fiemap_extent &extent = map->fm_extents[i];
268 
269     GTEST_LOG_(INFO) << "Extent " << i + 1 << " of " << map->fm_mapped_extents
270                      << " is logical offset " << extent.fe_logical
271                      << ", physical offset " << extent.fe_physical
272                      << ", length " << extent.fe_length << ", flags 0x"
273                      << std::hex << extent.fe_flags << std::dec;
274     // Make sure the flags indicate that fe_physical is actually valid.
275     if (extent.fe_flags & (FIEMAP_EXTENT_UNKNOWN | FIEMAP_EXTENT_UNWRITTEN)) {
276       ADD_FAILURE() << "Unsupported extent flags: 0x" << std::hex
277                     << extent.fe_flags << std::dec;
278       return false;
279     }
280     if (extent.fe_length % kFilesystemBlockSize != 0) {
281       ADD_FAILURE() << "Extent is not aligned to filesystem block size";
282       return false;
283     }
284     if (extent.fe_length > expected_data_size - offset) {
285       ADD_FAILURE() << "File is longer than expected";
286       return false;
287     }
288     if (pread(blk_fd, &buf[offset], extent.fe_length, extent.fe_physical) !=
289         extent.fe_length) {
290       ADD_FAILURE() << "Error reading raw data from block device" << Errno();
291       return false;
292     }
293     offset += extent.fe_length;
294   }
295   if (offset != expected_data_size) {
296     ADD_FAILURE() << "File is shorter than expected";
297     return false;
298   }
299   *raw_data = std::vector<uint8_t>(&buf[0], &buf[offset]);
300   return true;
301 }
302 
303 // Writes |plaintext| to a file |path| located on the block device |blk_device|.
304 // 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,std::vector<uint8_t> * ciphertext)305 static bool WriteTestFile(const std::vector<uint8_t> &plaintext,
306                           const std::string &path,
307                           const std::string &blk_device,
308                           std::vector<uint8_t> *ciphertext) {
309   GTEST_LOG_(INFO) << "Creating test file " << path << " containing "
310                    << plaintext.size() << " bytes of data";
311   android::base::unique_fd fd(
312       open(path.c_str(), O_WRONLY | O_CREAT | O_CLOEXEC, 0600));
313   if (fd < 0) {
314     ADD_FAILURE() << "Failed to create " << path << Errno();
315     return false;
316   }
317   if (!android::base::WriteFully(fd, plaintext.data(), plaintext.size())) {
318     ADD_FAILURE() << "Error writing to " << path << Errno();
319     return false;
320   }
321 
322   GTEST_LOG_(INFO) << "Reading the raw ciphertext of " << path << " from disk";
323   if (!ReadRawDataOfFile(fd, blk_device, plaintext.size(), ciphertext)) {
324     ADD_FAILURE() << "Failed to read the raw ciphertext of " << path;
325     return false;
326   }
327   return true;
328 }
329 
330 class FBEPolicyTest : public ::testing::Test {
331  protected:
332   // Location of the test directory and file.  Since it's not possible to
333   // override an existing encryption policy, in order for these tests to set
334   // their own encryption policy the parent directory must be unencrypted.
335   static constexpr const char *kTestMountpoint = "/data";
336   static constexpr const char *kTestDir = "/data/unencrypted/vts-test-dir";
337   static constexpr const char *kTestFile =
338       "/data/unencrypted/vts-test-dir/file";
339 
340   void SetUp() override;
341   void TearDown() override;
342   bool SetMasterKey(const std::vector<uint8_t> &master_key, uint32_t flags = 0,
343                     bool required = true);
344   bool CreateAndSetHwWrappedKey(std::vector<uint8_t> *enc_key,
345                                 std::vector<uint8_t> *sw_secret);
346   int GetSkipFlagsForInoBasedEncryption();
347   bool SetEncryptionPolicy(int contents_mode, int filenames_mode, int flags,
348                            int skip_flags);
349   bool GenerateTestFile(TestFileInfo *info);
350   bool VerifyKeyIdentifier(const std::vector<uint8_t> &master_key);
351   bool DerivePerModeEncryptionKey(const std::vector<uint8_t> &master_key,
352                                   int mode, FscryptHkdfContext context,
353                                   std::vector<uint8_t> &enc_key);
354   bool DerivePerFileEncryptionKey(const std::vector<uint8_t> &master_key,
355                                   const FscryptFileNonce &nonce,
356                                   std::vector<uint8_t> &enc_key);
357   void VerifyCiphertext(const std::vector<uint8_t> &enc_key,
358                         const FscryptIV &starting_iv, const Cipher &cipher,
359                         const TestFileInfo &file_info);
360   void TestEmmcOptimizedDunWraparound(const std::vector<uint8_t> &master_key,
361                                       const std::vector<uint8_t> &enc_key);
362   struct fscrypt_key_specifier master_key_specifier_;
363   bool skip_test_ = false;
364   bool key_added_ = false;
365   FilesystemInfo fs_info_;
366 };
367 
368 // Test setup procedure.  Creates a test directory kTestDir and does other
369 // preparations. skip_test_ is set to true if the test should be skipped.
SetUp()370 void FBEPolicyTest::SetUp() {
371   if (!IsFscryptV2Supported(kTestMountpoint)) {
372     int first_api_level;
373     ASSERT_TRUE(GetFirstApiLevel(&first_api_level));
374     // Devices launching with R or higher must support fscrypt v2.
375     ASSERT_LE(first_api_level, __ANDROID_API_Q__);
376     GTEST_LOG_(INFO) << "Skipping test because fscrypt v2 is unsupported";
377     skip_test_ = true;
378     return;
379   }
380 
381   ASSERT_TRUE(GetFilesystemInfo(kTestMountpoint, &fs_info_));
382 
383   DeleteRecursively(kTestDir);
384   if (mkdir(kTestDir, 0700) != 0) {
385     FAIL() << "Failed to create " << kTestDir << Errno();
386   }
387 }
388 
TearDown()389 void FBEPolicyTest::TearDown() {
390   DeleteRecursively(kTestDir);
391 
392   // Remove the test key from kTestMountpoint.
393   if (key_added_) {
394     android::base::unique_fd mntfd(
395         open(kTestMountpoint, O_RDONLY | O_DIRECTORY | O_CLOEXEC));
396     if (mntfd < 0) {
397       FAIL() << "Failed to open " << kTestMountpoint << Errno();
398     }
399     struct fscrypt_remove_key_arg arg;
400     memset(&arg, 0, sizeof(arg));
401     arg.key_spec = master_key_specifier_;
402 
403     if (ioctl(mntfd, FS_IOC_REMOVE_ENCRYPTION_KEY, &arg) != 0) {
404       FAIL() << "FS_IOC_REMOVE_ENCRYPTION_KEY failed on " << kTestMountpoint
405              << Errno();
406     }
407   }
408 }
409 
410 // Adds |master_key| to kTestMountpoint and places the resulting key identifier
411 // in master_key_specifier_.
SetMasterKey(const std::vector<uint8_t> & master_key,uint32_t flags,bool required)412 bool FBEPolicyTest::SetMasterKey(const std::vector<uint8_t> &master_key,
413                                  uint32_t flags, bool required) {
414   size_t allocsize = sizeof(struct fscrypt_add_key_arg) + master_key.size();
415   std::unique_ptr<struct fscrypt_add_key_arg> arg(
416       new (::operator new(allocsize)) struct fscrypt_add_key_arg);
417   memset(arg.get(), 0, allocsize);
418   arg->key_spec.type = FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER;
419   arg->__flags = flags;
420   arg->raw_size = master_key.size();
421   std::copy(master_key.begin(), master_key.end(), arg->raw);
422 
423   GTEST_LOG_(INFO) << "Adding fscrypt master key, flags are 0x" << std::hex
424                    << flags << std::dec << ", raw bytes are "
425                    << BytesToHex(master_key);
426   android::base::unique_fd mntfd(
427       open(kTestMountpoint, O_RDONLY | O_DIRECTORY | O_CLOEXEC));
428   if (mntfd < 0) {
429     ADD_FAILURE() << "Failed to open " << kTestMountpoint << Errno();
430     return false;
431   }
432   if (ioctl(mntfd, FS_IOC_ADD_ENCRYPTION_KEY, arg.get()) != 0) {
433     if (required || (errno != EINVAL && errno != EOPNOTSUPP)) {
434       ADD_FAILURE() << "FS_IOC_ADD_ENCRYPTION_KEY failed on " << kTestMountpoint
435                     << Errno();
436     }
437     return false;
438   }
439   master_key_specifier_ = arg->key_spec;
440   GTEST_LOG_(INFO) << "Master key identifier is "
441                    << BytesToHex(master_key_specifier_.u.identifier);
442   key_added_ = true;
443   if (!(flags & __FSCRYPT_ADD_KEY_FLAG_HW_WRAPPED) &&
444       !VerifyKeyIdentifier(master_key))
445     return false;
446   return true;
447 }
448 
449 // Creates a hardware-wrapped key, adds it to the filesystem, and derives the
450 // corresponding inline encryption key |enc_key| and software secret
451 // |sw_secret|.  Returns false if unsuccessful (either the test failed, or the
452 // 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)453 bool FBEPolicyTest::CreateAndSetHwWrappedKey(std::vector<uint8_t> *enc_key,
454                                              std::vector<uint8_t> *sw_secret) {
455   std::vector<uint8_t> master_key, exported_key;
456   if (!CreateHwWrappedKey(&master_key, &exported_key)) return false;
457 
458   if (!SetMasterKey(exported_key, __FSCRYPT_ADD_KEY_FLAG_HW_WRAPPED, false)) {
459     if (!HasFailure()) {
460       GTEST_LOG_(INFO) << "Skipping test because kernel doesn't support "
461                           "hardware-wrapped keys";
462     }
463     return false;
464   }
465 
466   if (!DeriveHwWrappedEncryptionKey(master_key, enc_key)) return false;
467   if (!DeriveHwWrappedRawSecret(master_key, sw_secret)) return false;
468 
469   if (!VerifyKeyIdentifier(*sw_secret)) return false;
470 
471   return true;
472 }
473 
474 enum {
475   kSkipIfNoPolicySupport = 1 << 0,
476   kSkipIfNoCryptoAPISupport = 1 << 1,
477   kSkipIfNoHardwareSupport = 1 << 2,
478 };
479 
480 // Returns 0 if encryption policies that include the inode number in the IVs
481 // (e.g. IV_INO_LBLK_64) are guaranteed to be settable on the test filesystem.
482 // Else returns kSkipIfNoPolicySupport.
483 //
484 // On f2fs, they're always settable.  On ext4, they're only settable if the
485 // filesystem has the 'stable_inodes' feature flag.  Android only sets
486 // 'stable_inodes' if the device uses one of these encryption policies "for
487 // real", e.g. "fileencryption=::inlinecrypt_optimized" in fstab.  Since the
488 // fstab could contain something else, we have to allow the tests for these
489 // encryption policies to be skipped on ext4.
GetSkipFlagsForInoBasedEncryption()490 int FBEPolicyTest::GetSkipFlagsForInoBasedEncryption() {
491   if (fs_info_.type == "ext4") return kSkipIfNoPolicySupport;
492   return 0;
493 }
494 
495 // Sets a v2 encryption policy on the test directory.  The policy will use the
496 // test key and the specified encryption modes and flags.  If the kernel doesn't
497 // support setting or using the encryption policy, then a failure will be added,
498 // unless the reason is covered by a bit set in |skip_flags|.
SetEncryptionPolicy(int contents_mode,int filenames_mode,int flags,int skip_flags)499 bool FBEPolicyTest::SetEncryptionPolicy(int contents_mode, int filenames_mode,
500                                         int flags, int skip_flags) {
501   if (!key_added_) {
502     ADD_FAILURE() << "SetEncryptionPolicy called but no key added";
503     return false;
504   }
505 
506   struct fscrypt_policy_v2 policy;
507   memset(&policy, 0, sizeof(policy));
508   policy.version = FSCRYPT_POLICY_V2;
509   policy.contents_encryption_mode = contents_mode;
510   policy.filenames_encryption_mode = filenames_mode;
511   // Always give PAD_16, to match the policies that Android sets for real.
512   // It doesn't affect contents encryption, though.
513   policy.flags = flags | FSCRYPT_POLICY_FLAGS_PAD_16;
514   memcpy(policy.master_key_identifier, master_key_specifier_.u.identifier,
515          FSCRYPT_KEY_IDENTIFIER_SIZE);
516 
517   android::base::unique_fd dirfd(
518       open(kTestDir, O_RDONLY | O_DIRECTORY | O_CLOEXEC));
519   if (dirfd < 0) {
520     ADD_FAILURE() << "Failed to open " << kTestDir << Errno();
521     return false;
522   }
523   GTEST_LOG_(INFO) << "Setting encryption policy on " << kTestDir;
524   if (ioctl(dirfd, FS_IOC_SET_ENCRYPTION_POLICY, &policy) != 0) {
525     if (errno == EINVAL && (skip_flags & kSkipIfNoPolicySupport)) {
526       GTEST_LOG_(INFO) << "Skipping test because encryption policy is "
527                           "unsupported on this filesystem / kernel";
528       return false;
529     }
530     ADD_FAILURE() << "FS_IOC_SET_ENCRYPTION_POLICY failed on " << kTestDir
531                   << " using contents_mode=" << contents_mode
532                   << ", filenames_mode=" << filenames_mode << ", flags=0x"
533                   << std::hex << flags << std::dec << Errno();
534     return false;
535   }
536   if (skip_flags & (kSkipIfNoCryptoAPISupport | kSkipIfNoHardwareSupport)) {
537     android::base::unique_fd fd(
538         open(kTestFile, O_WRONLY | O_CREAT | O_CLOEXEC, 0600));
539     if (fd < 0) {
540       // Setting an encryption policy that uses modes that aren't enabled in the
541       // kernel's crypto API (e.g. FSCRYPT_MODE_ADIANTUM when the kernel lacks
542       // CONFIG_CRYPTO_ADIANTUM) will still succeed, but actually creating a
543       // file will fail with ENOPKG.  Make sure to check for this case.
544       if (errno == ENOPKG && (skip_flags & kSkipIfNoCryptoAPISupport)) {
545         GTEST_LOG_(INFO)
546             << "Skipping test because encryption policy is "
547                "unsupported on this kernel, due to missing crypto API support";
548         return false;
549       }
550       // We get EINVAL here when using a hardware-wrapped key and the inline
551       // encryption hardware supports wrapped keys but doesn't support the
552       // number of DUN bytes that the file contents encryption requires.
553       if (errno == EINVAL && (skip_flags & kSkipIfNoHardwareSupport)) {
554         GTEST_LOG_(INFO)
555             << "Skipping test because encryption policy is not compatible with "
556                "this device's inline encryption hardware";
557         return false;
558       }
559     }
560     unlink(kTestFile);
561   }
562   return true;
563 }
564 
565 // Generates some test data, writes it to a file in the test directory, and
566 // returns in |info| the file's plaintext, the file's raw ciphertext read from
567 // disk, and other information about the file.
GenerateTestFile(TestFileInfo * info)568 bool FBEPolicyTest::GenerateTestFile(TestFileInfo *info) {
569   info->plaintext.resize(kTestFileBytes);
570   RandomBytesForTesting(info->plaintext);
571 
572   if (!WriteTestFile(info->plaintext, kTestFile, fs_info_.raw_blk_device,
573                      &info->actual_ciphertext))
574     return false;
575 
576   android::base::unique_fd fd(open(kTestFile, O_RDONLY | O_CLOEXEC));
577   if (fd < 0) {
578     ADD_FAILURE() << "Failed to open " << kTestFile << Errno();
579     return false;
580   }
581 
582   // Get the file's inode number.
583   if (!GetInodeNumber(kTestFile, &info->inode_number)) return false;
584   GTEST_LOG_(INFO) << "Inode number: " << info->inode_number;
585 
586   // Get the file's nonce.
587   if (ioctl(fd, FS_IOC_GET_ENCRYPTION_NONCE, info->nonce.bytes) != 0) {
588     ADD_FAILURE() << "FS_IOC_GET_ENCRYPTION_NONCE failed on " << kTestFile
589                   << Errno();
590     return false;
591   }
592   GTEST_LOG_(INFO) << "File nonce: " << BytesToHex(info->nonce.bytes);
593   return true;
594 }
595 
InitHkdfInfo(FscryptHkdfContext context)596 static std::vector<uint8_t> InitHkdfInfo(FscryptHkdfContext context) {
597   return {
598       'f', 's', 'c', 'r', 'y', 'p', 't', '\0', static_cast<uint8_t>(context)};
599 }
600 
DeriveKey(const std::vector<uint8_t> & master_key,const std::vector<uint8_t> & hkdf_info,std::vector<uint8_t> & out)601 static bool DeriveKey(const std::vector<uint8_t> &master_key,
602                       const std::vector<uint8_t> &hkdf_info,
603                       std::vector<uint8_t> &out) {
604   if (HKDF(out.data(), out.size(), EVP_sha512(), master_key.data(),
605            master_key.size(), nullptr, 0, hkdf_info.data(),
606            hkdf_info.size()) != 1) {
607     ADD_FAILURE() << "BoringSSL HKDF-SHA512 call failed";
608     return false;
609   }
610   GTEST_LOG_(INFO) << "Derived subkey " << BytesToHex(out)
611                    << " using HKDF info " << BytesToHex(hkdf_info);
612   return true;
613 }
614 
615 // Derives the key identifier from |master_key| and verifies that it matches the
616 // value the kernel returned in |master_key_specifier_|.
VerifyKeyIdentifier(const std::vector<uint8_t> & master_key)617 bool FBEPolicyTest::VerifyKeyIdentifier(
618     const std::vector<uint8_t> &master_key) {
619   std::vector<uint8_t> hkdf_info = InitHkdfInfo(HKDF_CONTEXT_KEY_IDENTIFIER);
620   std::vector<uint8_t> computed_key_identifier(FSCRYPT_KEY_IDENTIFIER_SIZE);
621   if (!DeriveKey(master_key, hkdf_info, computed_key_identifier)) return false;
622 
623   std::vector<uint8_t> actual_key_identifier(
624       std::begin(master_key_specifier_.u.identifier),
625       std::end(master_key_specifier_.u.identifier));
626   EXPECT_EQ(actual_key_identifier, computed_key_identifier);
627   return actual_key_identifier == computed_key_identifier;
628 }
629 
630 // Derives a per-mode encryption key from |master_key|, |mode|, |context|, and
631 // (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)632 bool FBEPolicyTest::DerivePerModeEncryptionKey(
633     const std::vector<uint8_t> &master_key, int mode,
634     FscryptHkdfContext context, std::vector<uint8_t> &enc_key) {
635   std::vector<uint8_t> hkdf_info = InitHkdfInfo(context);
636 
637   hkdf_info.push_back(mode);
638   if (context == HKDF_CONTEXT_IV_INO_LBLK_64_KEY ||
639       context == HKDF_CONTEXT_IV_INO_LBLK_32_KEY)
640     hkdf_info.insert(hkdf_info.end(), fs_info_.uuid.bytes,
641                      std::end(fs_info_.uuid.bytes));
642 
643   return DeriveKey(master_key, hkdf_info, enc_key);
644 }
645 
646 // 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)647 bool FBEPolicyTest::DerivePerFileEncryptionKey(
648     const std::vector<uint8_t> &master_key, const FscryptFileNonce &nonce,
649     std::vector<uint8_t> &enc_key) {
650   std::vector<uint8_t> hkdf_info = InitHkdfInfo(HKDF_CONTEXT_PER_FILE_ENC_KEY);
651 
652   hkdf_info.insert(hkdf_info.end(), nonce.bytes, std::end(nonce.bytes));
653 
654   return DeriveKey(master_key, hkdf_info, enc_key);
655 }
656 
657 // For IV_INO_LBLK_32: Hashes the |inode_number| using the SipHash key derived
658 // from |master_key|.  Returns the resulting hash in |hash|.
HashInodeNumber(const std::vector<uint8_t> & master_key,uint64_t inode_number,uint32_t * hash)659 static bool HashInodeNumber(const std::vector<uint8_t> &master_key,
660                             uint64_t inode_number, uint32_t *hash) {
661   union {
662     uint64_t words[2];
663     __le64 le_words[2];
664   } siphash_key;
665   union {
666     __le64 inode_number;
667     uint8_t bytes[8];
668   } input;
669 
670   std::vector<uint8_t> hkdf_info = InitHkdfInfo(HKDF_CONTEXT_INODE_HASH_KEY);
671   std::vector<uint8_t> ino_hash_key(sizeof(siphash_key));
672   if (!DeriveKey(master_key, hkdf_info, ino_hash_key)) return false;
673 
674   memcpy(&siphash_key, &ino_hash_key[0], sizeof(siphash_key));
675   siphash_key.words[0] = __le64_to_cpu(siphash_key.le_words[0]);
676   siphash_key.words[1] = __le64_to_cpu(siphash_key.le_words[1]);
677 
678   GTEST_LOG_(INFO) << "Inode hash key is {" << std::hex << "0x"
679                    << siphash_key.words[0] << ", 0x" << siphash_key.words[1]
680                    << "}" << std::dec;
681 
682   input.inode_number = __cpu_to_le64(inode_number);
683 
684   *hash = SIPHASH_24(siphash_key.words, input.bytes, sizeof(input));
685   GTEST_LOG_(INFO) << "Hashed inode number " << inode_number << " to 0x"
686                    << std::hex << *hash << std::dec;
687   return true;
688 }
689 
VerifyCiphertext(const std::vector<uint8_t> & enc_key,const FscryptIV & starting_iv,const Cipher & cipher,const TestFileInfo & file_info)690 void FBEPolicyTest::VerifyCiphertext(const std::vector<uint8_t> &enc_key,
691                                      const FscryptIV &starting_iv,
692                                      const Cipher &cipher,
693                                      const TestFileInfo &file_info) {
694   const std::vector<uint8_t> &plaintext = file_info.plaintext;
695 
696   GTEST_LOG_(INFO) << "Verifying correctness of encrypted data";
697   FscryptIV iv = starting_iv;
698 
699   std::vector<uint8_t> computed_ciphertext(plaintext.size());
700 
701   // Encrypt each filesystem block of file contents.
702   for (size_t i = 0; i < plaintext.size(); i += kFilesystemBlockSize) {
703     int block_size =
704         std::min<size_t>(kFilesystemBlockSize, plaintext.size() - i);
705 
706     ASSERT_GE(sizeof(iv.bytes), cipher.ivsize());
707     ASSERT_TRUE(cipher.Encrypt(enc_key, iv.bytes, &plaintext[i],
708                                &computed_ciphertext[i], block_size));
709 
710     // Update the IV by incrementing the file logical block number.
711     iv.lblk_num = __cpu_to_le32(__le32_to_cpu(iv.lblk_num) + 1);
712   }
713 
714   ASSERT_EQ(file_info.actual_ciphertext, computed_ciphertext);
715 }
716 
InitIVForPerFileKey(FscryptIV * iv)717 static bool InitIVForPerFileKey(FscryptIV *iv) {
718   memset(iv, 0, kFscryptMaxIVSize);
719   return true;
720 }
721 
InitIVForDirectKey(const FscryptFileNonce & nonce,FscryptIV * iv)722 static bool InitIVForDirectKey(const FscryptFileNonce &nonce, FscryptIV *iv) {
723   memset(iv, 0, kFscryptMaxIVSize);
724   memcpy(iv->file_nonce, nonce.bytes, kFscryptFileNonceSize);
725   return true;
726 }
727 
InitIVForInoLblk64(uint64_t inode_number,FscryptIV * iv)728 static bool InitIVForInoLblk64(uint64_t inode_number, FscryptIV *iv) {
729   if (inode_number > UINT32_MAX) {
730     ADD_FAILURE() << "inode number doesn't fit in 32 bits";
731     return false;
732   }
733   memset(iv, 0, kFscryptMaxIVSize);
734   iv->inode_number = __cpu_to_le32(inode_number);
735   return true;
736 }
737 
InitIVForInoLblk32(const std::vector<uint8_t> & master_key,uint64_t inode_number,FscryptIV * iv)738 static bool InitIVForInoLblk32(const std::vector<uint8_t> &master_key,
739                                uint64_t inode_number, FscryptIV *iv) {
740   uint32_t hash;
741   if (!HashInodeNumber(master_key, inode_number, &hash)) return false;
742   memset(iv, 0, kFscryptMaxIVSize);
743   iv->lblk_num = __cpu_to_le32(hash);
744   return true;
745 }
746 
747 // Tests a policy matching "fileencryption=aes-256-xts:aes-256-cts:v2"
748 // (or simply "fileencryption=" on devices launched with R or higher)
TEST_F(FBEPolicyTest,TestAesPerFileKeysPolicy)749 TEST_F(FBEPolicyTest, TestAesPerFileKeysPolicy) {
750   if (skip_test_) return;
751 
752   auto master_key = GenerateTestKey(kFscryptMasterKeySize);
753   ASSERT_TRUE(SetMasterKey(master_key));
754 
755   if (!SetEncryptionPolicy(FSCRYPT_MODE_AES_256_XTS, FSCRYPT_MODE_AES_256_CTS,
756                            0, 0))
757     return;
758 
759   TestFileInfo file_info;
760   ASSERT_TRUE(GenerateTestFile(&file_info));
761 
762   std::vector<uint8_t> enc_key(kAes256XtsKeySize);
763   ASSERT_TRUE(DerivePerFileEncryptionKey(master_key, file_info.nonce, enc_key));
764 
765   FscryptIV iv;
766   ASSERT_TRUE(InitIVForPerFileKey(&iv));
767   VerifyCiphertext(enc_key, iv, Aes256XtsCipher(), file_info);
768 }
769 
770 // Tests a policy matching
771 // "fileencryption=aes-256-xts:aes-256-cts:v2+inlinecrypt_optimized"
772 // (or simply "fileencryption=::inlinecrypt_optimized" on devices launched with
773 // R or higher)
TEST_F(FBEPolicyTest,TestAesInlineCryptOptimizedPolicy)774 TEST_F(FBEPolicyTest, TestAesInlineCryptOptimizedPolicy) {
775   if (skip_test_) return;
776 
777   auto master_key = GenerateTestKey(kFscryptMasterKeySize);
778   ASSERT_TRUE(SetMasterKey(master_key));
779 
780   if (!SetEncryptionPolicy(FSCRYPT_MODE_AES_256_XTS, FSCRYPT_MODE_AES_256_CTS,
781                            FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64,
782                            GetSkipFlagsForInoBasedEncryption()))
783     return;
784 
785   TestFileInfo file_info;
786   ASSERT_TRUE(GenerateTestFile(&file_info));
787 
788   std::vector<uint8_t> enc_key(kAes256XtsKeySize);
789   ASSERT_TRUE(DerivePerModeEncryptionKey(master_key, FSCRYPT_MODE_AES_256_XTS,
790                                          HKDF_CONTEXT_IV_INO_LBLK_64_KEY,
791                                          enc_key));
792 
793   FscryptIV iv;
794   ASSERT_TRUE(InitIVForInoLblk64(file_info.inode_number, &iv));
795   VerifyCiphertext(enc_key, iv, Aes256XtsCipher(), file_info);
796 }
797 
798 // Tests a policy matching
799 // "fileencryption=aes-256-xts:aes-256-cts:v2+inlinecrypt_optimized+wrappedkey_v0"
800 // (or simply "fileencryption=::inlinecrypt_optimized+wrappedkey_v0" on devices
801 // launched with R or higher)
TEST_F(FBEPolicyTest,TestAesInlineCryptOptimizedHwWrappedKeyPolicy)802 TEST_F(FBEPolicyTest, TestAesInlineCryptOptimizedHwWrappedKeyPolicy) {
803   if (skip_test_) return;
804 
805   std::vector<uint8_t> enc_key, sw_secret;
806   if (!CreateAndSetHwWrappedKey(&enc_key, &sw_secret)) return;
807 
808   if (!SetEncryptionPolicy(
809           FSCRYPT_MODE_AES_256_XTS, FSCRYPT_MODE_AES_256_CTS,
810           FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64,
811           // 64-bit DUN support is not guaranteed.
812           kSkipIfNoHardwareSupport | GetSkipFlagsForInoBasedEncryption()))
813     return;
814 
815   TestFileInfo file_info;
816   ASSERT_TRUE(GenerateTestFile(&file_info));
817 
818   FscryptIV iv;
819   ASSERT_TRUE(InitIVForInoLblk64(file_info.inode_number, &iv));
820   VerifyCiphertext(enc_key, iv, Aes256XtsCipher(), file_info);
821 }
822 
823 // With IV_INO_LBLK_32, the DUN (IV) can wrap from UINT32_MAX to 0 in the middle
824 // of the file.  This method tests that this case appears to be handled
825 // correctly, by doing I/O across the place where the DUN wraps around.  Assumes
826 // that kTestDir 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)827 void FBEPolicyTest::TestEmmcOptimizedDunWraparound(
828     const std::vector<uint8_t> &master_key,
829     const std::vector<uint8_t> &enc_key) {
830   // We'll test writing 'block_count' filesystem blocks.  The first
831   // 'block_count_1' blocks will have DUNs [..., UINT32_MAX - 1, UINT32_MAX].
832   // The remaining 'block_count_2' blocks will have DUNs [0, 1, ...].
833   constexpr uint32_t block_count_1 = 3;
834   constexpr uint32_t block_count_2 = 7;
835   constexpr uint32_t block_count = block_count_1 + block_count_2;
836   constexpr size_t data_size = block_count * kFilesystemBlockSize;
837 
838   // Assumed maximum file size.  Unfortunately there isn't a syscall to get
839   // this.  ext4 allows ~16TB and f2fs allows ~4TB.  However, an underestimate
840   // works fine for our purposes, so just go with 1TB.
841   constexpr off_t max_file_size = 1000000000000;
842   constexpr off_t max_file_blocks = max_file_size / kFilesystemBlockSize;
843 
844   // Repeatedly create empty files until we find one that can be used for DUN
845   // wraparound testing, due to SipHash(inode_number) being almost UINT32_MAX.
846   std::string path;
847   TestFileInfo file_info;
848   uint32_t lblk_with_dun_0;
849   for (int i = 0;; i++) {
850     // The probability of finding a usable file is about 'max_file_blocks /
851     // UINT32_MAX', or about 5.6%.  So on average we'll need about 18 tries.
852     // The probability we'll need over 1000 tries is less than 1e-25.
853     ASSERT_LT(i, 1000) << "Tried too many times to find a usable test file";
854 
855     path = android::base::StringPrintf("%s/file%d", kTestDir, i);
856     android::base::unique_fd fd(
857         open(path.c_str(), O_WRONLY | O_CREAT | O_CLOEXEC, 0600));
858     ASSERT_GE(fd, 0) << "Failed to create " << path << Errno();
859 
860     ASSERT_TRUE(GetInodeNumber(path, &file_info.inode_number));
861     uint32_t hash;
862     ASSERT_TRUE(HashInodeNumber(master_key, file_info.inode_number, &hash));
863     // Negating the hash gives the distance to DUN 0, and hence the 0-based
864     // logical block number of the block which has DUN 0.
865     lblk_with_dun_0 = -hash;
866     if (lblk_with_dun_0 >= block_count_1 &&
867         static_cast<off_t>(lblk_with_dun_0) + block_count_2 < max_file_blocks)
868       break;
869   }
870 
871   GTEST_LOG_(INFO) << "DUN wraparound test: path=" << path
872                    << ", inode_number=" << file_info.inode_number
873                    << ", lblk_with_dun_0=" << lblk_with_dun_0;
874 
875   // Write some data across the DUN wraparound boundary and verify that the
876   // resulting on-disk ciphertext is as expected.  Note that we don't actually
877   // have to fill the file until the boundary; we can just write to the needed
878   // part and leave a hole before it.
879   for (int i = 0; i < 2; i++) {
880     // Try both buffered I/O and direct I/O.
881     int open_flags = O_RDWR | O_CLOEXEC;
882     if (i == 1) open_flags |= O_DIRECT;
883 
884     android::base::unique_fd fd(open(path.c_str(), open_flags));
885     ASSERT_GE(fd, 0) << "Failed to open " << path << Errno();
886 
887     // Generate some test data.
888     file_info.plaintext.resize(data_size);
889     RandomBytesForTesting(file_info.plaintext);
890 
891     // Write the test data.  To support O_DIRECT, use a block-aligned buffer.
892     std::unique_ptr<void, void (*)(void *)> buf_mem(
893         aligned_alloc(kFilesystemBlockSize, data_size), free);
894     ASSERT_TRUE(buf_mem != nullptr);
895     memcpy(buf_mem.get(), &file_info.plaintext[0], data_size);
896     off_t pos = static_cast<off_t>(lblk_with_dun_0 - block_count_1) *
897                 kFilesystemBlockSize;
898     ASSERT_EQ(data_size, pwrite(fd, buf_mem.get(), data_size, pos))
899         << "Error writing data to " << path << Errno();
900 
901     // Verify the ciphertext.
902     ASSERT_TRUE(ReadRawDataOfFile(fd, fs_info_.raw_blk_device, data_size,
903                                   &file_info.actual_ciphertext));
904     FscryptIV iv;
905     memset(&iv, 0, sizeof(iv));
906     iv.lblk_num = __cpu_to_le32(-block_count_1);
907     VerifyCiphertext(enc_key, iv, Aes256XtsCipher(), file_info);
908   }
909 }
910 
911 // Tests a policy matching
912 // "fileencryption=aes-256-xts:aes-256-cts:v2+emmc_optimized" (or simply
913 // "fileencryption=::emmc_optimized" on devices launched with R or higher)
TEST_F(FBEPolicyTest,TestAesEmmcOptimizedPolicy)914 TEST_F(FBEPolicyTest, TestAesEmmcOptimizedPolicy) {
915   if (skip_test_) return;
916 
917   auto master_key = GenerateTestKey(kFscryptMasterKeySize);
918   ASSERT_TRUE(SetMasterKey(master_key));
919 
920   if (!SetEncryptionPolicy(FSCRYPT_MODE_AES_256_XTS, FSCRYPT_MODE_AES_256_CTS,
921                            FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32,
922                            GetSkipFlagsForInoBasedEncryption()))
923     return;
924 
925   TestFileInfo file_info;
926   ASSERT_TRUE(GenerateTestFile(&file_info));
927 
928   std::vector<uint8_t> enc_key(kAes256XtsKeySize);
929   ASSERT_TRUE(DerivePerModeEncryptionKey(master_key, FSCRYPT_MODE_AES_256_XTS,
930                                          HKDF_CONTEXT_IV_INO_LBLK_32_KEY,
931                                          enc_key));
932 
933   FscryptIV iv;
934   ASSERT_TRUE(InitIVForInoLblk32(master_key, file_info.inode_number, &iv));
935   VerifyCiphertext(enc_key, iv, Aes256XtsCipher(), file_info);
936 
937   TestEmmcOptimizedDunWraparound(master_key, enc_key);
938 }
939 
940 // Tests a policy matching
941 // "fileencryption=aes-256-xts:aes-256-cts:v2+emmc_optimized+wrappedkey_v0"
942 // (or simply "fileencryption=::emmc_optimized+wrappedkey_v0" on devices
943 // launched with R or higher)
TEST_F(FBEPolicyTest,TestAesEmmcOptimizedHwWrappedKeyPolicy)944 TEST_F(FBEPolicyTest, TestAesEmmcOptimizedHwWrappedKeyPolicy) {
945   if (skip_test_) return;
946 
947   std::vector<uint8_t> enc_key, sw_secret;
948   if (!CreateAndSetHwWrappedKey(&enc_key, &sw_secret)) return;
949 
950   if (!SetEncryptionPolicy(FSCRYPT_MODE_AES_256_XTS, FSCRYPT_MODE_AES_256_CTS,
951                            FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32,
952                            GetSkipFlagsForInoBasedEncryption()))
953     return;
954 
955   TestFileInfo file_info;
956   ASSERT_TRUE(GenerateTestFile(&file_info));
957 
958   FscryptIV iv;
959   ASSERT_TRUE(InitIVForInoLblk32(sw_secret, file_info.inode_number, &iv));
960   VerifyCiphertext(enc_key, iv, Aes256XtsCipher(), file_info);
961 
962   TestEmmcOptimizedDunWraparound(sw_secret, enc_key);
963 }
964 
965 // Tests a policy matching "fileencryption=adiantum:adiantum:v2" (or simply
966 // "fileencryption=adiantum" on devices launched with R or higher)
TEST_F(FBEPolicyTest,TestAdiantumPolicy)967 TEST_F(FBEPolicyTest, TestAdiantumPolicy) {
968   if (skip_test_) return;
969 
970   auto master_key = GenerateTestKey(kFscryptMasterKeySize);
971   ASSERT_TRUE(SetMasterKey(master_key));
972 
973   // Adiantum support isn't required (since CONFIG_CRYPTO_ADIANTUM can be unset
974   // in the kernel config), so we may skip the test here.
975   //
976   // We don't need to use GetSkipFlagsForInoBasedEncryption() here, since the
977   // "DIRECT_KEY" IV generation method doesn't include inode numbers in the IVs.
978   if (!SetEncryptionPolicy(FSCRYPT_MODE_ADIANTUM, FSCRYPT_MODE_ADIANTUM,
979                            FSCRYPT_POLICY_FLAG_DIRECT_KEY,
980                            kSkipIfNoCryptoAPISupport))
981     return;
982 
983   TestFileInfo file_info;
984   ASSERT_TRUE(GenerateTestFile(&file_info));
985 
986   std::vector<uint8_t> enc_key(kAdiantumKeySize);
987   ASSERT_TRUE(DerivePerModeEncryptionKey(master_key, FSCRYPT_MODE_ADIANTUM,
988                                          HKDF_CONTEXT_DIRECT_KEY, enc_key));
989 
990   FscryptIV iv;
991   ASSERT_TRUE(InitIVForDirectKey(file_info.nonce, &iv));
992   VerifyCiphertext(enc_key, iv, AdiantumCipher(), file_info);
993 }
994 
995 // Tests adding a corrupted wrapped key to fscrypt keyring.
996 // If wrapped key is corrupted, fscrypt should return a failure.
TEST_F(FBEPolicyTest,TestHwWrappedKeyCorruption)997 TEST_F(FBEPolicyTest, TestHwWrappedKeyCorruption) {
998   if (skip_test_) return;
999 
1000   std::vector<uint8_t> master_key, exported_key;
1001   if (!CreateHwWrappedKey(&master_key, &exported_key)) return;
1002 
1003   for (int i = 0; i < exported_key.size(); i++) {
1004     std::vector<uint8_t> corrupt_key(exported_key.begin(), exported_key.end());
1005     corrupt_key[i] = ~corrupt_key[i];
1006     ASSERT_FALSE(
1007         SetMasterKey(corrupt_key, __FSCRYPT_ADD_KEY_FLAG_HW_WRAPPED, false));
1008   }
1009 }
1010 
1011 // Tests that if the device uses FBE, then the ciphertext for file contents in
1012 // encrypted directories seems to be random.
1013 //
1014 // This isn't as strong a test as the correctness tests, but it's useful because
1015 // it applies regardless of the encryption format and key.  Thus it runs even on
1016 // old devices, including ones that used a vendor-specific encryption format.
TEST(FBETest,TestFileContentsRandomness)1017 TEST(FBETest, TestFileContentsRandomness) {
1018   constexpr const char *path = "/data/local/tmp/vts-test-file";
1019 
1020   if (android::base::GetProperty("ro.crypto.type", "") != "file") {
1021     // FBE has been required since Android Q.
1022     int first_api_level;
1023     ASSERT_TRUE(GetFirstApiLevel(&first_api_level));
1024     ASSERT_LE(first_api_level, __ANDROID_API_P__)
1025         << "File-based encryption is required";
1026     GTEST_LOG_(INFO)
1027         << "Skipping test because device doesn't use file-based encryption";
1028     return;
1029   }
1030   FilesystemInfo fs_info;
1031   ASSERT_TRUE(GetFilesystemInfo("/data", &fs_info));
1032 
1033   std::vector<uint8_t> zeroes(kTestFileBytes, 0);
1034   std::vector<uint8_t> ciphertext;
1035   ASSERT_TRUE(WriteTestFile(zeroes, path, fs_info.raw_blk_device, &ciphertext));
1036 
1037   GTEST_LOG_(INFO) << "Verifying randomness of ciphertext";
1038 
1039   ASSERT_TRUE(VerifyDataRandomness(ciphertext));
1040 
1041   ASSERT_EQ(unlink(path), 0);
1042 }
1043 
1044 }  // namespace kernel
1045 }  // namespace android
1046