blob: 8a63363edf0fc18af17f10b0449793898cf0cdf2 [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>
Tom Cherry7bfea3d2018-11-06 14:12:05 -080063#include <cutils/android_reboot.h>
Bowgo Tsai1dacd422019-03-04 17:53:34 +080064#include <fs_avb/fs_avb.h>
Tom Cherryc3170092017-08-10 12:22:44 -070065#include <selinux/android.h>
66
Bowgo Tsai30afda72019-04-11 23:57:24 +080067#include "debug_ramdisk.h"
Tom Cherry7bfea3d2018-11-06 14:12:05 -080068#include "reboot_utils.h"
Tom Cherryc3170092017-08-10 12:22:44 -070069#include "util.h"
70
Bowgo Tsai1dacd422019-03-04 17:53:34 +080071using namespace std::string_literals;
72
Logan Chien837b2a42018-05-03 14:33:52 +080073using android::base::ParseInt;
Tom Cherryc3170092017-08-10 12:22:44 -070074using android::base::Timer;
75using android::base::unique_fd;
Bowgo Tsai1dacd422019-03-04 17:53:34 +080076using android::fs_mgr::AvbHandle;
Tom Cherryc3170092017-08-10 12:22:44 -070077
78namespace android {
79namespace init {
80
Tom Cherryc3170092017-08-10 12:22:44 -070081namespace {
82
Tom Cherry94f3bcd2017-08-17 16:52:10 -070083selabel_handle* sehandle = nullptr;
84
Tom Cherryc3170092017-08-10 12:22:44 -070085enum EnforcingStatus { SELINUX_PERMISSIVE, SELINUX_ENFORCING };
86
87EnforcingStatus StatusFromCmdline() {
88 EnforcingStatus status = SELINUX_ENFORCING;
89
90 import_kernel_cmdline(false,
91 [&](const std::string& key, const std::string& value, bool in_qemu) {
92 if (key == "androidboot.selinux" && value == "permissive") {
93 status = SELINUX_PERMISSIVE;
94 }
95 });
96
97 return status;
98}
99
100bool IsEnforcing() {
101 if (ALLOW_PERMISSIVE_SELINUX) {
102 return StatusFromCmdline() == SELINUX_ENFORCING;
103 }
104 return true;
105}
106
107// Forks, executes the provided program in the child, and waits for the completion in the parent.
108// Child's stderr is captured and logged using LOG(ERROR).
109bool ForkExecveAndWaitForCompletion(const char* filename, char* const argv[]) {
110 // Create a pipe used for redirecting child process's output.
111 // * pipe_fds[0] is the FD the parent will use for reading.
112 // * pipe_fds[1] is the FD the child will use for writing.
113 int pipe_fds[2];
114 if (pipe(pipe_fds) == -1) {
115 PLOG(ERROR) << "Failed to create pipe";
116 return false;
117 }
118
119 pid_t child_pid = fork();
120 if (child_pid == -1) {
121 PLOG(ERROR) << "Failed to fork for " << filename;
122 return false;
123 }
124
125 if (child_pid == 0) {
126 // fork succeeded -- this is executing in the child process
127
128 // Close the pipe FD not used by this process
Nick Kralevich3d118e72017-10-24 10:45:48 -0700129 close(pipe_fds[0]);
Tom Cherryc3170092017-08-10 12:22:44 -0700130
131 // Redirect stderr to the pipe FD provided by the parent
132 if (TEMP_FAILURE_RETRY(dup2(pipe_fds[1], STDERR_FILENO)) == -1) {
133 PLOG(ERROR) << "Failed to redirect stderr of " << filename;
134 _exit(127);
135 return false;
136 }
Nick Kralevich3d118e72017-10-24 10:45:48 -0700137 close(pipe_fds[1]);
Tom Cherryc3170092017-08-10 12:22:44 -0700138
Tom Cherry6de21f12017-08-22 15:41:03 -0700139 if (execv(filename, argv) == -1) {
Tom Cherryc3170092017-08-10 12:22:44 -0700140 PLOG(ERROR) << "Failed to execve " << filename;
141 return false;
142 }
143 // Unreachable because execve will have succeeded and replaced this code
144 // with child process's code.
145 _exit(127);
146 return false;
147 } else {
148 // fork succeeded -- this is executing in the original/parent process
149
150 // Close the pipe FD not used by this process
Nick Kralevich3d118e72017-10-24 10:45:48 -0700151 close(pipe_fds[1]);
Tom Cherryc3170092017-08-10 12:22:44 -0700152
153 // Log the redirected output of the child process.
154 // It's unfortunate that there's no standard way to obtain an istream for a file descriptor.
155 // As a result, we're buffering all output and logging it in one go at the end of the
156 // invocation, instead of logging it as it comes in.
157 const int child_out_fd = pipe_fds[0];
158 std::string child_output;
159 if (!android::base::ReadFdToString(child_out_fd, &child_output)) {
160 PLOG(ERROR) << "Failed to capture full output of " << filename;
161 }
Nick Kralevich3d118e72017-10-24 10:45:48 -0700162 close(child_out_fd);
Tom Cherryc3170092017-08-10 12:22:44 -0700163 if (!child_output.empty()) {
164 // Log captured output, line by line, because LOG expects to be invoked for each line
165 std::istringstream in(child_output);
166 std::string line;
167 while (std::getline(in, line)) {
168 LOG(ERROR) << filename << ": " << line;
169 }
170 }
171
172 // Wait for child to terminate
173 int status;
174 if (TEMP_FAILURE_RETRY(waitpid(child_pid, &status, 0)) != child_pid) {
175 PLOG(ERROR) << "Failed to wait for " << filename;
176 return false;
177 }
178
179 if (WIFEXITED(status)) {
180 int status_code = WEXITSTATUS(status);
181 if (status_code == 0) {
182 return true;
183 } else {
184 LOG(ERROR) << filename << " exited with status " << status_code;
185 }
186 } else if (WIFSIGNALED(status)) {
187 LOG(ERROR) << filename << " killed by signal " << WTERMSIG(status);
188 } else if (WIFSTOPPED(status)) {
189 LOG(ERROR) << filename << " stopped by signal " << WSTOPSIG(status);
190 } else {
191 LOG(ERROR) << "waitpid for " << filename << " returned unexpected status: " << status;
192 }
193
194 return false;
195 }
196}
197
198bool ReadFirstLine(const char* file, std::string* line) {
199 line->clear();
200
201 std::string contents;
202 if (!android::base::ReadFileToString(file, &contents, true /* follow symlinks */)) {
203 return false;
204 }
205 std::istringstream in(contents);
206 std::getline(in, *line);
207 return true;
208}
209
210bool FindPrecompiledSplitPolicy(std::string* file) {
211 file->clear();
kaichieheef4cd72017-08-31 22:07:19 +0800212 // If there is an odm partition, precompiled_sepolicy will be in
213 // odm/etc/selinux. Otherwise it will be in vendor/etc/selinux.
214 static constexpr const char vendor_precompiled_sepolicy[] =
215 "/vendor/etc/selinux/precompiled_sepolicy";
216 static constexpr const char odm_precompiled_sepolicy[] =
217 "/odm/etc/selinux/precompiled_sepolicy";
218 if (access(odm_precompiled_sepolicy, R_OK) == 0) {
219 *file = odm_precompiled_sepolicy;
220 } else if (access(vendor_precompiled_sepolicy, R_OK) == 0) {
221 *file = vendor_precompiled_sepolicy;
222 } else {
223 PLOG(INFO) << "No precompiled sepolicy";
Tom Cherryc3170092017-08-10 12:22:44 -0700224 return false;
225 }
226 std::string actual_plat_id;
Tri Voc8137f92019-01-22 18:22:25 -0800227 if (!ReadFirstLine("/system/etc/selinux/plat_sepolicy_and_mapping.sha256", &actual_plat_id)) {
Tom Cherryc3170092017-08-10 12:22:44 -0700228 PLOG(INFO) << "Failed to read "
Tri Voc8137f92019-01-22 18:22:25 -0800229 "/system/etc/selinux/plat_sepolicy_and_mapping.sha256";
230 return false;
231 }
232 std::string actual_product_id;
233 if (!ReadFirstLine("/product/etc/selinux/product_sepolicy_and_mapping.sha256",
234 &actual_product_id)) {
235 PLOG(INFO) << "Failed to read "
236 "/product/etc/selinux/product_sepolicy_and_mapping.sha256";
Tom Cherryc3170092017-08-10 12:22:44 -0700237 return false;
238 }
kaichieheef4cd72017-08-31 22:07:19 +0800239
Tom Cherryc3170092017-08-10 12:22:44 -0700240 std::string precompiled_plat_id;
Tri Voc8137f92019-01-22 18:22:25 -0800241 std::string precompiled_plat_sha256 = *file + ".plat_sepolicy_and_mapping.sha256";
242 if (!ReadFirstLine(precompiled_plat_sha256.c_str(), &precompiled_plat_id)) {
243 PLOG(INFO) << "Failed to read " << precompiled_plat_sha256;
kaichieheef4cd72017-08-31 22:07:19 +0800244 file->clear();
Tom Cherryc3170092017-08-10 12:22:44 -0700245 return false;
246 }
Tri Voc8137f92019-01-22 18:22:25 -0800247 std::string precompiled_product_id;
248 std::string precompiled_product_sha256 = *file + ".product_sepolicy_and_mapping.sha256";
249 if (!ReadFirstLine(precompiled_product_sha256.c_str(), &precompiled_product_id)) {
250 PLOG(INFO) << "Failed to read " << precompiled_product_sha256;
251 file->clear();
252 return false;
253 }
254 if (actual_plat_id.empty() || actual_plat_id != precompiled_plat_id ||
255 actual_product_id.empty() || actual_product_id != precompiled_product_id) {
kaichieheef4cd72017-08-31 22:07:19 +0800256 file->clear();
Tom Cherryc3170092017-08-10 12:22:44 -0700257 return false;
258 }
Tom Cherryc3170092017-08-10 12:22:44 -0700259 return true;
260}
261
262bool GetVendorMappingVersion(std::string* plat_vers) {
263 if (!ReadFirstLine("/vendor/etc/selinux/plat_sepolicy_vers.txt", plat_vers)) {
264 PLOG(ERROR) << "Failed to read /vendor/etc/selinux/plat_sepolicy_vers.txt";
265 return false;
266 }
267 if (plat_vers->empty()) {
268 LOG(ERROR) << "No version present in plat_sepolicy_vers.txt";
269 return false;
270 }
271 return true;
272}
273
274constexpr const char plat_policy_cil_file[] = "/system/etc/selinux/plat_sepolicy.cil";
275
276bool IsSplitPolicyDevice() {
277 return access(plat_policy_cil_file, R_OK) != -1;
278}
279
280bool LoadSplitPolicy() {
281 // IMPLEMENTATION NOTE: Split policy consists of three CIL files:
282 // * platform -- policy needed due to logic contained in the system image,
283 // * non-platform -- policy needed due to logic contained in the vendor image,
284 // * mapping -- mapping policy which helps preserve forward-compatibility of non-platform policy
285 // with newer versions of platform policy.
286 //
287 // secilc is invoked to compile the above three policy files into a single monolithic policy
288 // file. This file is then loaded into the kernel.
289
Bowgo Tsai1dacd422019-03-04 17:53:34 +0800290 // See if we need to load userdebug_plat_sepolicy.cil instead of plat_sepolicy.cil.
291 const char* force_debuggable_env = getenv("INIT_FORCE_DEBUGGABLE");
292 bool use_userdebug_policy =
293 ((force_debuggable_env && "true"s == force_debuggable_env) &&
Bowgo Tsai30afda72019-04-11 23:57:24 +0800294 AvbHandle::IsDeviceUnlocked() && access(kDebugRamdiskSEPolicy, F_OK) == 0);
Bowgo Tsai1dacd422019-03-04 17:53:34 +0800295 if (use_userdebug_policy) {
296 LOG(WARNING) << "Using userdebug system sepolicy";
297 }
298
Tom Cherryc3170092017-08-10 12:22:44 -0700299 // Load precompiled policy from vendor image, if a matching policy is found there. The policy
300 // must match the platform policy on the system image.
301 std::string precompiled_sepolicy_file;
Bowgo Tsai1dacd422019-03-04 17:53:34 +0800302 // use_userdebug_policy requires compiling sepolicy with userdebug_plat_sepolicy.cil.
303 // Thus it cannot use the precompiled policy from vendor image.
304 if (!use_userdebug_policy && FindPrecompiledSplitPolicy(&precompiled_sepolicy_file)) {
Tom Cherryc3170092017-08-10 12:22:44 -0700305 unique_fd fd(open(precompiled_sepolicy_file.c_str(), O_RDONLY | O_CLOEXEC | O_BINARY));
306 if (fd != -1) {
307 if (selinux_android_load_policy_from_fd(fd, precompiled_sepolicy_file.c_str()) < 0) {
308 LOG(ERROR) << "Failed to load SELinux policy from " << precompiled_sepolicy_file;
309 return false;
310 }
311 return true;
312 }
313 }
314 // No suitable precompiled policy could be loaded
315
316 LOG(INFO) << "Compiling SELinux policy";
317
Tom Cherryc3170092017-08-10 12:22:44 -0700318 // We store the output of the compilation on /dev because this is the most convenient tmpfs
319 // storage mount available this early in the boot sequence.
320 char compiled_sepolicy[] = "/dev/sepolicy.XXXXXX";
321 unique_fd compiled_sepolicy_fd(mkostemp(compiled_sepolicy, O_CLOEXEC));
322 if (compiled_sepolicy_fd < 0) {
323 PLOG(ERROR) << "Failed to create temporary file " << compiled_sepolicy;
324 return false;
325 }
326
327 // Determine which mapping file to include
328 std::string vend_plat_vers;
329 if (!GetVendorMappingVersion(&vend_plat_vers)) {
330 return false;
331 }
Tri Vo503f1852019-01-16 11:57:19 -0800332 std::string plat_mapping_file("/system/etc/selinux/mapping/" + vend_plat_vers + ".cil");
kaichieheef4cd72017-08-31 22:07:19 +0800333
Jeff Vander Stoep0ac51cf2019-05-02 14:05:18 -0700334 std::string plat_compat_cil_file("/system/etc/selinux/mapping/" + vend_plat_vers +
335 ".compat.cil");
336 if (access(plat_compat_cil_file.c_str(), F_OK) == -1) {
337 plat_compat_cil_file.clear();
338 }
339
Tri Vod3518cf2018-12-14 14:25:08 -0800340 std::string product_policy_cil_file("/product/etc/selinux/product_sepolicy.cil");
341 if (access(product_policy_cil_file.c_str(), F_OK) == -1) {
342 product_policy_cil_file.clear();
343 }
344
Tri Vo503f1852019-01-16 11:57:19 -0800345 std::string product_mapping_file("/product/etc/selinux/mapping/" + vend_plat_vers + ".cil");
346 if (access(product_mapping_file.c_str(), F_OK) == -1) {
347 product_mapping_file.clear();
348 }
349
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800350 // vendor_sepolicy.cil and plat_pub_versioned.cil are the new design to replace
kaichieheef4cd72017-08-31 22:07:19 +0800351 // nonplat_sepolicy.cil.
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800352 std::string plat_pub_versioned_cil_file("/vendor/etc/selinux/plat_pub_versioned.cil");
kaichieheef4cd72017-08-31 22:07:19 +0800353 std::string vendor_policy_cil_file("/vendor/etc/selinux/vendor_sepolicy.cil");
354
355 if (access(vendor_policy_cil_file.c_str(), F_OK) == -1) {
356 // For backward compatibility.
357 // TODO: remove this after no device is using nonplat_sepolicy.cil.
358 vendor_policy_cil_file = "/vendor/etc/selinux/nonplat_sepolicy.cil";
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800359 plat_pub_versioned_cil_file.clear();
360 } else if (access(plat_pub_versioned_cil_file.c_str(), F_OK) == -1) {
361 LOG(ERROR) << "Missing " << plat_pub_versioned_cil_file;
kaichieheef4cd72017-08-31 22:07:19 +0800362 return false;
363 }
364
365 // odm_sepolicy.cil is default but optional.
366 std::string odm_policy_cil_file("/odm/etc/selinux/odm_sepolicy.cil");
367 if (access(odm_policy_cil_file.c_str(), F_OK) == -1) {
368 odm_policy_cil_file.clear();
369 }
Jeff Vander Stoep724eda52019-02-15 12:13:38 -0800370 const std::string version_as_string = std::to_string(SEPOLICY_VERSION);
Andreas Huberc41b8382017-08-18 14:43:52 -0700371
Tom Cherryc3170092017-08-10 12:22:44 -0700372 // clang-format off
kaichieheef4cd72017-08-31 22:07:19 +0800373 std::vector<const char*> compile_args {
Tom Cherryc3170092017-08-10 12:22:44 -0700374 "/system/bin/secilc",
Bowgo Tsai30afda72019-04-11 23:57:24 +0800375 use_userdebug_policy ? kDebugRamdiskSEPolicy: plat_policy_cil_file,
Jeff Vander Stoep5e9ba3c2017-10-06 17:03:45 -0700376 "-m", "-M", "true", "-G", "-N",
Andreas Huberc41b8382017-08-18 14:43:52 -0700377 "-c", version_as_string.c_str(),
Tri Vo503f1852019-01-16 11:57:19 -0800378 plat_mapping_file.c_str(),
Tom Cherryc3170092017-08-10 12:22:44 -0700379 "-o", compiled_sepolicy,
380 // We don't care about file_contexts output by the compiler
381 "-f", "/sys/fs/selinux/null", // /dev/null is not yet available
kaichieheef4cd72017-08-31 22:07:19 +0800382 };
Tom Cherryc3170092017-08-10 12:22:44 -0700383 // clang-format on
384
Jeff Vander Stoep0ac51cf2019-05-02 14:05:18 -0700385 if (!plat_compat_cil_file.empty()) {
386 compile_args.push_back(plat_compat_cil_file.c_str());
387 }
Tri Vod3518cf2018-12-14 14:25:08 -0800388 if (!product_policy_cil_file.empty()) {
389 compile_args.push_back(product_policy_cil_file.c_str());
390 }
Tri Vo503f1852019-01-16 11:57:19 -0800391 if (!product_mapping_file.empty()) {
392 compile_args.push_back(product_mapping_file.c_str());
393 }
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800394 if (!plat_pub_versioned_cil_file.empty()) {
395 compile_args.push_back(plat_pub_versioned_cil_file.c_str());
kaichieheef4cd72017-08-31 22:07:19 +0800396 }
397 if (!vendor_policy_cil_file.empty()) {
398 compile_args.push_back(vendor_policy_cil_file.c_str());
399 }
400 if (!odm_policy_cil_file.empty()) {
401 compile_args.push_back(odm_policy_cil_file.c_str());
402 }
403 compile_args.push_back(nullptr);
404
405 if (!ForkExecveAndWaitForCompletion(compile_args[0], (char**)compile_args.data())) {
Tom Cherryc3170092017-08-10 12:22:44 -0700406 unlink(compiled_sepolicy);
407 return false;
408 }
409 unlink(compiled_sepolicy);
410
411 LOG(INFO) << "Loading compiled SELinux policy";
412 if (selinux_android_load_policy_from_fd(compiled_sepolicy_fd, compiled_sepolicy) < 0) {
413 LOG(ERROR) << "Failed to load SELinux policy from " << compiled_sepolicy;
414 return false;
415 }
416
417 return true;
418}
419
420bool LoadMonolithicPolicy() {
421 LOG(VERBOSE) << "Loading SELinux policy from monolithic file";
422 if (selinux_android_load_policy() < 0) {
423 PLOG(ERROR) << "Failed to load monolithic SELinux policy";
424 return false;
425 }
426 return true;
427}
428
429bool LoadPolicy() {
430 return IsSplitPolicyDevice() ? LoadSplitPolicy() : LoadMonolithicPolicy();
431}
432
Tom Cherryc3170092017-08-10 12:22:44 -0700433void SelinuxInitialize() {
Tom Cherryc3170092017-08-10 12:22:44 -0700434 LOG(INFO) << "Loading SELinux policy";
435 if (!LoadPolicy()) {
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700436 LOG(FATAL) << "Unable to load SELinux policy";
Tom Cherryc3170092017-08-10 12:22:44 -0700437 }
438
439 bool kernel_enforcing = (security_getenforce() == 1);
440 bool is_enforcing = IsEnforcing();
441 if (kernel_enforcing != is_enforcing) {
442 if (security_setenforce(is_enforcing)) {
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700443 PLOG(FATAL) << "security_setenforce(%s) failed" << (is_enforcing ? "true" : "false");
Tom Cherryc3170092017-08-10 12:22:44 -0700444 }
445 }
446
Tom Cherry11a3aee2017-08-03 12:54:07 -0700447 if (auto result = WriteFile("/sys/fs/selinux/checkreqprot", "0"); !result) {
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700448 LOG(FATAL) << "Unable to write to /sys/fs/selinux/checkreqprot: " << result.error();
Tom Cherryc3170092017-08-10 12:22:44 -0700449 }
Tom Cherryc3170092017-08-10 12:22:44 -0700450}
451
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800452} // namespace
453
Tom Cherryc3170092017-08-10 12:22:44 -0700454// The files and directories that were created before initial sepolicy load or
455// files on ramdisk need to have their security context restored to the proper
456// value. This must happen before /dev is populated by ueventd.
457void SelinuxRestoreContext() {
458 LOG(INFO) << "Running restorecon...";
459 selinux_android_restorecon("/dev", 0);
460 selinux_android_restorecon("/dev/kmsg", 0);
461 if constexpr (WORLD_WRITABLE_KMSG) {
462 selinux_android_restorecon("/dev/kmsg_debug", 0);
463 }
Tom Cherry81ae0752018-07-30 16:23:49 -0700464 selinux_android_restorecon("/dev/null", 0);
465 selinux_android_restorecon("/dev/ptmx", 0);
Tom Cherryc3170092017-08-10 12:22:44 -0700466 selinux_android_restorecon("/dev/socket", 0);
467 selinux_android_restorecon("/dev/random", 0);
468 selinux_android_restorecon("/dev/urandom", 0);
469 selinux_android_restorecon("/dev/__properties__", 0);
470
Tom Cherryc3170092017-08-10 12:22:44 -0700471 selinux_android_restorecon("/dev/block", SELINUX_ANDROID_RESTORECON_RECURSE);
472 selinux_android_restorecon("/dev/device-mapper", 0);
Jiyong Park4ba548d2019-02-22 16:04:35 +0900473
474 selinux_android_restorecon("/apex", 0);
Tom Cherryc3170092017-08-10 12:22:44 -0700475}
476
Tom Cherry74069d12018-07-20 15:26:25 -0700477int SelinuxKlogCallback(int type, const char* fmt, ...) {
478 android::base::LogSeverity severity = android::base::ERROR;
479 if (type == SELINUX_WARNING) {
480 severity = android::base::WARNING;
481 } else if (type == SELINUX_INFO) {
482 severity = android::base::INFO;
483 }
484 char buf[1024];
485 va_list ap;
486 va_start(ap, fmt);
487 vsnprintf(buf, sizeof(buf), fmt, ap);
488 va_end(ap);
489 android::base::KernelLogger(android::base::MAIN, severity, "selinux", nullptr, 0, buf);
490 return 0;
491}
492
Tom Cherryc3170092017-08-10 12:22:44 -0700493// This function sets up SELinux logging to be written to kmsg, to match init's logging.
494void SelinuxSetupKernelLogging() {
495 selinux_callback cb;
Tom Cherry74069d12018-07-20 15:26:25 -0700496 cb.func_log = SelinuxKlogCallback;
Tom Cherryc3170092017-08-10 12:22:44 -0700497 selinux_set_callback(SELINUX_CB_LOG, cb);
498}
499
Tom Cherry40acb372018-08-01 13:41:12 -0700500// This function returns the Android version with which the vendor SEPolicy was compiled.
501// It is used for version checks such as whether or not vendor_init should be used
502int SelinuxGetVendorAndroidVersion() {
Logan Chien837b2a42018-05-03 14:33:52 +0800503 if (!IsSplitPolicyDevice()) {
Tom Cherry40acb372018-08-01 13:41:12 -0700504 // If this device does not split sepolicy files, it's not a Treble device and therefore,
505 // we assume it's always on the latest platform.
506 return __ANDROID_API_FUTURE__;
Logan Chien837b2a42018-05-03 14:33:52 +0800507 }
508
509 std::string version;
510 if (!GetVendorMappingVersion(&version)) {
Tom Cherry40acb372018-08-01 13:41:12 -0700511 LOG(FATAL) << "Could not read vendor SELinux version";
Logan Chien837b2a42018-05-03 14:33:52 +0800512 }
513
514 int major_version;
515 std::string major_version_str(version, 0, version.find('.'));
516 if (!ParseInt(major_version_str, &major_version)) {
Tom Cherry40acb372018-08-01 13:41:12 -0700517 PLOG(FATAL) << "Failed to parse the vendor sepolicy major version " << major_version_str;
Logan Chien837b2a42018-05-03 14:33:52 +0800518 }
519
Tom Cherry40acb372018-08-01 13:41:12 -0700520 return major_version;
Logan Chien837b2a42018-05-03 14:33:52 +0800521}
522
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800523// This function initializes SELinux then execs init to run in the init SELinux context.
524int SetupSelinux(char** argv) {
525 android::base::InitLogging(argv, &android::base::KernelLogger, [](const char*) {
526 RebootSystem(ANDROID_RB_RESTART2, "bootloader");
527 });
528
529 if (REBOOT_BOOTLOADER_ON_PANIC) {
530 InstallRebootSignalHandlers();
531 }
532
Mark Salyzyn10377df2019-03-27 08:10:41 -0700533 boot_clock::time_point start_time = boot_clock::now();
534
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800535 // Set up SELinux, loading the SELinux policy.
536 SelinuxSetupKernelLogging();
537 SelinuxInitialize();
538
539 // We're in the kernel domain and want to transition to the init domain. File systems that
540 // store SELabels in their xattrs, such as ext4 do not need an explicit restorecon here,
541 // but other file systems do. In particular, this is needed for ramdisks such as the
542 // recovery image for A/B devices.
543 if (selinux_android_restorecon("/system/bin/init", 0) == -1) {
544 PLOG(FATAL) << "restorecon failed of /system/bin/init failed";
545 }
546
Mark Salyzyn44505ec2019-05-08 12:44:50 -0700547 setenv(kEnvSelinuxStartedAt, std::to_string(start_time.time_since_epoch().count()).c_str(), 1);
Mark Salyzyn10377df2019-03-27 08:10:41 -0700548
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800549 const char* path = "/system/bin/init";
550 const char* args[] = {path, "second_stage", nullptr};
551 execv(path, const_cast<char**>(args));
552
553 // execv() only returns if an error happened, in which case we
554 // panic and never return from this function.
555 PLOG(FATAL) << "execv(\"" << path << "\") failed";
556
557 return 1;
558}
559
Tom Cherryc3170092017-08-10 12:22:44 -0700560// selinux_android_file_context_handle() takes on the order of 10+ms to run, so we want to cache
561// its value. selinux_android_restorecon() also needs an sehandle for file context look up. It
562// will create and store its own copy, but selinux_android_set_sehandle() can be used to provide
563// one, thus eliminating an extra call to selinux_android_file_context_handle().
564void SelabelInitialize() {
565 sehandle = selinux_android_file_context_handle();
566 selinux_android_set_sehandle(sehandle);
567}
568
569// A C++ wrapper around selabel_lookup() using the cached sehandle.
570// If sehandle is null, this returns success with an empty context.
571bool SelabelLookupFileContext(const std::string& key, int type, std::string* result) {
572 result->clear();
573
574 if (!sehandle) return true;
575
576 char* context;
577 if (selabel_lookup(sehandle, &context, key.c_str(), type) != 0) {
578 return false;
579 }
580 *result = context;
581 free(context);
582 return true;
583}
584
585// A C++ wrapper around selabel_lookup_best_match() using the cached sehandle.
586// If sehandle is null, this returns success with an empty context.
587bool SelabelLookupFileContextBestMatch(const std::string& key,
588 const std::vector<std::string>& aliases, int type,
589 std::string* result) {
590 result->clear();
591
592 if (!sehandle) return true;
593
594 std::vector<const char*> c_aliases;
595 for (const auto& alias : aliases) {
596 c_aliases.emplace_back(alias.c_str());
597 }
598 c_aliases.emplace_back(nullptr);
599
600 char* context;
601 if (selabel_lookup_best_match(sehandle, &context, key.c_str(), &c_aliases[0], type) != 0) {
602 return false;
603 }
604 *result = context;
605 free(context);
606 return true;
607}
608
609} // namespace init
610} // namespace android