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