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 #include <linux/filter.h>
17 #include <linux/seccomp.h>
18 #include <sys/stat.h>
19 #include <sys/prctl.h>
20 #include <string>
21 #include <sys/syscall.h>
22 #include <errno.h>
23 
24 #include <jni.h>
25 #include <nativehelper/JNIHelp.h>
26 #include <nativehelper/ScopedUtfChars.h>
27 
Java_libcore_java_io_FileTest_nativeTestFilesWithSurrogatePairs(JNIEnv * env,jobject,jstring baseDir)28 extern "C" void Java_libcore_java_io_FileTest_nativeTestFilesWithSurrogatePairs(
29     JNIEnv* env, jobject /* clazz */, jstring baseDir) {
30   ScopedUtfChars baseDirUtf(env, baseDir);
31 
32   std::string base(baseDirUtf.c_str());
33   std::string subDir = base + "/dir_\xF0\x93\x80\x80";
34   std::string subFile = subDir + "/file_\xF0\x93\x80\x80";
35 
36   struct stat sb;
37   int ret = stat(subDir.c_str(), &sb);
38   if (ret == -1) {
39       jniThrowIOException(env, errno);
40       return;
41   }
42   if (!S_ISDIR(sb.st_mode)) {
43       jniThrowException(env, "java/lang/IllegalStateException", "expected dir");
44       return;
45   }
46 
47   ret = stat(subFile.c_str(), &sb);
48   if (ret == -1) {
49       jniThrowIOException(env, errno);
50       return;
51   }
52 
53   if (!S_ISREG(sb.st_mode)) {
54       jniThrowException(env, "java/lang/IllegalStateException", "expected file");
55       return;
56   }
57 }
58 
Java_libcore_java_io_FileTest_installSeccompFilter(JNIEnv *,jclass)59 extern "C" int Java_libcore_java_io_FileTest_installSeccompFilter(JNIEnv* , jclass /* clazz */) {
60     struct sock_filter filter[] = {
61         BPF_STMT(BPF_LD|BPF_W|BPF_ABS, offsetof(struct seccomp_data, nr)),
62 
63 // for arm, x86.
64 #ifdef __NR_fstatat64
65         BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_fstatat64, 0, 1),
66 #else
67 // for arm64, x86_64.
68         BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __NR_newfstatat, 0, 1),
69 #endif
70         BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ERRNO | EPERM),
71         BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
72     };
73     struct sock_fprog prog = {
74         .len = (unsigned short)(sizeof(filter)/sizeof(filter[0])),
75         .filter = filter,
76     };
77     long ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
78 
79     return ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog);
80 }
81