blob: da258019f053fc319b1b57df8298812476830170 [file] [log] [blame]
Narayan Kamath973b4662014-03-31 13:41:26 +01001/*
2 * Copyright (C) 2008 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
Colin Cross18cd9f52014-06-13 12:58:55 -070017#define LOG_TAG "Zygote"
Narayan Kamath973b4662014-03-31 13:41:26 +010018
19// sys/mount.h has to come before linux/fs.h due to redefinition of MS_RDONLY, MS_BIND, etc
20#include <sys/mount.h>
21#include <linux/fs.h>
22
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070023#include <list>
Andreas Gampeb053cce2015-11-17 16:38:59 -080024#include <sstream>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070025#include <string>
26
Josh Gaod7951102018-06-26 16:05:12 -070027#include <android/fdsan.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070028#include <fcntl.h>
Dan Albert46d84442014-11-18 16:07:51 -080029#include <grp.h>
30#include <inttypes.h>
Christopher Ferrisab16dd12017-05-15 16:50:29 -070031#include <malloc.h>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070032#include <mntent.h>
Narayan Kamath973b4662014-03-31 13:41:26 +010033#include <paths.h>
34#include <signal.h>
35#include <stdlib.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070036#include <sys/capability.h>
Robert Seseke4f8d692016-09-13 19:13:01 -040037#include <sys/cdefs.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070038#include <sys/personality.h>
39#include <sys/prctl.h>
40#include <sys/resource.h>
41#include <sys/stat.h>
Vitalii Tomkiv5cbce852016-05-18 17:43:02 -070042#include <sys/time.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070043#include <sys/types.h>
44#include <sys/utsname.h>
45#include <sys/wait.h>
Dan Albert46d84442014-11-18 16:07:51 -080046#include <unistd.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070047
Andreas Gampe8dfa1782017-01-05 12:45:58 -080048#include "android-base/logging.h"
Minchan Kim696873e2018-06-27 11:32:40 +090049#include <android-base/properties.h>
Carmen Jacksondd401252017-02-23 15:21:10 -080050#include <android-base/file.h>
51#include <android-base/stringprintf.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070052#include <cutils/fs.h>
53#include <cutils/multiuser.h>
54#include <cutils/sched_policy.h>
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -070055#include <private/android_filesystem_config.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070056#include <utils/String8.h>
57#include <selinux/android.h>
Victor Hsiehc8176ef2018-01-08 12:43:00 -080058#include <seccomp_policy.h>
Colin Cross0161bbc2014-06-03 13:26:58 -070059#include <processgroup/processgroup.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070060
Andreas Gampeed6b9df2014-11-20 22:02:20 -080061#include "core_jni_helpers.h"
Steven Moreland2279b252017-07-19 09:50:45 -070062#include <nativehelper/JNIHelp.h>
63#include <nativehelper/ScopedLocalRef.h>
64#include <nativehelper/ScopedPrimitiveArray.h>
65#include <nativehelper/ScopedUtfChars.h>
Robert Sesek8225b7c2016-12-16 14:02:31 -050066#include "fd_utils.h"
Narayan Kamath973b4662014-03-31 13:41:26 +010067
jgu212eacd062014-09-10 06:55:07 -040068#include "nativebridge/native_bridge.h"
69
Narayan Kamath973b4662014-03-31 13:41:26 +010070namespace {
71
72using android::String8;
Carmen Jacksondd401252017-02-23 15:21:10 -080073using android::base::StringPrintf;
74using android::base::WriteStringToFile;
Minchan Kim696873e2018-06-27 11:32:40 +090075using android::base::GetBoolProperty;
Narayan Kamath973b4662014-03-31 13:41:26 +010076
Andreas Gamped5758f62018-03-12 12:08:55 -070077#define CREATE_ERROR(...) StringPrintf("%s:%d: ", __FILE__, __LINE__). \
78 append(StringPrintf(__VA_ARGS__))
79
Narayan Kamath973b4662014-03-31 13:41:26 +010080static pid_t gSystemServerPid = 0;
81
82static const char kZygoteClassName[] = "com/android/internal/os/Zygote";
83static jclass gZygoteClass;
Orion Hodson46724e72018-10-19 13:05:33 +010084static jmethodID gCallPostForkSystemServerHooks;
Narayan Kamath973b4662014-03-31 13:41:26 +010085static jmethodID gCallPostForkChildHooks;
86
Victor Hsiehc8176ef2018-01-08 12:43:00 -080087static bool g_is_security_enforced = true;
88
Narayan Kamath973b4662014-03-31 13:41:26 +010089// Must match values in com.android.internal.os.Zygote.
90enum MountExternalKind {
91 MOUNT_EXTERNAL_NONE = 0,
Jeff Sharkey48877892015-03-18 11:27:19 -070092 MOUNT_EXTERNAL_DEFAULT = 1,
Jeff Sharkey9527b222015-06-24 15:24:48 -070093 MOUNT_EXTERNAL_READ = 2,
94 MOUNT_EXTERNAL_WRITE = 3,
Narayan Kamath973b4662014-03-31 13:41:26 +010095};
96
Andreas Gampeb053cce2015-11-17 16:38:59 -080097static void RuntimeAbort(JNIEnv* env, int line, const char* msg) {
98 std::ostringstream oss;
99 oss << __FILE__ << ":" << line << ": " << msg;
100 env->FatalError(oss.str().c_str());
Narayan Kamath973b4662014-03-31 13:41:26 +0100101}
102
103// This signal handler is for zygote mode, since the zygote must reap its children
104static void SigChldHandler(int /*signal_number*/) {
105 pid_t pid;
106 int status;
107
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700108 // It's necessary to save and restore the errno during this function.
109 // Since errno is stored per thread, changing it here modifies the errno
110 // on the thread on which this signal handler executes. If a signal occurs
111 // between a call and an errno check, it's possible to get the errno set
112 // here.
113 // See b/23572286 for extra information.
114 int saved_errno = errno;
115
Narayan Kamath973b4662014-03-31 13:41:26 +0100116 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
117 // Log process-death status that we care about. In general it is
118 // not safe to call LOG(...) from a signal handler because of
119 // possible reentrancy. However, we know a priori that the
120 // current implementation of LOG() is safe to call from a SIGCHLD
121 // handler in the zygote process. If the LOG() implementation
122 // changes its locking strategy or its use of syscalls within the
123 // lazy-init critical section, its use here may become unsafe.
124 if (WIFEXITED(status)) {
Josh Gao6d747ca2017-08-02 12:54:05 -0700125 ALOGI("Process %d exited cleanly (%d)", pid, WEXITSTATUS(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100126 } else if (WIFSIGNALED(status)) {
Josh Gao6d747ca2017-08-02 12:54:05 -0700127 ALOGI("Process %d exited due to signal (%d)", pid, WTERMSIG(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100128 if (WCOREDUMP(status)) {
129 ALOGI("Process %d dumped core.", pid);
130 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100131 }
132
133 // If the just-crashed process is the system_server, bring down zygote
134 // so that it is restarted by init and system server will be restarted
135 // from there.
136 if (pid == gSystemServerPid) {
Dan Albert46d84442014-11-18 16:07:51 -0800137 ALOGE("Exit zygote because system server (%d) has terminated", pid);
Narayan Kamath973b4662014-03-31 13:41:26 +0100138 kill(getpid(), SIGKILL);
139 }
140 }
141
Narayan Kamath160992d2014-04-14 14:46:07 +0100142 // Note that we shouldn't consider ECHILD an error because
143 // the secondary zygote might have no children left to wait for.
144 if (pid < 0 && errno != ECHILD) {
145 ALOGW("Zygote SIGCHLD error in waitpid: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100146 }
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700147
148 errno = saved_errno;
Narayan Kamath973b4662014-03-31 13:41:26 +0100149}
150
yuanhao435e84b2018-01-15 15:37:02 +0800151// Configures the SIGCHLD/SIGHUP handlers for the zygote process. This is
152// configured very late, because earlier in the runtime we may fork() and
153// exec() other processes, and we want to waitpid() for those rather than
Narayan Kamath973b4662014-03-31 13:41:26 +0100154// have them be harvested immediately.
155//
yuanhao435e84b2018-01-15 15:37:02 +0800156// Ignore SIGHUP because all processes forked by the zygote are in the same
157// process group as the zygote and we don't want to be notified if we become
158// an orphaned group and have one or more stopped processes. This is not a
159// theoretical concern :
160// - we can become an orphaned group if one of our direct descendants forks
161// and is subsequently killed before its children.
162// - crash_dump routinely STOPs the process it's tracing.
163//
164// See issues b/71965619 and b/25567761 for further details.
165//
Narayan Kamath973b4662014-03-31 13:41:26 +0100166// This ends up being called repeatedly before each fork(), but there's
167// no real harm in that.
yuanhao435e84b2018-01-15 15:37:02 +0800168static void SetSignalHandlers() {
169 struct sigaction sig_chld = {};
170 sig_chld.sa_handler = SigChldHandler;
Narayan Kamath973b4662014-03-31 13:41:26 +0100171
yuanhao435e84b2018-01-15 15:37:02 +0800172 if (sigaction(SIGCHLD, &sig_chld, NULL) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700173 ALOGW("Error setting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100174 }
yuanhao435e84b2018-01-15 15:37:02 +0800175
176 struct sigaction sig_hup = {};
177 sig_hup.sa_handler = SIG_IGN;
178 if (sigaction(SIGHUP, &sig_hup, NULL) < 0) {
179 ALOGW("Error setting SIGHUP handler: %s", strerror(errno));
180 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100181}
182
183// Sets the SIGCHLD handler back to default behavior in zygote children.
yuanhao435e84b2018-01-15 15:37:02 +0800184static void UnsetChldSignalHandler() {
Narayan Kamath973b4662014-03-31 13:41:26 +0100185 struct sigaction sa;
186 memset(&sa, 0, sizeof(sa));
187 sa.sa_handler = SIG_DFL;
188
yuanhao435e84b2018-01-15 15:37:02 +0800189 if (sigaction(SIGCHLD, &sa, NULL) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700190 ALOGW("Error unsetting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100191 }
192}
193
194// Calls POSIX setgroups() using the int[] object as an argument.
195// A NULL argument is tolerated.
Andreas Gamped5758f62018-03-12 12:08:55 -0700196static bool SetGids(JNIEnv* env, jintArray javaGids, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100197 if (javaGids == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700198 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100199 }
200
201 ScopedIntArrayRO gids(env, javaGids);
202 if (gids.get() == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700203 *error_msg = CREATE_ERROR("Getting gids int array failed");
204 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100205 }
206 int rc = setgroups(gids.size(), reinterpret_cast<const gid_t*>(&gids[0]));
207 if (rc == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700208 *error_msg = CREATE_ERROR("setgroups failed: %s, gids.size=%zu", strerror(errno), gids.size());
209 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100210 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700211
212 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100213}
214
215// Sets the resource limits via setrlimit(2) for the values in the
216// two-dimensional array of integers that's passed in. The second dimension
217// contains a tuple of length 3: (resource, rlim_cur, rlim_max). NULL is
218// treated as an empty array.
Andreas Gamped5758f62018-03-12 12:08:55 -0700219static bool SetRLimits(JNIEnv* env, jobjectArray javaRlimits, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100220 if (javaRlimits == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700221 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100222 }
223
224 rlimit rlim;
225 memset(&rlim, 0, sizeof(rlim));
226
227 for (int i = 0; i < env->GetArrayLength(javaRlimits); ++i) {
228 ScopedLocalRef<jobject> javaRlimitObject(env, env->GetObjectArrayElement(javaRlimits, i));
229 ScopedIntArrayRO javaRlimit(env, reinterpret_cast<jintArray>(javaRlimitObject.get()));
230 if (javaRlimit.size() != 3) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700231 *error_msg = CREATE_ERROR("rlimits array must have a second dimension of size 3");
232 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100233 }
234
235 rlim.rlim_cur = javaRlimit[1];
236 rlim.rlim_max = javaRlimit[2];
237
238 int rc = setrlimit(javaRlimit[0], &rlim);
239 if (rc == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700240 *error_msg = CREATE_ERROR("setrlimit(%d, {%ld, %ld}) failed", javaRlimit[0], rlim.rlim_cur,
Dan Albert46d84442014-11-18 16:07:51 -0800241 rlim.rlim_max);
Andreas Gamped5758f62018-03-12 12:08:55 -0700242 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100243 }
244 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700245
246 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100247}
248
Narayan Kamath973b4662014-03-31 13:41:26 +0100249// The debug malloc library needs to know whether it's the zygote or a child.
250extern "C" int gMallocLeakZygoteChild;
251
Christopher Ferris76de39e2017-06-20 16:13:40 -0700252static void PreApplicationInit() {
253 // The child process sets this to indicate it's not the zygote.
254 gMallocLeakZygoteChild = 1;
255
256 // Set the jemalloc decay time to 1.
257 mallopt(M_DECAY_TIME, 1);
258}
259
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800260static void SetUpSeccompFilter(uid_t uid) {
261 if (!g_is_security_enforced) {
262 ALOGI("seccomp disabled by setenforce 0");
263 return;
264 }
265
266 // Apply system or app filter based on uid.
Victor Hsiehfa046a12018-03-28 16:26:28 -0700267 if (uid >= AID_APP_START) {
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800268 set_app_seccomp_filter();
269 } else {
270 set_system_seccomp_filter();
271 }
272}
273
Andreas Gamped5758f62018-03-12 12:08:55 -0700274static bool EnableKeepCapabilities(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100275 int rc = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
276 if (rc == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700277 *error_msg = CREATE_ERROR("prctl(PR_SET_KEEPCAPS) failed: %s", strerror(errno));
278 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100279 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700280 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100281}
282
Andreas Gamped5758f62018-03-12 12:08:55 -0700283static bool DropCapabilitiesBoundingSet(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100284 for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {
285 int rc = prctl(PR_CAPBSET_DROP, i, 0, 0, 0);
286 if (rc == -1) {
287 if (errno == EINVAL) {
288 ALOGE("prctl(PR_CAPBSET_DROP) failed with EINVAL. Please verify "
289 "your kernel is compiled with file capabilities support");
290 } else {
Andreas Gamped5758f62018-03-12 12:08:55 -0700291 *error_msg = CREATE_ERROR("prctl(PR_CAPBSET_DROP, %d) failed: %s", i, strerror(errno));
292 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100293 }
294 }
295 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700296 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100297}
298
Andreas Gamped5758f62018-03-12 12:08:55 -0700299static bool SetInheritable(uint64_t inheritable, std::string* error_msg) {
Josh Gao45dab782017-02-01 14:56:09 -0800300 __user_cap_header_struct capheader;
301 memset(&capheader, 0, sizeof(capheader));
302 capheader.version = _LINUX_CAPABILITY_VERSION_3;
303 capheader.pid = 0;
304
305 __user_cap_data_struct capdata[2];
306 if (capget(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700307 *error_msg = CREATE_ERROR("capget failed: %s", strerror(errno));
308 return false;
Josh Gao45dab782017-02-01 14:56:09 -0800309 }
310
311 capdata[0].inheritable = inheritable;
312 capdata[1].inheritable = inheritable >> 32;
313
314 if (capset(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700315 *error_msg = CREATE_ERROR("capset(inh=%" PRIx64 ") failed: %s", inheritable, strerror(errno));
316 return false;
Josh Gao45dab782017-02-01 14:56:09 -0800317 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700318
319 return true;
Josh Gao45dab782017-02-01 14:56:09 -0800320}
321
Andreas Gamped5758f62018-03-12 12:08:55 -0700322static bool SetCapabilities(uint64_t permitted, uint64_t effective, uint64_t inheritable,
323 std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100324 __user_cap_header_struct capheader;
325 memset(&capheader, 0, sizeof(capheader));
326 capheader.version = _LINUX_CAPABILITY_VERSION_3;
327 capheader.pid = 0;
328
329 __user_cap_data_struct capdata[2];
330 memset(&capdata, 0, sizeof(capdata));
331 capdata[0].effective = effective;
332 capdata[1].effective = effective >> 32;
333 capdata[0].permitted = permitted;
334 capdata[1].permitted = permitted >> 32;
Josh Gao45dab782017-02-01 14:56:09 -0800335 capdata[0].inheritable = inheritable;
336 capdata[1].inheritable = inheritable >> 32;
Narayan Kamath973b4662014-03-31 13:41:26 +0100337
338 if (capset(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700339 *error_msg = CREATE_ERROR("capset(perm=%" PRIx64 ", eff=%" PRIx64 ", inh=%" PRIx64 ") "
340 "failed: %s", permitted, effective, inheritable, strerror(errno));
341 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100342 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700343 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100344}
345
Andreas Gamped5758f62018-03-12 12:08:55 -0700346static bool SetSchedulerPolicy(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100347 errno = -set_sched_policy(0, SP_DEFAULT);
348 if (errno != 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700349 *error_msg = CREATE_ERROR("set_sched_policy(0, SP_DEFAULT) failed: %s", strerror(errno));
350 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100351 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700352 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100353}
354
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700355static int UnmountTree(const char* path) {
356 size_t path_len = strlen(path);
357
358 FILE* fp = setmntent("/proc/mounts", "r");
359 if (fp == NULL) {
360 ALOGE("Error opening /proc/mounts: %s", strerror(errno));
361 return -errno;
362 }
363
364 // Some volumes can be stacked on each other, so force unmount in
365 // reverse order to give us the best chance of success.
366 std::list<std::string> toUnmount;
367 mntent* mentry;
368 while ((mentry = getmntent(fp)) != NULL) {
369 if (strncmp(mentry->mnt_dir, path, path_len) == 0) {
370 toUnmount.push_front(std::string(mentry->mnt_dir));
371 }
372 }
373 endmntent(fp);
374
375 for (auto path : toUnmount) {
376 if (umount2(path.c_str(), MNT_DETACH)) {
377 ALOGW("Failed to unmount %s: %s", path.c_str(), strerror(errno));
378 }
379 }
380 return 0;
381}
382
Narayan Kamath973b4662014-03-31 13:41:26 +0100383// Create a private mount namespace and bind mount appropriate emulated
384// storage for the given user.
Jeff Sharkey9527b222015-06-24 15:24:48 -0700385static bool MountEmulatedStorage(uid_t uid, jint mount_mode,
Andreas Gamped5758f62018-03-12 12:08:55 -0700386 bool force_mount_namespace, std::string* error_msg) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700387 // See storage config details at http://source.android.com/tech/storage/
388
Jeff Sharkey9527b222015-06-24 15:24:48 -0700389 String8 storageSource;
390 if (mount_mode == MOUNT_EXTERNAL_DEFAULT) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700391 storageSource = "/mnt/runtime/default";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700392 } else if (mount_mode == MOUNT_EXTERNAL_READ) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700393 storageSource = "/mnt/runtime/read";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700394 } else if (mount_mode == MOUNT_EXTERNAL_WRITE) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700395 storageSource = "/mnt/runtime/write";
Robert Sesek06af1c02016-11-10 21:50:04 -0500396 } else if (!force_mount_namespace) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700397 // Sane default of no storage visible
398 return true;
399 }
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400400
401 // Create a second private mount namespace for our process
402 if (unshare(CLONE_NEWNS) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700403 *error_msg = CREATE_ERROR("Failed to unshare(): %s", strerror(errno));
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400404 return false;
405 }
406
Robert Sesek06f39302017-03-20 17:30:05 -0400407 // Handle force_mount_namespace with MOUNT_EXTERNAL_NONE.
408 if (mount_mode == MOUNT_EXTERNAL_NONE) {
409 return true;
410 }
411
Jeff Sharkey9527b222015-06-24 15:24:48 -0700412 if (TEMP_FAILURE_RETRY(mount(storageSource.string(), "/storage",
413 NULL, MS_BIND | MS_REC | MS_SLAVE, NULL)) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700414 *error_msg = CREATE_ERROR("Failed to mount %s to /storage: %s",
415 storageSource.string(),
416 strerror(errno));
Jeff Sharkey9527b222015-06-24 15:24:48 -0700417 return false;
418 }
419
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700420 // Mount user-specific symlink helper into place
Jeff Sharkey9527b222015-06-24 15:24:48 -0700421 userid_t user_id = multiuser_get_user_id(uid);
422 const String8 userSource(String8::format("/mnt/user/%d", user_id));
423 if (fs_prepare_dir(userSource.string(), 0751, 0, 0) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700424 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", userSource.string());
Jeff Sharkey9527b222015-06-24 15:24:48 -0700425 return false;
426 }
427 if (TEMP_FAILURE_RETRY(mount(userSource.string(), "/storage/self",
428 NULL, MS_BIND, NULL)) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700429 *error_msg = CREATE_ERROR("Failed to mount %s to /storage/self: %s",
430 userSource.string(),
431 strerror(errno));
Jeff Sharkey9527b222015-06-24 15:24:48 -0700432 return false;
433 }
434
Narayan Kamath973b4662014-03-31 13:41:26 +0100435 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100436}
437
Narayan Kamath973b4662014-03-31 13:41:26 +0100438static bool NeedsNoRandomizeWorkaround() {
439#if !defined(__arm__)
440 return false;
441#else
442 int major;
443 int minor;
444 struct utsname uts;
445 if (uname(&uts) == -1) {
446 return false;
447 }
448
449 if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
450 return false;
451 }
452
453 // Kernels before 3.4.* need the workaround.
454 return (major < 3) || ((major == 3) && (minor < 4));
455#endif
456}
Narayan Kamath973b4662014-03-31 13:41:26 +0100457
458// Utility to close down the Zygote socket file descriptors while
459// the child is still running as root with Zygote's privileges. Each
460// descriptor (if any) is closed via dup2(), replacing it with a valid
461// (open) descriptor to /dev/null.
462
Andreas Gamped5758f62018-03-12 12:08:55 -0700463static bool DetachDescriptors(JNIEnv* env, jintArray fdsToClose, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100464 if (!fdsToClose) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700465 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100466 }
467 jsize count = env->GetArrayLength(fdsToClose);
Mykola Kondratenko1ca062f2015-07-31 17:22:26 +0200468 ScopedIntArrayRO ar(env, fdsToClose);
469 if (ar.get() == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700470 *error_msg = "Bad fd array";
471 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100472 }
473 jsize i;
474 int devnull;
475 for (i = 0; i < count; i++) {
476 devnull = open("/dev/null", O_RDWR);
477 if (devnull < 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700478 *error_msg = std::string("Failed to open /dev/null: ").append(strerror(errno));
479 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100480 }
Elliott Hughes960e8312014-09-30 08:49:01 -0700481 ALOGV("Switching descriptor %d to /dev/null: %s", ar[i], strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100482 if (dup2(devnull, ar[i]) < 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700483 *error_msg = StringPrintf("Failed dup2() on descriptor %d: %s", ar[i], strerror(errno));
484 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100485 }
486 close(devnull);
487 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700488 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100489}
490
491void SetThreadName(const char* thread_name) {
492 bool hasAt = false;
493 bool hasDot = false;
494 const char* s = thread_name;
495 while (*s) {
496 if (*s == '.') {
497 hasDot = true;
498 } else if (*s == '@') {
499 hasAt = true;
500 }
501 s++;
502 }
503 const int len = s - thread_name;
504 if (len < 15 || hasAt || !hasDot) {
505 s = thread_name;
506 } else {
507 s = thread_name + len - 15;
508 }
509 // pthread_setname_np fails rather than truncating long strings.
510 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
511 strlcpy(buf, s, sizeof(buf)-1);
512 errno = pthread_setname_np(pthread_self(), buf);
513 if (errno != 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700514 ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100515 }
Andreas Gampe041483a2018-03-05 13:00:42 -0800516 // Update base::logging default tag.
517 android::base::SetDefaultTag(buf);
Narayan Kamath973b4662014-03-31 13:41:26 +0100518}
519
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100520// The list of open zygote file descriptors.
521static FileDescriptorTable* gOpenFdTable = NULL;
522
Andreas Gamped5758f62018-03-12 12:08:55 -0700523static bool FillFileDescriptorVector(JNIEnv* env,
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800524 jintArray java_fds,
Andreas Gamped5758f62018-03-12 12:08:55 -0700525 std::vector<int>* fds,
526 std::string* error_msg) {
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800527 CHECK(fds != nullptr);
528 if (java_fds != nullptr) {
529 ScopedIntArrayRO ar(env, java_fds);
530 if (ar.get() == nullptr) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700531 *error_msg = "Bad fd array";
532 return false;
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800533 }
534 fds->reserve(ar.size());
535 for (size_t i = 0; i < ar.size(); ++i) {
536 fds->push_back(ar[i]);
537 }
538 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700539 return true;
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800540}
541
David Sehrde8d0bd2018-06-22 10:45:36 -0700542// Utility routine to specialize a zygote child process.
543static void SpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids,
544 jint runtime_flags, jobjectArray javaRlimits,
545 jlong permittedCapabilities, jlong effectiveCapabilities,
546 jint mount_external, jstring java_se_info, jstring java_se_name,
547 bool is_system_server, bool is_child_zygote, jstring instructionSet,
548 jstring dataDir) {
549 std::string error_msg;
550
551 auto fail_fn = [env, java_se_name, is_system_server](const std::string& msg)
552 __attribute__ ((noreturn)) {
553 const char* se_name_c_str = nullptr;
554 std::unique_ptr<ScopedUtfChars> se_name;
555 if (java_se_name != nullptr) {
556 se_name.reset(new ScopedUtfChars(env, java_se_name));
557 se_name_c_str = se_name->c_str();
558 }
559 if (se_name_c_str == nullptr && is_system_server) {
560 se_name_c_str = "system_server";
561 }
562 const std::string& error_msg = (se_name_c_str == nullptr)
563 ? msg
564 : StringPrintf("(%s) %s", se_name_c_str, msg.c_str());
565 env->FatalError(error_msg.c_str());
566 __builtin_unreachable();
567 };
568
569 // Keep capabilities across UID change, unless we're staying root.
570 if (uid != 0) {
571 if (!EnableKeepCapabilities(&error_msg)) {
572 fail_fn(error_msg);
573 }
574 }
575
576 if (!SetInheritable(permittedCapabilities, &error_msg)) {
577 fail_fn(error_msg);
578 }
579 if (!DropCapabilitiesBoundingSet(&error_msg)) {
580 fail_fn(error_msg);
581 }
582
583 bool use_native_bridge = !is_system_server && (instructionSet != NULL)
584 && android::NativeBridgeAvailable();
585 if (use_native_bridge) {
586 ScopedUtfChars isa_string(env, instructionSet);
587 use_native_bridge = android::NeedsNativeBridge(isa_string.c_str());
588 }
589 if (use_native_bridge && dataDir == NULL) {
590 // dataDir should never be null if we need to use a native bridge.
591 // In general, dataDir will never be null for normal applications. It can only happen in
592 // special cases (for isolated processes which are not associated with any app). These are
593 // launched by the framework and should not be emulated anyway.
594 use_native_bridge = false;
595 ALOGW("Native bridge will not be used because dataDir == NULL.");
596 }
597
598 if (!MountEmulatedStorage(uid, mount_external, use_native_bridge, &error_msg)) {
599 ALOGW("Failed to mount emulated storage: %s (%s)", error_msg.c_str(), strerror(errno));
600 if (errno == ENOTCONN || errno == EROFS) {
601 // When device is actively encrypting, we get ENOTCONN here
602 // since FUSE was mounted before the framework restarted.
603 // When encrypted device is booting, we get EROFS since
604 // FUSE hasn't been created yet by init.
605 // In either case, continue without external storage.
606 } else {
607 fail_fn(error_msg);
608 }
609 }
610
611 // If this zygote isn't root, it won't be able to create a process group,
612 // since the directory is owned by root.
613 if (!is_system_server && getuid() == 0) {
614 int rc = createProcessGroup(uid, getpid());
615 if (rc != 0) {
616 if (rc == -EROFS) {
617 ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
618 } else {
619 ALOGE("createProcessGroup(%d, %d) failed: %s", uid, 0/*pid*/, strerror(-rc));
620 }
621 }
622 }
623
624 if (!SetGids(env, javaGids, &error_msg)) {
625 fail_fn(error_msg);
626 }
627
628 if (!SetRLimits(env, javaRlimits, &error_msg)) {
629 fail_fn(error_msg);
630 }
631
632 if (use_native_bridge) {
633 ScopedUtfChars isa_string(env, instructionSet);
634 ScopedUtfChars data_dir(env, dataDir);
635 android::PreInitializeNativeBridge(data_dir.c_str(), isa_string.c_str());
636 }
637
638 int rc = setresgid(gid, gid, gid);
639 if (rc == -1) {
640 fail_fn(CREATE_ERROR("setresgid(%d) failed: %s", gid, strerror(errno)));
641 }
642
643 // Must be called when the new process still has CAP_SYS_ADMIN, in this case, before changing
644 // uid from 0, which clears capabilities. The other alternative is to call
645 // prctl(PR_SET_NO_NEW_PRIVS, 1) afterward, but that breaks SELinux domain transition (see
646 // b/71859146). As the result, privileged syscalls used below still need to be accessible in
647 // app process.
648 SetUpSeccompFilter(uid);
649
650 rc = setresuid(uid, uid, uid);
651 if (rc == -1) {
652 fail_fn(CREATE_ERROR("setresuid(%d) failed: %s", uid, strerror(errno)));
653 }
654
655 // The "dumpable" flag of a process, which controls core dump generation, is
656 // overwritten by the value in /proc/sys/fs/suid_dumpable when the effective
657 // user or group ID changes. See proc(5) for possible values. In most cases,
658 // the value is 0, so core dumps are disabled for zygote children. However,
659 // when running in a Chrome OS container, the value is already set to 2,
660 // which allows the external crash reporter to collect all core dumps. Since
661 // only system crashes are interested, core dump is disabled for app
662 // processes. This also ensures compliance with CTS.
663 int dumpable = prctl(PR_GET_DUMPABLE);
664 if (dumpable == -1) {
665 ALOGE("prctl(PR_GET_DUMPABLE) failed: %s", strerror(errno));
666 RuntimeAbort(env, __LINE__, "prctl(PR_GET_DUMPABLE) failed");
667 }
668 if (dumpable == 2 && uid >= AID_APP) {
669 if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) == -1) {
670 ALOGE("prctl(PR_SET_DUMPABLE, 0) failed: %s", strerror(errno));
671 RuntimeAbort(env, __LINE__, "prctl(PR_SET_DUMPABLE, 0) failed");
672 }
673 }
674
675 if (NeedsNoRandomizeWorkaround()) {
676 // Work around ARM kernel ASLR lossage (http://b/5817320).
677 int old_personality = personality(0xffffffff);
678 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
679 if (new_personality == -1) {
680 ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
681 }
682 }
683
684 if (!SetCapabilities(permittedCapabilities, effectiveCapabilities, permittedCapabilities,
685 &error_msg)) {
686 fail_fn(error_msg);
687 }
688
689 if (!SetSchedulerPolicy(&error_msg)) {
690 fail_fn(error_msg);
691 }
692
693 const char* se_info_c_str = NULL;
694 ScopedUtfChars* se_info = NULL;
695 if (java_se_info != NULL) {
696 se_info = new ScopedUtfChars(env, java_se_info);
697 se_info_c_str = se_info->c_str();
698 if (se_info_c_str == NULL) {
699 fail_fn("se_info_c_str == NULL");
700 }
701 }
702 const char* se_name_c_str = NULL;
703 ScopedUtfChars* se_name = NULL;
704 if (java_se_name != NULL) {
705 se_name = new ScopedUtfChars(env, java_se_name);
706 se_name_c_str = se_name->c_str();
707 if (se_name_c_str == NULL) {
708 fail_fn("se_name_c_str == NULL");
709 }
710 }
711 rc = selinux_android_setcontext(uid, is_system_server, se_info_c_str, se_name_c_str);
712 if (rc == -1) {
713 fail_fn(CREATE_ERROR("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed", uid,
714 is_system_server, se_info_c_str, se_name_c_str));
715 }
716
717 // Make it easier to debug audit logs by setting the main thread's name to the
718 // nice name rather than "app_process".
719 if (se_name_c_str == NULL && is_system_server) {
720 se_name_c_str = "system_server";
721 }
722 if (se_name_c_str != NULL) {
723 SetThreadName(se_name_c_str);
724 }
725
726 delete se_info;
727 delete se_name;
728
729 // Unset the SIGCHLD handler, but keep ignoring SIGHUP (rationale in SetSignalHandlers).
730 UnsetChldSignalHandler();
731
Orion Hodson46724e72018-10-19 13:05:33 +0100732 if (is_system_server) {
733 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkSystemServerHooks);
734 if (env->ExceptionCheck()) {
735 fail_fn("Error calling post fork system server hooks.");
736 }
737 // TODO(oth): Remove hardcoded label here (b/117874058).
738 static const char* kSystemServerLabel = "u:r:system_server:s0";
739 if (selinux_android_setcon(kSystemServerLabel) != 0) {
740 fail_fn(CREATE_ERROR("selinux_android_setcon(%s)", kSystemServerLabel));
741 }
742 }
743
David Sehrde8d0bd2018-06-22 10:45:36 -0700744 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, runtime_flags,
745 is_system_server, is_child_zygote, instructionSet);
746 if (env->ExceptionCheck()) {
747 fail_fn("Error calling post fork hooks.");
748 }
749}
750
Narayan Kamath973b4662014-03-31 13:41:26 +0100751// Utility routine to fork zygote and specialize the child process.
David Sehrde8d0bd2018-06-22 10:45:36 -0700752static pid_t ForkCommon(JNIEnv* env, jstring java_se_name, bool is_system_server,
753 jintArray fdsToClose, jintArray fdsToIgnore) {
yuanhao435e84b2018-01-15 15:37:02 +0800754 SetSignalHandlers();
Narayan Kamath973b4662014-03-31 13:41:26 +0100755
David Sehrde8d0bd2018-06-22 10:45:36 -0700756 // Block SIGCHLD prior to fork.
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000757 sigset_t sigchld;
758 sigemptyset(&sigchld);
759 sigaddset(&sigchld, SIGCHLD);
760
Andreas Gampe5f35c4e2018-03-12 12:17:25 -0700761 auto fail_fn = [env, java_se_name, is_system_server](const std::string& msg)
762 __attribute__ ((noreturn)) {
763 const char* se_name_c_str = nullptr;
764 std::unique_ptr<ScopedUtfChars> se_name;
765 if (java_se_name != nullptr) {
766 se_name.reset(new ScopedUtfChars(env, java_se_name));
767 se_name_c_str = se_name->c_str();
768 }
769 if (se_name_c_str == nullptr && is_system_server) {
770 se_name_c_str = "system_server";
771 }
772 const std::string& error_msg = (se_name_c_str == nullptr)
773 ? msg
774 : StringPrintf("(%s) %s", se_name_c_str, msg.c_str());
775 env->FatalError(error_msg.c_str());
Andreas Gamped5758f62018-03-12 12:08:55 -0700776 __builtin_unreachable();
777 };
778
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000779 // Temporarily block SIGCHLD during forks. The SIGCHLD handler might
780 // log, which would result in the logging FDs we close being reopened.
781 // This would cause failures because the FDs are not whitelisted.
782 //
783 // Note that the zygote process is single threaded at this point.
784 if (sigprocmask(SIG_BLOCK, &sigchld, nullptr) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700785 fail_fn(CREATE_ERROR("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno)));
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000786 }
787
Narayan Kamath3764a262016-08-30 15:36:19 +0100788 // Close any logging related FDs before we start evaluating the list of
789 // file descriptors.
790 __android_log_close();
791
Andreas Gamped5758f62018-03-12 12:08:55 -0700792 std::string error_msg;
793
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100794 // If this is the first fork for this zygote, create the open FD table.
795 // If it isn't, we just need to check whether the list of open files has
796 // changed (and it shouldn't in the normal case).
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800797 std::vector<int> fds_to_ignore;
Andreas Gamped5758f62018-03-12 12:08:55 -0700798 if (!FillFileDescriptorVector(env, fdsToIgnore, &fds_to_ignore, &error_msg)) {
799 fail_fn(error_msg);
800 }
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100801 if (gOpenFdTable == NULL) {
Andreas Gampec362a442018-03-12 14:53:34 -0700802 gOpenFdTable = FileDescriptorTable::Create(fds_to_ignore, &error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100803 if (gOpenFdTable == NULL) {
Andreas Gampec362a442018-03-12 14:53:34 -0700804 fail_fn(error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100805 }
Andreas Gampec362a442018-03-12 14:53:34 -0700806 } else if (!gOpenFdTable->Restat(fds_to_ignore, &error_msg)) {
807 fail_fn(error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100808 }
809
Josh Gaod7951102018-06-26 16:05:12 -0700810 android_fdsan_error_level fdsan_error_level = android_fdsan_get_error_level();
811
Narayan Kamath973b4662014-03-31 13:41:26 +0100812 pid_t pid = fork();
813
814 if (pid == 0) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700815 // The child process.
Christopher Ferris76de39e2017-06-20 16:13:40 -0700816 PreApplicationInit();
Christopher Ferrisab16dd12017-05-15 16:50:29 -0700817
Narayan Kamath973b4662014-03-31 13:41:26 +0100818 // Clean up any descriptors which must be closed immediately
Andreas Gamped5758f62018-03-12 12:08:55 -0700819 if (!DetachDescriptors(env, fdsToClose, &error_msg)) {
820 fail_fn(error_msg);
821 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100822
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100823 // Re-open all remaining open file descriptors so that they aren't shared
824 // with the zygote across a fork.
Andreas Gampec362a442018-03-12 14:53:34 -0700825 if (!gOpenFdTable->ReopenOrDetach(&error_msg)) {
826 fail_fn(error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100827 }
Josh Gaod7951102018-06-26 16:05:12 -0700828
829 // Turn fdsan back on.
830 android_fdsan_set_error_level(fdsan_error_level);
David Sehrde8d0bd2018-06-22 10:45:36 -0700831 }
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100832
David Sehrde8d0bd2018-06-22 10:45:36 -0700833 // We blocked SIGCHLD prior to a fork, we unblock it here.
834 if (sigprocmask(SIG_UNBLOCK, &sigchld, nullptr) == -1) {
835 fail_fn(CREATE_ERROR("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100836 }
837 return pid;
838}
Luis Hector Chavez72042c92017-07-12 10:03:30 -0700839
840static uint64_t GetEffectiveCapabilityMask(JNIEnv* env) {
841 __user_cap_header_struct capheader;
842 memset(&capheader, 0, sizeof(capheader));
843 capheader.version = _LINUX_CAPABILITY_VERSION_3;
844 capheader.pid = 0;
845
846 __user_cap_data_struct capdata[2];
847 if (capget(&capheader, &capdata[0]) == -1) {
848 ALOGE("capget failed: %s", strerror(errno));
849 RuntimeAbort(env, __LINE__, "capget failed");
850 }
851
852 return capdata[0].effective |
853 (static_cast<uint64_t>(capdata[1].effective) << 32);
854}
Narayan Kamath973b4662014-03-31 13:41:26 +0100855} // anonymous namespace
856
857namespace android {
858
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800859static void com_android_internal_os_Zygote_nativeSecurityInit(JNIEnv*, jclass) {
860 // security_getenforce is not allowed on app process. Initialize and cache the value before
861 // zygote forks.
862 g_is_security_enforced = security_getenforce();
863}
864
Christopher Ferris76de39e2017-06-20 16:13:40 -0700865static void com_android_internal_os_Zygote_nativePreApplicationInit(JNIEnv*, jclass) {
866 PreApplicationInit();
867}
868
Narayan Kamath973b4662014-03-31 13:41:26 +0100869static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
870 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100871 jint runtime_flags, jobjectArray rlimits,
Narayan Kamath973b4662014-03-31 13:41:26 +0100872 jint mount_external, jstring se_info, jstring se_name,
Robert Sesekd0a190df2018-02-12 18:46:01 -0500873 jintArray fdsToClose, jintArray fdsToIgnore, jboolean is_child_zygote,
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800874 jstring instructionSet, jstring appDataDir) {
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -0700875 jlong capabilities = 0;
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800876
877 // Grant CAP_WAKE_ALARM to the Bluetooth process.
Erik Kline0f6ae2e2016-02-22 15:42:07 +0900878 // Additionally, allow bluetooth to open packet sockets so it can start the DHCP client.
Philip Cuadra0fabba32017-04-26 13:49:37 -0700879 // Grant CAP_SYS_NICE to allow Bluetooth to set RT priority for
880 // audio-related threads.
Erik Kline0f6ae2e2016-02-22 15:42:07 +0900881 // TODO: consider making such functionality an RPC to netd.
Pavlin Radoslavov2956bee2016-01-27 16:22:15 -0800882 if (multiuser_get_app_id(uid) == AID_BLUETOOTH) {
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800883 capabilities |= (1LL << CAP_WAKE_ALARM);
Erik Kline0f6ae2e2016-02-22 15:42:07 +0900884 capabilities |= (1LL << CAP_NET_RAW);
885 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
Philip Cuadra0fabba32017-04-26 13:49:37 -0700886 capabilities |= (1LL << CAP_SYS_NICE);
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800887 }
Sharvil Nanavatibabe8152015-08-31 23:25:06 -0700888
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800889 // Grant CAP_BLOCK_SUSPEND to processes that belong to GID "wakelock"
890 bool gid_wakelock_found = false;
891 if (gid == AID_WAKELOCK) {
892 gid_wakelock_found = true;
893 } else if (gids != NULL) {
894 jsize gids_num = env->GetArrayLength(gids);
895 ScopedIntArrayRO ar(env, gids);
896 if (ar.get() == NULL) {
897 RuntimeAbort(env, __LINE__, "Bad gids array");
898 }
899 for (int i = 0; i < gids_num; i++) {
900 if (ar[i] == AID_WAKELOCK) {
901 gid_wakelock_found = true;
902 break;
Sharvil Nanavatibabe8152015-08-31 23:25:06 -0700903 }
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800904 }
905 }
906 if (gid_wakelock_found) {
907 capabilities |= (1LL << CAP_BLOCK_SUSPEND);
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -0700908 }
909
Robert Sesekd0a190df2018-02-12 18:46:01 -0500910 // If forking a child zygote process, that zygote will need to be able to change
911 // the UID and GID of processes it forks, as well as drop those capabilities.
912 if (is_child_zygote) {
913 capabilities |= (1LL << CAP_SETUID);
914 capabilities |= (1LL << CAP_SETGID);
915 capabilities |= (1LL << CAP_SETPCAP);
916 }
917
Luis Hector Chavez72042c92017-07-12 10:03:30 -0700918 // Containers run without some capabilities, so drop any caps that are not
919 // available.
920 capabilities &= GetEffectiveCapabilityMask(env);
921
David Sehrde8d0bd2018-06-22 10:45:36 -0700922 pid_t pid = ForkCommon(env, se_name, false, fdsToClose, fdsToIgnore);
923 if (pid == 0) {
924 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
925 capabilities, capabilities,
926 mount_external, se_info, se_name, false,
927 is_child_zygote == JNI_TRUE, instructionSet, appDataDir);
928 }
929 return pid;
Narayan Kamath973b4662014-03-31 13:41:26 +0100930}
931
932static jint com_android_internal_os_Zygote_nativeForkSystemServer(
933 JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100934 jint runtime_flags, jobjectArray rlimits, jlong permittedCapabilities,
Narayan Kamath973b4662014-03-31 13:41:26 +0100935 jlong effectiveCapabilities) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700936 pid_t pid = ForkCommon(env, NULL, true, NULL, NULL);
937 if (pid == 0) {
938 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
939 permittedCapabilities, effectiveCapabilities,
940 MOUNT_EXTERNAL_DEFAULT, NULL, NULL, true,
941 false, NULL, NULL);
942 } else if (pid > 0) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100943 // The zygote process checks whether the child process has died or not.
944 ALOGI("System server process %d has been created", pid);
945 gSystemServerPid = pid;
946 // There is a slight window that the system server process has crashed
947 // but it went unnoticed because we haven't published its pid yet. So
948 // we recheck here just to make sure that all is well.
949 int status;
950 if (waitpid(pid, &status, WNOHANG) == pid) {
951 ALOGE("System server process %d has died. Restarting Zygote!", pid);
Andreas Gampeb053cce2015-11-17 16:38:59 -0800952 RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
Narayan Kamath973b4662014-03-31 13:41:26 +0100953 }
Carmen Jacksondd401252017-02-23 15:21:10 -0800954
Minchan Kim696873e2018-06-27 11:32:40 +0900955 bool low_ram_device = GetBoolProperty("ro.config.low_ram", false);
956 bool per_app_memcg = GetBoolProperty("ro.config.per_app_memcg", low_ram_device);
957 if (per_app_memcg) {
958 // Assign system_server to the correct memory cgroup.
959 // Not all devices mount /dev/memcg so check for the file first
960 // to avoid unnecessarily printing errors and denials in the logs.
961 if (!access("/dev/memcg/system/tasks", F_OK) &&
Jeff Vander Stoep6bdc3a22017-11-22 23:09:23 -0800962 !WriteStringToFile(StringPrintf("%d", pid), "/dev/memcg/system/tasks")) {
Minchan Kim696873e2018-06-27 11:32:40 +0900963 ALOGE("couldn't write %d to /dev/memcg/system/tasks", pid);
964 }
Carmen Jacksondd401252017-02-23 15:21:10 -0800965 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100966 }
967 return pid;
968}
969
Robert Sesek54e387d2016-12-02 17:27:50 -0500970static void com_android_internal_os_Zygote_nativeAllowFileAcrossFork(
971 JNIEnv* env, jclass, jstring path) {
972 ScopedUtfChars path_native(env, path);
973 const char* path_cstr = path_native.c_str();
974 if (!path_cstr) {
975 RuntimeAbort(env, __LINE__, "path_cstr == NULL");
976 }
977 FileDescriptorWhitelist::Get()->Allow(path_cstr);
978}
979
doheon1.lee885b7422016-01-20 13:07:27 +0900980static void com_android_internal_os_Zygote_nativeUnmountStorageOnInit(JNIEnv* env, jclass) {
981 // Zygote process unmount root storage space initially before every child processes are forked.
982 // Every forked child processes (include SystemServer) only mount their own root storage space
Robert Seseke4f8d692016-09-13 19:13:01 -0400983 // and no need unmount storage operation in MountEmulatedStorage method.
984 // Zygote process does not utilize root storage spaces and unshares its mount namespace below.
985
986 // See storage config details at http://source.android.com/tech/storage/
987 // Create private mount namespace shared by all children
988 if (unshare(CLONE_NEWNS) == -1) {
989 RuntimeAbort(env, __LINE__, "Failed to unshare()");
990 return;
991 }
992
993 // Mark rootfs as being a slave so that changes from default
994 // namespace only flow into our children.
995 if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
996 RuntimeAbort(env, __LINE__, "Failed to mount() rootfs as MS_SLAVE");
997 return;
998 }
999
1000 // Create a staging tmpfs that is shared by our children; they will
1001 // bind mount storage into their respective private namespaces, which
1002 // are isolated from each other.
1003 const char* target_base = getenv("EMULATED_STORAGE_TARGET");
1004 if (target_base != nullptr) {
1005#define STRINGIFY_UID(x) __STRING(x)
1006 if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
1007 "uid=0,gid=" STRINGIFY_UID(AID_SDCARD_R) ",mode=0751") == -1) {
1008 ALOGE("Failed to mount tmpfs to %s", target_base);
1009 RuntimeAbort(env, __LINE__, "Failed to mount tmpfs");
1010 return;
1011 }
1012#undef STRINGIFY_UID
1013 }
doheon1.lee885b7422016-01-20 13:07:27 +09001014
1015 UnmountTree("/storage");
doheon1.lee885b7422016-01-20 13:07:27 +09001016}
1017
Daniel Micay76f6a862015-09-19 17:31:01 -04001018static const JNINativeMethod gMethods[] = {
Victor Hsiehc8176ef2018-01-08 12:43:00 -08001019 { "nativeSecurityInit", "()V",
1020 (void *) com_android_internal_os_Zygote_nativeSecurityInit },
Andreas Gampeaec67dc2014-09-02 21:23:06 -07001021 { "nativeForkAndSpecialize",
Robert Sesekd0a190df2018-02-12 18:46:01 -05001022 "(II[II[[IILjava/lang/String;Ljava/lang/String;[I[IZLjava/lang/String;Ljava/lang/String;)I",
Narayan Kamath973b4662014-03-31 13:41:26 +01001023 (void *) com_android_internal_os_Zygote_nativeForkAndSpecialize },
1024 { "nativeForkSystemServer", "(II[II[[IJJ)I",
doheon1.lee885b7422016-01-20 13:07:27 +09001025 (void *) com_android_internal_os_Zygote_nativeForkSystemServer },
Robert Sesek54e387d2016-12-02 17:27:50 -05001026 { "nativeAllowFileAcrossFork", "(Ljava/lang/String;)V",
1027 (void *) com_android_internal_os_Zygote_nativeAllowFileAcrossFork },
doheon1.lee885b7422016-01-20 13:07:27 +09001028 { "nativeUnmountStorageOnInit", "()V",
Christopher Ferris76de39e2017-06-20 16:13:40 -07001029 (void *) com_android_internal_os_Zygote_nativeUnmountStorageOnInit },
1030 { "nativePreApplicationInit", "()V",
1031 (void *) com_android_internal_os_Zygote_nativePreApplicationInit }
Narayan Kamath973b4662014-03-31 13:41:26 +01001032};
1033
1034int register_com_android_internal_os_Zygote(JNIEnv* env) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001035 gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName));
Orion Hodson46724e72018-10-19 13:05:33 +01001036 gCallPostForkSystemServerHooks = GetStaticMethodIDOrDie(env, gZygoteClass,
1037 "callPostForkSystemServerHooks",
1038 "()V");
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001039 gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
Robert Sesekd0a190df2018-02-12 18:46:01 -05001040 "(IZZLjava/lang/String;)V");
Narayan Kamath973b4662014-03-31 13:41:26 +01001041
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001042 return RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
Narayan Kamath973b4662014-03-31 13:41:26 +01001043}
1044} // namespace android