blob: db2a7fcf4521fbaab0fcef610e719b08f8cf58f6 [file] [log] [blame]
Tom Cherryc3170092017-08-10 12:22:44 -07001/*
2 * Copyright (C) 2017 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// This file contains the functions that initialize SELinux during boot as well as helper functions
18// for SELinux operation for init.
19
20// When the system boots, there is no SEPolicy present and init is running in the kernel domain.
Tom Cherry7bfea3d2018-11-06 14:12:05 -080021// Init loads the SEPolicy from the file system, restores the context of /system/bin/init based on
22// this SEPolicy, and finally exec()'s itself to run in the proper domain.
Tom Cherryc3170092017-08-10 12:22:44 -070023
24// The SEPolicy on Android comes in two variants: monolithic and split.
25
26// The monolithic policy variant is for legacy non-treble devices that contain a single SEPolicy
27// file located at /sepolicy and is directly loaded into the kernel SELinux subsystem.
28
29// The split policy is for supporting treble devices. It splits the SEPolicy across files on
30// /system/etc/selinux (the 'plat' portion of the policy) and /vendor/etc/selinux (the 'nonplat'
31// portion of the policy). This is necessary to allow the system image to be updated independently
32// of the vendor image, while maintaining contributions from both partitions in the SEPolicy. This
33// is especially important for VTS testing, where the SEPolicy on the Google System Image may not be
34// identical to the system image shipped on a vendor's device.
35
36// The split SEPolicy is loaded as described below:
Tri Voc8137f92019-01-22 18:22:25 -080037// 1) There is a precompiled SEPolicy located at either /vendor/etc/selinux/precompiled_sepolicy or
38// /odm/etc/selinux/precompiled_sepolicy if odm parition is present. Stored along with this file
39// are the sha256 hashes of the parts of the SEPolicy on /system and /product that were used to
40// compile this precompiled policy. The system partition contains a similar sha256 of the parts
41// of the SEPolicy that it currently contains. Symmetrically, product paritition contains a
42// sha256 of its SEPolicy. System loads this precompiled_sepolicy directly if and only if hashes
43// for system policy match and hashes for product policy match.
44// 2) If these hashes do not match, then either /system or /product (or both) have been updated out
45// of sync with /vendor and the init needs to compile the SEPolicy. /system contains the
46// SEPolicy compiler, secilc, and it is used by the LoadSplitPolicy() function below to compile
47// the SEPolicy to a temp directory and load it. That function contains even more documentation
48// with the specific implementation details of how the SEPolicy is compiled if needed.
Tom Cherryc3170092017-08-10 12:22:44 -070049
50#include "selinux.h"
51
Tom Cherry40acb372018-08-01 13:41:12 -070052#include <android/api-level.h>
Tom Cherryc3170092017-08-10 12:22:44 -070053#include <fcntl.h>
Tom Cherryc3170092017-08-10 12:22:44 -070054#include <stdlib.h>
55#include <sys/wait.h>
56#include <unistd.h>
57
58#include <android-base/chrono_utils.h>
59#include <android-base/file.h>
60#include <android-base/logging.h>
Logan Chien837b2a42018-05-03 14:33:52 +080061#include <android-base/parseint.h>
Tom Cherryc3170092017-08-10 12:22:44 -070062#include <android-base/unique_fd.h>
Bowgo Tsai1dacd422019-03-04 17:53:34 +080063#include <fs_avb/fs_avb.h>
Tom Cherryc3170092017-08-10 12:22:44 -070064#include <selinux/android.h>
65
Bowgo Tsai30afda72019-04-11 23:57:24 +080066#include "debug_ramdisk.h"
Tom Cherry7bfea3d2018-11-06 14:12:05 -080067#include "reboot_utils.h"
Tom Cherryc3170092017-08-10 12:22:44 -070068#include "util.h"
69
Bowgo Tsai1dacd422019-03-04 17:53:34 +080070using namespace std::string_literals;
71
Logan Chien837b2a42018-05-03 14:33:52 +080072using android::base::ParseInt;
Tom Cherryc3170092017-08-10 12:22:44 -070073using android::base::Timer;
74using android::base::unique_fd;
Bowgo Tsai1dacd422019-03-04 17:53:34 +080075using android::fs_mgr::AvbHandle;
Tom Cherryc3170092017-08-10 12:22:44 -070076
77namespace android {
78namespace init {
79
Tom Cherryc3170092017-08-10 12:22:44 -070080namespace {
81
82enum EnforcingStatus { SELINUX_PERMISSIVE, SELINUX_ENFORCING };
83
84EnforcingStatus StatusFromCmdline() {
85 EnforcingStatus status = SELINUX_ENFORCING;
86
87 import_kernel_cmdline(false,
88 [&](const std::string& key, const std::string& value, bool in_qemu) {
89 if (key == "androidboot.selinux" && value == "permissive") {
90 status = SELINUX_PERMISSIVE;
91 }
92 });
93
94 return status;
95}
96
97bool IsEnforcing() {
98 if (ALLOW_PERMISSIVE_SELINUX) {
99 return StatusFromCmdline() == SELINUX_ENFORCING;
100 }
101 return true;
102}
103
104// Forks, executes the provided program in the child, and waits for the completion in the parent.
105// Child's stderr is captured and logged using LOG(ERROR).
106bool ForkExecveAndWaitForCompletion(const char* filename, char* const argv[]) {
107 // Create a pipe used for redirecting child process's output.
108 // * pipe_fds[0] is the FD the parent will use for reading.
109 // * pipe_fds[1] is the FD the child will use for writing.
110 int pipe_fds[2];
111 if (pipe(pipe_fds) == -1) {
112 PLOG(ERROR) << "Failed to create pipe";
113 return false;
114 }
115
116 pid_t child_pid = fork();
117 if (child_pid == -1) {
118 PLOG(ERROR) << "Failed to fork for " << filename;
119 return false;
120 }
121
122 if (child_pid == 0) {
123 // fork succeeded -- this is executing in the child process
124
125 // Close the pipe FD not used by this process
Nick Kralevich3d118e72017-10-24 10:45:48 -0700126 close(pipe_fds[0]);
Tom Cherryc3170092017-08-10 12:22:44 -0700127
128 // Redirect stderr to the pipe FD provided by the parent
129 if (TEMP_FAILURE_RETRY(dup2(pipe_fds[1], STDERR_FILENO)) == -1) {
130 PLOG(ERROR) << "Failed to redirect stderr of " << filename;
131 _exit(127);
132 return false;
133 }
Nick Kralevich3d118e72017-10-24 10:45:48 -0700134 close(pipe_fds[1]);
Tom Cherryc3170092017-08-10 12:22:44 -0700135
Tom Cherry6de21f12017-08-22 15:41:03 -0700136 if (execv(filename, argv) == -1) {
Tom Cherryc3170092017-08-10 12:22:44 -0700137 PLOG(ERROR) << "Failed to execve " << filename;
138 return false;
139 }
140 // Unreachable because execve will have succeeded and replaced this code
141 // with child process's code.
142 _exit(127);
143 return false;
144 } else {
145 // fork succeeded -- this is executing in the original/parent process
146
147 // Close the pipe FD not used by this process
Nick Kralevich3d118e72017-10-24 10:45:48 -0700148 close(pipe_fds[1]);
Tom Cherryc3170092017-08-10 12:22:44 -0700149
150 // Log the redirected output of the child process.
151 // It's unfortunate that there's no standard way to obtain an istream for a file descriptor.
152 // As a result, we're buffering all output and logging it in one go at the end of the
153 // invocation, instead of logging it as it comes in.
154 const int child_out_fd = pipe_fds[0];
155 std::string child_output;
156 if (!android::base::ReadFdToString(child_out_fd, &child_output)) {
157 PLOG(ERROR) << "Failed to capture full output of " << filename;
158 }
Nick Kralevich3d118e72017-10-24 10:45:48 -0700159 close(child_out_fd);
Tom Cherryc3170092017-08-10 12:22:44 -0700160 if (!child_output.empty()) {
161 // Log captured output, line by line, because LOG expects to be invoked for each line
162 std::istringstream in(child_output);
163 std::string line;
164 while (std::getline(in, line)) {
165 LOG(ERROR) << filename << ": " << line;
166 }
167 }
168
169 // Wait for child to terminate
170 int status;
171 if (TEMP_FAILURE_RETRY(waitpid(child_pid, &status, 0)) != child_pid) {
172 PLOG(ERROR) << "Failed to wait for " << filename;
173 return false;
174 }
175
176 if (WIFEXITED(status)) {
177 int status_code = WEXITSTATUS(status);
178 if (status_code == 0) {
179 return true;
180 } else {
181 LOG(ERROR) << filename << " exited with status " << status_code;
182 }
183 } else if (WIFSIGNALED(status)) {
184 LOG(ERROR) << filename << " killed by signal " << WTERMSIG(status);
185 } else if (WIFSTOPPED(status)) {
186 LOG(ERROR) << filename << " stopped by signal " << WSTOPSIG(status);
187 } else {
188 LOG(ERROR) << "waitpid for " << filename << " returned unexpected status: " << status;
189 }
190
191 return false;
192 }
193}
194
195bool ReadFirstLine(const char* file, std::string* line) {
196 line->clear();
197
198 std::string contents;
199 if (!android::base::ReadFileToString(file, &contents, true /* follow symlinks */)) {
200 return false;
201 }
202 std::istringstream in(contents);
203 std::getline(in, *line);
204 return true;
205}
206
207bool FindPrecompiledSplitPolicy(std::string* file) {
208 file->clear();
kaichieheef4cd72017-08-31 22:07:19 +0800209 // If there is an odm partition, precompiled_sepolicy will be in
210 // odm/etc/selinux. Otherwise it will be in vendor/etc/selinux.
211 static constexpr const char vendor_precompiled_sepolicy[] =
212 "/vendor/etc/selinux/precompiled_sepolicy";
213 static constexpr const char odm_precompiled_sepolicy[] =
214 "/odm/etc/selinux/precompiled_sepolicy";
215 if (access(odm_precompiled_sepolicy, R_OK) == 0) {
216 *file = odm_precompiled_sepolicy;
217 } else if (access(vendor_precompiled_sepolicy, R_OK) == 0) {
218 *file = vendor_precompiled_sepolicy;
219 } else {
220 PLOG(INFO) << "No precompiled sepolicy";
Tom Cherryc3170092017-08-10 12:22:44 -0700221 return false;
222 }
223 std::string actual_plat_id;
Tri Voc8137f92019-01-22 18:22:25 -0800224 if (!ReadFirstLine("/system/etc/selinux/plat_sepolicy_and_mapping.sha256", &actual_plat_id)) {
Tom Cherryc3170092017-08-10 12:22:44 -0700225 PLOG(INFO) << "Failed to read "
Tri Voc8137f92019-01-22 18:22:25 -0800226 "/system/etc/selinux/plat_sepolicy_and_mapping.sha256";
227 return false;
228 }
229 std::string actual_product_id;
230 if (!ReadFirstLine("/product/etc/selinux/product_sepolicy_and_mapping.sha256",
231 &actual_product_id)) {
232 PLOG(INFO) << "Failed to read "
233 "/product/etc/selinux/product_sepolicy_and_mapping.sha256";
Tom Cherryc3170092017-08-10 12:22:44 -0700234 return false;
235 }
kaichieheef4cd72017-08-31 22:07:19 +0800236
Tom Cherryc3170092017-08-10 12:22:44 -0700237 std::string precompiled_plat_id;
Tri Voc8137f92019-01-22 18:22:25 -0800238 std::string precompiled_plat_sha256 = *file + ".plat_sepolicy_and_mapping.sha256";
239 if (!ReadFirstLine(precompiled_plat_sha256.c_str(), &precompiled_plat_id)) {
240 PLOG(INFO) << "Failed to read " << precompiled_plat_sha256;
kaichieheef4cd72017-08-31 22:07:19 +0800241 file->clear();
Tom Cherryc3170092017-08-10 12:22:44 -0700242 return false;
243 }
Tri Voc8137f92019-01-22 18:22:25 -0800244 std::string precompiled_product_id;
245 std::string precompiled_product_sha256 = *file + ".product_sepolicy_and_mapping.sha256";
246 if (!ReadFirstLine(precompiled_product_sha256.c_str(), &precompiled_product_id)) {
247 PLOG(INFO) << "Failed to read " << precompiled_product_sha256;
248 file->clear();
249 return false;
250 }
251 if (actual_plat_id.empty() || actual_plat_id != precompiled_plat_id ||
252 actual_product_id.empty() || actual_product_id != precompiled_product_id) {
kaichieheef4cd72017-08-31 22:07:19 +0800253 file->clear();
Tom Cherryc3170092017-08-10 12:22:44 -0700254 return false;
255 }
Tom Cherryc3170092017-08-10 12:22:44 -0700256 return true;
257}
258
259bool GetVendorMappingVersion(std::string* plat_vers) {
260 if (!ReadFirstLine("/vendor/etc/selinux/plat_sepolicy_vers.txt", plat_vers)) {
261 PLOG(ERROR) << "Failed to read /vendor/etc/selinux/plat_sepolicy_vers.txt";
262 return false;
263 }
264 if (plat_vers->empty()) {
265 LOG(ERROR) << "No version present in plat_sepolicy_vers.txt";
266 return false;
267 }
268 return true;
269}
270
271constexpr const char plat_policy_cil_file[] = "/system/etc/selinux/plat_sepolicy.cil";
272
273bool IsSplitPolicyDevice() {
274 return access(plat_policy_cil_file, R_OK) != -1;
275}
276
277bool LoadSplitPolicy() {
278 // IMPLEMENTATION NOTE: Split policy consists of three CIL files:
279 // * platform -- policy needed due to logic contained in the system image,
280 // * non-platform -- policy needed due to logic contained in the vendor image,
281 // * mapping -- mapping policy which helps preserve forward-compatibility of non-platform policy
282 // with newer versions of platform policy.
283 //
284 // secilc is invoked to compile the above three policy files into a single monolithic policy
285 // file. This file is then loaded into the kernel.
286
Bowgo Tsai1dacd422019-03-04 17:53:34 +0800287 // See if we need to load userdebug_plat_sepolicy.cil instead of plat_sepolicy.cil.
288 const char* force_debuggable_env = getenv("INIT_FORCE_DEBUGGABLE");
289 bool use_userdebug_policy =
290 ((force_debuggable_env && "true"s == force_debuggable_env) &&
Bowgo Tsai30afda72019-04-11 23:57:24 +0800291 AvbHandle::IsDeviceUnlocked() && access(kDebugRamdiskSEPolicy, F_OK) == 0);
Bowgo Tsai1dacd422019-03-04 17:53:34 +0800292 if (use_userdebug_policy) {
293 LOG(WARNING) << "Using userdebug system sepolicy";
294 }
295
Tom Cherryc3170092017-08-10 12:22:44 -0700296 // Load precompiled policy from vendor image, if a matching policy is found there. The policy
297 // must match the platform policy on the system image.
298 std::string precompiled_sepolicy_file;
Bowgo Tsai1dacd422019-03-04 17:53:34 +0800299 // use_userdebug_policy requires compiling sepolicy with userdebug_plat_sepolicy.cil.
300 // Thus it cannot use the precompiled policy from vendor image.
301 if (!use_userdebug_policy && FindPrecompiledSplitPolicy(&precompiled_sepolicy_file)) {
Tom Cherryc3170092017-08-10 12:22:44 -0700302 unique_fd fd(open(precompiled_sepolicy_file.c_str(), O_RDONLY | O_CLOEXEC | O_BINARY));
303 if (fd != -1) {
304 if (selinux_android_load_policy_from_fd(fd, precompiled_sepolicy_file.c_str()) < 0) {
305 LOG(ERROR) << "Failed to load SELinux policy from " << precompiled_sepolicy_file;
306 return false;
307 }
308 return true;
309 }
310 }
311 // No suitable precompiled policy could be loaded
312
313 LOG(INFO) << "Compiling SELinux policy";
314
Tom Cherryc3170092017-08-10 12:22:44 -0700315 // We store the output of the compilation on /dev because this is the most convenient tmpfs
316 // storage mount available this early in the boot sequence.
317 char compiled_sepolicy[] = "/dev/sepolicy.XXXXXX";
318 unique_fd compiled_sepolicy_fd(mkostemp(compiled_sepolicy, O_CLOEXEC));
319 if (compiled_sepolicy_fd < 0) {
320 PLOG(ERROR) << "Failed to create temporary file " << compiled_sepolicy;
321 return false;
322 }
323
324 // Determine which mapping file to include
325 std::string vend_plat_vers;
326 if (!GetVendorMappingVersion(&vend_plat_vers)) {
327 return false;
328 }
Tri Vo503f1852019-01-16 11:57:19 -0800329 std::string plat_mapping_file("/system/etc/selinux/mapping/" + vend_plat_vers + ".cil");
kaichieheef4cd72017-08-31 22:07:19 +0800330
Jeff Vander Stoep0ac51cf2019-05-02 14:05:18 -0700331 std::string plat_compat_cil_file("/system/etc/selinux/mapping/" + vend_plat_vers +
332 ".compat.cil");
333 if (access(plat_compat_cil_file.c_str(), F_OK) == -1) {
334 plat_compat_cil_file.clear();
335 }
336
Tri Vod3518cf2018-12-14 14:25:08 -0800337 std::string product_policy_cil_file("/product/etc/selinux/product_sepolicy.cil");
338 if (access(product_policy_cil_file.c_str(), F_OK) == -1) {
339 product_policy_cil_file.clear();
340 }
341
Tri Vo503f1852019-01-16 11:57:19 -0800342 std::string product_mapping_file("/product/etc/selinux/mapping/" + vend_plat_vers + ".cil");
343 if (access(product_mapping_file.c_str(), F_OK) == -1) {
344 product_mapping_file.clear();
345 }
346
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800347 // vendor_sepolicy.cil and plat_pub_versioned.cil are the new design to replace
kaichieheef4cd72017-08-31 22:07:19 +0800348 // nonplat_sepolicy.cil.
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800349 std::string plat_pub_versioned_cil_file("/vendor/etc/selinux/plat_pub_versioned.cil");
kaichieheef4cd72017-08-31 22:07:19 +0800350 std::string vendor_policy_cil_file("/vendor/etc/selinux/vendor_sepolicy.cil");
351
352 if (access(vendor_policy_cil_file.c_str(), F_OK) == -1) {
353 // For backward compatibility.
354 // TODO: remove this after no device is using nonplat_sepolicy.cil.
355 vendor_policy_cil_file = "/vendor/etc/selinux/nonplat_sepolicy.cil";
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800356 plat_pub_versioned_cil_file.clear();
357 } else if (access(plat_pub_versioned_cil_file.c_str(), F_OK) == -1) {
358 LOG(ERROR) << "Missing " << plat_pub_versioned_cil_file;
kaichieheef4cd72017-08-31 22:07:19 +0800359 return false;
360 }
361
362 // odm_sepolicy.cil is default but optional.
363 std::string odm_policy_cil_file("/odm/etc/selinux/odm_sepolicy.cil");
364 if (access(odm_policy_cil_file.c_str(), F_OK) == -1) {
365 odm_policy_cil_file.clear();
366 }
Jeff Vander Stoep724eda52019-02-15 12:13:38 -0800367 const std::string version_as_string = std::to_string(SEPOLICY_VERSION);
Andreas Huberc41b8382017-08-18 14:43:52 -0700368
Tom Cherryc3170092017-08-10 12:22:44 -0700369 // clang-format off
kaichieheef4cd72017-08-31 22:07:19 +0800370 std::vector<const char*> compile_args {
Tom Cherryc3170092017-08-10 12:22:44 -0700371 "/system/bin/secilc",
Bowgo Tsai30afda72019-04-11 23:57:24 +0800372 use_userdebug_policy ? kDebugRamdiskSEPolicy: plat_policy_cil_file,
Jeff Vander Stoep5e9ba3c2017-10-06 17:03:45 -0700373 "-m", "-M", "true", "-G", "-N",
Andreas Huberc41b8382017-08-18 14:43:52 -0700374 "-c", version_as_string.c_str(),
Tri Vo503f1852019-01-16 11:57:19 -0800375 plat_mapping_file.c_str(),
Tom Cherryc3170092017-08-10 12:22:44 -0700376 "-o", compiled_sepolicy,
377 // We don't care about file_contexts output by the compiler
378 "-f", "/sys/fs/selinux/null", // /dev/null is not yet available
kaichieheef4cd72017-08-31 22:07:19 +0800379 };
Tom Cherryc3170092017-08-10 12:22:44 -0700380 // clang-format on
381
Jeff Vander Stoep0ac51cf2019-05-02 14:05:18 -0700382 if (!plat_compat_cil_file.empty()) {
383 compile_args.push_back(plat_compat_cil_file.c_str());
384 }
Tri Vod3518cf2018-12-14 14:25:08 -0800385 if (!product_policy_cil_file.empty()) {
386 compile_args.push_back(product_policy_cil_file.c_str());
387 }
Tri Vo503f1852019-01-16 11:57:19 -0800388 if (!product_mapping_file.empty()) {
389 compile_args.push_back(product_mapping_file.c_str());
390 }
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800391 if (!plat_pub_versioned_cil_file.empty()) {
392 compile_args.push_back(plat_pub_versioned_cil_file.c_str());
kaichieheef4cd72017-08-31 22:07:19 +0800393 }
394 if (!vendor_policy_cil_file.empty()) {
395 compile_args.push_back(vendor_policy_cil_file.c_str());
396 }
397 if (!odm_policy_cil_file.empty()) {
398 compile_args.push_back(odm_policy_cil_file.c_str());
399 }
400 compile_args.push_back(nullptr);
401
402 if (!ForkExecveAndWaitForCompletion(compile_args[0], (char**)compile_args.data())) {
Tom Cherryc3170092017-08-10 12:22:44 -0700403 unlink(compiled_sepolicy);
404 return false;
405 }
406 unlink(compiled_sepolicy);
407
408 LOG(INFO) << "Loading compiled SELinux policy";
409 if (selinux_android_load_policy_from_fd(compiled_sepolicy_fd, compiled_sepolicy) < 0) {
410 LOG(ERROR) << "Failed to load SELinux policy from " << compiled_sepolicy;
411 return false;
412 }
413
414 return true;
415}
416
417bool LoadMonolithicPolicy() {
418 LOG(VERBOSE) << "Loading SELinux policy from monolithic file";
419 if (selinux_android_load_policy() < 0) {
420 PLOG(ERROR) << "Failed to load monolithic SELinux policy";
421 return false;
422 }
423 return true;
424}
425
426bool LoadPolicy() {
427 return IsSplitPolicyDevice() ? LoadSplitPolicy() : LoadMonolithicPolicy();
428}
429
Tom Cherryc3170092017-08-10 12:22:44 -0700430void SelinuxInitialize() {
Tom Cherryc3170092017-08-10 12:22:44 -0700431 LOG(INFO) << "Loading SELinux policy";
432 if (!LoadPolicy()) {
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700433 LOG(FATAL) << "Unable to load SELinux policy";
Tom Cherryc3170092017-08-10 12:22:44 -0700434 }
435
436 bool kernel_enforcing = (security_getenforce() == 1);
437 bool is_enforcing = IsEnforcing();
438 if (kernel_enforcing != is_enforcing) {
439 if (security_setenforce(is_enforcing)) {
Paul Lawrenceb2c2d692019-08-30 11:11:44 -0700440 PLOG(FATAL) << "security_setenforce(" << (is_enforcing ? "true" : "false")
441 << ") failed";
Tom Cherryc3170092017-08-10 12:22:44 -0700442 }
443 }
444
Tom Cherry11a3aee2017-08-03 12:54:07 -0700445 if (auto result = WriteFile("/sys/fs/selinux/checkreqprot", "0"); !result) {
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700446 LOG(FATAL) << "Unable to write to /sys/fs/selinux/checkreqprot: " << result.error();
Tom Cherryc3170092017-08-10 12:22:44 -0700447 }
Tom Cherryc3170092017-08-10 12:22:44 -0700448}
449
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800450} // namespace
451
Tom Cherryc3170092017-08-10 12:22:44 -0700452// The files and directories that were created before initial sepolicy load or
453// files on ramdisk need to have their security context restored to the proper
454// value. This must happen before /dev is populated by ueventd.
455void SelinuxRestoreContext() {
456 LOG(INFO) << "Running restorecon...";
457 selinux_android_restorecon("/dev", 0);
458 selinux_android_restorecon("/dev/kmsg", 0);
459 if constexpr (WORLD_WRITABLE_KMSG) {
460 selinux_android_restorecon("/dev/kmsg_debug", 0);
461 }
Tom Cherry81ae0752018-07-30 16:23:49 -0700462 selinux_android_restorecon("/dev/null", 0);
463 selinux_android_restorecon("/dev/ptmx", 0);
Tom Cherryc3170092017-08-10 12:22:44 -0700464 selinux_android_restorecon("/dev/socket", 0);
465 selinux_android_restorecon("/dev/random", 0);
466 selinux_android_restorecon("/dev/urandom", 0);
467 selinux_android_restorecon("/dev/__properties__", 0);
468
Tom Cherryc3170092017-08-10 12:22:44 -0700469 selinux_android_restorecon("/dev/block", SELINUX_ANDROID_RESTORECON_RECURSE);
470 selinux_android_restorecon("/dev/device-mapper", 0);
Jiyong Park4ba548d2019-02-22 16:04:35 +0900471
472 selinux_android_restorecon("/apex", 0);
Tom Cherryc3170092017-08-10 12:22:44 -0700473}
474
Tom Cherry74069d12018-07-20 15:26:25 -0700475int SelinuxKlogCallback(int type, const char* fmt, ...) {
476 android::base::LogSeverity severity = android::base::ERROR;
477 if (type == SELINUX_WARNING) {
478 severity = android::base::WARNING;
479 } else if (type == SELINUX_INFO) {
480 severity = android::base::INFO;
481 }
482 char buf[1024];
483 va_list ap;
484 va_start(ap, fmt);
485 vsnprintf(buf, sizeof(buf), fmt, ap);
486 va_end(ap);
487 android::base::KernelLogger(android::base::MAIN, severity, "selinux", nullptr, 0, buf);
488 return 0;
489}
490
Tom Cherryc3170092017-08-10 12:22:44 -0700491// This function sets up SELinux logging to be written to kmsg, to match init's logging.
492void SelinuxSetupKernelLogging() {
493 selinux_callback cb;
Tom Cherry74069d12018-07-20 15:26:25 -0700494 cb.func_log = SelinuxKlogCallback;
Tom Cherryc3170092017-08-10 12:22:44 -0700495 selinux_set_callback(SELINUX_CB_LOG, cb);
496}
497
Tom Cherry40acb372018-08-01 13:41:12 -0700498// This function returns the Android version with which the vendor SEPolicy was compiled.
499// It is used for version checks such as whether or not vendor_init should be used
500int SelinuxGetVendorAndroidVersion() {
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700501 static int vendor_android_version = [] {
502 if (!IsSplitPolicyDevice()) {
503 // If this device does not split sepolicy files, it's not a Treble device and therefore,
504 // we assume it's always on the latest platform.
505 return __ANDROID_API_FUTURE__;
506 }
Logan Chien837b2a42018-05-03 14:33:52 +0800507
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700508 std::string version;
509 if (!GetVendorMappingVersion(&version)) {
510 LOG(FATAL) << "Could not read vendor SELinux version";
511 }
Logan Chien837b2a42018-05-03 14:33:52 +0800512
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700513 int major_version;
514 std::string major_version_str(version, 0, version.find('.'));
515 if (!ParseInt(major_version_str, &major_version)) {
516 PLOG(FATAL) << "Failed to parse the vendor sepolicy major version "
517 << major_version_str;
518 }
Logan Chien837b2a42018-05-03 14:33:52 +0800519
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700520 return major_version;
521 }();
522 return vendor_android_version;
Logan Chien837b2a42018-05-03 14:33:52 +0800523}
524
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800525// This function initializes SELinux then execs init to run in the init SELinux context.
526int SetupSelinux(char** argv) {
Mark Salyzynbeb6abe2019-07-29 09:35:18 -0700527 SetStdioToDevNull(argv);
Tom Cherry59656fb2019-05-28 10:19:44 -0700528 InitKernelLogging(argv);
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800529
530 if (REBOOT_BOOTLOADER_ON_PANIC) {
531 InstallRebootSignalHandlers();
532 }
533
Mark Salyzyn10377df2019-03-27 08:10:41 -0700534 boot_clock::time_point start_time = boot_clock::now();
535
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800536 // Set up SELinux, loading the SELinux policy.
537 SelinuxSetupKernelLogging();
538 SelinuxInitialize();
539
540 // We're in the kernel domain and want to transition to the init domain. File systems that
541 // store SELabels in their xattrs, such as ext4 do not need an explicit restorecon here,
542 // but other file systems do. In particular, this is needed for ramdisks such as the
543 // recovery image for A/B devices.
544 if (selinux_android_restorecon("/system/bin/init", 0) == -1) {
545 PLOG(FATAL) << "restorecon failed of /system/bin/init failed";
546 }
547
Mark Salyzyn44505ec2019-05-08 12:44:50 -0700548 setenv(kEnvSelinuxStartedAt, std::to_string(start_time.time_since_epoch().count()).c_str(), 1);
Mark Salyzyn10377df2019-03-27 08:10:41 -0700549
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800550 const char* path = "/system/bin/init";
551 const char* args[] = {path, "second_stage", nullptr};
552 execv(path, const_cast<char**>(args));
553
554 // execv() only returns if an error happened, in which case we
555 // panic and never return from this function.
556 PLOG(FATAL) << "execv(\"" << path << "\") failed";
557
558 return 1;
559}
560
Tom Cherryc3170092017-08-10 12:22:44 -0700561} // namespace init
562} // namespace android