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 <stdio.h>
21 #include <stdbool.h>
22 #include <sys/stat.h>
23 #include <sys/types.h>
24 #include <unistd.h>
25
26 #include "fscrypt_log.h"
27 #include "fscrypt_sysparam.h"
28 #include "init_utils.h"
29 #include "key_control.h"
30 #include "securec.h"
31 #include <sys/ioctl.h>
32
33 #define ARRAY_LEN(array) (sizeof((array)) / sizeof((array)[0]))
34
35 typedef struct FscrtpyItem_ {
36 char *key;
37 uint8_t value;
38 }FscrtpyItem;
39
40 typedef struct EncryptPolicy_ {
41 uint8_t version;
42 uint8_t fileName;
43 uint8_t content;
44 uint8_t flags;
45 bool hwWrappedKey;
46 }EncryptPolicy;
47
48 static EncryptPolicy g_fscryptPolicy = {
49 FSCRYPT_V2,
50 FSCRYPT_MODE_AES_256_CTS,
51 FSCRYPT_MODE_AES_256_XTS,
52 FSCRYPT_POLICY_FLAGS_PAD_32,
53 false
54 };
55
56 enum FscryptOptins {
57 FSCRYPT_VERSION_NUM = 0,
58 FSCRYPT_FILENAME_MODE,
59 FSCRYPT_CONTENT_MODE,
60 FSCRYPT_OPTIONS_MAX,
61 };
62
63 static const FscrtpyItem ALL_VERSION[] = {
64 {"1", FSCRYPT_V1},
65 {"2", FSCRYPT_V2},
66 };
67
68 static const FscrtpyItem FILENAME_MODES[] = {
69 {"aes-256-cts", FSCRYPT_MODE_AES_256_CTS},
70 };
71
72 static const FscrtpyItem CONTENTS_MODES[] = {
73 {"aes-256-xts", FSCRYPT_MODE_AES_256_XTS},
74 };
75
76 static bool g_fscryptEnabled = false;
77 static bool g_fscryptInited = false;
78
79 static const char *GLOBAL_FSCRYPT_DIR[] = {
80 "/data/app/el1/bundle/public",
81 "/data/service/el1/public",
82 "/data/chipset/el1/public",
83 };
84
85 static const char *DEVICE_EL1_DIR = "/data/service/el0/storage_daemon/sd";
86 static const char *PATH_KEYDESC = "/key_desc";
87 #ifdef SUPPORT_FSCRYPT_V2
88 static const char *PATH_KEYID = "/key_id";
89 #endif
90
IsSupportedPolicyKey(const char * key,const FscrtpyItem * items,size_t len)91 static bool IsSupportedPolicyKey(const char *key,
92 const FscrtpyItem *items,
93 size_t len)
94 {
95 for (size_t i = 0 ; i < len; i++) {
96 if (strncmp(key, items[i].key, strlen(items[i].key)) == 0) {
97 return true;
98 }
99 }
100 return false;
101 }
102
IsSupportedPolicy(const char * policy,enum FscryptOptins number)103 static bool IsSupportedPolicy(const char *policy,
104 enum FscryptOptins number)
105 {
106 if ((number >= FSCRYPT_OPTIONS_MAX) || (!policy)) {
107 return false;
108 }
109
110 switch (number) {
111 case FSCRYPT_VERSION_NUM:
112 return IsSupportedPolicyKey(policy, ALL_VERSION,
113 ARRAY_LEN(ALL_VERSION));
114 case FSCRYPT_FILENAME_MODE:
115 return IsSupportedPolicyKey(policy, FILENAME_MODES,
116 ARRAY_LEN(FILENAME_MODES));
117 case FSCRYPT_CONTENT_MODE:
118 return IsSupportedPolicyKey(policy, CONTENTS_MODES,
119 ARRAY_LEN(CONTENTS_MODES));
120 default:
121 return false;
122 }
123 return false;
124 }
125
FscryptSetSysparam(const char * policy)126 int FscryptSetSysparam(const char *policy)
127 {
128 if (!policy) {
129 return -EINVAL;
130 }
131
132 char *tmp = strdup(policy);
133 if (!tmp) {
134 LOGE("No memory for policy option");
135 return -ENOMEM;
136 }
137 int optNums = 0;
138 char **options = SplitStringExt(tmp, ":", &optNums, FSCRYPT_OPTIONS_MAX);
139 free(tmp);
140 if (!options) {
141 return -ENOMEM;
142 }
143 if (optNums != FSCRYPT_OPTIONS_MAX) {
144 LOGE("Mount fscrypt option setting error, not enabled crypto!");
145 FreeStringVector(options, optNums);
146 return -EINVAL;
147 }
148
149 // check supported policy
150 for (enum FscryptOptins i = FSCRYPT_VERSION_NUM; i < FSCRYPT_OPTIONS_MAX; i++) {
151 char *temp = options[i];
152 if (!IsSupportedPolicy(temp, i)) {
153 LOGE("Not supported policy, %{public}s", temp);
154 FreeStringVector(options, optNums);
155 return -ENOTSUP;
156 }
157 }
158 FreeStringVector(options, optNums);
159
160 int ret = SetFscryptParameter(FSCRYPT_POLICY_KEY, policy);
161 if (ret < 0) {
162 LOGE("Set fscrypt system parameter failed %{public}d", ret);
163 return ret;
164 }
165 g_fscryptEnabled = true;
166 g_fscryptInited = false; // need to re-init
167
168 return 0;
169 }
170
171 #ifdef USER_CRYPTO_MANAGER
PraseOnePloicyValue(uint8_t * value,const char * key,const FscrtpyItem * table,size_t numbers)172 static void PraseOnePloicyValue(uint8_t *value, const char *key,
173 const FscrtpyItem *table, size_t numbers)
174 {
175 for (size_t i = 0; i < numbers; i++) {
176 size_t len = strlen(table[i].key);
177 if (strncmp(key, table[i].key, len) == 0 &&
178 strlen(key) == len) {
179 *value = table[i].value;
180 return;
181 }
182 }
183 LOGE("Have not found value for the key!");
184 }
185 #endif
186
InitFscryptPolicy(void)187 int InitFscryptPolicy(void)
188 {
189 #ifdef USER_CRYPTO_MANAGER
190 if (g_fscryptInited) {
191 LOGI("Have been init");
192 return 0;
193 }
194 char policy[POLICY_BUF_SIZE];
195 uint32_t len = POLICY_BUF_SIZE - 1;
196 int ret = GetFscryptParameter(FSCRYPT_POLICY_KEY, "", policy, &len);
197 if (ret != 0) {
198 LOGI("Get fscrypt policy failed");
199 return -ENOTSUP;
200 }
201 int count = 0;
202 char **option = SplitStringExt(policy, ":", &count, FSCRYPT_OPTIONS_MAX);
203 if (!option) {
204 LOGE("Fscrypt setting error");
205 return -ENOTSUP;
206 }
207 if (count != FSCRYPT_OPTIONS_MAX) {
208 LOGE("Fscrypt policy count error");
209 FreeStringVector(option, count);
210 return -ENOTSUP;
211 }
212
213 PraseOnePloicyValue(&g_fscryptPolicy.version, option[FSCRYPT_VERSION_NUM],
214 ALL_VERSION, ARRAY_LEN(ALL_VERSION));
215 PraseOnePloicyValue(&g_fscryptPolicy.fileName, option[FSCRYPT_FILENAME_MODE],
216 FILENAME_MODES, ARRAY_LEN(FILENAME_MODES));
217 PraseOnePloicyValue(&g_fscryptPolicy.content, option[FSCRYPT_CONTENT_MODE],
218 CONTENTS_MODES, ARRAY_LEN(CONTENTS_MODES));
219
220 FreeStringVector(option, count);
221 g_fscryptInited = true;
222 LOGI("Fscrypt policy init success");
223 #endif
224
225 return 0;
226 }
227
228 /*
229 * Splic full path, Caller need to free *buf after using
230 * if return success.
231 *
232 * @path: base key path
233 * @name: fscrypt file, so as /key_id
234 * @buf: splic result if return 0
235 */
SpliceKeyPath(const char * path,size_t pathLen,const char * name,size_t nameLen,char ** buf)236 static int SpliceKeyPath(const char *path, size_t pathLen,
237 const char *name, size_t nameLen,
238 char **buf)
239 {
240 LOGI("key path %{public}s, name %{public}s", path, name);
241 *buf = NULL;
242 size_t bufMax = pathLen + nameLen + 1;
243 char *tmpBuf = (char *)malloc(bufMax);
244 if (!tmpBuf) {
245 LOGE("No memory for fscrypt v1 path buffer");
246 return -ENOMEM;
247 }
248 tmpBuf[0] = '\0';
249
250 int ret = strncat_s(tmpBuf, bufMax, path, pathLen);
251 if (ret != 0) {
252 free(tmpBuf);
253 LOGE("splic previous path error");
254 return ret;
255 }
256 ret = strncat_s(tmpBuf, bufMax, name, nameLen);
257 if (ret != 0) {
258 free(tmpBuf);
259 LOGE("splic later path error");
260 return ret;
261 }
262 *buf = tmpBuf;
263
264 return 0;
265 }
266
ReadKeyFile(const char * path,char * buf,size_t len)267 static int ReadKeyFile(const char *path, char *buf, size_t len)
268 {
269 if (!path || !buf) {
270 LOGE("path or buf is null");
271 return -EINVAL;
272 }
273 struct stat st = {0};
274 if (stat(path, &st) != 0) {
275 LOGE("stat file failed");
276 return -EFAULT;
277 }
278 if ((size_t)st.st_size != len) {
279 LOGE("target file size is not equal to buf len");
280 return -EINVAL;
281 }
282 char *realPath = realpath(path, NULL);
283 if (realPath == NULL) {
284 LOGE("realpath failed");
285 return -ENOENT;
286 }
287
288 FILE *f = fopen(realPath, "r");
289 free(realPath);
290 if (f == NULL) {
291 LOGE("key file read open failed");
292 return -ENOENT;
293 }
294 int fd = fileno(f);
295 if (fd < 0) {
296 LOGE("key file read open failed");
297 return -EIO;
298 }
299 if (read(fd, buf, len) != (ssize_t)len) {
300 LOGE("bad file content");
301 (void)fclose(f);
302 return -EBADF;
303 }
304 (void)fclose(f);
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 return ret;
385 }
386 ret = SetPolicyLegacy(pathBuf, dir, &arg);
387 if (ret != 0) {
388 LOGE("SetPolicyLegacy fail, ret: %{public}d", ret);
389 }
390 #ifdef SUPPORT_FSCRYPT_V2
391 } else if (fscryptVer == FSCRYPT_V2) {
392 ret = SpliceKeyPath(keyDir, strlen(keyDir), PATH_KEYID,
393 strlen(PATH_KEYID), &pathBuf);
394 if (ret != 0) {
395 LOGE("path splice error");
396 return ret;
397 }
398 ret = SetPolicyV2(pathBuf, dir, &arg);
399 if (ret != 0) {
400 LOGE("SetPolicyV2 fail, ret: %{public}d", ret);
401 }
402 #endif
403 }
404 if (pathBuf != NULL) {
405 free(pathBuf);
406 pathBuf = NULL;
407 }
408
409 return ret;
410 }
411
ActSetFileXattrActSetFileXattr(const char * path,char * keyDesc,int storageType)412 static int ActSetFileXattrActSetFileXattr(const char *path, char *keyDesc, int storageType)
413 {
414 struct FscryptSdpPolicy PolicySDP = {0, 0, 0, 0, 0, {0, 0, 0, 0, 0, 0, 0, 0}};
415 PolicySDP.version = SDP_VERSIOIN;
416 PolicySDP.sdpclass = storageType;
417 PolicySDP.contentsEncryptionMode = SDP_CONTENTS_ENCRYPTION_MODE;
418 PolicySDP.filenamesEncryptionMode = SDP_FILENAMES_ENCRYPTION_MODE;
419 PolicySDP.flags = SDP_FLAGS;
420
421 int ret = memcpy_s((char *)PolicySDP.masterKeyDescriptor, FS_KEY_DESC_SIZE, (char *)keyDesc,
422 FSCRYPT_KEY_DESCRIPTOR_SIZE);
423 if (ret != 0) {
424 LOGE("memcpy_s copy failed");
425 return -errno;
426 }
427 int fd = open((char *)path, O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
428 if (fd < 0) {
429 LOGE("install File or Directory open failed: %{public}d", errno);
430 return -errno;
431 }
432 ret = ioctl(fd, F2FS_IOC_SET_SDP_ENCRYPTION_POLICY, &PolicySDP);
433 if (ret != 0) {
434 LOGE("ioctl fbex_cmd failed, ret: 0x%{public}X, errno: %{public}d", ret, errno);
435 close(fd);
436 return ret;
437 }
438 close(fd);
439 return ret;
440 }
441
LoadAndSetEceAndSecePolicy(const char * keyDir,const char * dir,int type)442 int LoadAndSetEceAndSecePolicy(const char *keyDir, const char *dir, int type)
443 {
444 int el3Key = 3; // el3
445 int el4Key = 4; // el4
446 if (!keyDir || !dir) {
447 LOGE("set policy parameters is null");
448 return -EINVAL;
449 }
450 char *pathBuf = NULL;
451 int ret = SpliceKeyPath(keyDir, strlen(keyDir), PATH_KEYDESC, strlen(PATH_KEYDESC), &pathBuf);
452 if (ret != 0) {
453 LOGE("path splice error");
454 return ret;
455 }
456
457 uint8_t fscryptVer = KeyCtrlLoadVersion(keyDir);
458 if (fscryptVer == FSCRYPT_V1) {
459 if (type == el3Key || type == el4Key) {
460 if (type == el3Key) {
461 type = FSCRYPT_SDP_SECE_CLASS;
462 } else {
463 type = FSCRYPT_SDP_ECE_CLASS;
464 }
465 char keyDesc[FSCRYPT_KEY_DESCRIPTOR_SIZE] = {0};
466 ret = ReadKeyFile(pathBuf, keyDesc, FSCRYPT_KEY_DESCRIPTOR_SIZE);
467 if (ret != 0) {
468 return ret;
469 }
470 ret = ActSetFileXattrActSetFileXattr(dir, keyDesc, type);
471 if (ret != 0) {
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 if (pathBuf != NULL) {
482 free(pathBuf);
483 }
484 return ret;
485 }
486
SetGlobalEl1DirPolicy(const char * dir)487 int SetGlobalEl1DirPolicy(const char *dir)
488 {
489 if (!g_fscryptEnabled) {
490 LOGI("Fscrypt have not enabled");
491 return 0;
492 }
493 for (size_t i = 0; i < ARRAY_LEN(GLOBAL_FSCRYPT_DIR); i++) {
494 size_t tmpLen = strlen(GLOBAL_FSCRYPT_DIR[i]);
495 if ((strncmp(dir, GLOBAL_FSCRYPT_DIR[i], tmpLen) == 0) && (strlen(dir) == tmpLen)) {
496 return LoadAndSetPolicy(DEVICE_EL1_DIR, dir);
497 }
498 }
499 return 0;
500 }
501
GetFscryptVersionFromPolicy(void)502 uint8_t GetFscryptVersionFromPolicy(void)
503 {
504 return g_fscryptPolicy.version;
505 }
506