blob: 17fc9c8b0f19e60c2d05c5439c36252e96332965 [file] [log] [blame]
Vic Yange01ca4d2019-05-29 15:58:32 -07001/*
2 * Copyright (C) 2019 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 "service_utils.h"
18
19#include <grp.h>
20#include <sys/mount.h>
21#include <sys/prctl.h>
22#include <sys/wait.h>
23
24#include <android-base/file.h>
25#include <android-base/logging.h>
26#include <android-base/properties.h>
27#include <android-base/stringprintf.h>
28#include <android-base/strings.h>
29#include <android-base/unique_fd.h>
30#include <processgroup/processgroup.h>
31
32#include "mount_namespace.h"
33
34using android::base::GetProperty;
35using android::base::StartsWith;
36using android::base::StringPrintf;
37using android::base::unique_fd;
38using android::base::WriteStringToFile;
39
40namespace android {
41namespace init {
42
43namespace {
44
45Result<Success> EnterNamespace(int nstype, const char* path) {
46 auto fd = unique_fd{open(path, O_RDONLY | O_CLOEXEC)};
47 if (fd == -1) {
48 return ErrnoError() << "Could not open namespace at " << path;
49 }
50 if (setns(fd, nstype) == -1) {
51 return ErrnoError() << "Could not setns() namespace at " << path;
52 }
53 return Success();
54}
55
56Result<Success> SetUpMountNamespace(bool remount_proc, bool remount_sys) {
57 constexpr unsigned int kSafeFlags = MS_NODEV | MS_NOEXEC | MS_NOSUID;
58
59 // Recursively remount / as slave like zygote does so unmounting and mounting /proc
60 // doesn't interfere with the parent namespace's /proc mount. This will also
61 // prevent any other mounts/unmounts initiated by the service from interfering
62 // with the parent namespace but will still allow mount events from the parent
63 // namespace to propagate to the child.
64 if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
65 return ErrnoError() << "Could not remount(/) recursively as slave";
66 }
67
68 // umount() then mount() /proc and/or /sys
69 // Note that it is not sufficient to mount with MS_REMOUNT.
70 if (remount_proc) {
71 if (umount("/proc") == -1) {
72 return ErrnoError() << "Could not umount(/proc)";
73 }
74 if (mount("", "/proc", "proc", kSafeFlags, "") == -1) {
75 return ErrnoError() << "Could not mount(/proc)";
76 }
77 }
78 if (remount_sys) {
79 if (umount2("/sys", MNT_DETACH) == -1) {
80 return ErrnoError() << "Could not umount(/sys)";
81 }
82 if (mount("", "/sys", "sysfs", kSafeFlags, "") == -1) {
83 return ErrnoError() << "Could not mount(/sys)";
84 }
85 }
86 return Success();
87}
88
89Result<Success> SetUpPidNamespace(const char* name) {
90 if (prctl(PR_SET_NAME, name) == -1) {
91 return ErrnoError() << "Could not set name";
92 }
93
94 pid_t child_pid = fork();
95 if (child_pid == -1) {
96 return ErrnoError() << "Could not fork init inside the PID namespace";
97 }
98
99 if (child_pid > 0) {
100 // So that we exit with the right status.
101 static int init_exitstatus = 0;
102 signal(SIGTERM, [](int) { _exit(init_exitstatus); });
103
104 pid_t waited_pid;
105 int status;
106 while ((waited_pid = wait(&status)) > 0) {
107 // This loop will end when there are no processes left inside the
108 // PID namespace or when the init process inside the PID namespace
109 // gets a signal.
110 if (waited_pid == child_pid) {
111 init_exitstatus = status;
112 }
113 }
114 if (!WIFEXITED(init_exitstatus)) {
115 _exit(EXIT_FAILURE);
116 }
117 _exit(WEXITSTATUS(init_exitstatus));
118 }
119 return Success();
120}
121
122void ZapStdio() {
123 int fd;
124 fd = open("/dev/null", O_RDWR);
125 dup2(fd, 0);
126 dup2(fd, 1);
127 dup2(fd, 2);
128 close(fd);
129}
130
131void OpenConsole(const std::string& console) {
132 int fd = open(console.c_str(), O_RDWR);
133 if (fd == -1) fd = open("/dev/null", O_RDWR);
134 ioctl(fd, TIOCSCTTY, 0);
135 dup2(fd, 0);
136 dup2(fd, 1);
137 dup2(fd, 2);
138 close(fd);
139}
140
141} // namespace
142
143Result<Success> EnterNamespaces(const NamespaceInfo& info, const std::string& name,
144 bool pre_apexd) {
145 for (const auto& [nstype, path] : info.namespaces_to_enter) {
146 if (auto result = EnterNamespace(nstype, path.c_str()); !result) {
147 return result;
148 }
149 }
150
151#if defined(__ANDROID__)
152 if (pre_apexd) {
153 if (!SwitchToBootstrapMountNamespaceIfNeeded()) {
154 return Error() << "could not enter into the bootstrap mount namespace";
155 }
156 }
157#endif
158
159 if (info.flags & CLONE_NEWNS) {
160 bool remount_proc = info.flags & CLONE_NEWPID;
161 bool remount_sys =
162 std::any_of(info.namespaces_to_enter.begin(), info.namespaces_to_enter.end(),
163 [](const auto& entry) { return entry.first == CLONE_NEWNET; });
164 if (auto result = SetUpMountNamespace(remount_proc, remount_sys); !result) {
165 return result;
166 }
167 }
168
169 if (info.flags & CLONE_NEWPID) {
170 // This will fork again to run an init process inside the PID namespace.
171 if (auto result = SetUpPidNamespace(name.c_str()); !result) {
172 return result;
173 }
174 }
175
176 return Success();
177}
178
179Result<Success> SetProcessAttributes(const ProcessAttributes& attr) {
180 if (attr.ioprio_class != IoSchedClass_NONE) {
181 if (android_set_ioprio(getpid(), attr.ioprio_class, attr.ioprio_pri)) {
182 PLOG(ERROR) << "failed to set pid " << getpid() << " ioprio=" << attr.ioprio_class
183 << "," << attr.ioprio_pri;
184 }
185 }
186
187 if (!attr.console.empty()) {
188 setsid();
189 OpenConsole(attr.console);
190 } else {
191 if (setpgid(0, getpid()) == -1) {
192 return ErrnoError() << "setpgid failed";
193 }
194 ZapStdio();
195 }
196
197 for (const auto& rlimit : attr.rlimits) {
198 if (setrlimit(rlimit.first, &rlimit.second) == -1) {
199 return ErrnoError() << StringPrintf(
200 "setrlimit(%d, {rlim_cur=%ld, rlim_max=%ld}) failed", rlimit.first,
201 rlimit.second.rlim_cur, rlimit.second.rlim_max);
202 }
203 }
204
205 if (attr.gid) {
206 if (setgid(attr.gid) != 0) {
207 return ErrnoError() << "setgid failed";
208 }
209 }
210 if (setgroups(attr.supp_gids.size(), const_cast<gid_t*>(&attr.supp_gids[0])) != 0) {
211 return ErrnoError() << "setgroups failed";
212 }
213 if (attr.uid) {
214 if (setuid(attr.uid) != 0) {
215 return ErrnoError() << "setuid failed";
216 }
217 }
218
219 if (attr.priority != 0) {
220 if (setpriority(PRIO_PROCESS, 0, attr.priority) != 0) {
221 return ErrnoError() << "setpriority failed";
222 }
223 }
224 return Success();
225}
226
227Result<Success> WritePidToFiles(std::vector<std::string>* files) {
228 // See if there were "writepid" instructions to write to files under cpuset path.
229 std::string cpuset_path;
230 if (CgroupGetControllerPath("cpuset", &cpuset_path)) {
231 auto cpuset_predicate = [&cpuset_path](const std::string& path) {
232 return StartsWith(path, cpuset_path + "/");
233 };
234 auto iter = std::find_if(files->begin(), files->end(), cpuset_predicate);
235 if (iter == files->end()) {
236 // There were no "writepid" instructions for cpusets, check if the system default
237 // cpuset is specified to be used for the process.
238 std::string default_cpuset = GetProperty("ro.cpuset.default", "");
239 if (!default_cpuset.empty()) {
240 // Make sure the cpuset name starts and ends with '/'.
241 // A single '/' means the 'root' cpuset.
242 if (default_cpuset.front() != '/') {
243 default_cpuset.insert(0, 1, '/');
244 }
245 if (default_cpuset.back() != '/') {
246 default_cpuset.push_back('/');
247 }
248 files->push_back(
249 StringPrintf("%s%stasks", cpuset_path.c_str(), default_cpuset.c_str()));
250 }
251 }
252 } else {
253 LOG(ERROR) << "cpuset cgroup controller is not mounted!";
254 }
255 std::string pid_str = std::to_string(getpid());
256 for (const auto& file : *files) {
257 if (!WriteStringToFile(pid_str, file)) {
258 return ErrnoError() << "couldn't write " << pid_str << " to " << file;
259 }
260 }
261 return Success();
262}
263
264} // namespace init
265} // namespace android