1 /*
2 * Copyright (C) 2023 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 #include <fcntl.h>
18 #include <grp.h>
19 #include <selinux/selinux.h>
20 #include <signal.h>
21 #include <stdio.h>
22 #include <string.h>
23 #include <sys/prctl.h>
24 #include <unistd.h>
25
26 #include "android_filesystem_config.h"
27 #include "seccomp_policy.h"
28
set_groups(const gid_t gid)29 static bool set_groups(const gid_t gid) {
30 const gid_t groups[] = {gid, AID_EVERYBODY, AID_MISC};
31 const size_t num_groups = sizeof(groups) / sizeof(gid_t);
32
33 if (setgroups(num_groups, groups) != 0) {
34 fprintf(stderr, "setgroups failed\n");
35 return false;
36 }
37
38 if (setresgid(gid, gid, gid) != 0) {
39 fprintf(stderr, "setresgid failed\n");
40 return false;
41 }
42
43 return true;
44 }
45
set_user(const uid_t uid)46 static bool set_user(const uid_t uid) {
47 if (setresuid(uid, uid, uid) != 0) {
48 fprintf(stderr, "setresuid failed\n");
49 return false;
50 }
51
52 if (prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0)) {
53 fprintf(stderr, "prctl failed\n");
54 return false;
55 }
56
57 return true;
58 }
59
enter_app_sandbox()60 static bool enter_app_sandbox() {
61 if (!set_groups(AID_APP_START)) {
62 return false;
63 }
64
65 if (!set_app_seccomp_filter()) {
66 return false;
67 }
68
69 if (!set_user(AID_APP_START)) {
70 return false;
71 };
72
73 // TODO: figure out the correct value or make this configurable.
74 setcon("u:r:untrusted_app:s0:c512,c768");
75
76 return true;
77 }
78
enter_system_sandbox()79 static bool enter_system_sandbox() {
80 if (!set_groups(AID_SYSTEM)) {
81 return false;
82 }
83
84 if (!set_system_seccomp_filter()) {
85 return false;
86 }
87
88 if (!set_user(AID_SYSTEM)) {
89 return false;
90 };
91
92 return true;
93 }
94
print_usage(char ** argv)95 void print_usage(char** argv) {
96 fprintf(stderr, "usage: %s <app|system> <file>\n", argv[0]);
97 }
98
main(int argc,char ** argv)99 int main(int argc, char** argv) {
100 if (argc != 3) {
101 print_usage(argv);
102 return 1;
103 }
104
105 if (!strcmp(argv[1], "app")) {
106 if (!enter_app_sandbox()) {
107 return 1;
108 }
109 } else if (!strcmp(argv[1], "system")) {
110 if (!enter_system_sandbox()) {
111 return 1;
112 }
113 } else {
114 print_usage(argv);
115 return 1;
116 }
117
118 if (open(argv[2], O_RDONLY) == -1) {
119 fprintf(stderr, "failed to open %s\n", argv[2]);
120 return 1;
121 }
122
123 return 0;
124 }
125