blob: 9b9f704e1f692eeac2aa7d15f94e22da3872b1c1 [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"
Carmen Jacksondd401252017-02-23 15:21:10 -080049#include <android-base/file.h>
50#include <android-base/stringprintf.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070051#include <cutils/fs.h>
52#include <cutils/multiuser.h>
53#include <cutils/sched_policy.h>
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -070054#include <private/android_filesystem_config.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070055#include <utils/String8.h>
56#include <selinux/android.h>
Victor Hsiehc8176ef2018-01-08 12:43:00 -080057#include <seccomp_policy.h>
Colin Cross0161bbc2014-06-03 13:26:58 -070058#include <processgroup/processgroup.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070059
Andreas Gampeed6b9df2014-11-20 22:02:20 -080060#include "core_jni_helpers.h"
Steven Moreland2279b252017-07-19 09:50:45 -070061#include <nativehelper/JNIHelp.h>
62#include <nativehelper/ScopedLocalRef.h>
63#include <nativehelper/ScopedPrimitiveArray.h>
64#include <nativehelper/ScopedUtfChars.h>
Robert Sesek8225b7c2016-12-16 14:02:31 -050065#include "fd_utils.h"
Narayan Kamath973b4662014-03-31 13:41:26 +010066
jgu212eacd062014-09-10 06:55:07 -040067#include "nativebridge/native_bridge.h"
68
Narayan Kamath973b4662014-03-31 13:41:26 +010069namespace {
70
71using android::String8;
Carmen Jacksondd401252017-02-23 15:21:10 -080072using android::base::StringPrintf;
73using android::base::WriteStringToFile;
Narayan Kamath973b4662014-03-31 13:41:26 +010074
Andreas Gampeb8aae192018-03-12 12:08:55 -070075#define CREATE_ERROR(...) StringPrintf("%s:%d: ", __FILE__, __LINE__). \
76 append(StringPrintf(__VA_ARGS__))
77
Narayan Kamath973b4662014-03-31 13:41:26 +010078static pid_t gSystemServerPid = 0;
79
80static const char kZygoteClassName[] = "com/android/internal/os/Zygote";
81static jclass gZygoteClass;
82static jmethodID gCallPostForkChildHooks;
83
Victor Hsiehc8176ef2018-01-08 12:43:00 -080084static bool g_is_security_enforced = true;
85
Narayan Kamath973b4662014-03-31 13:41:26 +010086// Must match values in com.android.internal.os.Zygote.
87enum MountExternalKind {
88 MOUNT_EXTERNAL_NONE = 0,
Jeff Sharkey48877892015-03-18 11:27:19 -070089 MOUNT_EXTERNAL_DEFAULT = 1,
Jeff Sharkey9527b222015-06-24 15:24:48 -070090 MOUNT_EXTERNAL_READ = 2,
91 MOUNT_EXTERNAL_WRITE = 3,
Narayan Kamath973b4662014-03-31 13:41:26 +010092};
93
Andreas Gampeb053cce2015-11-17 16:38:59 -080094static void RuntimeAbort(JNIEnv* env, int line, const char* msg) {
95 std::ostringstream oss;
96 oss << __FILE__ << ":" << line << ": " << msg;
97 env->FatalError(oss.str().c_str());
Narayan Kamath973b4662014-03-31 13:41:26 +010098}
99
100// This signal handler is for zygote mode, since the zygote must reap its children
101static void SigChldHandler(int /*signal_number*/) {
102 pid_t pid;
103 int status;
104
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700105 // It's necessary to save and restore the errno during this function.
106 // Since errno is stored per thread, changing it here modifies the errno
107 // on the thread on which this signal handler executes. If a signal occurs
108 // between a call and an errno check, it's possible to get the errno set
109 // here.
110 // See b/23572286 for extra information.
111 int saved_errno = errno;
112
Narayan Kamath973b4662014-03-31 13:41:26 +0100113 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
114 // Log process-death status that we care about. In general it is
115 // not safe to call LOG(...) from a signal handler because of
116 // possible reentrancy. However, we know a priori that the
117 // current implementation of LOG() is safe to call from a SIGCHLD
118 // handler in the zygote process. If the LOG() implementation
119 // changes its locking strategy or its use of syscalls within the
120 // lazy-init critical section, its use here may become unsafe.
121 if (WIFEXITED(status)) {
Josh Gao6d747ca2017-08-02 12:54:05 -0700122 ALOGI("Process %d exited cleanly (%d)", pid, WEXITSTATUS(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100123 } else if (WIFSIGNALED(status)) {
Josh Gao6d747ca2017-08-02 12:54:05 -0700124 ALOGI("Process %d exited due to signal (%d)", pid, WTERMSIG(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100125 if (WCOREDUMP(status)) {
126 ALOGI("Process %d dumped core.", pid);
127 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100128 }
129
130 // If the just-crashed process is the system_server, bring down zygote
131 // so that it is restarted by init and system server will be restarted
132 // from there.
133 if (pid == gSystemServerPid) {
Dan Albert46d84442014-11-18 16:07:51 -0800134 ALOGE("Exit zygote because system server (%d) has terminated", pid);
Narayan Kamath973b4662014-03-31 13:41:26 +0100135 kill(getpid(), SIGKILL);
136 }
137 }
138
Narayan Kamath160992d2014-04-14 14:46:07 +0100139 // Note that we shouldn't consider ECHILD an error because
140 // the secondary zygote might have no children left to wait for.
141 if (pid < 0 && errno != ECHILD) {
142 ALOGW("Zygote SIGCHLD error in waitpid: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100143 }
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700144
145 errno = saved_errno;
Narayan Kamath973b4662014-03-31 13:41:26 +0100146}
147
yuanhao435e84b2018-01-15 15:37:02 +0800148// Configures the SIGCHLD/SIGHUP handlers for the zygote process. This is
149// configured very late, because earlier in the runtime we may fork() and
150// exec() other processes, and we want to waitpid() for those rather than
Narayan Kamath973b4662014-03-31 13:41:26 +0100151// have them be harvested immediately.
152//
yuanhao435e84b2018-01-15 15:37:02 +0800153// Ignore SIGHUP because all processes forked by the zygote are in the same
154// process group as the zygote and we don't want to be notified if we become
155// an orphaned group and have one or more stopped processes. This is not a
156// theoretical concern :
157// - we can become an orphaned group if one of our direct descendants forks
158// and is subsequently killed before its children.
159// - crash_dump routinely STOPs the process it's tracing.
160//
161// See issues b/71965619 and b/25567761 for further details.
162//
Narayan Kamath973b4662014-03-31 13:41:26 +0100163// This ends up being called repeatedly before each fork(), but there's
164// no real harm in that.
yuanhao435e84b2018-01-15 15:37:02 +0800165static void SetSignalHandlers() {
166 struct sigaction sig_chld = {};
167 sig_chld.sa_handler = SigChldHandler;
Narayan Kamath973b4662014-03-31 13:41:26 +0100168
yuanhao435e84b2018-01-15 15:37:02 +0800169 if (sigaction(SIGCHLD, &sig_chld, NULL) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700170 ALOGW("Error setting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100171 }
yuanhao435e84b2018-01-15 15:37:02 +0800172
173 struct sigaction sig_hup = {};
174 sig_hup.sa_handler = SIG_IGN;
175 if (sigaction(SIGHUP, &sig_hup, NULL) < 0) {
176 ALOGW("Error setting SIGHUP handler: %s", strerror(errno));
177 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100178}
179
180// Sets the SIGCHLD handler back to default behavior in zygote children.
yuanhao435e84b2018-01-15 15:37:02 +0800181static void UnsetChldSignalHandler() {
Narayan Kamath973b4662014-03-31 13:41:26 +0100182 struct sigaction sa;
183 memset(&sa, 0, sizeof(sa));
184 sa.sa_handler = SIG_DFL;
185
yuanhao435e84b2018-01-15 15:37:02 +0800186 if (sigaction(SIGCHLD, &sa, NULL) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700187 ALOGW("Error unsetting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100188 }
189}
190
191// Calls POSIX setgroups() using the int[] object as an argument.
192// A NULL argument is tolerated.
Andreas Gampeb8aae192018-03-12 12:08:55 -0700193static bool SetGids(JNIEnv* env, jintArray javaGids, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100194 if (javaGids == NULL) {
Andreas Gampeb8aae192018-03-12 12:08:55 -0700195 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100196 }
197
198 ScopedIntArrayRO gids(env, javaGids);
199 if (gids.get() == NULL) {
Andreas Gampeb8aae192018-03-12 12:08:55 -0700200 *error_msg = CREATE_ERROR("Getting gids int array failed");
201 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100202 }
203 int rc = setgroups(gids.size(), reinterpret_cast<const gid_t*>(&gids[0]));
204 if (rc == -1) {
Andreas Gampeb8aae192018-03-12 12:08:55 -0700205 *error_msg = CREATE_ERROR("setgroups failed: %s, gids.size=%zu", strerror(errno), gids.size());
206 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100207 }
Andreas Gampeb8aae192018-03-12 12:08:55 -0700208
209 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100210}
211
212// Sets the resource limits via setrlimit(2) for the values in the
213// two-dimensional array of integers that's passed in. The second dimension
214// contains a tuple of length 3: (resource, rlim_cur, rlim_max). NULL is
215// treated as an empty array.
Andreas Gampeb8aae192018-03-12 12:08:55 -0700216static bool SetRLimits(JNIEnv* env, jobjectArray javaRlimits, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100217 if (javaRlimits == NULL) {
Andreas Gampeb8aae192018-03-12 12:08:55 -0700218 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100219 }
220
221 rlimit rlim;
222 memset(&rlim, 0, sizeof(rlim));
223
224 for (int i = 0; i < env->GetArrayLength(javaRlimits); ++i) {
225 ScopedLocalRef<jobject> javaRlimitObject(env, env->GetObjectArrayElement(javaRlimits, i));
226 ScopedIntArrayRO javaRlimit(env, reinterpret_cast<jintArray>(javaRlimitObject.get()));
227 if (javaRlimit.size() != 3) {
Andreas Gampeb8aae192018-03-12 12:08:55 -0700228 *error_msg = CREATE_ERROR("rlimits array must have a second dimension of size 3");
229 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100230 }
231
232 rlim.rlim_cur = javaRlimit[1];
233 rlim.rlim_max = javaRlimit[2];
234
235 int rc = setrlimit(javaRlimit[0], &rlim);
236 if (rc == -1) {
Andreas Gampeb8aae192018-03-12 12:08:55 -0700237 *error_msg = CREATE_ERROR("setrlimit(%d, {%ld, %ld}) failed", javaRlimit[0], rlim.rlim_cur,
Dan Albert46d84442014-11-18 16:07:51 -0800238 rlim.rlim_max);
Andreas Gampeb8aae192018-03-12 12:08:55 -0700239 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100240 }
241 }
Andreas Gampeb8aae192018-03-12 12:08:55 -0700242
243 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100244}
245
Narayan Kamath973b4662014-03-31 13:41:26 +0100246// The debug malloc library needs to know whether it's the zygote or a child.
247extern "C" int gMallocLeakZygoteChild;
248
Christopher Ferris76de39e2017-06-20 16:13:40 -0700249static void PreApplicationInit() {
250 // The child process sets this to indicate it's not the zygote.
251 gMallocLeakZygoteChild = 1;
252
253 // Set the jemalloc decay time to 1.
254 mallopt(M_DECAY_TIME, 1);
255}
256
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800257static void SetUpSeccompFilter(uid_t uid) {
258 if (!g_is_security_enforced) {
259 ALOGI("seccomp disabled by setenforce 0");
260 return;
261 }
262
263 // Apply system or app filter based on uid.
Victor Hsiehfa046a12018-03-28 16:26:28 -0700264 if (uid >= AID_APP_START) {
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800265 set_app_seccomp_filter();
266 } else {
267 set_system_seccomp_filter();
268 }
269}
270
Andreas Gampeb8aae192018-03-12 12:08:55 -0700271static bool EnableKeepCapabilities(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100272 int rc = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
273 if (rc == -1) {
Andreas Gampeb8aae192018-03-12 12:08:55 -0700274 *error_msg = CREATE_ERROR("prctl(PR_SET_KEEPCAPS) failed: %s", strerror(errno));
275 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100276 }
Andreas Gampeb8aae192018-03-12 12:08:55 -0700277 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100278}
279
Andreas Gampeb8aae192018-03-12 12:08:55 -0700280static bool DropCapabilitiesBoundingSet(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100281 for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {
282 int rc = prctl(PR_CAPBSET_DROP, i, 0, 0, 0);
283 if (rc == -1) {
284 if (errno == EINVAL) {
285 ALOGE("prctl(PR_CAPBSET_DROP) failed with EINVAL. Please verify "
286 "your kernel is compiled with file capabilities support");
287 } else {
Andreas Gampeb8aae192018-03-12 12:08:55 -0700288 *error_msg = CREATE_ERROR("prctl(PR_CAPBSET_DROP, %d) failed: %s", i, strerror(errno));
289 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100290 }
291 }
292 }
Andreas Gampeb8aae192018-03-12 12:08:55 -0700293 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100294}
295
Andreas Gampeb8aae192018-03-12 12:08:55 -0700296static bool SetInheritable(uint64_t inheritable, std::string* error_msg) {
Josh Gao45dab782017-02-01 14:56:09 -0800297 __user_cap_header_struct capheader;
298 memset(&capheader, 0, sizeof(capheader));
299 capheader.version = _LINUX_CAPABILITY_VERSION_3;
300 capheader.pid = 0;
301
302 __user_cap_data_struct capdata[2];
303 if (capget(&capheader, &capdata[0]) == -1) {
Andreas Gampeb8aae192018-03-12 12:08:55 -0700304 *error_msg = CREATE_ERROR("capget failed: %s", strerror(errno));
305 return false;
Josh Gao45dab782017-02-01 14:56:09 -0800306 }
307
308 capdata[0].inheritable = inheritable;
309 capdata[1].inheritable = inheritable >> 32;
310
311 if (capset(&capheader, &capdata[0]) == -1) {
Andreas Gampeb8aae192018-03-12 12:08:55 -0700312 *error_msg = CREATE_ERROR("capset(inh=%" PRIx64 ") failed: %s", inheritable, strerror(errno));
313 return false;
Josh Gao45dab782017-02-01 14:56:09 -0800314 }
Andreas Gampeb8aae192018-03-12 12:08:55 -0700315
316 return true;
Josh Gao45dab782017-02-01 14:56:09 -0800317}
318
Andreas Gampeb8aae192018-03-12 12:08:55 -0700319static bool SetCapabilities(uint64_t permitted, uint64_t effective, uint64_t inheritable,
320 std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100321 __user_cap_header_struct capheader;
322 memset(&capheader, 0, sizeof(capheader));
323 capheader.version = _LINUX_CAPABILITY_VERSION_3;
324 capheader.pid = 0;
325
326 __user_cap_data_struct capdata[2];
327 memset(&capdata, 0, sizeof(capdata));
328 capdata[0].effective = effective;
329 capdata[1].effective = effective >> 32;
330 capdata[0].permitted = permitted;
331 capdata[1].permitted = permitted >> 32;
Josh Gao45dab782017-02-01 14:56:09 -0800332 capdata[0].inheritable = inheritable;
333 capdata[1].inheritable = inheritable >> 32;
Narayan Kamath973b4662014-03-31 13:41:26 +0100334
335 if (capset(&capheader, &capdata[0]) == -1) {
Andreas Gampeb8aae192018-03-12 12:08:55 -0700336 *error_msg = CREATE_ERROR("capset(perm=%" PRIx64 ", eff=%" PRIx64 ", inh=%" PRIx64 ") "
337 "failed: %s", permitted, effective, inheritable, strerror(errno));
338 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100339 }
Andreas Gampeb8aae192018-03-12 12:08:55 -0700340 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100341}
342
Andreas Gampeb8aae192018-03-12 12:08:55 -0700343static bool SetSchedulerPolicy(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100344 errno = -set_sched_policy(0, SP_DEFAULT);
345 if (errno != 0) {
Andreas Gampeb8aae192018-03-12 12:08:55 -0700346 *error_msg = CREATE_ERROR("set_sched_policy(0, SP_DEFAULT) failed: %s", strerror(errno));
347 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100348 }
Andreas Gampeb8aae192018-03-12 12:08:55 -0700349 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100350}
351
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700352static int UnmountTree(const char* path) {
353 size_t path_len = strlen(path);
354
355 FILE* fp = setmntent("/proc/mounts", "r");
356 if (fp == NULL) {
357 ALOGE("Error opening /proc/mounts: %s", strerror(errno));
358 return -errno;
359 }
360
361 // Some volumes can be stacked on each other, so force unmount in
362 // reverse order to give us the best chance of success.
363 std::list<std::string> toUnmount;
364 mntent* mentry;
365 while ((mentry = getmntent(fp)) != NULL) {
366 if (strncmp(mentry->mnt_dir, path, path_len) == 0) {
367 toUnmount.push_front(std::string(mentry->mnt_dir));
368 }
369 }
370 endmntent(fp);
371
372 for (auto path : toUnmount) {
373 if (umount2(path.c_str(), MNT_DETACH)) {
374 ALOGW("Failed to unmount %s: %s", path.c_str(), strerror(errno));
375 }
376 }
377 return 0;
378}
379
Narayan Kamath973b4662014-03-31 13:41:26 +0100380// Create a private mount namespace and bind mount appropriate emulated
381// storage for the given user.
Jeff Sharkey9527b222015-06-24 15:24:48 -0700382static bool MountEmulatedStorage(uid_t uid, jint mount_mode,
Andreas Gampeb8aae192018-03-12 12:08:55 -0700383 bool force_mount_namespace, std::string* error_msg) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700384 // See storage config details at http://source.android.com/tech/storage/
385
Jeff Sharkey9527b222015-06-24 15:24:48 -0700386 String8 storageSource;
387 if (mount_mode == MOUNT_EXTERNAL_DEFAULT) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700388 storageSource = "/mnt/runtime/default";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700389 } else if (mount_mode == MOUNT_EXTERNAL_READ) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700390 storageSource = "/mnt/runtime/read";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700391 } else if (mount_mode == MOUNT_EXTERNAL_WRITE) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700392 storageSource = "/mnt/runtime/write";
Robert Sesek06af1c02016-11-10 21:50:04 -0500393 } else if (!force_mount_namespace) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700394 // Sane default of no storage visible
395 return true;
396 }
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400397
398 // Create a second private mount namespace for our process
399 if (unshare(CLONE_NEWNS) == -1) {
Andreas Gampeb8aae192018-03-12 12:08:55 -0700400 *error_msg = CREATE_ERROR("Failed to unshare(): %s", strerror(errno));
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400401 return false;
402 }
403
Robert Sesek06f39302017-03-20 17:30:05 -0400404 // Handle force_mount_namespace with MOUNT_EXTERNAL_NONE.
405 if (mount_mode == MOUNT_EXTERNAL_NONE) {
406 return true;
407 }
408
Jeff Sharkey9527b222015-06-24 15:24:48 -0700409 if (TEMP_FAILURE_RETRY(mount(storageSource.string(), "/storage",
410 NULL, MS_BIND | MS_REC | MS_SLAVE, NULL)) == -1) {
Andreas Gampeb8aae192018-03-12 12:08:55 -0700411 *error_msg = CREATE_ERROR("Failed to mount %s to /storage: %s",
412 storageSource.string(),
413 strerror(errno));
Jeff Sharkey9527b222015-06-24 15:24:48 -0700414 return false;
415 }
416
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700417 // Mount user-specific symlink helper into place
Jeff Sharkey9527b222015-06-24 15:24:48 -0700418 userid_t user_id = multiuser_get_user_id(uid);
419 const String8 userSource(String8::format("/mnt/user/%d", user_id));
420 if (fs_prepare_dir(userSource.string(), 0751, 0, 0) == -1) {
Andreas Gampeb8aae192018-03-12 12:08:55 -0700421 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", userSource.string());
Jeff Sharkey9527b222015-06-24 15:24:48 -0700422 return false;
423 }
424 if (TEMP_FAILURE_RETRY(mount(userSource.string(), "/storage/self",
425 NULL, MS_BIND, NULL)) == -1) {
Andreas Gampeb8aae192018-03-12 12:08:55 -0700426 *error_msg = CREATE_ERROR("Failed to mount %s to /storage/self: %s",
427 userSource.string(),
428 strerror(errno));
Jeff Sharkey9527b222015-06-24 15:24:48 -0700429 return false;
430 }
431
Narayan Kamath973b4662014-03-31 13:41:26 +0100432 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100433}
434
Narayan Kamath973b4662014-03-31 13:41:26 +0100435static bool NeedsNoRandomizeWorkaround() {
436#if !defined(__arm__)
437 return false;
438#else
439 int major;
440 int minor;
441 struct utsname uts;
442 if (uname(&uts) == -1) {
443 return false;
444 }
445
446 if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
447 return false;
448 }
449
450 // Kernels before 3.4.* need the workaround.
451 return (major < 3) || ((major == 3) && (minor < 4));
452#endif
453}
Narayan Kamath973b4662014-03-31 13:41:26 +0100454
455// Utility to close down the Zygote socket file descriptors while
456// the child is still running as root with Zygote's privileges. Each
457// descriptor (if any) is closed via dup2(), replacing it with a valid
458// (open) descriptor to /dev/null.
459
Andreas Gampeb8aae192018-03-12 12:08:55 -0700460static bool DetachDescriptors(JNIEnv* env, jintArray fdsToClose, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100461 if (!fdsToClose) {
Andreas Gampeb8aae192018-03-12 12:08:55 -0700462 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100463 }
464 jsize count = env->GetArrayLength(fdsToClose);
Mykola Kondratenko1ca062f2015-07-31 17:22:26 +0200465 ScopedIntArrayRO ar(env, fdsToClose);
466 if (ar.get() == NULL) {
Andreas Gampeb8aae192018-03-12 12:08:55 -0700467 *error_msg = "Bad fd array";
468 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100469 }
470 jsize i;
471 int devnull;
472 for (i = 0; i < count; i++) {
473 devnull = open("/dev/null", O_RDWR);
474 if (devnull < 0) {
Andreas Gampeb8aae192018-03-12 12:08:55 -0700475 *error_msg = std::string("Failed to open /dev/null: ").append(strerror(errno));
476 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100477 }
Elliott Hughes960e8312014-09-30 08:49:01 -0700478 ALOGV("Switching descriptor %d to /dev/null: %s", ar[i], strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100479 if (dup2(devnull, ar[i]) < 0) {
Andreas Gampeb8aae192018-03-12 12:08:55 -0700480 *error_msg = StringPrintf("Failed dup2() on descriptor %d: %s", ar[i], strerror(errno));
481 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100482 }
483 close(devnull);
484 }
Andreas Gampeb8aae192018-03-12 12:08:55 -0700485 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100486}
487
488void SetThreadName(const char* thread_name) {
489 bool hasAt = false;
490 bool hasDot = false;
491 const char* s = thread_name;
492 while (*s) {
493 if (*s == '.') {
494 hasDot = true;
495 } else if (*s == '@') {
496 hasAt = true;
497 }
498 s++;
499 }
500 const int len = s - thread_name;
501 if (len < 15 || hasAt || !hasDot) {
502 s = thread_name;
503 } else {
504 s = thread_name + len - 15;
505 }
506 // pthread_setname_np fails rather than truncating long strings.
507 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
508 strlcpy(buf, s, sizeof(buf)-1);
509 errno = pthread_setname_np(pthread_self(), buf);
510 if (errno != 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700511 ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100512 }
Andreas Gampe39613972018-03-05 13:00:42 -0800513 // Update base::logging default tag.
514 android::base::SetDefaultTag(buf);
Narayan Kamath973b4662014-03-31 13:41:26 +0100515}
516
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100517// The list of open zygote file descriptors.
518static FileDescriptorTable* gOpenFdTable = NULL;
519
Andreas Gampeb8aae192018-03-12 12:08:55 -0700520static bool FillFileDescriptorVector(JNIEnv* env,
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800521 jintArray java_fds,
Andreas Gampeb8aae192018-03-12 12:08:55 -0700522 std::vector<int>* fds,
523 std::string* error_msg) {
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800524 CHECK(fds != nullptr);
525 if (java_fds != nullptr) {
526 ScopedIntArrayRO ar(env, java_fds);
527 if (ar.get() == nullptr) {
Andreas Gampeb8aae192018-03-12 12:08:55 -0700528 *error_msg = "Bad fd array";
529 return false;
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800530 }
531 fds->reserve(ar.size());
532 for (size_t i = 0; i < ar.size(); ++i) {
533 fds->push_back(ar[i]);
534 }
535 }
Andreas Gampeb8aae192018-03-12 12:08:55 -0700536 return true;
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800537}
538
David Sehr9a810052018-05-23 15:23:01 -0700539// Utility routine to specialize a zygote child process.
540static void SpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids,
541 jint runtime_flags, jobjectArray javaRlimits,
542 jlong permittedCapabilities, jlong effectiveCapabilities,
543 jint mount_external, jstring java_se_info, jstring java_se_name,
544 bool is_system_server, bool is_child_zygote, jstring instructionSet,
545 jstring dataDir) {
546 std::string error_msg;
547
548 auto fail_fn = [env, java_se_name, is_system_server](const std::string& msg)
549 __attribute__ ((noreturn)) {
550 const char* se_name_c_str = nullptr;
551 std::unique_ptr<ScopedUtfChars> se_name;
552 if (java_se_name != nullptr) {
553 se_name.reset(new ScopedUtfChars(env, java_se_name));
554 se_name_c_str = se_name->c_str();
555 }
556 if (se_name_c_str == nullptr && is_system_server) {
557 se_name_c_str = "system_server";
558 }
559 const std::string& error_msg = (se_name_c_str == nullptr)
560 ? msg
561 : StringPrintf("(%s) %s", se_name_c_str, msg.c_str());
562 env->FatalError(error_msg.c_str());
563 __builtin_unreachable();
564 };
565
566 // Keep capabilities across UID change, unless we're staying root.
567 if (uid != 0) {
568 if (!EnableKeepCapabilities(&error_msg)) {
569 fail_fn(error_msg);
570 }
571 }
572
573 if (!SetInheritable(permittedCapabilities, &error_msg)) {
574 fail_fn(error_msg);
575 }
576 if (!DropCapabilitiesBoundingSet(&error_msg)) {
577 fail_fn(error_msg);
578 }
579
580 bool use_native_bridge = !is_system_server && (instructionSet != NULL)
581 && android::NativeBridgeAvailable();
582 if (use_native_bridge) {
583 ScopedUtfChars isa_string(env, instructionSet);
584 use_native_bridge = android::NeedsNativeBridge(isa_string.c_str());
585 }
586 if (use_native_bridge && dataDir == NULL) {
587 // dataDir should never be null if we need to use a native bridge.
588 // In general, dataDir will never be null for normal applications. It can only happen in
589 // special cases (for isolated processes which are not associated with any app). These are
590 // launched by the framework and should not be emulated anyway.
591 use_native_bridge = false;
592 ALOGW("Native bridge will not be used because dataDir == NULL.");
593 }
594
595 if (!MountEmulatedStorage(uid, mount_external, use_native_bridge, &error_msg)) {
596 ALOGW("Failed to mount emulated storage: %s (%s)", error_msg.c_str(), strerror(errno));
597 if (errno == ENOTCONN || errno == EROFS) {
598 // When device is actively encrypting, we get ENOTCONN here
599 // since FUSE was mounted before the framework restarted.
600 // When encrypted device is booting, we get EROFS since
601 // FUSE hasn't been created yet by init.
602 // In either case, continue without external storage.
603 } else {
604 fail_fn(error_msg);
605 }
606 }
607
608 if (!is_system_server) {
609 int rc = createProcessGroup(uid, getpid());
610 if (rc != 0) {
611 if (rc == -EROFS) {
612 ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
613 } else {
614 ALOGE("createProcessGroup(%d, %d) failed: %s", uid, 0/*pid*/, strerror(-rc));
615 }
616 }
617 }
618
619 if (!SetGids(env, javaGids, &error_msg)) {
620 fail_fn(error_msg);
621 }
622
623 if (!SetRLimits(env, javaRlimits, &error_msg)) {
624 fail_fn(error_msg);
625 }
626
627 if (use_native_bridge) {
628 ScopedUtfChars isa_string(env, instructionSet);
629 ScopedUtfChars data_dir(env, dataDir);
630 android::PreInitializeNativeBridge(data_dir.c_str(), isa_string.c_str());
631 }
632
633 int rc = setresgid(gid, gid, gid);
634 if (rc == -1) {
635 fail_fn(CREATE_ERROR("setresgid(%d) failed: %s", gid, strerror(errno)));
636 }
637
638 // Must be called when the new process still has CAP_SYS_ADMIN, in this case, before changing
639 // uid from 0, which clears capabilities. The other alternative is to call
640 // prctl(PR_SET_NO_NEW_PRIVS, 1) afterward, but that breaks SELinux domain transition (see
641 // b/71859146). As the result, privileged syscalls used below still need to be accessible in
642 // app process.
643 SetUpSeccompFilter(uid);
644
645 rc = setresuid(uid, uid, uid);
646 if (rc == -1) {
647 fail_fn(CREATE_ERROR("setresuid(%d) failed: %s", uid, strerror(errno)));
648 }
649
650 // The "dumpable" flag of a process, which controls core dump generation, is
651 // overwritten by the value in /proc/sys/fs/suid_dumpable when the effective
652 // user or group ID changes. See proc(5) for possible values. In most cases,
653 // the value is 0, so core dumps are disabled for zygote children. However,
654 // when running in a Chrome OS container, the value is already set to 2,
655 // which allows the external crash reporter to collect all core dumps. Since
656 // only system crashes are interested, core dump is disabled for app
657 // processes. This also ensures compliance with CTS.
658 int dumpable = prctl(PR_GET_DUMPABLE);
659 if (dumpable == -1) {
660 ALOGE("prctl(PR_GET_DUMPABLE) failed: %s", strerror(errno));
661 RuntimeAbort(env, __LINE__, "prctl(PR_GET_DUMPABLE) failed");
662 }
663 if (dumpable == 2 && uid >= AID_APP) {
664 if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) == -1) {
665 ALOGE("prctl(PR_SET_DUMPABLE, 0) failed: %s", strerror(errno));
666 RuntimeAbort(env, __LINE__, "prctl(PR_SET_DUMPABLE, 0) failed");
667 }
668 }
669
670 if (NeedsNoRandomizeWorkaround()) {
671 // Work around ARM kernel ASLR lossage (http://b/5817320).
672 int old_personality = personality(0xffffffff);
673 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
674 if (new_personality == -1) {
675 ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
676 }
677 }
678
679 if (!SetCapabilities(permittedCapabilities, effectiveCapabilities, permittedCapabilities,
680 &error_msg)) {
681 fail_fn(error_msg);
682 }
683
684 if (!SetSchedulerPolicy(&error_msg)) {
685 fail_fn(error_msg);
686 }
687
688 const char* se_info_c_str = NULL;
689 ScopedUtfChars* se_info = NULL;
690 if (java_se_info != NULL) {
691 se_info = new ScopedUtfChars(env, java_se_info);
692 se_info_c_str = se_info->c_str();
693 if (se_info_c_str == NULL) {
694 fail_fn("se_info_c_str == NULL");
695 }
696 }
697 const char* se_name_c_str = NULL;
698 ScopedUtfChars* se_name = NULL;
699 if (java_se_name != NULL) {
700 se_name = new ScopedUtfChars(env, java_se_name);
701 se_name_c_str = se_name->c_str();
702 if (se_name_c_str == NULL) {
703 fail_fn("se_name_c_str == NULL");
704 }
705 }
706 rc = selinux_android_setcontext(uid, is_system_server, se_info_c_str, se_name_c_str);
707 if (rc == -1) {
708 fail_fn(CREATE_ERROR("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed", uid,
709 is_system_server, se_info_c_str, se_name_c_str));
710 }
711
712 // Make it easier to debug audit logs by setting the main thread's name to the
713 // nice name rather than "app_process".
714 if (se_name_c_str == NULL && is_system_server) {
715 se_name_c_str = "system_server";
716 }
717 if (se_name_c_str != NULL) {
718 SetThreadName(se_name_c_str);
719 }
720
721 delete se_info;
722 delete se_name;
723
724 // Unset the SIGCHLD handler, but keep ignoring SIGHUP (rationale in SetSignalHandlers).
725 UnsetChldSignalHandler();
726
727 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, runtime_flags,
728 is_system_server, is_child_zygote, instructionSet);
729 if (env->ExceptionCheck()) {
730 fail_fn("Error calling post fork hooks.");
731 }
732}
733
Narayan Kamath973b4662014-03-31 13:41:26 +0100734// Utility routine to fork zygote and specialize the child process.
David Sehr9a810052018-05-23 15:23:01 -0700735static pid_t ForkCommon(JNIEnv* env, jstring java_se_name, bool is_system_server,
736 jintArray fdsToClose, jintArray fdsToIgnore) {
yuanhao435e84b2018-01-15 15:37:02 +0800737 SetSignalHandlers();
Narayan Kamath973b4662014-03-31 13:41:26 +0100738
David Sehr9a810052018-05-23 15:23:01 -0700739 // Block SIGCHLD prior to fork.
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000740 sigset_t sigchld;
741 sigemptyset(&sigchld);
742 sigaddset(&sigchld, SIGCHLD);
743
Andreas Gampebf94c2c2018-03-12 12:17:25 -0700744 auto fail_fn = [env, java_se_name, is_system_server](const std::string& msg)
745 __attribute__ ((noreturn)) {
746 const char* se_name_c_str = nullptr;
747 std::unique_ptr<ScopedUtfChars> se_name;
748 if (java_se_name != nullptr) {
749 se_name.reset(new ScopedUtfChars(env, java_se_name));
750 se_name_c_str = se_name->c_str();
751 }
752 if (se_name_c_str == nullptr && is_system_server) {
753 se_name_c_str = "system_server";
754 }
755 const std::string& error_msg = (se_name_c_str == nullptr)
756 ? msg
757 : StringPrintf("(%s) %s", se_name_c_str, msg.c_str());
758 env->FatalError(error_msg.c_str());
Andreas Gampeb8aae192018-03-12 12:08:55 -0700759 __builtin_unreachable();
760 };
761
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000762 // Temporarily block SIGCHLD during forks. The SIGCHLD handler might
763 // log, which would result in the logging FDs we close being reopened.
764 // This would cause failures because the FDs are not whitelisted.
765 //
766 // Note that the zygote process is single threaded at this point.
767 if (sigprocmask(SIG_BLOCK, &sigchld, nullptr) == -1) {
Andreas Gampeb8aae192018-03-12 12:08:55 -0700768 fail_fn(CREATE_ERROR("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno)));
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000769 }
770
Narayan Kamath3764a262016-08-30 15:36:19 +0100771 // Close any logging related FDs before we start evaluating the list of
772 // file descriptors.
773 __android_log_close();
774
Andreas Gampeb8aae192018-03-12 12:08:55 -0700775 std::string error_msg;
776
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100777 // If this is the first fork for this zygote, create the open FD table.
778 // If it isn't, we just need to check whether the list of open files has
779 // changed (and it shouldn't in the normal case).
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800780 std::vector<int> fds_to_ignore;
Andreas Gampeb8aae192018-03-12 12:08:55 -0700781 if (!FillFileDescriptorVector(env, fdsToIgnore, &fds_to_ignore, &error_msg)) {
782 fail_fn(error_msg);
783 }
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100784 if (gOpenFdTable == NULL) {
Andreas Gampe183a5d32018-03-12 14:53:34 -0700785 gOpenFdTable = FileDescriptorTable::Create(fds_to_ignore, &error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100786 if (gOpenFdTable == NULL) {
Andreas Gampe183a5d32018-03-12 14:53:34 -0700787 fail_fn(error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100788 }
Andreas Gampe183a5d32018-03-12 14:53:34 -0700789 } else if (!gOpenFdTable->Restat(fds_to_ignore, &error_msg)) {
790 fail_fn(error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100791 }
792
Josh Gaod7951102018-06-26 16:05:12 -0700793 android_fdsan_error_level fdsan_error_level = android_fdsan_get_error_level();
794
Narayan Kamath973b4662014-03-31 13:41:26 +0100795 pid_t pid = fork();
796
797 if (pid == 0) {
David Sehr9a810052018-05-23 15:23:01 -0700798 // The child process.
Christopher Ferris76de39e2017-06-20 16:13:40 -0700799 PreApplicationInit();
Christopher Ferrisab16dd12017-05-15 16:50:29 -0700800
Narayan Kamath973b4662014-03-31 13:41:26 +0100801 // Clean up any descriptors which must be closed immediately
Andreas Gampeb8aae192018-03-12 12:08:55 -0700802 if (!DetachDescriptors(env, fdsToClose, &error_msg)) {
803 fail_fn(error_msg);
804 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100805
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100806 // Re-open all remaining open file descriptors so that they aren't shared
807 // with the zygote across a fork.
Andreas Gampe183a5d32018-03-12 14:53:34 -0700808 if (!gOpenFdTable->ReopenOrDetach(&error_msg)) {
809 fail_fn(error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100810 }
Josh Gaod7951102018-06-26 16:05:12 -0700811
812 // Turn fdsan back on.
813 android_fdsan_set_error_level(fdsan_error_level);
Narayan Kamath973b4662014-03-31 13:41:26 +0100814 }
David Sehr9a810052018-05-23 15:23:01 -0700815
816 // We blocked SIGCHLD prior to a fork, we unblock it here.
817 if (sigprocmask(SIG_UNBLOCK, &sigchld, nullptr) == -1) {
818 fail_fn(CREATE_ERROR("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno)));
819 }
820
Narayan Kamath973b4662014-03-31 13:41:26 +0100821 return pid;
822}
Luis Hector Chavez72042c92017-07-12 10:03:30 -0700823
824static uint64_t GetEffectiveCapabilityMask(JNIEnv* env) {
825 __user_cap_header_struct capheader;
826 memset(&capheader, 0, sizeof(capheader));
827 capheader.version = _LINUX_CAPABILITY_VERSION_3;
828 capheader.pid = 0;
829
830 __user_cap_data_struct capdata[2];
831 if (capget(&capheader, &capdata[0]) == -1) {
832 ALOGE("capget failed: %s", strerror(errno));
833 RuntimeAbort(env, __LINE__, "capget failed");
834 }
835
836 return capdata[0].effective |
837 (static_cast<uint64_t>(capdata[1].effective) << 32);
838}
Narayan Kamath973b4662014-03-31 13:41:26 +0100839} // anonymous namespace
840
841namespace android {
842
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800843static void com_android_internal_os_Zygote_nativeSecurityInit(JNIEnv*, jclass) {
844 // security_getenforce is not allowed on app process. Initialize and cache the value before
845 // zygote forks.
846 g_is_security_enforced = security_getenforce();
847}
848
Christopher Ferris76de39e2017-06-20 16:13:40 -0700849static void com_android_internal_os_Zygote_nativePreApplicationInit(JNIEnv*, jclass) {
850 PreApplicationInit();
851}
852
Narayan Kamath973b4662014-03-31 13:41:26 +0100853static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
854 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100855 jint runtime_flags, jobjectArray rlimits,
Narayan Kamath973b4662014-03-31 13:41:26 +0100856 jint mount_external, jstring se_info, jstring se_name,
Robert Sesekd0a190df2018-02-12 18:46:01 -0500857 jintArray fdsToClose, jintArray fdsToIgnore, jboolean is_child_zygote,
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800858 jstring instructionSet, jstring appDataDir) {
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -0700859 jlong capabilities = 0;
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800860
861 // Grant CAP_WAKE_ALARM to the Bluetooth process.
Erik Kline0f6ae2e2016-02-22 15:42:07 +0900862 // Additionally, allow bluetooth to open packet sockets so it can start the DHCP client.
Philip Cuadra0fabba32017-04-26 13:49:37 -0700863 // Grant CAP_SYS_NICE to allow Bluetooth to set RT priority for
864 // audio-related threads.
Erik Kline0f6ae2e2016-02-22 15:42:07 +0900865 // TODO: consider making such functionality an RPC to netd.
Pavlin Radoslavov2956bee2016-01-27 16:22:15 -0800866 if (multiuser_get_app_id(uid) == AID_BLUETOOTH) {
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800867 capabilities |= (1LL << CAP_WAKE_ALARM);
Erik Kline0f6ae2e2016-02-22 15:42:07 +0900868 capabilities |= (1LL << CAP_NET_RAW);
869 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
Philip Cuadra0fabba32017-04-26 13:49:37 -0700870 capabilities |= (1LL << CAP_SYS_NICE);
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800871 }
Sharvil Nanavatibabe8152015-08-31 23:25:06 -0700872
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800873 // Grant CAP_BLOCK_SUSPEND to processes that belong to GID "wakelock"
874 bool gid_wakelock_found = false;
875 if (gid == AID_WAKELOCK) {
876 gid_wakelock_found = true;
877 } else if (gids != NULL) {
878 jsize gids_num = env->GetArrayLength(gids);
879 ScopedIntArrayRO ar(env, gids);
880 if (ar.get() == NULL) {
881 RuntimeAbort(env, __LINE__, "Bad gids array");
882 }
883 for (int i = 0; i < gids_num; i++) {
884 if (ar[i] == AID_WAKELOCK) {
885 gid_wakelock_found = true;
886 break;
Sharvil Nanavatibabe8152015-08-31 23:25:06 -0700887 }
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800888 }
889 }
890 if (gid_wakelock_found) {
891 capabilities |= (1LL << CAP_BLOCK_SUSPEND);
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -0700892 }
893
Robert Sesekd0a190df2018-02-12 18:46:01 -0500894 // If forking a child zygote process, that zygote will need to be able to change
895 // the UID and GID of processes it forks, as well as drop those capabilities.
896 if (is_child_zygote) {
897 capabilities |= (1LL << CAP_SETUID);
898 capabilities |= (1LL << CAP_SETGID);
899 capabilities |= (1LL << CAP_SETPCAP);
900 }
901
Luis Hector Chavez72042c92017-07-12 10:03:30 -0700902 // Containers run without some capabilities, so drop any caps that are not
903 // available.
904 capabilities &= GetEffectiveCapabilityMask(env);
905
David Sehr9a810052018-05-23 15:23:01 -0700906 pid_t pid = ForkCommon(env, se_name, false, fdsToClose, fdsToIgnore);
907 if (pid == 0) {
908 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
909 capabilities, capabilities,
910 mount_external, se_info, se_name, false,
911 is_child_zygote == JNI_TRUE, instructionSet, appDataDir);
912 }
913 return pid;
Narayan Kamath973b4662014-03-31 13:41:26 +0100914}
915
916static jint com_android_internal_os_Zygote_nativeForkSystemServer(
917 JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100918 jint runtime_flags, jobjectArray rlimits, jlong permittedCapabilities,
Narayan Kamath973b4662014-03-31 13:41:26 +0100919 jlong effectiveCapabilities) {
David Sehr9a810052018-05-23 15:23:01 -0700920 pid_t pid = ForkCommon(env, NULL, true, NULL, NULL);
921 if (pid == 0) {
922 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
923 permittedCapabilities, effectiveCapabilities,
924 MOUNT_EXTERNAL_DEFAULT, NULL, NULL, true,
925 false, NULL, NULL);
926 } else if (pid > 0) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100927 // The zygote process checks whether the child process has died or not.
928 ALOGI("System server process %d has been created", pid);
929 gSystemServerPid = pid;
930 // There is a slight window that the system server process has crashed
931 // but it went unnoticed because we haven't published its pid yet. So
932 // we recheck here just to make sure that all is well.
933 int status;
934 if (waitpid(pid, &status, WNOHANG) == pid) {
935 ALOGE("System server process %d has died. Restarting Zygote!", pid);
Andreas Gampeb053cce2015-11-17 16:38:59 -0800936 RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
Narayan Kamath973b4662014-03-31 13:41:26 +0100937 }
Carmen Jacksondd401252017-02-23 15:21:10 -0800938
939 // Assign system_server to the correct memory cgroup.
940 if (!WriteStringToFile(StringPrintf("%d", pid), "/dev/memcg/system/tasks")) {
941 ALOGE("couldn't write %d to /dev/memcg/system/tasks", pid);
942 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100943 }
944 return pid;
945}
946
Robert Sesek54e387d2016-12-02 17:27:50 -0500947static void com_android_internal_os_Zygote_nativeAllowFileAcrossFork(
948 JNIEnv* env, jclass, jstring path) {
949 ScopedUtfChars path_native(env, path);
950 const char* path_cstr = path_native.c_str();
951 if (!path_cstr) {
952 RuntimeAbort(env, __LINE__, "path_cstr == NULL");
953 }
954 FileDescriptorWhitelist::Get()->Allow(path_cstr);
955}
956
doheon1.lee885b7422016-01-20 13:07:27 +0900957static void com_android_internal_os_Zygote_nativeUnmountStorageOnInit(JNIEnv* env, jclass) {
958 // Zygote process unmount root storage space initially before every child processes are forked.
959 // Every forked child processes (include SystemServer) only mount their own root storage space
Robert Seseke4f8d692016-09-13 19:13:01 -0400960 // and no need unmount storage operation in MountEmulatedStorage method.
961 // Zygote process does not utilize root storage spaces and unshares its mount namespace below.
962
963 // See storage config details at http://source.android.com/tech/storage/
964 // Create private mount namespace shared by all children
965 if (unshare(CLONE_NEWNS) == -1) {
966 RuntimeAbort(env, __LINE__, "Failed to unshare()");
967 return;
968 }
969
970 // Mark rootfs as being a slave so that changes from default
971 // namespace only flow into our children.
972 if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
973 RuntimeAbort(env, __LINE__, "Failed to mount() rootfs as MS_SLAVE");
974 return;
975 }
976
977 // Create a staging tmpfs that is shared by our children; they will
978 // bind mount storage into their respective private namespaces, which
979 // are isolated from each other.
980 const char* target_base = getenv("EMULATED_STORAGE_TARGET");
981 if (target_base != nullptr) {
982#define STRINGIFY_UID(x) __STRING(x)
983 if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
984 "uid=0,gid=" STRINGIFY_UID(AID_SDCARD_R) ",mode=0751") == -1) {
985 ALOGE("Failed to mount tmpfs to %s", target_base);
986 RuntimeAbort(env, __LINE__, "Failed to mount tmpfs");
987 return;
988 }
989#undef STRINGIFY_UID
990 }
doheon1.lee885b7422016-01-20 13:07:27 +0900991
992 UnmountTree("/storage");
doheon1.lee885b7422016-01-20 13:07:27 +0900993}
994
Daniel Micay76f6a862015-09-19 17:31:01 -0400995static const JNINativeMethod gMethods[] = {
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800996 { "nativeSecurityInit", "()V",
997 (void *) com_android_internal_os_Zygote_nativeSecurityInit },
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700998 { "nativeForkAndSpecialize",
Robert Sesekd0a190df2018-02-12 18:46:01 -0500999 "(II[II[[IILjava/lang/String;Ljava/lang/String;[I[IZLjava/lang/String;Ljava/lang/String;)I",
Narayan Kamath973b4662014-03-31 13:41:26 +01001000 (void *) com_android_internal_os_Zygote_nativeForkAndSpecialize },
1001 { "nativeForkSystemServer", "(II[II[[IJJ)I",
doheon1.lee885b7422016-01-20 13:07:27 +09001002 (void *) com_android_internal_os_Zygote_nativeForkSystemServer },
Robert Sesek54e387d2016-12-02 17:27:50 -05001003 { "nativeAllowFileAcrossFork", "(Ljava/lang/String;)V",
1004 (void *) com_android_internal_os_Zygote_nativeAllowFileAcrossFork },
doheon1.lee885b7422016-01-20 13:07:27 +09001005 { "nativeUnmountStorageOnInit", "()V",
Christopher Ferris76de39e2017-06-20 16:13:40 -07001006 (void *) com_android_internal_os_Zygote_nativeUnmountStorageOnInit },
1007 { "nativePreApplicationInit", "()V",
1008 (void *) com_android_internal_os_Zygote_nativePreApplicationInit }
Narayan Kamath973b4662014-03-31 13:41:26 +01001009};
1010
1011int register_com_android_internal_os_Zygote(JNIEnv* env) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001012 gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName));
1013 gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
Robert Sesekd0a190df2018-02-12 18:46:01 -05001014 "(IZZLjava/lang/String;)V");
Narayan Kamath973b4662014-03-31 13:41:26 +01001015
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001016 return RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
Narayan Kamath973b4662014-03-31 13:41:26 +01001017}
1018} // namespace android