1/*
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
17#include "init.h"
18
19#include <ctype.h>
20#include <dirent.h>
21#include <errno.h>
22#include <fcntl.h>
23#include <inttypes.h>
24#include <libgen.h>
25#include <paths.h>
26#include <signal.h>
27#include <stdarg.h>
28#include <stdio.h>
29#include <stdlib.h>
30#include <string.h>
31#include <sys/epoll.h>
32#include <sys/mount.h>
33#include <sys/socket.h>
34#include <sys/stat.h>
35#include <sys/sysmacros.h>
36#include <sys/types.h>
37#include <sys/un.h>
38#include <sys/wait.h>
39#include <unistd.h>
40
41#include <android-base/chrono_utils.h>
42#include <android-base/file.h>
43#include <android-base/logging.h>
44#include <android-base/properties.h>
45#include <android-base/strings.h>
46#include <android-base/unique_fd.h>
47#include <keyutils.h>
48#include <libavb/libavb.h>
49#include <private/android_filesystem_config.h>
50#include <selinux/android.h>
51#include <selinux/selinux.h>
52
53#include <fstream>
54#include <memory>
55#include <vector>
56
57#include "action.h"
58#include "bootchart.h"
59#include "import_parser.h"
60#include "init_first_stage.h"
61#include "init_parser.h"
62#include "keychords.h"
63#include "log.h"
64#include "property_service.h"
65#include "reboot.h"
66#include "service.h"
67#include "signal_handler.h"
68#include "ueventd.h"
69#include "util.h"
70#include "watchdogd.h"
71
72using namespace std::string_literals;
73
74using android::base::boot_clock;
75using android::base::GetProperty;
76using android::base::Timer;
77
78namespace android {
79namespace init {
80
81struct selabel_handle *sehandle;
82struct selabel_handle *sehandle_prop;
83
84static int property_triggers_enabled = 0;
85
86static char qemu[32];
87
88std::string default_console = "/dev/console";
89static time_t process_needs_restart_at;
90
91const char *ENV[32];
92
93static int epoll_fd = -1;
94
95static std::unique_ptr<Timer> waiting_for_prop(nullptr);
96static std::string wait_prop_name;
97static std::string wait_prop_value;
98static bool shutting_down;
99static std::string shutdown_command;
100static bool do_shutdown = false;
101
102void DumpState() {
103    ServiceManager::GetInstance().DumpState();
104    ActionManager::GetInstance().DumpState();
105}
106
107void register_epoll_handler(int fd, void (*fn)()) {
108    epoll_event ev;
109    ev.events = EPOLLIN;
110    ev.data.ptr = reinterpret_cast<void*>(fn);
111    if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) {
112        PLOG(ERROR) << "epoll_ctl failed";
113    }
114}
115
116/* add_environment - add "key=value" to the current environment */
117int add_environment(const char *key, const char *val)
118{
119    size_t n;
120    size_t key_len = strlen(key);
121
122    /* The last environment entry is reserved to terminate the list */
123    for (n = 0; n < (arraysize(ENV) - 1); n++) {
124
125        /* Delete any existing entry for this key */
126        if (ENV[n] != NULL) {
127            size_t entry_key_len = strcspn(ENV[n], "=");
128            if ((entry_key_len == key_len) && (strncmp(ENV[n], key, entry_key_len) == 0)) {
129                free((char*)ENV[n]);
130                ENV[n] = NULL;
131            }
132        }
133
134        /* Add entry if a free slot is available */
135        if (ENV[n] == NULL) {
136            char* entry;
137            asprintf(&entry, "%s=%s", key, val);
138            ENV[n] = entry;
139            return 0;
140        }
141    }
142
143    LOG(ERROR) << "No env. room to store: '" << key << "':'" << val << "'";
144
145    return -1;
146}
147
148bool start_waiting_for_property(const char *name, const char *value)
149{
150    if (waiting_for_prop) {
151        return false;
152    }
153    if (GetProperty(name, "") != value) {
154        // Current property value is not equal to expected value
155        wait_prop_name = name;
156        wait_prop_value = value;
157        waiting_for_prop.reset(new Timer());
158    } else {
159        LOG(INFO) << "start_waiting_for_property(\""
160                  << name << "\", \"" << value << "\"): already set";
161    }
162    return true;
163}
164
165void ResetWaitForProp() {
166    wait_prop_name.clear();
167    wait_prop_value.clear();
168    waiting_for_prop.reset();
169}
170
171void property_changed(const std::string& name, const std::string& value) {
172    // If the property is sys.powerctl, we bypass the event queue and immediately handle it.
173    // This is to ensure that init will always and immediately shutdown/reboot, regardless of
174    // if there are other pending events to process or if init is waiting on an exec service or
175    // waiting on a property.
176    // In non-thermal-shutdown case, 'shutdown' trigger will be fired to let device specific
177    // commands to be executed.
178    if (name == "sys.powerctl") {
179        // Despite the above comment, we can't call HandlePowerctlMessage() in this function,
180        // because it modifies the contents of the action queue, which can cause the action queue
181        // to get into a bad state if this function is called from a command being executed by the
182        // action queue.  Instead we set this flag and ensure that shutdown happens before the next
183        // command is run in the main init loop.
184        // TODO: once property service is removed from init, this will never happen from a builtin,
185        // but rather from a callback from the property service socket, in which case this hack can
186        // go away.
187        shutdown_command = value;
188        do_shutdown = true;
189    }
190
191    if (property_triggers_enabled) ActionManager::GetInstance().QueuePropertyChange(name, value);
192
193    if (waiting_for_prop) {
194        if (wait_prop_name == name && wait_prop_value == value) {
195            LOG(INFO) << "Wait for property took " << *waiting_for_prop;
196            ResetWaitForProp();
197        }
198    }
199}
200
201static void restart_processes()
202{
203    process_needs_restart_at = 0;
204    ServiceManager::GetInstance().ForEachServiceWithFlags(SVC_RESTARTING, [](Service* s) {
205        s->RestartIfNeeded(&process_needs_restart_at);
206    });
207}
208
209void handle_control_message(const std::string& msg, const std::string& name) {
210    Service* svc = ServiceManager::GetInstance().FindServiceByName(name);
211    if (svc == nullptr) {
212        LOG(ERROR) << "no such service '" << name << "'";
213        return;
214    }
215
216    if (msg == "start") {
217        svc->Start();
218    } else if (msg == "stop") {
219        svc->Stop();
220    } else if (msg == "restart") {
221        svc->Restart();
222    } else {
223        LOG(ERROR) << "unknown control msg '" << msg << "'";
224    }
225}
226
227static int wait_for_coldboot_done_action(const std::vector<std::string>& args) {
228    Timer t;
229
230    LOG(VERBOSE) << "Waiting for " COLDBOOT_DONE "...";
231
232    // Historically we had a 1s timeout here because we weren't otherwise
233    // tracking boot time, and many OEMs made their sepolicy regular
234    // expressions too expensive (http://b/19899875).
235
236    // Now we're tracking boot time, just log the time taken to a system
237    // property. We still panic if it takes more than a minute though,
238    // because any build that slow isn't likely to boot at all, and we'd
239    // rather any test lab devices fail back to the bootloader.
240    if (wait_for_file(COLDBOOT_DONE, 60s) < 0) {
241        LOG(ERROR) << "Timed out waiting for " COLDBOOT_DONE;
242        panic();
243    }
244
245    property_set("ro.boottime.init.cold_boot_wait", std::to_string(t.duration().count()));
246    return 0;
247}
248
249/*
250 * Writes 512 bytes of output from Hardware RNG (/dev/hw_random, backed
251 * by Linux kernel's hw_random framework) into Linux RNG's via /dev/urandom.
252 * Does nothing if Hardware RNG is not present.
253 *
254 * Since we don't yet trust the quality of Hardware RNG, these bytes are not
255 * mixed into the primary pool of Linux RNG and the entropy estimate is left
256 * unmodified.
257 *
258 * If the HW RNG device /dev/hw_random is present, we require that at least
259 * 512 bytes read from it are written into Linux RNG. QA is expected to catch
260 * devices/configurations where these I/O operations are blocking for a long
261 * time. We do not reboot or halt on failures, as this is a best-effort
262 * attempt.
263 */
264static int mix_hwrng_into_linux_rng_action(const std::vector<std::string>& args)
265{
266    int result = -1;
267    int hwrandom_fd = -1;
268    int urandom_fd = -1;
269    char buf[512];
270    ssize_t chunk_size;
271    size_t total_bytes_written = 0;
272
273    hwrandom_fd = TEMP_FAILURE_RETRY(
274            open("/dev/hw_random", O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
275    if (hwrandom_fd == -1) {
276        if (errno == ENOENT) {
277            LOG(ERROR) << "/dev/hw_random not found";
278            // It's not an error to not have a Hardware RNG.
279            result = 0;
280        } else {
281            PLOG(ERROR) << "Failed to open /dev/hw_random";
282        }
283        goto ret;
284    }
285
286    urandom_fd = TEMP_FAILURE_RETRY(
287            open("/dev/urandom", O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
288    if (urandom_fd == -1) {
289        PLOG(ERROR) << "Failed to open /dev/urandom";
290        goto ret;
291    }
292
293    while (total_bytes_written < sizeof(buf)) {
294        chunk_size = TEMP_FAILURE_RETRY(
295                read(hwrandom_fd, buf, sizeof(buf) - total_bytes_written));
296        if (chunk_size == -1) {
297            PLOG(ERROR) << "Failed to read from /dev/hw_random";
298            goto ret;
299        } else if (chunk_size == 0) {
300            LOG(ERROR) << "Failed to read from /dev/hw_random: EOF";
301            goto ret;
302        }
303
304        chunk_size = TEMP_FAILURE_RETRY(write(urandom_fd, buf, chunk_size));
305        if (chunk_size == -1) {
306            PLOG(ERROR) << "Failed to write to /dev/urandom";
307            goto ret;
308        }
309        total_bytes_written += chunk_size;
310    }
311
312    LOG(INFO) << "Mixed " << total_bytes_written << " bytes from /dev/hw_random into /dev/urandom";
313    result = 0;
314
315ret:
316    if (hwrandom_fd != -1) {
317        close(hwrandom_fd);
318    }
319    if (urandom_fd != -1) {
320        close(urandom_fd);
321    }
322    return result;
323}
324
325static void security_failure() {
326    LOG(ERROR) << "Security failure...";
327    panic();
328}
329
330static bool set_highest_available_option_value(std::string path, int min, int max)
331{
332    std::ifstream inf(path, std::fstream::in);
333    if (!inf) {
334        LOG(ERROR) << "Cannot open for reading: " << path;
335        return false;
336    }
337
338    int current = max;
339    while (current >= min) {
340        // try to write out new value
341        std::string str_val = std::to_string(current);
342        std::ofstream of(path, std::fstream::out);
343        if (!of) {
344            LOG(ERROR) << "Cannot open for writing: " << path;
345            return false;
346        }
347        of << str_val << std::endl;
348        of.close();
349
350        // check to make sure it was recorded
351        inf.seekg(0);
352        std::string str_rec;
353        inf >> str_rec;
354        if (str_val.compare(str_rec) == 0) {
355            break;
356        }
357        current--;
358    }
359    inf.close();
360
361    if (current < min) {
362        LOG(ERROR) << "Unable to set minimum option value " << min << " in " << path;
363        return false;
364    }
365    return true;
366}
367
368#define MMAP_RND_PATH "/proc/sys/vm/mmap_rnd_bits"
369#define MMAP_RND_COMPAT_PATH "/proc/sys/vm/mmap_rnd_compat_bits"
370
371/* __attribute__((unused)) due to lack of mips support: see mips block
372 * in set_mmap_rnd_bits_action */
373static bool __attribute__((unused)) set_mmap_rnd_bits_min(int start, int min, bool compat) {
374    std::string path;
375    if (compat) {
376        path = MMAP_RND_COMPAT_PATH;
377    } else {
378        path = MMAP_RND_PATH;
379    }
380
381    return set_highest_available_option_value(path, min, start);
382}
383
384/*
385 * Set /proc/sys/vm/mmap_rnd_bits and potentially
386 * /proc/sys/vm/mmap_rnd_compat_bits to the maximum supported values.
387 * Returns -1 if unable to set these to an acceptable value.
388 *
389 * To support this sysctl, the following upstream commits are needed:
390 *
391 * d07e22597d1d mm: mmap: add new /proc tunable for mmap_base ASLR
392 * e0c25d958f78 arm: mm: support ARCH_MMAP_RND_BITS
393 * 8f0d3aa9de57 arm64: mm: support ARCH_MMAP_RND_BITS
394 * 9e08f57d684a x86: mm: support ARCH_MMAP_RND_BITS
395 * ec9ee4acd97c drivers: char: random: add get_random_long()
396 * 5ef11c35ce86 mm: ASLR: use get_random_long()
397 */
398static int set_mmap_rnd_bits_action(const std::vector<std::string>& args)
399{
400    int ret = -1;
401
402    /* values are arch-dependent */
403#if defined(USER_MODE_LINUX)
404    /* uml does not support mmap_rnd_bits */
405    ret = 0;
406#elif defined(__aarch64__)
407    /* arm64 supports 18 - 33 bits depending on pagesize and VA_SIZE */
408    if (set_mmap_rnd_bits_min(33, 24, false)
409            && set_mmap_rnd_bits_min(16, 16, true)) {
410        ret = 0;
411    }
412#elif defined(__x86_64__)
413    /* x86_64 supports 28 - 32 bits */
414    if (set_mmap_rnd_bits_min(32, 32, false)
415            && set_mmap_rnd_bits_min(16, 16, true)) {
416        ret = 0;
417    }
418#elif defined(__arm__) || defined(__i386__)
419    /* check to see if we're running on 64-bit kernel */
420    bool h64 = !access(MMAP_RND_COMPAT_PATH, F_OK);
421    /* supported 32-bit architecture must have 16 bits set */
422    if (set_mmap_rnd_bits_min(16, 16, h64)) {
423        ret = 0;
424    }
425#elif defined(__mips__) || defined(__mips64__)
426    // TODO: add mips support b/27788820
427    ret = 0;
428#else
429    LOG(ERROR) << "Unknown architecture";
430#endif
431
432    if (ret == -1) {
433        LOG(ERROR) << "Unable to set adequate mmap entropy value!";
434        security_failure();
435    }
436    return ret;
437}
438
439#define KPTR_RESTRICT_PATH "/proc/sys/kernel/kptr_restrict"
440#define KPTR_RESTRICT_MINVALUE 2
441#define KPTR_RESTRICT_MAXVALUE 4
442
443/* Set kptr_restrict to the highest available level.
444 *
445 * Aborts if unable to set this to an acceptable value.
446 */
447static int set_kptr_restrict_action(const std::vector<std::string>& args)
448{
449    std::string path = KPTR_RESTRICT_PATH;
450
451    if (!set_highest_available_option_value(path, KPTR_RESTRICT_MINVALUE, KPTR_RESTRICT_MAXVALUE)) {
452        LOG(ERROR) << "Unable to set adequate kptr_restrict value!";
453        security_failure();
454    }
455    return 0;
456}
457
458static int keychord_init_action(const std::vector<std::string>& args)
459{
460    keychord_init();
461    return 0;
462}
463
464static int console_init_action(const std::vector<std::string>& args)
465{
466    std::string console = GetProperty("ro.boot.console", "");
467    if (!console.empty()) {
468        default_console = "/dev/" + console;
469    }
470    return 0;
471}
472
473static void import_kernel_nv(const std::string& key, const std::string& value, bool for_emulator) {
474    if (key.empty()) return;
475
476    if (for_emulator) {
477        // In the emulator, export any kernel option with the "ro.kernel." prefix.
478        property_set("ro.kernel." + key, value);
479        return;
480    }
481
482    if (key == "qemu") {
483        strlcpy(qemu, value.c_str(), sizeof(qemu));
484    } else if (android::base::StartsWith(key, "androidboot.")) {
485        property_set("ro.boot." + key.substr(12), value);
486    }
487}
488
489static void export_oem_lock_status() {
490    if (!android::base::GetBoolProperty("ro.oem_unlock_supported", false)) {
491        return;
492    }
493
494    std::string value = GetProperty("ro.boot.verifiedbootstate", "");
495
496    if (!value.empty()) {
497        property_set("ro.boot.flash.locked", value == "orange" ? "0" : "1");
498    }
499}
500
501static void export_kernel_boot_props() {
502    struct {
503        const char *src_prop;
504        const char *dst_prop;
505        const char *default_value;
506    } prop_map[] = {
507        { "ro.boot.serialno",   "ro.serialno",   "", },
508        { "ro.boot.mode",       "ro.bootmode",   "unknown", },
509        { "ro.boot.baseband",   "ro.baseband",   "unknown", },
510        { "ro.boot.bootloader", "ro.bootloader", "unknown", },
511        { "ro.boot.hardware",   "ro.hardware",   "unknown", },
512        { "ro.boot.revision",   "ro.revision",   "0", },
513    };
514    for (size_t i = 0; i < arraysize(prop_map); i++) {
515        std::string value = GetProperty(prop_map[i].src_prop, "");
516        property_set(prop_map[i].dst_prop, (!value.empty()) ? value : prop_map[i].default_value);
517    }
518}
519
520static void process_kernel_dt() {
521    if (!is_android_dt_value_expected("compatible", "android,firmware")) {
522        return;
523    }
524
525    std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(get_android_dt_dir().c_str()), closedir);
526    if (!dir) return;
527
528    std::string dt_file;
529    struct dirent *dp;
530    while ((dp = readdir(dir.get())) != NULL) {
531        if (dp->d_type != DT_REG || !strcmp(dp->d_name, "compatible") || !strcmp(dp->d_name, "name")) {
532            continue;
533        }
534
535        std::string file_name = get_android_dt_dir() + dp->d_name;
536
537        android::base::ReadFileToString(file_name, &dt_file);
538        std::replace(dt_file.begin(), dt_file.end(), ',', '.');
539
540        property_set("ro.boot."s + dp->d_name, dt_file);
541    }
542}
543
544static void process_kernel_cmdline() {
545    // The first pass does the common stuff, and finds if we are in qemu.
546    // The second pass is only necessary for qemu to export all kernel params
547    // as properties.
548    import_kernel_cmdline(false, import_kernel_nv);
549    if (qemu[0]) import_kernel_cmdline(true, import_kernel_nv);
550}
551
552static int property_enable_triggers_action(const std::vector<std::string>& args)
553{
554    /* Enable property triggers. */
555    property_triggers_enabled = 1;
556    return 0;
557}
558
559static int queue_property_triggers_action(const std::vector<std::string>& args)
560{
561    ActionManager::GetInstance().QueueBuiltinAction(property_enable_triggers_action, "enable_property_trigger");
562    ActionManager::GetInstance().QueueAllPropertyActions();
563    return 0;
564}
565
566static void selinux_init_all_handles(void)
567{
568    sehandle = selinux_android_file_context_handle();
569    selinux_android_set_sehandle(sehandle);
570    sehandle_prop = selinux_android_prop_context_handle();
571}
572
573enum selinux_enforcing_status { SELINUX_PERMISSIVE, SELINUX_ENFORCING };
574
575static selinux_enforcing_status selinux_status_from_cmdline() {
576    selinux_enforcing_status status = SELINUX_ENFORCING;
577
578    import_kernel_cmdline(false, [&](const std::string& key, const std::string& value, bool in_qemu) {
579        if (key == "androidboot.selinux" && value == "permissive") {
580            status = SELINUX_PERMISSIVE;
581        }
582    });
583
584    return status;
585}
586
587static bool selinux_is_enforcing(void)
588{
589    if (ALLOW_PERMISSIVE_SELINUX) {
590        return selinux_status_from_cmdline() == SELINUX_ENFORCING;
591    }
592    return true;
593}
594
595static int audit_callback(void *data, security_class_t /*cls*/, char *buf, size_t len) {
596
597    property_audit_data *d = reinterpret_cast<property_audit_data*>(data);
598
599    if (!d || !d->name || !d->cr) {
600        LOG(ERROR) << "audit_callback invoked with null data arguments!";
601        return 0;
602    }
603
604    snprintf(buf, len, "property=%s pid=%d uid=%d gid=%d", d->name,
605            d->cr->pid, d->cr->uid, d->cr->gid);
606    return 0;
607}
608
609/*
610 * Forks, executes the provided program in the child, and waits for the completion in the parent.
611 * Child's stderr is captured and logged using LOG(ERROR).
612 *
613 * Returns true if the child exited with status code 0, returns false otherwise.
614 */
615static bool fork_execve_and_wait_for_completion(const char* filename, char* const argv[],
616                                                char* const envp[]) {
617    // Create a pipe used for redirecting child process's output.
618    // * pipe_fds[0] is the FD the parent will use for reading.
619    // * pipe_fds[1] is the FD the child will use for writing.
620    int pipe_fds[2];
621    if (pipe(pipe_fds) == -1) {
622        PLOG(ERROR) << "Failed to create pipe";
623        return false;
624    }
625
626    pid_t child_pid = fork();
627    if (child_pid == -1) {
628        PLOG(ERROR) << "Failed to fork for " << filename;
629        return false;
630    }
631
632    if (child_pid == 0) {
633        // fork succeeded -- this is executing in the child process
634
635        // Close the pipe FD not used by this process
636        TEMP_FAILURE_RETRY(close(pipe_fds[0]));
637
638        // Redirect stderr to the pipe FD provided by the parent
639        if (TEMP_FAILURE_RETRY(dup2(pipe_fds[1], STDERR_FILENO)) == -1) {
640            PLOG(ERROR) << "Failed to redirect stderr of " << filename;
641            _exit(127);
642            return false;
643        }
644        TEMP_FAILURE_RETRY(close(pipe_fds[1]));
645
646        if (execve(filename, argv, envp) == -1) {
647            PLOG(ERROR) << "Failed to execve " << filename;
648            return false;
649        }
650        // Unreachable because execve will have succeeded and replaced this code
651        // with child process's code.
652        _exit(127);
653        return false;
654    } else {
655        // fork succeeded -- this is executing in the original/parent process
656
657        // Close the pipe FD not used by this process
658        TEMP_FAILURE_RETRY(close(pipe_fds[1]));
659
660        // Log the redirected output of the child process.
661        // It's unfortunate that there's no standard way to obtain an istream for a file descriptor.
662        // As a result, we're buffering all output and logging it in one go at the end of the
663        // invocation, instead of logging it as it comes in.
664        const int child_out_fd = pipe_fds[0];
665        std::string child_output;
666        if (!android::base::ReadFdToString(child_out_fd, &child_output)) {
667            PLOG(ERROR) << "Failed to capture full output of " << filename;
668        }
669        TEMP_FAILURE_RETRY(close(child_out_fd));
670        if (!child_output.empty()) {
671            // Log captured output, line by line, because LOG expects to be invoked for each line
672            std::istringstream in(child_output);
673            std::string line;
674            while (std::getline(in, line)) {
675                LOG(ERROR) << filename << ": " << line;
676            }
677        }
678
679        // Wait for child to terminate
680        int status;
681        if (TEMP_FAILURE_RETRY(waitpid(child_pid, &status, 0)) != child_pid) {
682            PLOG(ERROR) << "Failed to wait for " << filename;
683            return false;
684        }
685
686        if (WIFEXITED(status)) {
687            int status_code = WEXITSTATUS(status);
688            if (status_code == 0) {
689                return true;
690            } else {
691                LOG(ERROR) << filename << " exited with status " << status_code;
692            }
693        } else if (WIFSIGNALED(status)) {
694            LOG(ERROR) << filename << " killed by signal " << WTERMSIG(status);
695        } else if (WIFSTOPPED(status)) {
696            LOG(ERROR) << filename << " stopped by signal " << WSTOPSIG(status);
697        } else {
698            LOG(ERROR) << "waitpid for " << filename << " returned unexpected status: " << status;
699        }
700
701        return false;
702    }
703}
704
705static bool read_first_line(const char* file, std::string* line) {
706    line->clear();
707
708    std::string contents;
709    if (!android::base::ReadFileToString(file, &contents, true /* follow symlinks */)) {
710        return false;
711    }
712    std::istringstream in(contents);
713    std::getline(in, *line);
714    return true;
715}
716
717static bool selinux_find_precompiled_split_policy(std::string* file) {
718    file->clear();
719
720    static constexpr const char precompiled_sepolicy[] = "/vendor/etc/selinux/precompiled_sepolicy";
721    if (access(precompiled_sepolicy, R_OK) == -1) {
722        return false;
723    }
724    std::string actual_plat_id;
725    if (!read_first_line("/system/etc/selinux/plat_and_mapping_sepolicy.cil.sha256",
726                         &actual_plat_id)) {
727        PLOG(INFO) << "Failed to read "
728                      "/system/etc/selinux/plat_and_mapping_sepolicy.cil.sha256";
729        return false;
730    }
731    std::string precompiled_plat_id;
732    if (!read_first_line("/vendor/etc/selinux/precompiled_sepolicy.plat_and_mapping.sha256",
733                         &precompiled_plat_id)) {
734        PLOG(INFO) << "Failed to read "
735                      "/vendor/etc/selinux/"
736                      "precompiled_sepolicy.plat_and_mapping.sha256";
737        return false;
738    }
739    if ((actual_plat_id.empty()) || (actual_plat_id != precompiled_plat_id)) {
740        return false;
741    }
742
743    *file = precompiled_sepolicy;
744    return true;
745}
746
747static bool selinux_get_vendor_mapping_version(std::string* plat_vers) {
748    if (!read_first_line("/vendor/etc/selinux/plat_sepolicy_vers.txt", plat_vers)) {
749        PLOG(ERROR) << "Failed to read /vendor/etc/selinux/plat_sepolicy_vers.txt";
750        return false;
751    }
752    if (plat_vers->empty()) {
753        LOG(ERROR) << "No version present in plat_sepolicy_vers.txt";
754        return false;
755    }
756    return true;
757}
758
759static constexpr const char plat_policy_cil_file[] = "/system/etc/selinux/plat_sepolicy.cil";
760
761static bool selinux_is_split_policy_device() { return access(plat_policy_cil_file, R_OK) != -1; }
762
763/*
764 * Loads SELinux policy split across platform/system and non-platform/vendor files.
765 *
766 * Returns true upon success, false otherwise (failure cause is logged).
767 */
768static bool selinux_load_split_policy() {
769    // IMPLEMENTATION NOTE: Split policy consists of three CIL files:
770    // * platform -- policy needed due to logic contained in the system image,
771    // * non-platform -- policy needed due to logic contained in the vendor image,
772    // * mapping -- mapping policy which helps preserve forward-compatibility of non-platform policy
773    //   with newer versions of platform policy.
774    //
775    // secilc is invoked to compile the above three policy files into a single monolithic policy
776    // file. This file is then loaded into the kernel.
777
778    // Load precompiled policy from vendor image, if a matching policy is found there. The policy
779    // must match the platform policy on the system image.
780    std::string precompiled_sepolicy_file;
781    if (selinux_find_precompiled_split_policy(&precompiled_sepolicy_file)) {
782        android::base::unique_fd fd(
783            open(precompiled_sepolicy_file.c_str(), O_RDONLY | O_CLOEXEC | O_BINARY));
784        if (fd != -1) {
785            if (selinux_android_load_policy_from_fd(fd, precompiled_sepolicy_file.c_str()) < 0) {
786                LOG(ERROR) << "Failed to load SELinux policy from " << precompiled_sepolicy_file;
787                return false;
788            }
789            return true;
790        }
791    }
792    // No suitable precompiled policy could be loaded
793
794    LOG(INFO) << "Compiling SELinux policy";
795
796    // Determine the highest policy language version supported by the kernel
797    set_selinuxmnt("/sys/fs/selinux");
798    int max_policy_version = security_policyvers();
799    if (max_policy_version == -1) {
800        PLOG(ERROR) << "Failed to determine highest policy version supported by kernel";
801        return false;
802    }
803
804    // We store the output of the compilation on /dev because this is the most convenient tmpfs
805    // storage mount available this early in the boot sequence.
806    char compiled_sepolicy[] = "/dev/sepolicy.XXXXXX";
807    android::base::unique_fd compiled_sepolicy_fd(mkostemp(compiled_sepolicy, O_CLOEXEC));
808    if (compiled_sepolicy_fd < 0) {
809        PLOG(ERROR) << "Failed to create temporary file " << compiled_sepolicy;
810        return false;
811    }
812
813    // Determine which mapping file to include
814    std::string vend_plat_vers;
815    if (!selinux_get_vendor_mapping_version(&vend_plat_vers)) {
816        return false;
817    }
818    std::string mapping_file("/system/etc/selinux/mapping/" + vend_plat_vers + ".cil");
819    const std::string version_as_string = std::to_string(max_policy_version);
820
821    // clang-format off
822    const char* compile_args[] = {
823        "/system/bin/secilc",
824        plat_policy_cil_file,
825        "-M", "true", "-G", "-N",
826        // Target the highest policy language version supported by the kernel
827        "-c", version_as_string.c_str(),
828        mapping_file.c_str(),
829        "/vendor/etc/selinux/nonplat_sepolicy.cil",
830        "-o", compiled_sepolicy,
831        // We don't care about file_contexts output by the compiler
832        "-f", "/sys/fs/selinux/null",  // /dev/null is not yet available
833        nullptr};
834    // clang-format on
835
836    if (!fork_execve_and_wait_for_completion(compile_args[0], (char**)compile_args, (char**)ENV)) {
837        unlink(compiled_sepolicy);
838        return false;
839    }
840    unlink(compiled_sepolicy);
841
842    LOG(INFO) << "Loading compiled SELinux policy";
843    if (selinux_android_load_policy_from_fd(compiled_sepolicy_fd, compiled_sepolicy) < 0) {
844        LOG(ERROR) << "Failed to load SELinux policy from " << compiled_sepolicy;
845        return false;
846    }
847
848    return true;
849}
850
851/*
852 * Loads SELinux policy from a monolithic file.
853 *
854 * Returns true upon success, false otherwise (failure cause is logged).
855 */
856static bool selinux_load_monolithic_policy() {
857    LOG(VERBOSE) << "Loading SELinux policy from monolithic file";
858    if (selinux_android_load_policy() < 0) {
859        PLOG(ERROR) << "Failed to load monolithic SELinux policy";
860        return false;
861    }
862    return true;
863}
864
865/*
866 * Loads SELinux policy into the kernel.
867 *
868 * Returns true upon success, false otherwise (failure cause is logged).
869 */
870static bool selinux_load_policy() {
871    return selinux_is_split_policy_device() ? selinux_load_split_policy()
872                                            : selinux_load_monolithic_policy();
873}
874
875static void selinux_initialize(bool in_kernel_domain) {
876    Timer t;
877
878    selinux_callback cb;
879    cb.func_log = selinux_klog_callback;
880    selinux_set_callback(SELINUX_CB_LOG, cb);
881    cb.func_audit = audit_callback;
882    selinux_set_callback(SELINUX_CB_AUDIT, cb);
883
884    if (in_kernel_domain) {
885        LOG(INFO) << "Loading SELinux policy";
886        if (!selinux_load_policy()) {
887            panic();
888        }
889
890        bool kernel_enforcing = (security_getenforce() == 1);
891        bool is_enforcing = selinux_is_enforcing();
892        if (kernel_enforcing != is_enforcing) {
893            if (security_setenforce(is_enforcing)) {
894                PLOG(ERROR) << "security_setenforce(%s) failed" << (is_enforcing ? "true" : "false");
895                security_failure();
896            }
897        }
898
899        std::string err;
900        if (!WriteFile("/sys/fs/selinux/checkreqprot", "0", &err)) {
901            LOG(ERROR) << err;
902            security_failure();
903        }
904
905        // init's first stage can't set properties, so pass the time to the second stage.
906        setenv("INIT_SELINUX_TOOK", std::to_string(t.duration().count()).c_str(), 1);
907    } else {
908        selinux_init_all_handles();
909    }
910}
911
912// The files and directories that were created before initial sepolicy load or
913// files on ramdisk need to have their security context restored to the proper
914// value. This must happen before /dev is populated by ueventd.
915static void selinux_restore_context() {
916    LOG(INFO) << "Running restorecon...";
917    selinux_android_restorecon("/dev", 0);
918    selinux_android_restorecon("/dev/kmsg", 0);
919    selinux_android_restorecon("/dev/socket", 0);
920    selinux_android_restorecon("/dev/random", 0);
921    selinux_android_restorecon("/dev/urandom", 0);
922    selinux_android_restorecon("/dev/__properties__", 0);
923
924    selinux_android_restorecon("/plat_file_contexts", 0);
925    selinux_android_restorecon("/nonplat_file_contexts", 0);
926    selinux_android_restorecon("/plat_property_contexts", 0);
927    selinux_android_restorecon("/nonplat_property_contexts", 0);
928    selinux_android_restorecon("/plat_seapp_contexts", 0);
929    selinux_android_restorecon("/nonplat_seapp_contexts", 0);
930    selinux_android_restorecon("/plat_service_contexts", 0);
931    selinux_android_restorecon("/nonplat_service_contexts", 0);
932    selinux_android_restorecon("/plat_hwservice_contexts", 0);
933    selinux_android_restorecon("/nonplat_hwservice_contexts", 0);
934    selinux_android_restorecon("/sepolicy", 0);
935    selinux_android_restorecon("/vndservice_contexts", 0);
936
937    selinux_android_restorecon("/dev/block", SELINUX_ANDROID_RESTORECON_RECURSE);
938    selinux_android_restorecon("/dev/device-mapper", 0);
939
940    selinux_android_restorecon("/sbin/mke2fs_static", 0);
941    selinux_android_restorecon("/sbin/e2fsdroid_static", 0);
942}
943
944// Set the UDC controller for the ConfigFS USB Gadgets.
945// Read the UDC controller in use from "/sys/class/udc".
946// In case of multiple UDC controllers select the first one.
947static void set_usb_controller() {
948    std::unique_ptr<DIR, decltype(&closedir)>dir(opendir("/sys/class/udc"), closedir);
949    if (!dir) return;
950
951    dirent* dp;
952    while ((dp = readdir(dir.get())) != nullptr) {
953        if (dp->d_name[0] == '.') continue;
954
955        property_set("sys.usb.controller", dp->d_name);
956        break;
957    }
958}
959
960static void InstallRebootSignalHandlers() {
961    // Instead of panic'ing the kernel as is the default behavior when init crashes,
962    // we prefer to reboot to bootloader on development builds, as this will prevent
963    // boot looping bad configurations and allow both developers and test farms to easily
964    // recover.
965    struct sigaction action;
966    memset(&action, 0, sizeof(action));
967    sigfillset(&action.sa_mask);
968    action.sa_handler = [](int signal) {
969        // These signal handlers are also caught for processes forked from init, however we do not
970        // want them to trigger reboot, so we directly call _exit() for children processes here.
971        if (getpid() != 1) {
972            _exit(signal);
973        }
974
975        // panic() reboots to bootloader
976        panic();
977    };
978    action.sa_flags = SA_RESTART;
979    sigaction(SIGABRT, &action, nullptr);
980    sigaction(SIGBUS, &action, nullptr);
981    sigaction(SIGFPE, &action, nullptr);
982    sigaction(SIGILL, &action, nullptr);
983    sigaction(SIGSEGV, &action, nullptr);
984#if defined(SIGSTKFLT)
985    sigaction(SIGSTKFLT, &action, nullptr);
986#endif
987    sigaction(SIGSYS, &action, nullptr);
988    sigaction(SIGTRAP, &action, nullptr);
989}
990
991int main(int argc, char** argv) {
992    if (!strcmp(basename(argv[0]), "ueventd")) {
993        return ueventd_main(argc, argv);
994    }
995
996    if (!strcmp(basename(argv[0]), "watchdogd")) {
997        return watchdogd_main(argc, argv);
998    }
999
1000    if (REBOOT_BOOTLOADER_ON_PANIC) {
1001        InstallRebootSignalHandlers();
1002    }
1003
1004    add_environment("PATH", _PATH_DEFPATH);
1005
1006    bool is_first_stage = (getenv("INIT_SECOND_STAGE") == nullptr);
1007
1008    if (is_first_stage) {
1009        boot_clock::time_point start_time = boot_clock::now();
1010
1011        // Clear the umask.
1012        umask(0);
1013
1014        // Get the basic filesystem setup we need put together in the initramdisk
1015        // on / and then we'll let the rc file figure out the rest.
1016        mount("tmpfs", "/dev", "tmpfs", MS_NOSUID, "mode=0755");
1017        mkdir("/dev/pts", 0755);
1018        mkdir("/dev/socket", 0755);
1019        mount("devpts", "/dev/pts", "devpts", 0, NULL);
1020        #define MAKE_STR(x) __STRING(x)
1021        mount("proc", "/proc", "proc", 0, "hidepid=2,gid=" MAKE_STR(AID_READPROC));
1022        // Don't expose the raw commandline to unprivileged processes.
1023        chmod("/proc/cmdline", 0440);
1024        gid_t groups[] = { AID_READPROC };
1025        setgroups(arraysize(groups), groups);
1026        mount("sysfs", "/sys", "sysfs", 0, NULL);
1027        mount("selinuxfs", "/sys/fs/selinux", "selinuxfs", 0, NULL);
1028        mknod("/dev/kmsg", S_IFCHR | 0600, makedev(1, 11));
1029        mknod("/dev/random", S_IFCHR | 0666, makedev(1, 8));
1030        mknod("/dev/urandom", S_IFCHR | 0666, makedev(1, 9));
1031
1032        // Now that tmpfs is mounted on /dev and we have /dev/kmsg, we can actually
1033        // talk to the outside world...
1034        InitKernelLogging(argv);
1035
1036        LOG(INFO) << "init first stage started!";
1037
1038        if (!DoFirstStageMount()) {
1039            LOG(ERROR) << "Failed to mount required partitions early ...";
1040            panic();
1041        }
1042
1043        SetInitAvbVersionInRecovery();
1044
1045        // Set up SELinux, loading the SELinux policy.
1046        selinux_initialize(true);
1047
1048        // We're in the kernel domain, so re-exec init to transition to the init domain now
1049        // that the SELinux policy has been loaded.
1050        if (selinux_android_restorecon("/init", 0) == -1) {
1051            PLOG(ERROR) << "restorecon failed";
1052            security_failure();
1053        }
1054
1055        setenv("INIT_SECOND_STAGE", "true", 1);
1056
1057        static constexpr uint32_t kNanosecondsPerMillisecond = 1e6;
1058        uint64_t start_ms = start_time.time_since_epoch().count() / kNanosecondsPerMillisecond;
1059        setenv("INIT_STARTED_AT", std::to_string(start_ms).c_str(), 1);
1060
1061        char* path = argv[0];
1062        char* args[] = { path, nullptr };
1063        execv(path, args);
1064
1065        // execv() only returns if an error happened, in which case we
1066        // panic and never fall through this conditional.
1067        PLOG(ERROR) << "execv(\"" << path << "\") failed";
1068        security_failure();
1069    }
1070
1071    // At this point we're in the second stage of init.
1072    InitKernelLogging(argv);
1073    LOG(INFO) << "init second stage started!";
1074
1075    // Set up a session keyring that all processes will have access to. It
1076    // will hold things like FBE encryption keys. No process should override
1077    // its session keyring.
1078    keyctl_get_keyring_ID(KEY_SPEC_SESSION_KEYRING, 1);
1079
1080    // Indicate that booting is in progress to background fw loaders, etc.
1081    close(open("/dev/.booting", O_WRONLY | O_CREAT | O_CLOEXEC, 0000));
1082
1083    property_init();
1084
1085    // If arguments are passed both on the command line and in DT,
1086    // properties set in DT always have priority over the command-line ones.
1087    process_kernel_dt();
1088    process_kernel_cmdline();
1089
1090    // Propagate the kernel variables to internal variables
1091    // used by init as well as the current required properties.
1092    export_kernel_boot_props();
1093
1094    // Make the time that init started available for bootstat to log.
1095    property_set("ro.boottime.init", getenv("INIT_STARTED_AT"));
1096    property_set("ro.boottime.init.selinux", getenv("INIT_SELINUX_TOOK"));
1097
1098    // Set libavb version for Framework-only OTA match in Treble build.
1099    const char* avb_version = getenv("INIT_AVB_VERSION");
1100    if (avb_version) property_set("ro.boot.avb_version", avb_version);
1101
1102    // Clean up our environment.
1103    unsetenv("INIT_SECOND_STAGE");
1104    unsetenv("INIT_STARTED_AT");
1105    unsetenv("INIT_SELINUX_TOOK");
1106    unsetenv("INIT_AVB_VERSION");
1107
1108    // Now set up SELinux for second stage.
1109    selinux_initialize(false);
1110    selinux_restore_context();
1111
1112    epoll_fd = epoll_create1(EPOLL_CLOEXEC);
1113    if (epoll_fd == -1) {
1114        PLOG(ERROR) << "epoll_create1 failed";
1115        exit(1);
1116    }
1117
1118    signal_handler_init();
1119
1120    property_load_boot_defaults();
1121    export_oem_lock_status();
1122    start_property_service();
1123    set_usb_controller();
1124
1125    const BuiltinFunctionMap function_map;
1126    Action::set_function_map(&function_map);
1127
1128    ActionManager& am = ActionManager::GetInstance();
1129    ServiceManager& sm = ServiceManager::GetInstance();
1130    Parser& parser = Parser::GetInstance();
1131
1132    parser.AddSectionParser("service", std::make_unique<ServiceParser>(&sm));
1133    parser.AddSectionParser("on", std::make_unique<ActionParser>(&am));
1134    parser.AddSectionParser("import", std::make_unique<ImportParser>(&parser));
1135    std::string bootscript = GetProperty("ro.boot.init_rc", "");
1136    if (bootscript.empty()) {
1137        parser.ParseConfig("/init.rc");
1138        parser.set_is_system_etc_init_loaded(
1139                parser.ParseConfig("/system/etc/init"));
1140        parser.set_is_vendor_etc_init_loaded(
1141                parser.ParseConfig("/vendor/etc/init"));
1142        parser.set_is_odm_etc_init_loaded(parser.ParseConfig("/odm/etc/init"));
1143    } else {
1144        parser.ParseConfig(bootscript);
1145        parser.set_is_system_etc_init_loaded(true);
1146        parser.set_is_vendor_etc_init_loaded(true);
1147        parser.set_is_odm_etc_init_loaded(true);
1148    }
1149
1150    // Turning this on and letting the INFO logging be discarded adds 0.2s to
1151    // Nexus 9 boot time, so it's disabled by default.
1152    if (false) DumpState();
1153
1154    am.QueueEventTrigger("early-init");
1155
1156    // Queue an action that waits for coldboot done so we know ueventd has set up all of /dev...
1157    am.QueueBuiltinAction(wait_for_coldboot_done_action, "wait_for_coldboot_done");
1158    // ... so that we can start queuing up actions that require stuff from /dev.
1159    am.QueueBuiltinAction(mix_hwrng_into_linux_rng_action, "mix_hwrng_into_linux_rng");
1160    am.QueueBuiltinAction(set_mmap_rnd_bits_action, "set_mmap_rnd_bits");
1161    am.QueueBuiltinAction(set_kptr_restrict_action, "set_kptr_restrict");
1162    am.QueueBuiltinAction(keychord_init_action, "keychord_init");
1163    am.QueueBuiltinAction(console_init_action, "console_init");
1164
1165    // Trigger all the boot actions to get us started.
1166    am.QueueEventTrigger("init");
1167
1168    // Repeat mix_hwrng_into_linux_rng in case /dev/hw_random or /dev/random
1169    // wasn't ready immediately after wait_for_coldboot_done
1170    am.QueueBuiltinAction(mix_hwrng_into_linux_rng_action, "mix_hwrng_into_linux_rng");
1171
1172    // Don't mount filesystems or start core system services in charger mode.
1173    std::string bootmode = GetProperty("ro.bootmode", "");
1174    if (bootmode == "charger") {
1175        am.QueueEventTrigger("charger");
1176    } else {
1177        am.QueueEventTrigger("late-init");
1178    }
1179
1180    // Run all property triggers based on current state of the properties.
1181    am.QueueBuiltinAction(queue_property_triggers_action, "queue_property_triggers");
1182
1183    while (true) {
1184        // By default, sleep until something happens.
1185        int epoll_timeout_ms = -1;
1186
1187        if (do_shutdown && !shutting_down) {
1188            do_shutdown = false;
1189            if (HandlePowerctlMessage(shutdown_command)) {
1190                shutting_down = true;
1191            }
1192        }
1193
1194        if (!(waiting_for_prop || sm.IsWaitingForExec())) {
1195            am.ExecuteOneCommand();
1196        }
1197        if (!(waiting_for_prop || sm.IsWaitingForExec())) {
1198            if (!shutting_down) restart_processes();
1199
1200            // If there's a process that needs restarting, wake up in time for that.
1201            if (process_needs_restart_at != 0) {
1202                epoll_timeout_ms = (process_needs_restart_at - time(nullptr)) * 1000;
1203                if (epoll_timeout_ms < 0) epoll_timeout_ms = 0;
1204            }
1205
1206            // If there's more work to do, wake up again immediately.
1207            if (am.HasMoreCommands()) epoll_timeout_ms = 0;
1208        }
1209
1210        epoll_event ev;
1211        int nr = TEMP_FAILURE_RETRY(epoll_wait(epoll_fd, &ev, 1, epoll_timeout_ms));
1212        if (nr == -1) {
1213            PLOG(ERROR) << "epoll_wait failed";
1214        } else if (nr == 1) {
1215            ((void (*)()) ev.data.ptr)();
1216        }
1217    }
1218
1219    return 0;
1220}
1221
1222}  // namespace init
1223}  // namespace android
1224
1225int main(int argc, char** argv) {
1226    android::init::main(argc, argv);
1227}
1228