1 /*
2  * Copyright (C) 2020 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 #define LOG_TAG "ApkVerityTestApp"
18 
19 #include "jni.h"
20 #include <nativehelper/JNIHelp.h>
21 #include <nativehelper/ScopedUtfChars.h>
22 
23 #include <android/log.h>
24 
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <linux/fs.h>
28 #include <sys/ioctl.h>
29 #include <sys/stat.h>
30 #include <sys/types.h>
31 #include <unistd.h>
32 
33 #define ALOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
34 
35 extern "C" JNIEXPORT jboolean JNICALL
Java_android_appsecurity_cts_apkveritytestapp_InstalledFilesCheck_hasFsverityNative(JNIEnv * env,jobject,jstring filePath)36 Java_android_appsecurity_cts_apkveritytestapp_InstalledFilesCheck_hasFsverityNative(
37     JNIEnv *env, jobject /*thiz*/, jstring filePath) {
38   ScopedUtfChars path(env, filePath);
39 
40   // Call statx and check STATX_ATTR_VERITY.
41   struct statx out = {};
42   if (statx(AT_FDCWD, path.c_str(), 0 /* flags */, STATX_ALL, &out) != 0) {
43     ALOGE("statx failed at %s", path.c_str());
44     return JNI_FALSE;
45   }
46 
47   if (out.stx_attributes_mask & STATX_ATTR_VERITY) {
48     return (out.stx_attributes & STATX_ATTR_VERITY) != 0 ? JNI_TRUE : JNI_FALSE;
49   }
50 
51   // STATX_ATTR_VERITY is not supported by kernel for the file path.
52   // In this case, call ioctl(FS_IOC_GETFLAGS) and check FS_VERITY_FL.
53   int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
54   if (fd < 0) {
55     ALOGE("failed to open %s", path.c_str());
56     return JNI_FALSE;
57   }
58 
59   unsigned int flags;
60   int ret = ioctl(fd, FS_IOC_GETFLAGS, &flags);
61   close(fd);
62 
63   if (ret < 0) {
64     ALOGE("ioctl(FS_IOC_GETFLAGS) failed at %s", path.c_str());
65     return JNI_FALSE;
66   }
67 
68   return (flags & FS_VERITY_FL) != 0 ? JNI_TRUE : JNI_FALSE;
69 }
70