blob: 1b4bdf313cf3ea89fc2b4659af5de93d627bfcac [file] [log] [blame]
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001/*
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
Tom Cherry3f5eaae52017-04-06 16:30:22 -070017#include "init.h"
18
Elliott Hughes8d82ea02015-02-06 20:15:18 -080019#include <ctype.h>
Rom Lemarchand6a524432015-02-28 06:39:11 -080020#include <dirent.h>
Elliott Hughes8d82ea02015-02-06 20:15:18 -080021#include <errno.h>
22#include <fcntl.h>
Elliott Hughes9605a942016-11-10 17:43:47 -080023#include <inttypes.h>
Elliott Hughes8d82ea02015-02-06 20:15:18 -080024#include <libgen.h>
Elliott Hughescc86fb22015-03-17 20:01:13 -070025#include <paths.h>
Elliott Hughes8d82ea02015-02-06 20:15:18 -080026#include <signal.h>
27#include <stdarg.h>
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070028#include <stdio.h>
29#include <stdlib.h>
30#include <string.h>
Elliott Hughes929f4072015-04-24 21:13:44 -070031#include <sys/epoll.h>
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070032#include <sys/mount.h>
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070033#include <sys/socket.h>
Elliott Hughes8d82ea02015-02-06 20:15:18 -080034#include <sys/stat.h>
Elliott Hughes35f5d042016-07-26 09:32:33 -070035#include <sys/sysmacros.h>
Elliott Hughes8d82ea02015-02-06 20:15:18 -080036#include <sys/types.h>
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070037#include <sys/un.h>
Elliott Hughes8d82ea02015-02-06 20:15:18 -080038#include <sys/wait.h>
Elliott Hughes8d82ea02015-02-06 20:15:18 -080039#include <unistd.h>
40
Stephen Smalleye46f9d52012-01-13 08:48:47 -050041#include <selinux/selinux.h>
42#include <selinux/label.h>
Stephen Smalleyae6f3d72012-05-01 15:02:53 -040043#include <selinux/android.h>
Stephen Smalleye46f9d52012-01-13 08:48:47 -050044
James Hawkinse78ea772017-03-24 11:43:02 -070045#include <android-base/chrono_utils.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080046#include <android-base/file.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070047#include <android-base/logging.h>
Tom Cherryccf23532017-03-28 16:40:41 -070048#include <android-base/properties.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080049#include <android-base/stringprintf.h>
50#include <android-base/strings.h>
Alex Klyubin16696e22017-02-28 12:32:20 -080051#include <android-base/unique_fd.h>
bowgotsai76351272017-02-14 22:06:20 +080052#include <libavb/libavb.h>
Colin Crossf83d0b92010-04-21 12:04:20 -070053#include <private/android_filesystem_config.h>
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070054
Elliott Hughes99dae542016-11-10 19:22:18 -080055#include <fstream>
Rom Lemarchand6a524432015-02-28 06:39:11 -080056#include <memory>
Bowgo Tsaid4beed22017-02-18 18:33:13 +080057#include <vector>
Rom Lemarchand6a524432015-02-28 06:39:11 -080058
Tom Cherryfa0c21c2015-07-23 17:53:11 -070059#include "action.h"
Tom Cherrybac32992015-07-31 12:45:25 -070060#include "bootchart.h"
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070061#include "devices.h"
Tom Cherryb7349902015-08-26 11:43:36 -070062#include "import_parser.h"
Bowgo Tsaid2620172017-04-17 22:17:09 +080063#include "init_first_stage.h"
Tom Cherrybac32992015-07-31 12:45:25 -070064#include "init_parser.h"
65#include "keychords.h"
Colin Crossed8a7d82010-04-19 17:05:34 -070066#include "log.h"
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070067#include "property_service.h"
Tom Cherry98ad32a2017-04-17 16:34:20 -070068#include "reboot.h"
Tom Cherrybac32992015-07-31 12:45:25 -070069#include "service.h"
Colin Cross9c5366b2010-04-13 19:48:59 -070070#include "signal_handler.h"
Colin Crossf83d0b92010-04-21 12:04:20 -070071#include "ueventd.h"
Tom Cherrybac32992015-07-31 12:45:25 -070072#include "util.h"
Arve Hjønnevågd97d9072012-06-13 21:51:56 -070073#include "watchdogd.h"
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070074
James Hawkinse78ea772017-03-24 11:43:02 -070075using android::base::boot_clock;
Tom Cherryccf23532017-03-28 16:40:41 -070076using android::base::GetProperty;
Elliott Hughes9605a942016-11-10 17:43:47 -080077using android::base::StringPrintf;
78
Stephen Smalleye46f9d52012-01-13 08:48:47 -050079struct selabel_handle *sehandle;
rpcraig63207cd2012-08-09 10:05:49 -040080struct selabel_handle *sehandle_prop;
Stephen Smalleye46f9d52012-01-13 08:48:47 -050081
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070082static int property_triggers_enabled = 0;
83
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070084static char qemu[32];
85
Viorel Suman70daa672016-03-21 10:08:07 +020086std::string default_console = "/dev/console";
Elliott Hughes9605a942016-11-10 17:43:47 -080087static time_t process_needs_restart_at;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070088
Tom Cherrybac32992015-07-31 12:45:25 -070089const char *ENV[32];
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070090
Elliott Hughes929f4072015-04-24 21:13:44 -070091static int epoll_fd = -1;
92
Wei Wang132ac312017-01-25 16:27:03 -080093static std::unique_ptr<Timer> waiting_for_prop(nullptr);
94static std::string wait_prop_name;
95static std::string wait_prop_value;
96
Elliott Hughes929f4072015-04-24 21:13:44 -070097void register_epoll_handler(int fd, void (*fn)()) {
98 epoll_event ev;
99 ev.events = EPOLLIN;
100 ev.data.ptr = reinterpret_cast<void*>(fn);
101 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700102 PLOG(ERROR) << "epoll_ctl failed";
Elliott Hughes929f4072015-04-24 21:13:44 -0700103 }
104}
105
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700106/* add_environment - add "key=value" to the current environment */
107int add_environment(const char *key, const char *val)
108{
James Morrissey381341f2014-05-16 11:36:36 +0100109 size_t n;
110 size_t key_len = strlen(key);
Vladimir Chtchetkine2b995432011-09-28 09:55:31 -0700111
James Morrissey381341f2014-05-16 11:36:36 +0100112 /* The last environment entry is reserved to terminate the list */
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700113 for (n = 0; n < (arraysize(ENV) - 1); n++) {
James Morrissey381341f2014-05-16 11:36:36 +0100114
115 /* Delete any existing entry for this key */
116 if (ENV[n] != NULL) {
117 size_t entry_key_len = strcspn(ENV[n], "=");
118 if ((entry_key_len == key_len) && (strncmp(ENV[n], key, entry_key_len) == 0)) {
119 free((char*)ENV[n]);
120 ENV[n] = NULL;
121 }
122 }
123
124 /* Add entry if a free slot is available */
125 if (ENV[n] == NULL) {
Elliott Hughesf3cf4382015-02-03 17:12:07 -0800126 char* entry;
127 asprintf(&entry, "%s=%s", key, val);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700128 ENV[n] = entry;
129 return 0;
130 }
131 }
132
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700133 LOG(ERROR) << "No env. room to store: '" << key << "':'" << val << "'";
James Morrissey381341f2014-05-16 11:36:36 +0100134
135 return -1;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700136}
137
Wei Wang2d0fdaa2017-02-02 10:52:39 -0800138bool start_waiting_for_property(const char *name, const char *value)
Wei Wang132ac312017-01-25 16:27:03 -0800139{
140 if (waiting_for_prop) {
141 return false;
142 }
Tom Cherryccf23532017-03-28 16:40:41 -0700143 if (GetProperty(name, "") != value) {
Wei Wang132ac312017-01-25 16:27:03 -0800144 // Current property value is not equal to expected value
145 wait_prop_name = name;
146 wait_prop_value = value;
147 waiting_for_prop.reset(new Timer());
148 } else {
Wei Wang2d0fdaa2017-02-02 10:52:39 -0800149 LOG(INFO) << "start_waiting_for_property(\""
150 << name << "\", \"" << value << "\"): already set";
Wei Wang132ac312017-01-25 16:27:03 -0800151 }
152 return true;
153}
154
Tom Cherry98ad32a2017-04-17 16:34:20 -0700155void property_changed(const std::string& name, const std::string& value) {
156 // If the property is sys.powerctl, we bypass the event queue and immediately handle it.
157 // This is to ensure that init will always and immediately shutdown/reboot, regardless of
158 // if there are other pending events to process or if init is waiting on an exec service or
159 // waiting on a property.
160 if (name == "sys.powerctl") HandlePowerctlMessage(value);
161
Colin Crossebc6ff12010-04-13 19:52:01 -0700162 if (property_triggers_enabled)
Tom Cherryfa0c21c2015-07-23 17:53:11 -0700163 ActionManager::GetInstance().QueuePropertyTrigger(name, value);
Wei Wang132ac312017-01-25 16:27:03 -0800164 if (waiting_for_prop) {
165 if (wait_prop_name == name && wait_prop_value == value) {
166 wait_prop_name.clear();
167 wait_prop_value.clear();
168 LOG(INFO) << "Wait for property took " << *waiting_for_prop;
169 waiting_for_prop.reset();
170 }
171 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700172}
173
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700174static void restart_processes()
175{
Elliott Hughes9605a942016-11-10 17:43:47 -0800176 process_needs_restart_at = 0;
177 ServiceManager::GetInstance().ForEachServiceWithFlags(SVC_RESTARTING, [](Service* s) {
178 s->RestartIfNeeded(&process_needs_restart_at);
179 });
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700180}
181
Elliott Hughesbdeac392016-04-12 15:38:27 -0700182void handle_control_message(const std::string& msg, const std::string& name) {
Tom Cherrybac32992015-07-31 12:45:25 -0700183 Service* svc = ServiceManager::GetInstance().FindServiceByName(name);
Elliott Hughesbdeac392016-04-12 15:38:27 -0700184 if (svc == nullptr) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700185 LOG(ERROR) << "no such service '" << name << "'";
Elliott Hughesbdeac392016-04-12 15:38:27 -0700186 return;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700187 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700188
Tom Cherrybac32992015-07-31 12:45:25 -0700189 if (msg == "start") {
Elliott Hughesbdeac392016-04-12 15:38:27 -0700190 svc->Start();
Tom Cherrybac32992015-07-31 12:45:25 -0700191 } else if (msg == "stop") {
Elliott Hughesbdeac392016-04-12 15:38:27 -0700192 svc->Stop();
Tom Cherrybac32992015-07-31 12:45:25 -0700193 } else if (msg == "restart") {
Elliott Hughesbdeac392016-04-12 15:38:27 -0700194 svc->Restart();
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700195 } else {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700196 LOG(ERROR) << "unknown control msg '" << msg << "'";
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700197 }
198}
199
Tom Cherry96f67312015-07-30 13:52:55 -0700200static int wait_for_coldboot_done_action(const std::vector<std::string>& args) {
Elliott Hughesc6c26ed2015-04-24 18:50:30 -0700201 Timer t;
202
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700203 LOG(VERBOSE) << "Waiting for " COLDBOOT_DONE "...";
Elliott Hughes331cf2f2016-11-29 19:20:58 +0000204
205 // Historically we had a 1s timeout here because we weren't otherwise
206 // tracking boot time, and many OEMs made their sepolicy regular
207 // expressions too expensive (http://b/19899875).
208
209 // Now we're tracking boot time, just log the time taken to a system
210 // property. We still panic if it takes more than a minute though,
211 // because any build that slow isn't likely to boot at all, and we'd
212 // rather any test lab devices fail back to the bootloader.
213 if (wait_for_file(COLDBOOT_DONE, 60s) < 0) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700214 LOG(ERROR) << "Timed out waiting for " COLDBOOT_DONE;
Elliott Hughes331cf2f2016-11-29 19:20:58 +0000215 panic();
Elliott Hughesc6c26ed2015-04-24 18:50:30 -0700216 }
217
James Hawkins27c05222017-01-26 11:55:44 -0800218 property_set("ro.boottime.init.cold_boot_wait", std::to_string(t.duration_ms()).c_str());
Elliott Hughesc6c26ed2015-04-24 18:50:30 -0700219 return 0;
Colin Crossebc6ff12010-04-13 19:52:01 -0700220}
221
Alex Klyubin0d872d82013-08-16 13:19:24 -0700222/*
223 * Writes 512 bytes of output from Hardware RNG (/dev/hw_random, backed
224 * by Linux kernel's hw_random framework) into Linux RNG's via /dev/urandom.
225 * Does nothing if Hardware RNG is not present.
226 *
227 * Since we don't yet trust the quality of Hardware RNG, these bytes are not
228 * mixed into the primary pool of Linux RNG and the entropy estimate is left
229 * unmodified.
230 *
231 * If the HW RNG device /dev/hw_random is present, we require that at least
232 * 512 bytes read from it are written into Linux RNG. QA is expected to catch
233 * devices/configurations where these I/O operations are blocking for a long
234 * time. We do not reboot or halt on failures, as this is a best-effort
235 * attempt.
236 */
Tom Cherry96f67312015-07-30 13:52:55 -0700237static int mix_hwrng_into_linux_rng_action(const std::vector<std::string>& args)
Alex Klyubin0d872d82013-08-16 13:19:24 -0700238{
239 int result = -1;
240 int hwrandom_fd = -1;
241 int urandom_fd = -1;
242 char buf[512];
243 ssize_t chunk_size;
244 size_t total_bytes_written = 0;
245
246 hwrandom_fd = TEMP_FAILURE_RETRY(
Nick Kralevich45a884f2015-02-02 14:37:22 -0800247 open("/dev/hw_random", O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
Alex Klyubin0d872d82013-08-16 13:19:24 -0700248 if (hwrandom_fd == -1) {
249 if (errno == ENOENT) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700250 LOG(ERROR) << "/dev/hw_random not found";
251 // It's not an error to not have a Hardware RNG.
252 result = 0;
Alex Klyubin0d872d82013-08-16 13:19:24 -0700253 } else {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700254 PLOG(ERROR) << "Failed to open /dev/hw_random";
Alex Klyubin0d872d82013-08-16 13:19:24 -0700255 }
256 goto ret;
257 }
258
259 urandom_fd = TEMP_FAILURE_RETRY(
Nick Kralevich45a884f2015-02-02 14:37:22 -0800260 open("/dev/urandom", O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
Alex Klyubin0d872d82013-08-16 13:19:24 -0700261 if (urandom_fd == -1) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700262 PLOG(ERROR) << "Failed to open /dev/urandom";
Alex Klyubin0d872d82013-08-16 13:19:24 -0700263 goto ret;
264 }
265
266 while (total_bytes_written < sizeof(buf)) {
267 chunk_size = TEMP_FAILURE_RETRY(
268 read(hwrandom_fd, buf, sizeof(buf) - total_bytes_written));
269 if (chunk_size == -1) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700270 PLOG(ERROR) << "Failed to read from /dev/hw_random";
Alex Klyubin0d872d82013-08-16 13:19:24 -0700271 goto ret;
272 } else if (chunk_size == 0) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700273 LOG(ERROR) << "Failed to read from /dev/hw_random: EOF";
Alex Klyubin0d872d82013-08-16 13:19:24 -0700274 goto ret;
275 }
276
277 chunk_size = TEMP_FAILURE_RETRY(write(urandom_fd, buf, chunk_size));
278 if (chunk_size == -1) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700279 PLOG(ERROR) << "Failed to write to /dev/urandom";
Alex Klyubin0d872d82013-08-16 13:19:24 -0700280 goto ret;
281 }
282 total_bytes_written += chunk_size;
283 }
284
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700285 LOG(INFO) << "Mixed " << total_bytes_written << " bytes from /dev/hw_random into /dev/urandom";
Alex Klyubin0d872d82013-08-16 13:19:24 -0700286 result = 0;
287
288ret:
289 if (hwrandom_fd != -1) {
290 close(hwrandom_fd);
291 }
292 if (urandom_fd != -1) {
293 close(urandom_fd);
294 }
Alex Klyubin0d872d82013-08-16 13:19:24 -0700295 return result;
296}
297
Daniel Cashmanbaccc402016-03-25 23:49:05 +0000298static void security_failure() {
299 LOG(ERROR) << "Security failure...";
300 panic();
301}
302
Dave Weinstein44f7e4f2017-01-19 18:03:34 -0800303static bool set_highest_available_option_value(std::string path, int min, int max)
304{
Daniel Cashmanbaccc402016-03-25 23:49:05 +0000305 std::ifstream inf(path, std::fstream::in);
306 if (!inf) {
307 LOG(ERROR) << "Cannot open for reading: " << path;
308 return false;
309 }
Dave Weinstein44f7e4f2017-01-19 18:03:34 -0800310
311 int current = max;
312 while (current >= min) {
Daniel Cashmanbaccc402016-03-25 23:49:05 +0000313 // try to write out new value
Dave Weinstein44f7e4f2017-01-19 18:03:34 -0800314 std::string str_val = std::to_string(current);
Daniel Cashmanbaccc402016-03-25 23:49:05 +0000315 std::ofstream of(path, std::fstream::out);
316 if (!of) {
317 LOG(ERROR) << "Cannot open for writing: " << path;
318 return false;
319 }
320 of << str_val << std::endl;
321 of.close();
322
323 // check to make sure it was recorded
324 inf.seekg(0);
325 std::string str_rec;
326 inf >> str_rec;
327 if (str_val.compare(str_rec) == 0) {
328 break;
329 }
Dave Weinstein44f7e4f2017-01-19 18:03:34 -0800330 current--;
Daniel Cashmanbaccc402016-03-25 23:49:05 +0000331 }
332 inf.close();
Dave Weinstein44f7e4f2017-01-19 18:03:34 -0800333
334 if (current < min) {
335 LOG(ERROR) << "Unable to set minimum option value " << min << " in " << path;
Daniel Cashmanbaccc402016-03-25 23:49:05 +0000336 return false;
337 }
338 return true;
339}
340
Dave Weinstein44f7e4f2017-01-19 18:03:34 -0800341#define MMAP_RND_PATH "/proc/sys/vm/mmap_rnd_bits"
342#define MMAP_RND_COMPAT_PATH "/proc/sys/vm/mmap_rnd_compat_bits"
343
344/* __attribute__((unused)) due to lack of mips support: see mips block
345 * in set_mmap_rnd_bits_action */
346static bool __attribute__((unused)) set_mmap_rnd_bits_min(int start, int min, bool compat) {
347 std::string path;
348 if (compat) {
349 path = MMAP_RND_COMPAT_PATH;
350 } else {
351 path = MMAP_RND_PATH;
352 }
353
354 return set_highest_available_option_value(path, min, start);
355}
356
Daniel Cashmanbaccc402016-03-25 23:49:05 +0000357/*
358 * Set /proc/sys/vm/mmap_rnd_bits and potentially
359 * /proc/sys/vm/mmap_rnd_compat_bits to the maximum supported values.
360 * Returns -1 if unable to set these to an acceptable value.
361 *
362 * To support this sysctl, the following upstream commits are needed:
363 *
364 * d07e22597d1d mm: mmap: add new /proc tunable for mmap_base ASLR
365 * e0c25d958f78 arm: mm: support ARCH_MMAP_RND_BITS
366 * 8f0d3aa9de57 arm64: mm: support ARCH_MMAP_RND_BITS
367 * 9e08f57d684a x86: mm: support ARCH_MMAP_RND_BITS
368 * ec9ee4acd97c drivers: char: random: add get_random_long()
369 * 5ef11c35ce86 mm: ASLR: use get_random_long()
370 */
371static int set_mmap_rnd_bits_action(const std::vector<std::string>& args)
372{
373 int ret = -1;
374
375 /* values are arch-dependent */
376#if defined(__aarch64__)
377 /* arm64 supports 18 - 33 bits depending on pagesize and VA_SIZE */
378 if (set_mmap_rnd_bits_min(33, 24, false)
379 && set_mmap_rnd_bits_min(16, 16, true)) {
380 ret = 0;
381 }
382#elif defined(__x86_64__)
383 /* x86_64 supports 28 - 32 bits */
384 if (set_mmap_rnd_bits_min(32, 32, false)
385 && set_mmap_rnd_bits_min(16, 16, true)) {
386 ret = 0;
387 }
388#elif defined(__arm__) || defined(__i386__)
389 /* check to see if we're running on 64-bit kernel */
390 bool h64 = !access(MMAP_RND_COMPAT_PATH, F_OK);
391 /* supported 32-bit architecture must have 16 bits set */
392 if (set_mmap_rnd_bits_min(16, 16, h64)) {
393 ret = 0;
394 }
395#elif defined(__mips__) || defined(__mips64__)
396 // TODO: add mips support b/27788820
397 ret = 0;
398#else
dcashman41d0b6d2016-12-14 08:37:11 -0800399 LOG(ERROR) << "Unknown architecture";
Daniel Cashmanbaccc402016-03-25 23:49:05 +0000400#endif
401
Daniel Cashmanbaccc402016-03-25 23:49:05 +0000402 if (ret == -1) {
403 LOG(ERROR) << "Unable to set adequate mmap entropy value!";
404 security_failure();
405 }
406 return ret;
407}
408
Dave Weinstein44f7e4f2017-01-19 18:03:34 -0800409#define KPTR_RESTRICT_PATH "/proc/sys/kernel/kptr_restrict"
410#define KPTR_RESTRICT_MINVALUE 2
411#define KPTR_RESTRICT_MAXVALUE 4
412
413/* Set kptr_restrict to the highest available level.
414 *
415 * Aborts if unable to set this to an acceptable value.
416 */
417static int set_kptr_restrict_action(const std::vector<std::string>& args)
418{
419 std::string path = KPTR_RESTRICT_PATH;
420
421 if (!set_highest_available_option_value(path, KPTR_RESTRICT_MINVALUE, KPTR_RESTRICT_MAXVALUE)) {
422 LOG(ERROR) << "Unable to set adequate kptr_restrict value!";
423 security_failure();
424 }
425 return 0;
426}
427
Tom Cherry96f67312015-07-30 13:52:55 -0700428static int keychord_init_action(const std::vector<std::string>& args)
Colin Crossebc6ff12010-04-13 19:52:01 -0700429{
430 keychord_init();
431 return 0;
432}
433
Tom Cherry96f67312015-07-30 13:52:55 -0700434static int console_init_action(const std::vector<std::string>& args)
Colin Crossebc6ff12010-04-13 19:52:01 -0700435{
Tom Cherryccf23532017-03-28 16:40:41 -0700436 std::string console = GetProperty("ro.boot.console", "");
Viorel Sumanefc72752016-03-21 10:23:43 +0200437 if (!console.empty()) {
Viorel Suman70daa672016-03-21 10:08:07 +0200438 default_console = "/dev/" + console;
Colin Crossebc6ff12010-04-13 19:52:01 -0700439 }
Colin Crossebc6ff12010-04-13 19:52:01 -0700440 return 0;
441}
442
Elliott Hughese5ce30f2015-05-06 19:19:24 -0700443static void import_kernel_nv(const std::string& key, const std::string& value, bool for_emulator) {
444 if (key.empty()) return;
Dima Zavin5511c842011-12-19 11:21:32 -0800445
446 if (for_emulator) {
Elliott Hughese5ce30f2015-05-06 19:19:24 -0700447 // In the emulator, export any kernel option with the "ro.kernel." prefix.
Elliott Hughes9605a942016-11-10 17:43:47 -0800448 property_set(StringPrintf("ro.kernel.%s", key.c_str()).c_str(), value.c_str());
Dima Zavin5511c842011-12-19 11:21:32 -0800449 return;
450 }
451
Elliott Hughese5ce30f2015-05-06 19:19:24 -0700452 if (key == "qemu") {
453 strlcpy(qemu, value.c_str(), sizeof(qemu));
454 } else if (android::base::StartsWith(key, "androidboot.")) {
Elliott Hughes9605a942016-11-10 17:43:47 -0800455 property_set(StringPrintf("ro.boot.%s", key.c_str() + 12).c_str(), value.c_str());
Dima Zavin5511c842011-12-19 11:21:32 -0800456 }
457}
458
Sami Tolvanen9e9efca2015-12-07 12:33:58 +0000459static void export_oem_lock_status() {
Tom Cherryccf23532017-03-28 16:40:41 -0700460 if (!android::base::GetBoolProperty("ro.oem_unlock_supported", false)) {
Sami Tolvanen9e9efca2015-12-07 12:33:58 +0000461 return;
462 }
463
Tom Cherryccf23532017-03-28 16:40:41 -0700464 std::string value = GetProperty("ro.boot.verifiedbootstate", "");
Sami Tolvanen9e9efca2015-12-07 12:33:58 +0000465
466 if (!value.empty()) {
467 property_set("ro.boot.flash.locked", value == "orange" ? "0" : "1");
468 }
469}
470
Elliott Hughesd679bc92015-03-20 08:50:46 -0700471static void export_kernel_boot_props() {
Dima Zavin5511c842011-12-19 11:21:32 -0800472 struct {
473 const char *src_prop;
Elliott Hughesd679bc92015-03-20 08:50:46 -0700474 const char *dst_prop;
475 const char *default_value;
Dima Zavin5511c842011-12-19 11:21:32 -0800476 } prop_map[] = {
Elliott Hughesd679bc92015-03-20 08:50:46 -0700477 { "ro.boot.serialno", "ro.serialno", "", },
478 { "ro.boot.mode", "ro.bootmode", "unknown", },
479 { "ro.boot.baseband", "ro.baseband", "unknown", },
Dima Zavin5511c842011-12-19 11:21:32 -0800480 { "ro.boot.bootloader", "ro.bootloader", "unknown", },
Elliott Hughesd679bc92015-03-20 08:50:46 -0700481 { "ro.boot.hardware", "ro.hardware", "unknown", },
482 { "ro.boot.revision", "ro.revision", "0", },
Dima Zavin5511c842011-12-19 11:21:32 -0800483 };
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700484 for (size_t i = 0; i < arraysize(prop_map); i++) {
Tom Cherryccf23532017-03-28 16:40:41 -0700485 std::string value = GetProperty(prop_map[i].src_prop, "");
Yabin Cui74edcea2015-07-24 10:11:05 -0700486 property_set(prop_map[i].dst_prop, (!value.empty()) ? value.c_str() : prop_map[i].default_value);
Dima Zavin5511c842011-12-19 11:21:32 -0800487 }
Dima Zavin5511c842011-12-19 11:21:32 -0800488}
Colin Crossebc6ff12010-04-13 19:52:01 -0700489
Sandeep Patilfc86f242017-02-09 19:19:31 -0800490static void process_kernel_dt() {
Bowgo Tsaid2620172017-04-17 22:17:09 +0800491 if (!is_android_dt_value_expected("compatible", "android,firmware")) {
492 return;
493 }
Sandeep Patilfc86f242017-02-09 19:19:31 -0800494
Bowgo Tsai8bba52f2017-04-06 21:01:40 +0800495 std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(kAndroidDtDir.c_str()), closedir);
Elliott Hughese5ce30f2015-05-06 19:19:24 -0700496 if (!dir) return;
Rom Lemarchand6a524432015-02-28 06:39:11 -0800497
Sandeep Patilfc86f242017-02-09 19:19:31 -0800498 std::string dt_file;
Rom Lemarchand6a524432015-02-28 06:39:11 -0800499 struct dirent *dp;
500 while ((dp = readdir(dir.get())) != NULL) {
Rom Lemarchand1dcf3252015-11-08 17:51:50 -0800501 if (dp->d_type != DT_REG || !strcmp(dp->d_name, "compatible") || !strcmp(dp->d_name, "name")) {
Rom Lemarchand6a524432015-02-28 06:39:11 -0800502 continue;
Elliott Hughese5ce30f2015-05-06 19:19:24 -0700503 }
Rom Lemarchand6a524432015-02-28 06:39:11 -0800504
Bowgo Tsai8bba52f2017-04-06 21:01:40 +0800505 std::string file_name = kAndroidDtDir + dp->d_name;
Rom Lemarchand6a524432015-02-28 06:39:11 -0800506
507 android::base::ReadFileToString(file_name, &dt_file);
508 std::replace(dt_file.begin(), dt_file.end(), ',', '.');
509
Elliott Hughes9605a942016-11-10 17:43:47 -0800510 std::string property_name = StringPrintf("ro.boot.%s", dp->d_name);
Elliott Hughesdb3f2672015-03-20 09:45:18 -0700511 property_set(property_name.c_str(), dt_file.c_str());
Rom Lemarchand6a524432015-02-28 06:39:11 -0800512 }
513}
514
Elliott Hughese5ce30f2015-05-06 19:19:24 -0700515static void process_kernel_cmdline() {
Elliott Hughese5ce30f2015-05-06 19:19:24 -0700516 // The first pass does the common stuff, and finds if we are in qemu.
517 // The second pass is only necessary for qemu to export all kernel params
518 // as properties.
Nick Kralevichf667a322015-04-25 17:42:52 -0700519 import_kernel_cmdline(false, import_kernel_nv);
Elliott Hughese5ce30f2015-05-06 19:19:24 -0700520 if (qemu[0]) import_kernel_cmdline(true, import_kernel_nv);
Colin Crossebc6ff12010-04-13 19:52:01 -0700521}
522
caozhiyuanb104c502016-11-26 21:14:07 +0800523static int property_enable_triggers_action(const std::vector<std::string>& args)
524{
525 /* Enable property triggers. */
526 property_triggers_enabled = 1;
527 return 0;
528}
529
Tom Cherry96f67312015-07-30 13:52:55 -0700530static int queue_property_triggers_action(const std::vector<std::string>& args)
Colin Crossebc6ff12010-04-13 19:52:01 -0700531{
caozhiyuanb104c502016-11-26 21:14:07 +0800532 ActionManager::GetInstance().QueueBuiltinAction(property_enable_triggers_action, "enable_property_trigger");
Tom Cherryfa0c21c2015-07-23 17:53:11 -0700533 ActionManager::GetInstance().QueueAllPropertyTriggers();
Colin Crossebc6ff12010-04-13 19:52:01 -0700534 return 0;
535}
536
Elliott Hughesc6c26ed2015-04-24 18:50:30 -0700537static void selinux_init_all_handles(void)
Stephen Smalleye46f9d52012-01-13 08:48:47 -0500538{
Stephen Smalleyae6f3d72012-05-01 15:02:53 -0400539 sehandle = selinux_android_file_context_handle();
Stephen Smalleydbd37f22014-01-28 10:34:09 -0500540 selinux_android_set_sehandle(sehandle);
rpcraig63207cd2012-08-09 10:05:49 -0400541 sehandle_prop = selinux_android_prop_context_handle();
Stephen Smalleyae6f3d72012-05-01 15:02:53 -0400542}
Stephen Smalleye46f9d52012-01-13 08:48:47 -0500543
Nick Kralevichd34e4072015-04-28 12:39:41 -0700544enum selinux_enforcing_status { SELINUX_PERMISSIVE, SELINUX_ENFORCING };
Nick Kralevichf667a322015-04-25 17:42:52 -0700545
546static selinux_enforcing_status selinux_status_from_cmdline() {
547 selinux_enforcing_status status = SELINUX_ENFORCING;
548
Elliott Hughese5ce30f2015-05-06 19:19:24 -0700549 import_kernel_cmdline(false, [&](const std::string& key, const std::string& value, bool in_qemu) {
550 if (key == "androidboot.selinux" && value == "permissive") {
551 status = SELINUX_PERMISSIVE;
Nick Kralevichf667a322015-04-25 17:42:52 -0700552 }
Elliott Hughese5ce30f2015-05-06 19:19:24 -0700553 });
Nick Kralevichf667a322015-04-25 17:42:52 -0700554
555 return status;
556}
557
Nick Kralevich935bd3e2013-06-26 15:37:26 -0700558static bool selinux_is_enforcing(void)
559{
Nick Kralevichd34e4072015-04-28 12:39:41 -0700560 if (ALLOW_PERMISSIVE_SELINUX) {
Nick Kralevichf667a322015-04-25 17:42:52 -0700561 return selinux_status_from_cmdline() == SELINUX_ENFORCING;
Nick Kralevich935bd3e2013-06-26 15:37:26 -0700562 }
Nick Kralevich935bd3e2013-06-26 15:37:26 -0700563 return true;
564}
565
Elliott Hughesda40c002015-03-27 23:20:44 -0700566static int audit_callback(void *data, security_class_t /*cls*/, char *buf, size_t len) {
William Robertsd7aea442015-10-01 16:03:47 -0700567
568 property_audit_data *d = reinterpret_cast<property_audit_data*>(data);
569
570 if (!d || !d->name || !d->cr) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700571 LOG(ERROR) << "audit_callback invoked with null data arguments!";
William Robertsd7aea442015-10-01 16:03:47 -0700572 return 0;
573 }
574
575 snprintf(buf, len, "property=%s pid=%d uid=%d gid=%d", d->name,
576 d->cr->pid, d->cr->uid, d->cr->gid);
rpcraig63207cd2012-08-09 10:05:49 -0400577 return 0;
578}
579
Alex Klyubin16696e22017-02-28 12:32:20 -0800580/*
581 * Forks, executes the provided program in the child, and waits for the completion in the parent.
Alex Klyubin11850502017-03-05 14:28:27 -0800582 * Child's stderr is captured and logged using LOG(ERROR).
Alex Klyubin16696e22017-02-28 12:32:20 -0800583 *
584 * Returns true if the child exited with status code 0, returns false otherwise.
585 */
586static bool fork_execve_and_wait_for_completion(const char* filename, char* const argv[],
587 char* const envp[]) {
Alex Klyubin11850502017-03-05 14:28:27 -0800588 // Create a pipe used for redirecting child process's output.
589 // * pipe_fds[0] is the FD the parent will use for reading.
590 // * pipe_fds[1] is the FD the child will use for writing.
591 int pipe_fds[2];
592 if (pipe(pipe_fds) == -1) {
593 PLOG(ERROR) << "Failed to create pipe";
594 return false;
595 }
596
Alex Klyubin16696e22017-02-28 12:32:20 -0800597 pid_t child_pid = fork();
598 if (child_pid == -1) {
599 PLOG(ERROR) << "Failed to fork for " << filename;
600 return false;
601 }
602
603 if (child_pid == 0) {
604 // fork succeeded -- this is executing in the child process
Alex Klyubin11850502017-03-05 14:28:27 -0800605
606 // Close the pipe FD not used by this process
607 TEMP_FAILURE_RETRY(close(pipe_fds[0]));
608
609 // Redirect stderr to the pipe FD provided by the parent
610 if (TEMP_FAILURE_RETRY(dup2(pipe_fds[1], STDERR_FILENO)) == -1) {
611 PLOG(ERROR) << "Failed to redirect stderr of " << filename;
612 _exit(127);
613 return false;
614 }
615 TEMP_FAILURE_RETRY(close(pipe_fds[1]));
616
Alex Klyubin16696e22017-02-28 12:32:20 -0800617 if (execve(filename, argv, envp) == -1) {
618 PLOG(ERROR) << "Failed to execve " << filename;
619 return false;
620 }
621 // Unreachable because execve will have succeeded and replaced this code
622 // with child process's code.
623 _exit(127);
624 return false;
625 } else {
626 // fork succeeded -- this is executing in the original/parent process
Alex Klyubin11850502017-03-05 14:28:27 -0800627
628 // Close the pipe FD not used by this process
629 TEMP_FAILURE_RETRY(close(pipe_fds[1]));
630
631 // Log the redirected output of the child process.
632 // It's unfortunate that there's no standard way to obtain an istream for a file descriptor.
633 // As a result, we're buffering all output and logging it in one go at the end of the
634 // invocation, instead of logging it as it comes in.
635 const int child_out_fd = pipe_fds[0];
636 std::string child_output;
637 if (!android::base::ReadFdToString(child_out_fd, &child_output)) {
638 PLOG(ERROR) << "Failed to capture full output of " << filename;
639 }
640 TEMP_FAILURE_RETRY(close(child_out_fd));
641 if (!child_output.empty()) {
642 // Log captured output, line by line, because LOG expects to be invoked for each line
643 std::istringstream in(child_output);
644 std::string line;
645 while (std::getline(in, line)) {
646 LOG(ERROR) << filename << ": " << line;
647 }
648 }
649
650 // Wait for child to terminate
Alex Klyubin16696e22017-02-28 12:32:20 -0800651 int status;
652 if (TEMP_FAILURE_RETRY(waitpid(child_pid, &status, 0)) != child_pid) {
653 PLOG(ERROR) << "Failed to wait for " << filename;
654 return false;
655 }
656
657 if (WIFEXITED(status)) {
658 int status_code = WEXITSTATUS(status);
659 if (status_code == 0) {
660 return true;
661 } else {
662 LOG(ERROR) << filename << " exited with status " << status_code;
663 }
664 } else if (WIFSIGNALED(status)) {
665 LOG(ERROR) << filename << " killed by signal " << WTERMSIG(status);
666 } else if (WIFSTOPPED(status)) {
667 LOG(ERROR) << filename << " stopped by signal " << WSTOPSIG(status);
668 } else {
669 LOG(ERROR) << "waitpid for " << filename << " returned unexpected status: " << status;
670 }
671
672 return false;
673 }
674}
675
Alex Klyubin2d19aeb2017-03-07 14:12:01 -0800676static bool read_first_line(const char* file, std::string* line) {
677 line->clear();
678
679 std::string contents;
680 if (!android::base::ReadFileToString(file, &contents, true /* follow symlinks */)) {
681 return false;
682 }
683 std::istringstream in(contents);
684 std::getline(in, *line);
685 return true;
686}
687
688static bool selinux_find_precompiled_split_policy(std::string* file) {
689 file->clear();
690
691 static constexpr const char precompiled_sepolicy[] = "/vendor/etc/selinux/precompiled_sepolicy";
692 if (access(precompiled_sepolicy, R_OK) == -1) {
693 return false;
694 }
695 std::string actual_plat_id;
Dan Cashman29923112017-04-06 09:51:23 -0700696 if (!read_first_line("/system/etc/selinux/plat_and_mapping_sepolicy.cil.sha256",
697 &actual_plat_id)) {
698 PLOG(INFO) << "Failed to read "
699 "/system/etc/selinux/plat_and_mapping_sepolicy.cil.sha256";
Alex Klyubin2d19aeb2017-03-07 14:12:01 -0800700 return false;
701 }
702 std::string precompiled_plat_id;
Dan Cashman29923112017-04-06 09:51:23 -0700703 if (!read_first_line("/vendor/etc/selinux/precompiled_sepolicy.plat_and_mapping.sha256",
Alex Klyubin2d19aeb2017-03-07 14:12:01 -0800704 &precompiled_plat_id)) {
Dan Cashman29923112017-04-06 09:51:23 -0700705 PLOG(INFO) << "Failed to read "
706 "/vendor/etc/selinux/"
707 "precompiled_sepolicy.plat_and_mapping.sha256";
Alex Klyubin2d19aeb2017-03-07 14:12:01 -0800708 return false;
709 }
710 if ((actual_plat_id.empty()) || (actual_plat_id != precompiled_plat_id)) {
711 return false;
712 }
713
714 *file = precompiled_sepolicy;
715 return true;
716}
717
Alex Klyubinc2a4c9a2017-03-02 12:43:10 -0800718static constexpr const char plat_policy_cil_file[] = "/system/etc/selinux/plat_sepolicy.cil";
Alex Klyubin16696e22017-02-28 12:32:20 -0800719
720static bool selinux_is_split_policy_device() { return access(plat_policy_cil_file, R_OK) != -1; }
721
722/*
723 * Loads SELinux policy split across platform/system and non-platform/vendor files.
724 *
725 * Returns true upon success, false otherwise (failure cause is logged).
726 */
727static bool selinux_load_split_policy() {
728 // IMPLEMENTATION NOTE: Split policy consists of three CIL files:
729 // * platform -- policy needed due to logic contained in the system image,
730 // * non-platform -- policy needed due to logic contained in the vendor image,
731 // * mapping -- mapping policy which helps preserve forward-compatibility of non-platform policy
732 // with newer versions of platform policy.
733 //
734 // secilc is invoked to compile the above three policy files into a single monolithic policy
735 // file. This file is then loaded into the kernel.
736
Alex Klyubin2d19aeb2017-03-07 14:12:01 -0800737 // Load precompiled policy from vendor image, if a matching policy is found there. The policy
738 // must match the platform policy on the system image.
739 std::string precompiled_sepolicy_file;
740 if (selinux_find_precompiled_split_policy(&precompiled_sepolicy_file)) {
741 android::base::unique_fd fd(
742 open(precompiled_sepolicy_file.c_str(), O_RDONLY | O_CLOEXEC | O_BINARY));
743 if (fd != -1) {
744 if (selinux_android_load_policy_from_fd(fd, precompiled_sepolicy_file.c_str()) < 0) {
745 LOG(ERROR) << "Failed to load SELinux policy from " << precompiled_sepolicy_file;
746 return false;
747 }
748 return true;
749 }
750 }
751 // No suitable precompiled policy could be loaded
752
Alex Klyubin16696e22017-02-28 12:32:20 -0800753 LOG(INFO) << "Compiling SELinux policy";
754
Alex Klyubina71dfec2017-03-09 10:56:58 -0800755 // Determine the highest policy language version supported by the kernel
756 set_selinuxmnt("/sys/fs/selinux");
757 int max_policy_version = security_policyvers();
758 if (max_policy_version == -1) {
759 PLOG(ERROR) << "Failed to determine highest policy version supported by kernel";
760 return false;
761 }
762
Alex Klyubin16696e22017-02-28 12:32:20 -0800763 // We store the output of the compilation on /dev because this is the most convenient tmpfs
764 // storage mount available this early in the boot sequence.
765 char compiled_sepolicy[] = "/dev/sepolicy.XXXXXX";
766 android::base::unique_fd compiled_sepolicy_fd(mkostemp(compiled_sepolicy, O_CLOEXEC));
767 if (compiled_sepolicy_fd < 0) {
768 PLOG(ERROR) << "Failed to create temporary file " << compiled_sepolicy;
769 return false;
770 }
771
Alex Klyubina71dfec2017-03-09 10:56:58 -0800772 // clang-format off
773 const char* compile_args[] = {
774 "/system/bin/secilc",
775 plat_policy_cil_file,
776 "-M", "true",
777 // Target the highest policy language version supported by the kernel
778 "-c", std::to_string(max_policy_version).c_str(),
Dan Cashman29923112017-04-06 09:51:23 -0700779 "/system/etc/selinux/mapping_sepolicy.cil",
Alex Klyubina71dfec2017-03-09 10:56:58 -0800780 "/vendor/etc/selinux/nonplat_sepolicy.cil",
781 "-o", compiled_sepolicy,
782 // We don't care about file_contexts output by the compiler
783 "-f", "/sys/fs/selinux/null", // /dev/null is not yet available
784 nullptr};
785 // clang-format on
Alex Klyubin16696e22017-02-28 12:32:20 -0800786
787 if (!fork_execve_and_wait_for_completion(compile_args[0], (char**)compile_args, (char**)ENV)) {
788 unlink(compiled_sepolicy);
789 return false;
790 }
791 unlink(compiled_sepolicy);
792
793 LOG(INFO) << "Loading compiled SELinux policy";
794 if (selinux_android_load_policy_from_fd(compiled_sepolicy_fd, compiled_sepolicy) < 0) {
795 LOG(ERROR) << "Failed to load SELinux policy from " << compiled_sepolicy;
796 return false;
797 }
798
799 return true;
800}
801
802/*
803 * Loads SELinux policy from a monolithic file.
804 *
805 * Returns true upon success, false otherwise (failure cause is logged).
806 */
807static bool selinux_load_monolithic_policy() {
808 LOG(VERBOSE) << "Loading SELinux policy from monolithic file";
809 if (selinux_android_load_policy() < 0) {
810 PLOG(ERROR) << "Failed to load monolithic SELinux policy";
811 return false;
812 }
813 return true;
814}
815
816/*
817 * Loads SELinux policy into the kernel.
818 *
819 * Returns true upon success, false otherwise (failure cause is logged).
820 */
821static bool selinux_load_policy() {
822 return selinux_is_split_policy_device() ? selinux_load_split_policy()
823 : selinux_load_monolithic_policy();
824}
825
Elliott Hughesf65730e2015-04-24 18:38:17 +0000826static void selinux_initialize(bool in_kernel_domain) {
Elliott Hughesda40c002015-03-27 23:20:44 -0700827 Timer t;
Stephen Smalleyeb3f4212014-02-12 16:17:00 -0500828
Elliott Hughesda40c002015-03-27 23:20:44 -0700829 selinux_callback cb;
830 cb.func_log = selinux_klog_callback;
831 selinux_set_callback(SELINUX_CB_LOG, cb);
832 cb.func_audit = audit_callback;
833 selinux_set_callback(SELINUX_CB_AUDIT, cb);
834
Elliott Hughesf65730e2015-04-24 18:38:17 +0000835 if (in_kernel_domain) {
Alex Klyubin16696e22017-02-28 12:32:20 -0800836 LOG(INFO) << "Loading SELinux policy";
837 if (!selinux_load_policy()) {
838 panic();
Elliott Hughesf65730e2015-04-24 18:38:17 +0000839 }
840
Nick Kralevichd34e4072015-04-28 12:39:41 -0700841 bool kernel_enforcing = (security_getenforce() == 1);
Elliott Hughesf65730e2015-04-24 18:38:17 +0000842 bool is_enforcing = selinux_is_enforcing();
Nick Kralevichd34e4072015-04-28 12:39:41 -0700843 if (kernel_enforcing != is_enforcing) {
844 if (security_setenforce(is_enforcing)) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700845 PLOG(ERROR) << "security_setenforce(%s) failed" << (is_enforcing ? "true" : "false");
Nick Kralevichd34e4072015-04-28 12:39:41 -0700846 security_failure();
847 }
848 }
Elliott Hughesf65730e2015-04-24 18:38:17 +0000849
Jorge Lucangeli Obes77f0e9f2016-12-28 14:07:02 -0500850 if (!write_file("/sys/fs/selinux/checkreqprot", "0")) {
Nick Kralevicheedbe812015-04-25 14:10:03 -0700851 security_failure();
852 }
853
Elliott Hughes331cf2f2016-11-29 19:20:58 +0000854 // init's first stage can't set properties, so pass the time to the second stage.
James Hawkins27c05222017-01-26 11:55:44 -0800855 setenv("INIT_SELINUX_TOOK", std::to_string(t.duration_ms()).c_str(), 1);
Elliott Hughesf65730e2015-04-24 18:38:17 +0000856 } else {
857 selinux_init_all_handles();
Nick Kralevich56fa0ac2013-06-24 17:41:40 -0700858 }
Nick Kralevich56fa0ac2013-06-24 17:41:40 -0700859}
860
Sandeep Patil7ef60b42017-03-29 10:31:26 -0700861// The files and directories that were created before initial sepolicy load
862// need to have their security context restored to the proper value.
863// This must happen before /dev is populated by ueventd.
864static void selinux_restore_context() {
865 LOG(INFO) << "Running restorecon...";
866 restorecon("/dev");
867 restorecon("/dev/kmsg");
Josh Gaobf2dd482017-03-28 13:07:15 -0700868 if constexpr (WORLD_WRITABLE_KMSG) {
869 restorecon("/dev/kmsg_debug");
870 }
Sandeep Patil7ef60b42017-03-29 10:31:26 -0700871 restorecon("/dev/socket");
872 restorecon("/dev/random");
873 restorecon("/dev/urandom");
874 restorecon("/dev/__properties__");
875 restorecon("/plat_property_contexts");
876 restorecon("/nonplat_property_contexts");
877 restorecon("/sys", SELINUX_ANDROID_RESTORECON_RECURSE);
878 restorecon("/dev/block", SELINUX_ANDROID_RESTORECON_RECURSE);
879 restorecon("/dev/device-mapper");
880}
881
Amit Pundird2e74db2016-06-29 19:00:00 +0530882// Set the UDC controller for the ConfigFS USB Gadgets.
883// Read the UDC controller in use from "/sys/class/udc".
884// In case of multiple UDC controllers select the first one.
885static void set_usb_controller() {
886 std::unique_ptr<DIR, decltype(&closedir)>dir(opendir("/sys/class/udc"), closedir);
887 if (!dir) return;
888
889 dirent* dp;
890 while ((dp = readdir(dir.get())) != nullptr) {
891 if (dp->d_name[0] == '.') continue;
892
893 property_set("sys.usb.controller", dp->d_name);
894 break;
895 }
896}
897
Tom Cherry663fdfc2017-03-10 14:46:38 -0800898static void install_reboot_signal_handlers() {
899 // Instead of panic'ing the kernel as is the default behavior when init crashes,
900 // we prefer to reboot to bootloader on development builds, as this will prevent
901 // boot looping bad configurations and allow both developers and test farms to easily
902 // recover.
903 struct sigaction action;
904 memset(&action, 0, sizeof(action));
905 sigfillset(&action.sa_mask);
906 action.sa_handler = [](int) {
907 // panic() reboots to bootloader
908 panic();
909 };
910 action.sa_flags = SA_RESTART;
911 sigaction(SIGABRT, &action, nullptr);
912 sigaction(SIGBUS, &action, nullptr);
913 sigaction(SIGFPE, &action, nullptr);
914 sigaction(SIGILL, &action, nullptr);
915 sigaction(SIGSEGV, &action, nullptr);
916#if defined(SIGSTKFLT)
917 sigaction(SIGSTKFLT, &action, nullptr);
918#endif
919 sigaction(SIGSYS, &action, nullptr);
920 sigaction(SIGTRAP, &action, nullptr);
921}
922
Elliott Hughes8d82ea02015-02-06 20:15:18 -0800923int main(int argc, char** argv) {
Elliott Hughesda40c002015-03-27 23:20:44 -0700924 if (!strcmp(basename(argv[0]), "ueventd")) {
Colin Crossf83d0b92010-04-21 12:04:20 -0700925 return ueventd_main(argc, argv);
Elliott Hughesda40c002015-03-27 23:20:44 -0700926 }
Colin Crossf83d0b92010-04-21 12:04:20 -0700927
Elliott Hughesda40c002015-03-27 23:20:44 -0700928 if (!strcmp(basename(argv[0]), "watchdogd")) {
Arve Hjønnevågd97d9072012-06-13 21:51:56 -0700929 return watchdogd_main(argc, argv);
Elliott Hughesda40c002015-03-27 23:20:44 -0700930 }
Arve Hjønnevågd97d9072012-06-13 21:51:56 -0700931
Tom Cherry663fdfc2017-03-10 14:46:38 -0800932 if (REBOOT_BOOTLOADER_ON_PANIC) {
933 install_reboot_signal_handlers();
934 }
935
Elliott Hughescc86fb22015-03-17 20:01:13 -0700936 add_environment("PATH", _PATH_DEFPATH);
937
Elliott Hughes9605a942016-11-10 17:43:47 -0800938 bool is_first_stage = (getenv("INIT_SECOND_STAGE") == nullptr);
Nick Kralevich9dec93b2015-04-25 15:50:03 -0700939
Nick Kralevich9dec93b2015-04-25 15:50:03 -0700940 if (is_first_stage) {
Tom Cherry34e70412017-03-16 18:08:56 -0700941 boot_clock::time_point start_time = boot_clock::now();
942
943 // Clear the umask.
944 umask(0);
945
946 // Get the basic filesystem setup we need put together in the initramdisk
947 // on / and then we'll let the rc file figure out the rest.
Nick Kralevichf667a322015-04-25 17:42:52 -0700948 mount("tmpfs", "/dev", "tmpfs", MS_NOSUID, "mode=0755");
949 mkdir("/dev/pts", 0755);
950 mkdir("/dev/socket", 0755);
951 mount("devpts", "/dev/pts", "devpts", 0, NULL);
Nick Kralevichc39ba5a2015-11-07 16:52:17 -0800952 #define MAKE_STR(x) __STRING(x)
953 mount("proc", "/proc", "proc", 0, "hidepid=2,gid=" MAKE_STR(AID_READPROC));
Tom Cherry34e70412017-03-16 18:08:56 -0700954 // Don't expose the raw commandline to unprivileged processes.
955 chmod("/proc/cmdline", 0440);
Nick Kralevich80960d22016-10-29 12:20:00 -0700956 gid_t groups[] = { AID_READPROC };
957 setgroups(arraysize(groups), groups);
Nick Kralevich9dec93b2015-04-25 15:50:03 -0700958 mount("sysfs", "/sys", "sysfs", 0, NULL);
Nick Kralevich3d9e2732016-03-03 10:40:12 -0800959 mount("selinuxfs", "/sys/fs/selinux", "selinuxfs", 0, NULL);
Josh Gaobf2dd482017-03-28 13:07:15 -0700960
Elliott Hughes35f5d042016-07-26 09:32:33 -0700961 mknod("/dev/kmsg", S_IFCHR | 0600, makedev(1, 11));
Josh Gaobf2dd482017-03-28 13:07:15 -0700962
963 if constexpr (WORLD_WRITABLE_KMSG) {
964 mknod("/dev/kmsg_debug", S_IFCHR | 0622, makedev(1, 11));
965 }
966
Evgenii Stepanov102daa32016-11-18 14:58:40 -0800967 mknod("/dev/random", S_IFCHR | 0666, makedev(1, 8));
968 mknod("/dev/urandom", S_IFCHR | 0666, makedev(1, 9));
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700969
Tom Cherry34e70412017-03-16 18:08:56 -0700970 // Now that tmpfs is mounted on /dev and we have /dev/kmsg, we can actually
971 // talk to the outside world...
972 InitKernelLogging(argv);
Elliott Hughesda40c002015-03-27 23:20:44 -0700973
Tom Cherry34e70412017-03-16 18:08:56 -0700974 LOG(INFO) << "init first stage started!";
Elliott Hughesda40c002015-03-27 23:20:44 -0700975
Bowgo Tsaid2620172017-04-17 22:17:09 +0800976 if (!DoFirstStageMount()) {
Sandeep Patil35403eb2017-02-08 20:27:12 -0800977 LOG(ERROR) << "Failed to mount required partitions early ...";
978 panic();
979 }
Wei Wang313b3522016-10-28 12:22:32 -0700980
Bowgo Tsaifd18a452017-04-24 18:36:25 +0800981 SetInitAvbVersionInRecovery();
982
Elliott Hughes9605a942016-11-10 17:43:47 -0800983 // Set up SELinux, loading the SELinux policy.
Wei Wang313b3522016-10-28 12:22:32 -0700984 selinux_initialize(true);
985
Elliott Hughes9605a942016-11-10 17:43:47 -0800986 // We're in the kernel domain, so re-exec init to transition to the init domain now
Wei Wang313b3522016-10-28 12:22:32 -0700987 // that the SELinux policy has been loaded.
Wei Wang313b3522016-10-28 12:22:32 -0700988 if (restorecon("/init") == -1) {
989 PLOG(ERROR) << "restorecon failed";
990 security_failure();
991 }
Elliott Hughes9605a942016-11-10 17:43:47 -0800992
993 setenv("INIT_SECOND_STAGE", "true", 1);
994
James Hawkins27c05222017-01-26 11:55:44 -0800995 static constexpr uint32_t kNanosecondsPerMillisecond = 1e6;
996 uint64_t start_ms = start_time.time_since_epoch().count() / kNanosecondsPerMillisecond;
997 setenv("INIT_STARTED_AT", StringPrintf("%" PRIu64, start_ms).c_str(), 1);
Elliott Hughes9605a942016-11-10 17:43:47 -0800998
Wei Wang313b3522016-10-28 12:22:32 -0700999 char* path = argv[0];
Elliott Hughes9605a942016-11-10 17:43:47 -08001000 char* args[] = { path, nullptr };
Tom Cherry34e70412017-03-16 18:08:56 -07001001 execv(path, args);
Vladimir Chtchetkine2b995432011-09-28 09:55:31 -07001002
Tom Cherry34e70412017-03-16 18:08:56 -07001003 // execv() only returns if an error happened, in which case we
1004 // panic and never fall through this conditional.
1005 PLOG(ERROR) << "execv(\"" << path << "\") failed";
1006 security_failure();
Elliott Hughesf65730e2015-04-24 18:38:17 +00001007 }
Elliott Hughes8d82ea02015-02-06 20:15:18 -08001008
Tom Cherry34e70412017-03-16 18:08:56 -07001009 // At this point we're in the second stage of init.
1010 InitKernelLogging(argv);
1011 LOG(INFO) << "init second stage started!";
1012
1013 // Indicate that booting is in progress to background fw loaders, etc.
1014 close(open("/dev/.booting", O_WRONLY | O_CREAT | O_CLOEXEC, 0000));
1015
1016 property_init();
1017
1018 // If arguments are passed both on the command line and in DT,
1019 // properties set in DT always have priority over the command-line ones.
1020 process_kernel_dt();
1021 process_kernel_cmdline();
1022
1023 // Propagate the kernel variables to internal variables
1024 // used by init as well as the current required properties.
1025 export_kernel_boot_props();
1026
1027 // Make the time that init started available for bootstat to log.
1028 property_set("ro.boottime.init", getenv("INIT_STARTED_AT"));
1029 property_set("ro.boottime.init.selinux", getenv("INIT_SELINUX_TOOK"));
1030
1031 // Set libavb version for Framework-only OTA match in Treble build.
Bowgo Tsai1a898c22017-04-13 21:17:48 +08001032 const char* avb_version = getenv("INIT_AVB_VERSION");
1033 if (avb_version) property_set("ro.boot.avb_version", avb_version);
Tom Cherry34e70412017-03-16 18:08:56 -07001034
1035 // Clean up our environment.
1036 unsetenv("INIT_SECOND_STAGE");
1037 unsetenv("INIT_STARTED_AT");
1038 unsetenv("INIT_SELINUX_TOOK");
Bowgo Tsai1a898c22017-04-13 21:17:48 +08001039 unsetenv("INIT_AVB_VERSION");
Tom Cherry34e70412017-03-16 18:08:56 -07001040
1041 // Now set up SELinux for second stage.
1042 selinux_initialize(false);
Sandeep Patil7ef60b42017-03-29 10:31:26 -07001043 selinux_restore_context();
Stephen Smalleye46f9d52012-01-13 08:48:47 -05001044
Elliott Hughes929f4072015-04-24 21:13:44 -07001045 epoll_fd = epoll_create1(EPOLL_CLOEXEC);
1046 if (epoll_fd == -1) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -07001047 PLOG(ERROR) << "epoll_create1 failed";
Elliott Hughes929f4072015-04-24 21:13:44 -07001048 exit(1);
1049 }
1050
1051 signal_handler_init();
Elliott Hughes9042cae2015-04-24 17:43:21 -07001052
Riley Andrewse4b7b292014-06-16 15:06:21 -07001053 property_load_boot_defaults();
Sami Tolvanen9e9efca2015-12-07 12:33:58 +00001054 export_oem_lock_status();
Elliott Hughesc6c26ed2015-04-24 18:50:30 -07001055 start_property_service();
Amit Pundird2e74db2016-06-29 19:00:00 +05301056 set_usb_controller();
Dima Zavind7634c92011-12-16 14:18:06 -08001057
Tom Cherryb7349902015-08-26 11:43:36 -07001058 const BuiltinFunctionMap function_map;
1059 Action::set_function_map(&function_map);
1060
1061 Parser& parser = Parser::GetInstance();
1062 parser.AddSectionParser("service",std::make_unique<ServiceParser>());
1063 parser.AddSectionParser("on", std::make_unique<ActionParser>());
1064 parser.AddSectionParser("import", std::make_unique<ImportParser>());
Tom Cherryccf23532017-03-28 16:40:41 -07001065 std::string bootscript = GetProperty("ro.boot.init_rc", "");
Hung-ying Tyan959aeb12017-01-18 09:39:36 +08001066 if (bootscript.empty()) {
1067 parser.ParseConfig("/init.rc");
Jaekyun Seok4ec72cc2017-02-22 20:37:57 +09001068 parser.set_is_system_etc_init_loaded(
1069 parser.ParseConfig("/system/etc/init"));
1070 parser.set_is_vendor_etc_init_loaded(
1071 parser.ParseConfig("/vendor/etc/init"));
1072 parser.set_is_odm_etc_init_loaded(parser.ParseConfig("/odm/etc/init"));
Hung-ying Tyan959aeb12017-01-18 09:39:36 +08001073 } else {
1074 parser.ParseConfig(bootscript);
Jaekyun Seok4ec72cc2017-02-22 20:37:57 +09001075 parser.set_is_system_etc_init_loaded(true);
1076 parser.set_is_vendor_etc_init_loaded(true);
1077 parser.set_is_odm_etc_init_loaded(true);
Hung-ying Tyan959aeb12017-01-18 09:39:36 +08001078 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001079
Tom Cherryd8a72572017-03-13 12:24:49 -07001080 // Turning this on and letting the INFO logging be discarded adds 0.2s to
1081 // Nexus 9 boot time, so it's disabled by default.
1082 if (false) parser.DumpState();
1083
Tom Cherryfa0c21c2015-07-23 17:53:11 -07001084 ActionManager& am = ActionManager::GetInstance();
1085
1086 am.QueueEventTrigger("early-init");
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001087
Elliott Hughesc6c26ed2015-04-24 18:50:30 -07001088 // Queue an action that waits for coldboot done so we know ueventd has set up all of /dev...
Tom Cherryfa0c21c2015-07-23 17:53:11 -07001089 am.QueueBuiltinAction(wait_for_coldboot_done_action, "wait_for_coldboot_done");
Elliott Hughesc6c26ed2015-04-24 18:50:30 -07001090 // ... so that we can start queuing up actions that require stuff from /dev.
Tom Cherryfa0c21c2015-07-23 17:53:11 -07001091 am.QueueBuiltinAction(mix_hwrng_into_linux_rng_action, "mix_hwrng_into_linux_rng");
Daniel Cashmanbaccc402016-03-25 23:49:05 +00001092 am.QueueBuiltinAction(set_mmap_rnd_bits_action, "set_mmap_rnd_bits");
Dave Weinstein44f7e4f2017-01-19 18:03:34 -08001093 am.QueueBuiltinAction(set_kptr_restrict_action, "set_kptr_restrict");
Tom Cherryfa0c21c2015-07-23 17:53:11 -07001094 am.QueueBuiltinAction(keychord_init_action, "keychord_init");
1095 am.QueueBuiltinAction(console_init_action, "console_init");
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001096
Elliott Hughesda40c002015-03-27 23:20:44 -07001097 // Trigger all the boot actions to get us started.
Tom Cherryfa0c21c2015-07-23 17:53:11 -07001098 am.QueueEventTrigger("init");
Dima Zavinca47cef2011-08-24 15:28:23 -07001099
Elliott Hughes8d82ea02015-02-06 20:15:18 -08001100 // Repeat mix_hwrng_into_linux_rng in case /dev/hw_random or /dev/random
1101 // wasn't ready immediately after wait_for_coldboot_done
Tom Cherryfa0c21c2015-07-23 17:53:11 -07001102 am.QueueBuiltinAction(mix_hwrng_into_linux_rng_action, "mix_hwrng_into_linux_rng");
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001103
Elliott Hughes8d82ea02015-02-06 20:15:18 -08001104 // Don't mount filesystems or start core system services in charger mode.
Tom Cherryccf23532017-03-28 16:40:41 -07001105 std::string bootmode = GetProperty("ro.bootmode", "");
Yabin Cui74edcea2015-07-24 10:11:05 -07001106 if (bootmode == "charger") {
Tom Cherryfa0c21c2015-07-23 17:53:11 -07001107 am.QueueEventTrigger("charger");
Dima Zavinca47cef2011-08-24 15:28:23 -07001108 } else {
Tom Cherryfa0c21c2015-07-23 17:53:11 -07001109 am.QueueEventTrigger("late-init");
Dima Zavinca47cef2011-08-24 15:28:23 -07001110 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001111
Elliott Hughes8d82ea02015-02-06 20:15:18 -08001112 // Run all property triggers based on current state of the properties.
Tom Cherryfa0c21c2015-07-23 17:53:11 -07001113 am.QueueBuiltinAction(queue_property_triggers_action, "queue_property_triggers");
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001114
Elliott Hughesc6c26ed2015-04-24 18:50:30 -07001115 while (true) {
Elliott Hughes9605a942016-11-10 17:43:47 -08001116 // By default, sleep until something happens.
1117 int epoll_timeout_ms = -1;
1118
Tom Cherryb27004a2017-03-27 16:27:30 -07001119 if (!(waiting_for_prop || ServiceManager::GetInstance().IsWaitingForExec())) {
Tom Cherry77ddcd52017-03-23 16:54:38 -07001120 am.ExecuteOneCommand();
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001121 }
Tom Cherryb27004a2017-03-27 16:27:30 -07001122 if (!(waiting_for_prop || ServiceManager::GetInstance().IsWaitingForExec())) {
Tom Cherry77ddcd52017-03-23 16:54:38 -07001123 restart_processes();
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001124
Tom Cherry77ddcd52017-03-23 16:54:38 -07001125 // If there's a process that needs restarting, wake up in time for that.
1126 if (process_needs_restart_at != 0) {
1127 epoll_timeout_ms = (process_needs_restart_at - time(nullptr)) * 1000;
1128 if (epoll_timeout_ms < 0) epoll_timeout_ms = 0;
1129 }
1130
1131 // If there's more work to do, wake up again immediately.
1132 if (am.HasMoreCommands()) epoll_timeout_ms = 0;
1133 }
Wei Wang16db4342016-11-30 15:43:42 -08001134
Elliott Hughes929f4072015-04-24 21:13:44 -07001135 epoll_event ev;
Elliott Hughes9605a942016-11-10 17:43:47 -08001136 int nr = TEMP_FAILURE_RETRY(epoll_wait(epoll_fd, &ev, 1, epoll_timeout_ms));
Elliott Hughes929f4072015-04-24 21:13:44 -07001137 if (nr == -1) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -07001138 PLOG(ERROR) << "epoll_wait failed";
Elliott Hughes929f4072015-04-24 21:13:44 -07001139 } else if (nr == 1) {
1140 ((void (*)()) ev.data.ptr)();
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001141 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001142 }
1143
1144 return 0;
1145}