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 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 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 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 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 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 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 135 unsigned int GetFirstApiLevel() { 136 return android::base::GetUintProperty<unsigned int>("ro.product.first_api_level", 0); 137 } 138 139 bool OptionsToString(const EncryptionOptions& options, std::string* options_string) { 140 return OptionsToStringForApiLevel(GetFirstApiLevel(), options, options_string); 141 } 142 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 176 bool ParseOptions(const std::string& options_string, EncryptionOptions* options) { 177 return ParseOptionsForApiLevel(GetFirstApiLevel(), options_string, options); 178 } 179 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 constexpr unsigned int pre_gki_level = 29; 207 auto is_gki = first_api_level > pre_gki_level; 208 options->version = is_gki ? 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 (!is_gki && options->version == 1 && options->filenames_mode == FSCRYPT_MODE_AES_256_CTS) { 238 options->flags |= FSCRYPT_POLICY_FLAGS_PAD_4; 239 } else { 240 options->flags |= FSCRYPT_POLICY_FLAGS_PAD_16; 241 } 242 243 // Use DIRECT_KEY for Adiantum, since it's much more efficient but just as 244 // secure since Android doesn't reuse the same master key for multiple 245 // encryption modes. 246 if (options->contents_mode == FSCRYPT_MODE_ADIANTUM) { 247 if (options->filenames_mode != FSCRYPT_MODE_ADIANTUM) { 248 LOG(ERROR) << "Adiantum must be both contents and filenames mode or neither, invalid options: " << options_string; 249 return false; 250 } 251 options->flags |= FSCRYPT_POLICY_FLAG_DIRECT_KEY; 252 } else if (options->filenames_mode == FSCRYPT_MODE_ADIANTUM) { 253 LOG(ERROR) << "Adiantum must be both contents and filenames mode or neither, invalid options: " << options_string; 254 return false; 255 } 256 257 // IV generation methods are mutually exclusive 258 int iv_methods = 0; 259 iv_methods += !!(options->flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64); 260 iv_methods += !!(options->flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32); 261 iv_methods += !!(options->flags & FSCRYPT_POLICY_FLAG_DIRECT_KEY); 262 if (iv_methods > 1) { 263 LOG(ERROR) << "At most one IV generation method can be set, invalid options: " 264 << options_string; 265 return false; 266 } 267 268 return true; 269 } 270 271 static std::string PolicyDebugString(const EncryptionPolicy& policy) { 272 std::stringstream ss; 273 std::string ref_hex; 274 BytesToHex(policy.key_raw_ref, &ref_hex); 275 ss << ref_hex; 276 ss << " v" << policy.options.version; 277 ss << " modes " << policy.options.contents_mode << "/" << policy.options.filenames_mode; 278 ss << std::hex << " flags 0x" << policy.options.flags; 279 return ss.str(); 280 } 281 282 bool EnsurePolicy(const EncryptionPolicy& policy, const std::string& directory) { 283 union { 284 fscrypt_policy_v1 v1; 285 fscrypt_policy_v2 v2; 286 } kern_policy; 287 memset(&kern_policy, 0, sizeof(kern_policy)); 288 289 switch (policy.options.version) { 290 case 1: 291 if (policy.key_raw_ref.size() != FSCRYPT_KEY_DESCRIPTOR_SIZE) { 292 LOG(ERROR) << "Invalid key descriptor length for v1 policy: " 293 << policy.key_raw_ref.size(); 294 return false; 295 } 296 // Careful: FSCRYPT_POLICY_V1 is actually 0 in the API, so make sure 297 // to use it here instead of a literal 1. 298 kern_policy.v1.version = FSCRYPT_POLICY_V1; 299 kern_policy.v1.contents_encryption_mode = policy.options.contents_mode; 300 kern_policy.v1.filenames_encryption_mode = policy.options.filenames_mode; 301 kern_policy.v1.flags = policy.options.flags; 302 policy.key_raw_ref.copy(reinterpret_cast<char*>(kern_policy.v1.master_key_descriptor), 303 FSCRYPT_KEY_DESCRIPTOR_SIZE); 304 break; 305 case 2: 306 if (policy.key_raw_ref.size() != FSCRYPT_KEY_IDENTIFIER_SIZE) { 307 LOG(ERROR) << "Invalid key identifier length for v2 policy: " 308 << policy.key_raw_ref.size(); 309 return false; 310 } 311 kern_policy.v2.version = FSCRYPT_POLICY_V2; 312 kern_policy.v2.contents_encryption_mode = policy.options.contents_mode; 313 kern_policy.v2.filenames_encryption_mode = policy.options.filenames_mode; 314 kern_policy.v2.flags = policy.options.flags; 315 policy.key_raw_ref.copy(reinterpret_cast<char*>(kern_policy.v2.master_key_identifier), 316 FSCRYPT_KEY_IDENTIFIER_SIZE); 317 break; 318 default: 319 LOG(ERROR) << "Invalid encryption policy version: " << policy.options.version; 320 return false; 321 } 322 323 android::base::unique_fd fd(open(directory.c_str(), O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)); 324 if (fd == -1) { 325 PLOG(ERROR) << "Failed to open directory " << directory; 326 return false; 327 } 328 329 bool already_encrypted = fscrypt_is_encrypted(fd); 330 331 // FS_IOC_SET_ENCRYPTION_POLICY will set the policy if the directory is 332 // unencrypted; otherwise it will verify that the existing policy matches. 333 // Setting the policy will fail if the directory is already nonempty. 334 if (ioctl(fd, FS_IOC_SET_ENCRYPTION_POLICY, &kern_policy) != 0) { 335 std::string reason; 336 switch (errno) { 337 case EEXIST: 338 reason = "The directory already has a different encryption policy."; 339 break; 340 default: 341 reason = strerror(errno); 342 break; 343 } 344 LOG(ERROR) << "Failed to set encryption policy of " << directory << " to " 345 << PolicyDebugString(policy) << ": " << reason; 346 if (errno == ENOTEMPTY) { 347 log_ls(directory.c_str()); 348 } 349 return false; 350 } 351 352 if (already_encrypted) { 353 LOG(INFO) << "Verified that " << directory << " has the encryption policy " 354 << PolicyDebugString(policy); 355 } else { 356 LOG(INFO) << "Encryption policy of " << directory << " set to " 357 << PolicyDebugString(policy); 358 } 359 return true; 360 } 361 362 } // namespace fscrypt 363 } // namespace android 364