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 metadata encryption is working, via:
19 //
20 // - Correctness tests.  These test the standard metadata encryption formats
21 //   supported by Android R and higher via dm-default-key v2.
22 //
23 // - Randomness test.  This runs on all devices that use metadata encryption.
24 //
25 // The correctness tests create a temporary default-key mapping over the raw
26 // userdata partition, read from it, and verify that the data got decrypted
27 // correctly.  This only tests decryption, since this avoids having to find a
28 // region on disk that can safely be modified.  This should be good enough since
29 // the device wouldn't work anyway if decryption didn't invert encryption.
30 //
31 // Note that this temporary default-key mapping will overlap the device's "real"
32 // default-key mapping, if the device has one.  The kernel allows this.  The
33 // tests don't use a loopback device instead, since dm-default-key over a
34 // loopback device can't use the real inline encryption hardware.
35 //
36 // The correctness tests cover the following settings:
37 //
38 //    metadata_encryption=aes-256-xts
39 //    metadata_encryption=adiantum
40 //    metadata_encryption=aes-256-xts:wrappedkey_v0
41 //
42 // The tests don't check which one of those settings, if any, the device is
43 // actually using; they just try to test everything they can.
44 //
45 // These tests don't specifically test that file contents aren't encrypted
46 // twice.  That's already implied by the file-based encryption test cases,
47 // provided that the device actually has metadata encryption enabled.
48 //
49 
50 #include <android-base/file.h>
51 #include <android-base/stringprintf.h>
52 #include <android-base/unique_fd.h>
53 #include <asm/byteorder.h>
54 #include <fcntl.h>
55 #include <fstab/fstab.h>
56 #include <gtest/gtest.h>
57 #include <libdm/dm.h>
58 #include <linux/types.h>
59 #include <stdlib.h>
60 #include <unistd.h>
61 
62 #include <chrono>
63 
64 #include "vts_kernel_encryption.h"
65 
66 using namespace android::dm;
67 
68 namespace android {
69 namespace kernel {
70 
71 #define cpu_to_le64 __cpu_to_le64
72 #define le64_to_cpu __le64_to_cpu
73 
74 // Alignment to use for direct I/O reads of block devices
75 static constexpr int kDirectIOAlignment = 4096;
76 
77 // Assumed size of filesystem blocks, in bytes
78 static constexpr int kFilesystemBlockSize = 4096;
79 
80 // Checks whether the kernel supports version 2 or higher of dm-default-key.
IsDmDefaultKeyV2Supported(DeviceMapper & dm)81 static bool IsDmDefaultKeyV2Supported(DeviceMapper &dm) {
82   DmTargetTypeInfo info;
83   if (!dm.GetTargetByName("default-key", &info)) {
84     GTEST_LOG_(INFO) << "dm-default-key not enabled";
85     return false;
86   }
87   if (!info.IsAtLeast(2, 0, 0)) {
88     // The legacy version of dm-default-key (which was never supported by the
89     // Android common kernels) used a vendor-specific on-disk format, so it's
90     // not testable by a vendor-independent test.
91     GTEST_LOG_(INFO) << "Detected legacy dm-default-key";
92     return false;
93   }
94   return true;
95 }
96 
97 // Reads |count| bytes from the beginning of |blk_device|, using direct I/O to
98 // avoid getting any stale cached data.  Direct I/O requires using a hardware
99 // sector size aligned buffer.
ReadBlockDevice(const std::string & blk_device,size_t count,std::vector<uint8_t> * data)100 static bool ReadBlockDevice(const std::string &blk_device, size_t count,
101                             std::vector<uint8_t> *data) {
102   GTEST_LOG_(INFO) << "Reading " << count << " bytes from " << blk_device;
103   std::unique_ptr<void, void (*)(void *)> buf_mem(
104       aligned_alloc(kDirectIOAlignment, count), free);
105   if (buf_mem == nullptr) {
106     ADD_FAILURE() << "out of memory";
107     return false;
108   }
109   uint8_t *buffer = static_cast<uint8_t *>(buf_mem.get());
110 
111   android::base::unique_fd fd(
112       open(blk_device.c_str(), O_RDONLY | O_DIRECT | O_CLOEXEC));
113   if (fd < 0) {
114     ADD_FAILURE() << "Failed to open " << blk_device << Errno();
115     return false;
116   }
117   if (!android::base::ReadFully(fd, buffer, count)) {
118     ADD_FAILURE() << "Failed to read from " << blk_device << Errno();
119     return false;
120   }
121 
122   *data = std::vector<uint8_t>(buffer, buffer + count);
123   return true;
124 }
125 
126 class DmDefaultKeyTest : public ::testing::Test {
127   // Filesystem whose underlying partition the test will use
128   static constexpr const char *kTestMountpoint = "/data";
129 
130   // Size of the dm-default-key crypto sector size (data unit size) in bytes
131   static constexpr int kCryptoSectorSize = 4096;
132 
133   // Size of the test data in crypto sectors
134   static constexpr int kTestDataSectors = 256;
135 
136   // Size of the test data in bytes
137   static constexpr int kTestDataBytes = kTestDataSectors * kCryptoSectorSize;
138 
139   // Device-mapper API sector size in bytes.
140   // This is unrelated to the crypto sector size.
141   static constexpr int kDmApiSectorSize = 512;
142 
143  protected:
144   void SetUp() override;
145   void TearDown() override;
146   bool CreateTestDevice(const std::string &cipher,
147                         const std::vector<uint8_t> &key, bool is_wrapped_key);
148   void VerifyDecryption(const std::vector<uint8_t> &key, const Cipher &cipher);
149   void DoTest(const std::string &cipher_string, const Cipher &cipher);
150   std::string test_dm_device_name_;
151   bool skip_test_ = false;
152   DeviceMapper *dm_ = nullptr;
153   std::string raw_blk_device_;
154   std::string dm_device_path_;
155 };
156 
157 // Test setup procedure.  Checks for the needed kernel support, finds the raw
158 // partition to use, and does other preparations.  skip_test_ is set to true if
159 // the test should be skipped.
SetUp()160 void DmDefaultKeyTest::SetUp() {
161   dm_ = &DeviceMapper::Instance();
162 
163   if (!IsDmDefaultKeyV2Supported(*dm_)) {
164     int first_api_level;
165     ASSERT_TRUE(GetFirstApiLevel(&first_api_level));
166     // Devices launching with R or higher must support dm-default-key v2.
167     ASSERT_LE(first_api_level, __ANDROID_API_Q__);
168     GTEST_LOG_(INFO)
169         << "Skipping test because dm-default-key v2 is unsupported";
170     skip_test_ = true;
171     return;
172   }
173   test_dm_device_name_ =
174       android::base::StringPrintf("DmDefaultKeyTest.%d", getpid());
175 
176   FilesystemInfo fs_info;
177   ASSERT_TRUE(GetFilesystemInfo(kTestMountpoint, &fs_info));
178   raw_blk_device_ = fs_info.raw_blk_device;
179 
180   dm_->DeleteDevice(test_dm_device_name_.c_str());
181 }
182 
TearDown()183 void DmDefaultKeyTest::TearDown() { dm_->DeleteDevice(test_dm_device_name_); }
184 
185 // Creates the test dm-default-key mapping using the given key and settings.
186 // If the dm device creation fails, then it is assumed the kernel doesn't
187 // support the given encryption settings, and a failure is not added.
CreateTestDevice(const std::string & cipher,const std::vector<uint8_t> & key,bool is_wrapped_key)188 bool DmDefaultKeyTest::CreateTestDevice(const std::string &cipher,
189                                         const std::vector<uint8_t> &key,
190                                         bool is_wrapped_key) {
191   static_assert(kTestDataBytes % kDmApiSectorSize == 0);
192   std::unique_ptr<DmTargetDefaultKey> target =
193       std::make_unique<DmTargetDefaultKey>(0, kTestDataBytes / kDmApiSectorSize,
194                                            cipher.c_str(), BytesToHex(key),
195                                            raw_blk_device_, 0);
196   target->SetSetDun();
197   if (is_wrapped_key) target->SetWrappedKeyV0();
198 
199   DmTable table;
200   if (!table.AddTarget(std::move(target))) {
201     ADD_FAILURE() << "Failed to add default-key target to table";
202     return false;
203   }
204   if (!table.valid()) {
205     ADD_FAILURE() << "Device-mapper table failed to validate";
206     return false;
207   }
208   if (!dm_->CreateDevice(test_dm_device_name_, table, &dm_device_path_,
209                          std::chrono::seconds(5))) {
210     GTEST_LOG_(INFO) << "Unable to create default-key mapping" << Errno()
211                      << ".  Assuming that the encryption settings cipher=\""
212                      << cipher << "\", is_wrapped_key=" << is_wrapped_key
213                      << " are unsupported and skipping the test.";
214     return false;
215   }
216   GTEST_LOG_(INFO) << "Created default-key mapping at " << dm_device_path_
217                    << " using cipher=\"" << cipher
218                    << "\", key=" << BytesToHex(key)
219                    << ", is_wrapped_key=" << is_wrapped_key;
220   return true;
221 }
222 
VerifyDecryption(const std::vector<uint8_t> & key,const Cipher & cipher)223 void DmDefaultKeyTest::VerifyDecryption(const std::vector<uint8_t> &key,
224                                         const Cipher &cipher) {
225   std::vector<uint8_t> raw_data;
226   std::vector<uint8_t> decrypted_data;
227 
228   ASSERT_TRUE(ReadBlockDevice(raw_blk_device_, kTestDataBytes, &raw_data));
229   ASSERT_TRUE(
230       ReadBlockDevice(dm_device_path_, kTestDataBytes, &decrypted_data));
231 
232   // Verify that the decrypted data encrypts to the raw data.
233 
234   GTEST_LOG_(INFO) << "Verifying correctness of decrypted data";
235 
236   // Initialize the IV for crypto sector 0.
237   ASSERT_GE(cipher.ivsize(), sizeof(__le64));
238   std::unique_ptr<__le64> iv(new (::operator new(cipher.ivsize())) __le64);
239   memset(iv.get(), 0, cipher.ivsize());
240 
241   // Encrypt each sector.
242   std::vector<uint8_t> encrypted_data(kTestDataBytes);
243   static_assert(kTestDataBytes % kCryptoSectorSize == 0);
244   for (size_t i = 0; i < kTestDataBytes; i += kCryptoSectorSize) {
245     ASSERT_TRUE(cipher.Encrypt(key, reinterpret_cast<const uint8_t *>(iv.get()),
246                                &decrypted_data[i], &encrypted_data[i],
247                                kCryptoSectorSize));
248 
249     // Update the IV by incrementing the crypto sector number.
250     *iv = cpu_to_le64(le64_to_cpu(*iv) + 1);
251   }
252 
253   ASSERT_EQ(encrypted_data, raw_data);
254 }
255 
DoTest(const std::string & cipher_string,const Cipher & cipher)256 void DmDefaultKeyTest::DoTest(const std::string &cipher_string,
257                               const Cipher &cipher) {
258   if (skip_test_) return;
259 
260   std::vector<uint8_t> key = GenerateTestKey(cipher.keysize());
261 
262   if (!CreateTestDevice(cipher_string, key, false)) return;
263 
264   VerifyDecryption(key, cipher);
265 }
266 
267 // Tests dm-default-key parameters matching metadata_encryption=aes-256-xts.
TEST_F(DmDefaultKeyTest,TestAes256Xts)268 TEST_F(DmDefaultKeyTest, TestAes256Xts) {
269   DoTest("aes-xts-plain64", Aes256XtsCipher());
270 }
271 
272 // Tests dm-default-key parameters matching metadata_encryption=adiantum.
TEST_F(DmDefaultKeyTest,TestAdiantum)273 TEST_F(DmDefaultKeyTest, TestAdiantum) {
274   DoTest("xchacha12,aes-adiantum-plain64", AdiantumCipher());
275 }
276 
277 // Tests dm-default-key parameters matching
278 // metadata_encryption=aes-256-xts:wrappedkey_v0.
TEST_F(DmDefaultKeyTest,TestHwWrappedKey)279 TEST_F(DmDefaultKeyTest, TestHwWrappedKey) {
280   if (skip_test_) return;
281 
282   std::vector<uint8_t> master_key, exported_key;
283   if (!CreateHwWrappedKey(&master_key, &exported_key)) return;
284 
285   if (!CreateTestDevice("aes-xts-plain64", exported_key, true)) return;
286 
287   std::vector<uint8_t> enc_key;
288   ASSERT_TRUE(DeriveHwWrappedEncryptionKey(master_key, &enc_key));
289 
290   VerifyDecryption(enc_key, Aes256XtsCipher());
291 }
292 
293 // Tests that if the device uses metadata encryption, then the first
294 // kFilesystemBlockSize bytes of the userdata partition appear random.  For ext4
295 // and f2fs, this block should contain the filesystem superblock; it therefore
296 // should be initialized and metadata-encrypted.  Ideally we'd check additional
297 // blocks too, but that would require awareness of the filesystem structure.
298 //
299 // This isn't as strong a test as the correctness tests, but it's useful because
300 // it applies regardless of the encryption format and key.  Thus it runs even on
301 // old devices, including ones that used a vendor-specific encryption format.
TEST(MetadataEncryptionTest,TestRandomness)302 TEST(MetadataEncryptionTest, TestRandomness) {
303   constexpr const char *mountpoint = "/data";
304 
305   android::fs_mgr::Fstab fstab;
306   ASSERT_TRUE(android::fs_mgr::ReadDefaultFstab(&fstab));
307   const fs_mgr::FstabEntry *entry = GetEntryForMountPoint(&fstab, mountpoint);
308   ASSERT_TRUE(entry != nullptr);
309 
310   if (entry->metadata_key_dir.empty()) {
311     int first_api_level;
312     ASSERT_TRUE(GetFirstApiLevel(&first_api_level));
313     ASSERT_LE(first_api_level, __ANDROID_API_Q__)
314         << "Metadata encryption is required";
315     GTEST_LOG_(INFO)
316         << "Skipping test because device doesn't use metadata encryption";
317     return;
318   }
319 
320   GTEST_LOG_(INFO) << "Verifying randomness of ciphertext";
321   std::vector<uint8_t> raw_data;
322   FilesystemInfo fs_info;
323   ASSERT_TRUE(GetFilesystemInfo(mountpoint, &fs_info));
324   ASSERT_TRUE(
325       ReadBlockDevice(fs_info.raw_blk_device, kFilesystemBlockSize, &raw_data));
326   ASSERT_TRUE(VerifyDataRandomness(raw_data));
327 }
328 
329 }  // namespace kernel
330 }  // namespace android
331