1 /*
2 * Copyright (C) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 #include "fscrypt_control.h"
16
17 #include <fcntl.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <stdbool.h>
21 #include <sys/stat.h>
22 #include <sys/types.h>
23 #include <unistd.h>
24
25 #include "fscrypt_log.h"
26 #include "fscrypt_sysparam.h"
27 #include "init_utils.h"
28 #include "key_control.h"
29 #include "securec.h"
30 #include <sys/ioctl.h>
31
32 #define ARRAY_LEN(array) (sizeof((array)) / sizeof((array)[0]))
33 #define SAFE_FREE_PTR(ptr) do { \
34 if ((ptr) != NULL) { \
35 free(ptr); \
36 (ptr) = NULL; \
37 } \
38 } while (0)
39
40 typedef struct FscrtpyItem_ {
41 char *key;
42 uint8_t value;
43 }FscrtpyItem;
44
45 typedef struct EncryptPolicy_ {
46 uint8_t version;
47 uint8_t fileName;
48 uint8_t content;
49 uint8_t flags;
50 bool hwWrappedKey;
51 }EncryptPolicy;
52
53 static EncryptPolicy g_fscryptPolicy = {
54 FSCRYPT_V2,
55 FSCRYPT_MODE_AES_256_CTS,
56 FSCRYPT_MODE_AES_256_XTS,
57 FSCRYPT_POLICY_FLAGS_PAD_32,
58 false
59 };
60
61 enum FscryptOptins {
62 FSCRYPT_VERSION_NUM = 0,
63 FSCRYPT_FILENAME_MODE,
64 FSCRYPT_CONTENT_MODE,
65 FSCRYPT_OPTIONS_MAX,
66 };
67
68 static const FscrtpyItem ALL_VERSION[] = {
69 {"1", FSCRYPT_V1},
70 {"2", FSCRYPT_V2},
71 };
72
73 static const FscrtpyItem FILENAME_MODES[] = {
74 {"aes-256-cts", FSCRYPT_MODE_AES_256_CTS},
75 };
76
77 static const FscrtpyItem CONTENTS_MODES[] = {
78 {"aes-256-xts", FSCRYPT_MODE_AES_256_XTS},
79 };
80
81 static bool g_fscryptEnabled = false;
82 static bool g_fscryptInited = false;
83
84 static const char *GLOBAL_FSCRYPT_DIR[] = {
85 "/data/app/el1/bundle/public",
86 "/data/service/el1/public",
87 "/data/chipset/el1/public",
88 };
89
90 static const char *DEVICE_EL1_DIR = "/data/service/el0/storage_daemon/sd";
91 static const char *PATH_KEYDESC = "/key_desc";
92 #ifdef SUPPORT_FSCRYPT_V2
93 static const char *PATH_KEYID = "/key_id";
94 #endif
95
IsSupportedPolicyKey(const char * key,const FscrtpyItem * items,size_t len)96 static bool IsSupportedPolicyKey(const char *key,
97 const FscrtpyItem *items,
98 size_t len)
99 {
100 for (size_t i = 0 ; i < len; i++) {
101 if (strncmp(key, items[i].key, strlen(items[i].key)) == 0) {
102 return true;
103 }
104 }
105 return false;
106 }
107
IsSupportedPolicy(const char * policy,enum FscryptOptins number)108 static bool IsSupportedPolicy(const char *policy,
109 enum FscryptOptins number)
110 {
111 if ((number >= FSCRYPT_OPTIONS_MAX) || (!policy)) {
112 return false;
113 }
114
115 switch (number) {
116 case FSCRYPT_VERSION_NUM:
117 return IsSupportedPolicyKey(policy, ALL_VERSION,
118 ARRAY_LEN(ALL_VERSION));
119 case FSCRYPT_FILENAME_MODE:
120 return IsSupportedPolicyKey(policy, FILENAME_MODES,
121 ARRAY_LEN(FILENAME_MODES));
122 case FSCRYPT_CONTENT_MODE:
123 return IsSupportedPolicyKey(policy, CONTENTS_MODES,
124 ARRAY_LEN(CONTENTS_MODES));
125 default:
126 return false;
127 }
128 return false;
129 }
130
FscryptSetSysparam(const char * policy)131 int FscryptSetSysparam(const char *policy)
132 {
133 if (!policy) {
134 return -EINVAL;
135 }
136
137 char *tmp = strdup(policy);
138 if (!tmp) {
139 LOGE("No memory for policy option");
140 return -ENOMEM;
141 }
142 int optNums = 0;
143 char **options = SplitStringExt(tmp, ":", &optNums, FSCRYPT_OPTIONS_MAX);
144 free(tmp);
145 if (!options) {
146 return -ENOMEM;
147 }
148 if (optNums != FSCRYPT_OPTIONS_MAX) {
149 LOGE("Mount fscrypt option setting error, not enabled crypto!");
150 FreeStringVector(options, optNums);
151 return -EINVAL;
152 }
153
154 // check supported policy
155 for (enum FscryptOptins i = FSCRYPT_VERSION_NUM; i < FSCRYPT_OPTIONS_MAX; i++) {
156 char *temp = options[i];
157 if (!IsSupportedPolicy(temp, i)) {
158 LOGE("Not supported policy, %{public}s", temp);
159 FreeStringVector(options, optNums);
160 return -ENOTSUP;
161 }
162 }
163 FreeStringVector(options, optNums);
164
165 int ret = SetFscryptParameter(FSCRYPT_POLICY_KEY, policy);
166 if (ret < 0) {
167 LOGE("Set fscrypt system parameter failed %{public}d", ret);
168 return ret;
169 }
170 g_fscryptEnabled = true;
171 g_fscryptInited = false; // need to re-init
172
173 return 0;
174 }
175
176 #ifdef USER_CRYPTO_MANAGER
PraseOnePloicyValue(uint8_t * value,const char * key,const FscrtpyItem * table,size_t numbers)177 static void PraseOnePloicyValue(uint8_t *value, const char *key,
178 const FscrtpyItem *table, size_t numbers)
179 {
180 for (size_t i = 0; i < numbers; i++) {
181 size_t len = strlen(table[i].key);
182 if (strncmp(key, table[i].key, len) == 0 &&
183 strlen(key) == len) {
184 *value = table[i].value;
185 return;
186 }
187 }
188 LOGE("Have not found value for the key!");
189 }
190 #endif
191
InitFscryptPolicy(void)192 int InitFscryptPolicy(void)
193 {
194 #ifdef USER_CRYPTO_MANAGER
195 if (g_fscryptInited) {
196 LOGI("Have been init");
197 return 0;
198 }
199 char policy[POLICY_BUF_SIZE];
200 uint32_t len = POLICY_BUF_SIZE - 1;
201 int ret = GetFscryptParameter(FSCRYPT_POLICY_KEY, "", policy, &len);
202 if (ret != 0) {
203 LOGI("Get fscrypt policy failed");
204 return -ENOTSUP;
205 }
206 int count = 0;
207 char **option = SplitStringExt(policy, ":", &count, FSCRYPT_OPTIONS_MAX);
208 if (!option) {
209 LOGE("Fscrypt setting error");
210 return -ENOTSUP;
211 }
212 if (count != FSCRYPT_OPTIONS_MAX) {
213 LOGE("Fscrypt policy count error");
214 FreeStringVector(option, count);
215 return -ENOTSUP;
216 }
217
218 PraseOnePloicyValue(&g_fscryptPolicy.version, option[FSCRYPT_VERSION_NUM],
219 ALL_VERSION, ARRAY_LEN(ALL_VERSION));
220 PraseOnePloicyValue(&g_fscryptPolicy.fileName, option[FSCRYPT_FILENAME_MODE],
221 FILENAME_MODES, ARRAY_LEN(FILENAME_MODES));
222 PraseOnePloicyValue(&g_fscryptPolicy.content, option[FSCRYPT_CONTENT_MODE],
223 CONTENTS_MODES, ARRAY_LEN(CONTENTS_MODES));
224
225 FreeStringVector(option, count);
226 g_fscryptInited = true;
227 LOGI("Fscrypt policy init success");
228 #endif
229
230 return 0;
231 }
232
233 /*
234 * Splic full path, Caller need to free *buf after using
235 * if return success.
236 *
237 * @path: base key path
238 * @name: fscrypt file, so as /key_id
239 * @buf: splic result if return 0
240 */
SpliceKeyPath(const char * path,size_t pathLen,const char * name,size_t nameLen,char ** buf)241 static int SpliceKeyPath(const char *path, size_t pathLen,
242 const char *name, size_t nameLen,
243 char **buf)
244 {
245 LOGI("key path %{public}s, name %{public}s", path, name);
246 *buf = NULL;
247 size_t bufMax = pathLen + nameLen + 1;
248 char *tmpBuf = (char *)malloc(bufMax);
249 if (!tmpBuf) {
250 LOGE("No memory for fscrypt v1 path buffer");
251 return -ENOMEM;
252 }
253 tmpBuf[0] = '\0';
254
255 int ret = strncat_s(tmpBuf, bufMax, path, pathLen);
256 if (ret != 0) {
257 free(tmpBuf);
258 LOGE("splic previous path error");
259 return ret;
260 }
261 ret = strncat_s(tmpBuf, bufMax, name, nameLen);
262 if (ret != 0) {
263 free(tmpBuf);
264 LOGE("splic later path error");
265 return ret;
266 }
267 *buf = tmpBuf;
268
269 return 0;
270 }
271
ReadKeyFile(const char * path,char * buf,size_t len)272 static int ReadKeyFile(const char *path, char *buf, size_t len)
273 {
274 if (!path || !buf) {
275 LOGE("path or buf is null");
276 return -EINVAL;
277 }
278 struct stat st = {0};
279 if (stat(path, &st) != 0) {
280 LOGE("stat file failed");
281 return -EFAULT;
282 }
283 if ((size_t)st.st_size != len) {
284 LOGE("target file size is not equal to buf len");
285 return -EINVAL;
286 }
287 char *realPath = realpath(path, NULL);
288 if (realPath == NULL) {
289 LOGE("realpath failed");
290 return -ENOENT;
291 }
292
293 int fd = open(realPath, O_RDONLY);
294 free(realPath);
295 if (fd < 0) {
296 LOGE("key file read open failed");
297 return -EFAULT;
298 }
299 if (read(fd, buf, len) != (ssize_t)len) {
300 LOGE("bad file content");
301 (void)close(fd);
302 return -EBADF;
303 }
304 (void)close(fd);
305
306 return 0;
307 }
308
SetPolicyLegacy(const char * keyDescPath,const char * toEncrypt,union FscryptPolicy * arg)309 static int SetPolicyLegacy(const char *keyDescPath,
310 const char *toEncrypt,
311 union FscryptPolicy *arg)
312 {
313 char keyDesc[FSCRYPT_KEY_DESCRIPTOR_SIZE] = {0};
314 int ret = ReadKeyFile(keyDescPath, keyDesc, FSCRYPT_KEY_DESCRIPTOR_SIZE);
315 if (ret != 0) {
316 return ret;
317 }
318 arg->v1.version = FSCRYPT_POLICY_V1;
319 ret = memcpy_s(arg->v1.master_key_descriptor,
320 FSCRYPT_KEY_DESCRIPTOR_SIZE, keyDesc, FSCRYPT_KEY_DESCRIPTOR_SIZE);
321 if (ret != 0) {
322 LOGE("memcpy_s copy failed");
323 return ret;
324 }
325 if (!KeyCtrlSetPolicy(toEncrypt, arg)) {
326 LOGE("Set Policy v1 failed");
327 return -EFAULT;
328 }
329 return 0;
330 }
331
332 #ifdef SUPPORT_FSCRYPT_V2
SetPolicyV2(const char * keyIdPath,const char * toEncrypt,union FscryptPolicy * arg)333 static int SetPolicyV2(const char *keyIdPath,
334 const char *toEncrypt,
335 union FscryptPolicy *arg)
336 {
337 char keyId[FSCRYPT_KEY_IDENTIFIER_SIZE] = {0};
338 int ret = ReadKeyFile(keyIdPath, keyId, FSCRYPT_KEY_IDENTIFIER_SIZE);
339 if (ret != 0) {
340 return ret;
341 }
342 arg->v2.version = FSCRYPT_POLICY_V2;
343 ret = memcpy_s(arg->v2.master_key_identifier,
344 FSCRYPT_KEY_IDENTIFIER_SIZE, keyId, FSCRYPT_KEY_IDENTIFIER_SIZE);
345 if (ret != 0) {
346 LOGE("memcpy_s copy failed");
347 return ret;
348 }
349 if (!KeyCtrlSetPolicy(toEncrypt, arg)) {
350 LOGE("Set Policy v2 failed");
351 return -EFAULT;
352 }
353 return 0;
354 }
355 #endif
356
LoadAndSetPolicy(const char * keyDir,const char * dir)357 int LoadAndSetPolicy(const char *keyDir, const char *dir)
358 {
359 if (!keyDir || !dir) {
360 LOGE("set policy parameters is null");
361 return -EINVAL;
362 }
363 int ret = InitFscryptPolicy();
364 if (ret != 0) {
365 LOGE("Get fscrypt policy error %{public}d", ret);
366 return ret;
367 }
368
369 union FscryptPolicy arg;
370 (void)memset_s(&arg, sizeof(arg), 0, sizeof(arg));
371 arg.v1.filenames_encryption_mode = g_fscryptPolicy.fileName;
372 arg.v1.contents_encryption_mode = g_fscryptPolicy.content;
373 arg.v1.flags = g_fscryptPolicy.flags;
374
375 char *pathBuf = NULL;
376 ret = -ENOTSUP;
377
378 uint8_t fscryptVer = KeyCtrlLoadVersion(keyDir);
379 if (fscryptVer == FSCRYPT_V1) {
380 ret = SpliceKeyPath(keyDir, strlen(keyDir), PATH_KEYDESC,
381 strlen(PATH_KEYDESC), &pathBuf);
382 if (ret != 0) {
383 LOGE("path splice error");
384 SAFE_FREE_PTR(pathBuf);
385 return ret;
386 }
387 ret = SetPolicyLegacy(pathBuf, dir, &arg);
388 if (ret != 0) {
389 LOGE("SetPolicyLegacy fail, ret: %{public}d", ret);
390 }
391 #ifdef SUPPORT_FSCRYPT_V2
392 } else if (fscryptVer == FSCRYPT_V2) {
393 ret = SpliceKeyPath(keyDir, strlen(keyDir), PATH_KEYID,
394 strlen(PATH_KEYID), &pathBuf);
395 if (ret != 0) {
396 LOGE("path splice error");
397 SAFE_FREE_PTR(pathBuf);
398 return ret;
399 }
400 ret = SetPolicyV2(pathBuf, dir, &arg);
401 if (ret != 0) {
402 LOGE("SetPolicyV2 fail, ret: %{public}d", ret);
403 }
404 #endif
405 }
406 SAFE_FREE_PTR(pathBuf);
407 return ret;
408 }
409
ActSetFileXattrActSetFileXattr(const char * path,char * keyDesc,int storageType)410 static int ActSetFileXattrActSetFileXattr(const char *path, char *keyDesc, int storageType)
411 {
412 struct FscryptSdpPolicy PolicySDP = {0, 0, 0, 0, 0, {0, 0, 0, 0, 0, 0, 0, 0}};
413 PolicySDP.version = SDP_VERSIOIN;
414 PolicySDP.sdpclass = storageType;
415 PolicySDP.contentsEncryptionMode = SDP_CONTENTS_ENCRYPTION_MODE;
416 PolicySDP.filenamesEncryptionMode = SDP_FILENAMES_ENCRYPTION_MODE;
417 PolicySDP.flags = SDP_FLAGS;
418
419 int ret = memcpy_s((char *)PolicySDP.masterKeyDescriptor, FS_KEY_DESC_SIZE, (char *)keyDesc,
420 FSCRYPT_KEY_DESCRIPTOR_SIZE);
421 if (ret != 0) {
422 LOGE("memcpy_s copy failed");
423 return -errno;
424 }
425 int fd = open((char *)path, O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
426 if (fd < 0) {
427 LOGE("install File or Directory open failed: %{public}d", errno);
428 return -errno;
429 }
430 ret = ioctl(fd, F2FS_IOC_SET_SDP_ENCRYPTION_POLICY, &PolicySDP);
431 if (ret != 0) {
432 LOGE("ioctl fbex_cmd failed, ret: 0x%{public}X, errno: %{public}d", ret, errno);
433 close(fd);
434 return ret;
435 }
436 close(fd);
437 return ret;
438 }
439
LoadAndSetEceAndSecePolicy(const char * keyDir,const char * dir,int type)440 int LoadAndSetEceAndSecePolicy(const char *keyDir, const char *dir, int type)
441 {
442 int el3Key = 3; // el3
443 int el4Key = 4; // el4
444 if (!keyDir || !dir) {
445 LOGE("set policy parameters is null");
446 return -EINVAL;
447 }
448 char *pathBuf = NULL;
449 int ret = SpliceKeyPath(keyDir, strlen(keyDir), PATH_KEYDESC, strlen(PATH_KEYDESC), &pathBuf);
450 if (ret != 0) {
451 LOGE("path splice error");
452 return ret;
453 }
454
455 uint8_t fscryptVer = KeyCtrlLoadVersion(keyDir);
456 if (fscryptVer == FSCRYPT_V1) {
457 if (type == el3Key || type == el4Key) {
458 if (type == el3Key) {
459 type = FSCRYPT_SDP_SECE_CLASS;
460 } else {
461 type = FSCRYPT_SDP_ECE_CLASS;
462 }
463 char keyDesc[FSCRYPT_KEY_DESCRIPTOR_SIZE] = {0};
464 ret = ReadKeyFile(pathBuf, keyDesc, FSCRYPT_KEY_DESCRIPTOR_SIZE);
465 if (ret != 0) {
466 SAFE_FREE_PTR(pathBuf);
467 return ret;
468 }
469 ret = ActSetFileXattrActSetFileXattr(dir, keyDesc, type);
470 if (ret != 0) {
471 SAFE_FREE_PTR(pathBuf);
472 LOGE("ActSetFileXattr failed");
473 return ret;
474 }
475 }
476 #ifdef SUPPORT_FSCRYPT_V2
477 } else if (fscryptVer == FSCRYPT_V2) {
478 return 0;
479 #endif
480 }
481 SAFE_FREE_PTR(pathBuf);
482 return ret;
483 }
484
SetGlobalEl1DirPolicy(const char * dir)485 int SetGlobalEl1DirPolicy(const char *dir)
486 {
487 if (!g_fscryptEnabled) {
488 LOGI("Fscrypt have not enabled");
489 return 0;
490 }
491 for (size_t i = 0; i < ARRAY_LEN(GLOBAL_FSCRYPT_DIR); i++) {
492 size_t tmpLen = strlen(GLOBAL_FSCRYPT_DIR[i]);
493 if ((strncmp(dir, GLOBAL_FSCRYPT_DIR[i], tmpLen) == 0) && (strlen(dir) == tmpLen)) {
494 return LoadAndSetPolicy(DEVICE_EL1_DIR, dir);
495 }
496 }
497 return 0;
498 }
499
GetFscryptVersionFromPolicy(void)500 uint8_t GetFscryptVersionFromPolicy(void)
501 {
502 return g_fscryptPolicy.version;
503 }
504