1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "fscrypt/fscrypt.h"
18 
19 #include <android-base/file.h>
20 #include <android-base/logging.h>
21 #include <android-base/properties.h>
22 #include <android-base/strings.h>
23 #include <android-base/unique_fd.h>
24 #include <asm/ioctl.h>
25 #include <cutils/properties.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <linux/fscrypt.h>
29 #include <logwrap/logwrap.h>
30 #include <string.h>
31 #include <sys/stat.h>
32 #include <sys/statvfs.h>
33 #include <sys/types.h>
34 #include <unistd.h>
35 #include <utils/misc.h>
36 
37 #include <array>
38 #include <string>
39 #include <vector>
40 
41 using namespace std::string_literals;
42 
43 /* modes not supported by upstream kernel, so not in <linux/fscrypt.h> */
44 #define FSCRYPT_MODE_AES_256_HEH 126
45 #define FSCRYPT_MODE_PRIVATE 127
46 
47 #define HEX_LOOKUP "0123456789abcdef"
48 
49 struct ModeLookupEntry {
50     std::string name;
51     int id;
52 };
53 
54 static const auto contents_modes = std::vector<ModeLookupEntry>{
55         {"aes-256-xts"s, FSCRYPT_MODE_AES_256_XTS},
56         {"software"s, FSCRYPT_MODE_AES_256_XTS},
57         {"adiantum"s, FSCRYPT_MODE_ADIANTUM},
58         {"ice"s, FSCRYPT_MODE_PRIVATE},
59 };
60 
61 static const auto filenames_modes = std::vector<ModeLookupEntry>{
62         {"aes-256-cts"s, FSCRYPT_MODE_AES_256_CTS},
63         {"aes-256-heh"s, FSCRYPT_MODE_AES_256_HEH},
64         {"adiantum"s, FSCRYPT_MODE_ADIANTUM},
65         {"aes-256-hctr2"s, FSCRYPT_MODE_AES_256_HCTR2},
66 };
67 
LookupModeByName(const std::vector<struct ModeLookupEntry> & modes,const std::string & name,int * result)68 static bool LookupModeByName(const std::vector<struct ModeLookupEntry>& modes,
69                              const std::string& name, int* result) {
70     for (const auto& e : modes) {
71         if (e.name == name) {
72             *result = e.id;
73             return true;
74         }
75     }
76     return false;
77 }
78 
LookupModeById(const std::vector<struct ModeLookupEntry> & modes,int id,std::string * result)79 static bool LookupModeById(const std::vector<struct ModeLookupEntry>& modes, int id,
80                            std::string* result) {
81     for (const auto& e : modes) {
82         if (e.id == id) {
83             *result = e.name;
84             return true;
85         }
86     }
87     return false;
88 }
89 
90 // Returns true if FBE (File Based Encryption) is enabled.
IsFbeEnabled()91 bool IsFbeEnabled() {
92     char value[PROPERTY_VALUE_MAX];
93     property_get("ro.crypto.type", value, "none");
94     return !strcmp(value, "file");
95 }
96 
97 namespace android {
98 namespace fscrypt {
99 
log_ls(const char * dirname)100 static void log_ls(const char* dirname) {
101     std::array<const char*, 3> argv = {"ls", "-laZ", dirname};
102     int status = 0;
103     auto res =
104             logwrap_fork_execvp(argv.size(), argv.data(), &status, false, LOG_ALOG, false, nullptr);
105     if (res != 0) {
106         PLOG(ERROR) << argv[0] << " " << argv[1] << " " << argv[2] << "failed";
107         return;
108     }
109     if (!WIFEXITED(status)) {
110         LOG(ERROR) << argv[0] << " " << argv[1] << " " << argv[2]
111                    << " did not exit normally, status: " << status;
112         return;
113     }
114     if (WEXITSTATUS(status) != 0) {
115         LOG(ERROR) << argv[0] << " " << argv[1] << " " << argv[2]
116                    << " returned failure: " << WEXITSTATUS(status);
117         return;
118     }
119 }
120 
BytesToHex(const std::string & bytes,std::string * hex)121 void BytesToHex(const std::string& bytes, std::string* hex) {
122     hex->clear();
123     for (char c : bytes) {
124         *hex += HEX_LOOKUP[(c & 0xF0) >> 4];
125         *hex += HEX_LOOKUP[c & 0x0F];
126     }
127 }
128 
fscrypt_is_encrypted(int fd)129 static bool fscrypt_is_encrypted(int fd) {
130     fscrypt_policy_v1 policy;
131 
132     // success => encrypted with v1 policy
133     // EINVAL => encrypted with v2 policy
134     // ENODATA => not encrypted
135     return ioctl(fd, FS_IOC_GET_ENCRYPTION_POLICY, &policy) == 0 || errno == EINVAL;
136 }
137 
GetFirstApiLevel()138 unsigned int GetFirstApiLevel() {
139     return android::base::GetUintProperty<unsigned int>("ro.product.first_api_level", 0);
140 }
141 
OptionsToString(const EncryptionOptions & options,std::string * options_string)142 bool OptionsToString(const EncryptionOptions& options, std::string* options_string) {
143     return OptionsToStringForApiLevel(GetFirstApiLevel(), options, options_string);
144 }
145 
OptionsToStringForApiLevel(unsigned int first_api_level,const EncryptionOptions & options,std::string * options_string)146 bool OptionsToStringForApiLevel(unsigned int first_api_level, const EncryptionOptions& options,
147                                 std::string* options_string) {
148     std::string contents_mode, filenames_mode;
149     if (!LookupModeById(contents_modes, options.contents_mode, &contents_mode)) {
150         return false;
151     }
152     if (!LookupModeById(filenames_modes, options.filenames_mode, &filenames_mode)) {
153         return false;
154     }
155     *options_string = contents_mode + ":" + filenames_mode + ":v" + std::to_string(options.version);
156     if ((options.flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64)) {
157         *options_string += "+inlinecrypt_optimized";
158     }
159     if ((options.flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32)) {
160         *options_string += "+emmc_optimized";
161     }
162     if (options.use_hw_wrapped_key) {
163         *options_string += "+wrappedkey_v0";
164     }
165     if (options.dusize_4k) {
166         *options_string += "+dusize_4k";
167     }
168 
169     EncryptionOptions options_check;
170     if (!ParseOptionsForApiLevel(first_api_level, *options_string, &options_check)) {
171         LOG(ERROR) << "Internal error serializing options as string: " << *options_string;
172         return false;
173     }
174     if (options != options_check) {
175         LOG(ERROR) << "Internal error serializing options as string, round trip failed: "
176                    << *options_string;
177         return false;
178     }
179     return true;
180 }
181 
ParseOptions(const std::string & options_string,EncryptionOptions * options)182 bool ParseOptions(const std::string& options_string, EncryptionOptions* options) {
183     return ParseOptionsForApiLevel(GetFirstApiLevel(), options_string, options);
184 }
185 
ParseOptionsForApiLevel(unsigned int first_api_level,const std::string & options_string,EncryptionOptions * options)186 bool ParseOptionsForApiLevel(unsigned int first_api_level, const std::string& options_string,
187                              EncryptionOptions* options) {
188     auto parts = android::base::Split(options_string, ":");
189     if (parts.size() > 3) {
190         LOG(ERROR) << "Invalid encryption options: " << options;
191         return false;
192     }
193     options->contents_mode = FSCRYPT_MODE_AES_256_XTS;
194     if (parts.size() > 0 && !parts[0].empty()) {
195         if (!LookupModeByName(contents_modes, parts[0], &options->contents_mode)) {
196             LOG(ERROR) << "Invalid file contents encryption mode: " << parts[0];
197             return false;
198         }
199     }
200     if (options->contents_mode == FSCRYPT_MODE_ADIANTUM) {
201         options->filenames_mode = FSCRYPT_MODE_ADIANTUM;
202     } else {
203         options->filenames_mode = FSCRYPT_MODE_AES_256_CTS;
204     }
205     if (parts.size() > 1 && !parts[1].empty()) {
206         if (!LookupModeByName(filenames_modes, parts[1], &options->filenames_mode)) {
207             LOG(ERROR) << "Invalid file names encryption mode: " << parts[1];
208             return false;
209         }
210     }
211     // Default to v2 after Q
212     options->version = first_api_level > __ANDROID_API_Q__ ? 2 : 1;
213     options->flags = 0;
214     options->dusize_4k = false;
215     options->use_hw_wrapped_key = false;
216     if (parts.size() > 2 && !parts[2].empty()) {
217         auto flags = android::base::Split(parts[2], "+");
218         for (const auto& flag : flags) {
219             if (flag == "v1") {
220                 options->version = 1;
221             } else if (flag == "v2") {
222                 options->version = 2;
223             } else if (flag == "inlinecrypt_optimized") {
224                 options->flags |= FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64;
225             } else if (flag == "emmc_optimized") {
226                 options->flags |= FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32;
227             } else if (flag == "wrappedkey_v0") {
228                 options->use_hw_wrapped_key = true;
229             } else if (flag == "dusize_4k") {
230                 options->dusize_4k = true;
231             } else {
232                 LOG(ERROR) << "Unknown flag: " << flag;
233                 return false;
234             }
235         }
236     }
237 
238     // In the original setting of v1 policies and AES-256-CTS we used 4-byte
239     // padding of filenames, so retain that on old first_api_levels.
240     //
241     // For everything else, use 16-byte padding.  This is more secure (it helps
242     // hide the length of filenames), and it makes the inputs evenly divisible
243     // into cipher blocks which is more efficient for encryption and decryption.
244     if (first_api_level <= __ANDROID_API_Q__ && options->version == 1 &&
245         options->filenames_mode == FSCRYPT_MODE_AES_256_CTS) {
246         options->flags |= FSCRYPT_POLICY_FLAGS_PAD_4;
247     } else {
248         options->flags |= FSCRYPT_POLICY_FLAGS_PAD_16;
249     }
250 
251     // Use DIRECT_KEY for Adiantum, since it's much more efficient but just as
252     // secure since Android doesn't reuse the same master key for multiple
253     // encryption modes.
254     if (options->contents_mode == FSCRYPT_MODE_ADIANTUM) {
255         if (options->filenames_mode != FSCRYPT_MODE_ADIANTUM) {
256             LOG(ERROR) << "Adiantum must be both contents and filenames mode or neither, invalid "
257                           "options: "
258                        << options_string;
259             return false;
260         }
261         options->flags |= FSCRYPT_POLICY_FLAG_DIRECT_KEY;
262     } else if (options->filenames_mode == FSCRYPT_MODE_ADIANTUM) {
263         LOG(ERROR)
264                 << "Adiantum must be both contents and filenames mode or neither, invalid options: "
265                 << options_string;
266         return false;
267     }
268 
269     // IV generation methods are mutually exclusive
270     int iv_methods = 0;
271     iv_methods += !!(options->flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64);
272     iv_methods += !!(options->flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32);
273     iv_methods += !!(options->flags & FSCRYPT_POLICY_FLAG_DIRECT_KEY);
274     if (iv_methods > 1) {
275         LOG(ERROR) << "At most one IV generation method can be set, invalid options: "
276                    << options_string;
277         return false;
278     }
279 
280     return true;
281 }
282 
PolicyDebugString(const EncryptionPolicy & policy)283 static std::string PolicyDebugString(const EncryptionPolicy& policy) {
284     std::stringstream ss;
285     std::string ref_hex;
286     BytesToHex(policy.key_raw_ref, &ref_hex);
287     ss << ref_hex;
288     ss << " v" << policy.options.version;
289     ss << " modes " << policy.options.contents_mode << "/" << policy.options.filenames_mode;
290     ss << std::hex << " flags 0x" << policy.options.flags;
291     return ss.str();
292 }
293 
GetFilesystemBlockSize(const std::string & path)294 static int GetFilesystemBlockSize(const std::string& path) {
295     struct statvfs info;
296     if (statvfs(path.c_str(), &info) == 0) {
297         return info.f_bsize;
298     }
299     PLOG(ERROR) << "Error retrieving filesystem information from " << path;
300     return getpagesize();
301 }
302 
EnsurePolicy(const EncryptionPolicy & policy,const std::string & directory)303 bool EnsurePolicy(const EncryptionPolicy& policy, const std::string& directory) {
304     union {
305         fscrypt_policy_v1 v1;
306         fscrypt_policy_v2 v2;
307     } kern_policy;
308     memset(&kern_policy, 0, sizeof(kern_policy));
309 
310     switch (policy.options.version) {
311         case 1:
312             if (policy.key_raw_ref.size() != FSCRYPT_KEY_DESCRIPTOR_SIZE) {
313                 LOG(ERROR) << "Invalid key descriptor length for v1 policy: "
314                            << policy.key_raw_ref.size();
315                 return false;
316             }
317             // Careful: FSCRYPT_POLICY_V1 is actually 0 in the API, so make sure
318             // to use it here instead of a literal 1.
319             kern_policy.v1.version = FSCRYPT_POLICY_V1;
320             kern_policy.v1.contents_encryption_mode = policy.options.contents_mode;
321             kern_policy.v1.filenames_encryption_mode = policy.options.filenames_mode;
322             kern_policy.v1.flags = policy.options.flags;
323             policy.key_raw_ref.copy(reinterpret_cast<char*>(kern_policy.v1.master_key_descriptor),
324                                     FSCRYPT_KEY_DESCRIPTOR_SIZE);
325             break;
326         case 2:
327             if (policy.key_raw_ref.size() != FSCRYPT_KEY_IDENTIFIER_SIZE) {
328                 LOG(ERROR) << "Invalid key identifier length for v2 policy: "
329                            << policy.key_raw_ref.size();
330                 return false;
331             }
332             kern_policy.v2.version = FSCRYPT_POLICY_V2;
333             kern_policy.v2.contents_encryption_mode = policy.options.contents_mode;
334             kern_policy.v2.filenames_encryption_mode = policy.options.filenames_mode;
335             kern_policy.v2.flags = policy.options.flags;
336             // Configure the data unit size if one was explicitly specified and it doesn't match the
337             // default data unit size of the filesystem.
338             //
339             // We don't configure a data unit size if one wasn't explicitly specified, since the
340             // kernel might not support it.  We also don't configure a data unit size that's already
341             // the filesystem default, since this allows dusize_4k to be added to the fstab of an
342             // existing device using 4K filesystem blocks without changing the policy.
343             if (policy.options.dusize_4k && GetFilesystemBlockSize(directory) != 4096) {
344                 kern_policy.v2.log2_data_unit_size = 12;
345             }
346             policy.key_raw_ref.copy(reinterpret_cast<char*>(kern_policy.v2.master_key_identifier),
347                                     FSCRYPT_KEY_IDENTIFIER_SIZE);
348             break;
349         default:
350             LOG(ERROR) << "Invalid encryption policy version: " << policy.options.version;
351             return false;
352     }
353 
354     android::base::unique_fd fd(open(directory.c_str(), O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
355     if (fd == -1) {
356         PLOG(ERROR) << "Failed to open directory " << directory;
357         return false;
358     }
359 
360     bool already_encrypted = fscrypt_is_encrypted(fd);
361 
362     // FS_IOC_SET_ENCRYPTION_POLICY will set the policy if the directory is
363     // unencrypted; otherwise it will verify that the existing policy matches.
364     // Setting the policy will fail if the directory is already nonempty.
365     if (ioctl(fd, FS_IOC_SET_ENCRYPTION_POLICY, &kern_policy) != 0) {
366         std::string reason;
367         switch (errno) {
368             case EEXIST:
369                 reason = "The directory already has a different encryption policy.";
370                 break;
371             default:
372                 reason = strerror(errno);
373                 break;
374         }
375         LOG(ERROR) << "Failed to set encryption policy of " << directory << " to "
376                    << PolicyDebugString(policy) << ": " << reason;
377         if (errno == ENOTEMPTY) {
378             log_ls(directory.c_str());
379         }
380         return false;
381     }
382 
383     if (already_encrypted) {
384         LOG(INFO) << "Verified that " << directory << " has the encryption policy "
385                   << PolicyDebugString(policy);
386     } else {
387         LOG(INFO) << "Encryption policy of " << directory << " set to "
388                   << PolicyDebugString(policy);
389     }
390     return true;
391 }
392 
393 }  // namespace fscrypt
394 }  // namespace android
395