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