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