blob: 3a0909664a8ab90bd272acd8ecfbae7731f6afa4 [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:
37// 1) There is a precompiled SEPolicy located at /vendor/etc/selinux/precompiled_sepolicy.
38// Stored along with this file is the sha256 hash of the parts of the SEPolicy on /system that
39// were used to compile this precompiled policy. The system partition contains a similar sha256
40// of the parts of the SEPolicy that it currently contains. If these two hashes match, then the
41// system loads this precompiled_sepolicy directly.
42// 2) If these hashes do not match, then /system has been updated out of sync with /vendor and the
43// init needs to compile the SEPolicy. /system contains the SEPolicy compiler, secilc, and it
44// is used by the LoadSplitPolicy() function below to compile the SEPolicy to a temp directory
45// and load it. That function contains even more documentation with the specific implementation
46// details of how the SEPolicy is compiled if needed.
47
48#include "selinux.h"
49
Tom Cherry40acb372018-08-01 13:41:12 -070050#include <android/api-level.h>
Tom Cherryc3170092017-08-10 12:22:44 -070051#include <fcntl.h>
Tom Cherryc3170092017-08-10 12:22:44 -070052#include <stdlib.h>
53#include <sys/wait.h>
54#include <unistd.h>
55
56#include <android-base/chrono_utils.h>
57#include <android-base/file.h>
58#include <android-base/logging.h>
Logan Chien837b2a42018-05-03 14:33:52 +080059#include <android-base/parseint.h>
Tom Cherryc3170092017-08-10 12:22:44 -070060#include <android-base/unique_fd.h>
Tom Cherry7bfea3d2018-11-06 14:12:05 -080061#include <cutils/android_reboot.h>
Tom Cherryc3170092017-08-10 12:22:44 -070062#include <selinux/android.h>
63
Tom Cherry7bfea3d2018-11-06 14:12:05 -080064#include "reboot_utils.h"
Tom Cherryc3170092017-08-10 12:22:44 -070065#include "util.h"
66
Logan Chien837b2a42018-05-03 14:33:52 +080067using android::base::ParseInt;
Tom Cherryc3170092017-08-10 12:22:44 -070068using android::base::Timer;
69using android::base::unique_fd;
70
71namespace android {
72namespace init {
73
Tom Cherryc3170092017-08-10 12:22:44 -070074namespace {
75
Tom Cherry94f3bcd2017-08-17 16:52:10 -070076selabel_handle* sehandle = nullptr;
77
Tom Cherryc3170092017-08-10 12:22:44 -070078enum EnforcingStatus { SELINUX_PERMISSIVE, SELINUX_ENFORCING };
79
80EnforcingStatus StatusFromCmdline() {
81 EnforcingStatus status = SELINUX_ENFORCING;
82
83 import_kernel_cmdline(false,
84 [&](const std::string& key, const std::string& value, bool in_qemu) {
85 if (key == "androidboot.selinux" && value == "permissive") {
86 status = SELINUX_PERMISSIVE;
87 }
88 });
89
90 return status;
91}
92
93bool IsEnforcing() {
94 if (ALLOW_PERMISSIVE_SELINUX) {
95 return StatusFromCmdline() == SELINUX_ENFORCING;
96 }
97 return true;
98}
99
100// Forks, executes the provided program in the child, and waits for the completion in the parent.
101// Child's stderr is captured and logged using LOG(ERROR).
102bool ForkExecveAndWaitForCompletion(const char* filename, char* const argv[]) {
103 // Create a pipe used for redirecting child process's output.
104 // * pipe_fds[0] is the FD the parent will use for reading.
105 // * pipe_fds[1] is the FD the child will use for writing.
106 int pipe_fds[2];
107 if (pipe(pipe_fds) == -1) {
108 PLOG(ERROR) << "Failed to create pipe";
109 return false;
110 }
111
112 pid_t child_pid = fork();
113 if (child_pid == -1) {
114 PLOG(ERROR) << "Failed to fork for " << filename;
115 return false;
116 }
117
118 if (child_pid == 0) {
119 // fork succeeded -- this is executing in the child process
120
121 // Close the pipe FD not used by this process
Nick Kralevich3d118e72017-10-24 10:45:48 -0700122 close(pipe_fds[0]);
Tom Cherryc3170092017-08-10 12:22:44 -0700123
124 // Redirect stderr to the pipe FD provided by the parent
125 if (TEMP_FAILURE_RETRY(dup2(pipe_fds[1], STDERR_FILENO)) == -1) {
126 PLOG(ERROR) << "Failed to redirect stderr of " << filename;
127 _exit(127);
128 return false;
129 }
Nick Kralevich3d118e72017-10-24 10:45:48 -0700130 close(pipe_fds[1]);
Tom Cherryc3170092017-08-10 12:22:44 -0700131
Tom Cherry6de21f12017-08-22 15:41:03 -0700132 if (execv(filename, argv) == -1) {
Tom Cherryc3170092017-08-10 12:22:44 -0700133 PLOG(ERROR) << "Failed to execve " << filename;
134 return false;
135 }
136 // Unreachable because execve will have succeeded and replaced this code
137 // with child process's code.
138 _exit(127);
139 return false;
140 } else {
141 // fork succeeded -- this is executing in the original/parent process
142
143 // Close the pipe FD not used by this process
Nick Kralevich3d118e72017-10-24 10:45:48 -0700144 close(pipe_fds[1]);
Tom Cherryc3170092017-08-10 12:22:44 -0700145
146 // Log the redirected output of the child process.
147 // It's unfortunate that there's no standard way to obtain an istream for a file descriptor.
148 // As a result, we're buffering all output and logging it in one go at the end of the
149 // invocation, instead of logging it as it comes in.
150 const int child_out_fd = pipe_fds[0];
151 std::string child_output;
152 if (!android::base::ReadFdToString(child_out_fd, &child_output)) {
153 PLOG(ERROR) << "Failed to capture full output of " << filename;
154 }
Nick Kralevich3d118e72017-10-24 10:45:48 -0700155 close(child_out_fd);
Tom Cherryc3170092017-08-10 12:22:44 -0700156 if (!child_output.empty()) {
157 // Log captured output, line by line, because LOG expects to be invoked for each line
158 std::istringstream in(child_output);
159 std::string line;
160 while (std::getline(in, line)) {
161 LOG(ERROR) << filename << ": " << line;
162 }
163 }
164
165 // Wait for child to terminate
166 int status;
167 if (TEMP_FAILURE_RETRY(waitpid(child_pid, &status, 0)) != child_pid) {
168 PLOG(ERROR) << "Failed to wait for " << filename;
169 return false;
170 }
171
172 if (WIFEXITED(status)) {
173 int status_code = WEXITSTATUS(status);
174 if (status_code == 0) {
175 return true;
176 } else {
177 LOG(ERROR) << filename << " exited with status " << status_code;
178 }
179 } else if (WIFSIGNALED(status)) {
180 LOG(ERROR) << filename << " killed by signal " << WTERMSIG(status);
181 } else if (WIFSTOPPED(status)) {
182 LOG(ERROR) << filename << " stopped by signal " << WSTOPSIG(status);
183 } else {
184 LOG(ERROR) << "waitpid for " << filename << " returned unexpected status: " << status;
185 }
186
187 return false;
188 }
189}
190
191bool ReadFirstLine(const char* file, std::string* line) {
192 line->clear();
193
194 std::string contents;
195 if (!android::base::ReadFileToString(file, &contents, true /* follow symlinks */)) {
196 return false;
197 }
198 std::istringstream in(contents);
199 std::getline(in, *line);
200 return true;
201}
202
203bool FindPrecompiledSplitPolicy(std::string* file) {
204 file->clear();
kaichieheef4cd72017-08-31 22:07:19 +0800205 // If there is an odm partition, precompiled_sepolicy will be in
206 // odm/etc/selinux. Otherwise it will be in vendor/etc/selinux.
207 static constexpr const char vendor_precompiled_sepolicy[] =
208 "/vendor/etc/selinux/precompiled_sepolicy";
209 static constexpr const char odm_precompiled_sepolicy[] =
210 "/odm/etc/selinux/precompiled_sepolicy";
211 if (access(odm_precompiled_sepolicy, R_OK) == 0) {
212 *file = odm_precompiled_sepolicy;
213 } else if (access(vendor_precompiled_sepolicy, R_OK) == 0) {
214 *file = vendor_precompiled_sepolicy;
215 } else {
216 PLOG(INFO) << "No precompiled sepolicy";
Tom Cherryc3170092017-08-10 12:22:44 -0700217 return false;
218 }
219 std::string actual_plat_id;
220 if (!ReadFirstLine("/system/etc/selinux/plat_and_mapping_sepolicy.cil.sha256", &actual_plat_id)) {
221 PLOG(INFO) << "Failed to read "
222 "/system/etc/selinux/plat_and_mapping_sepolicy.cil.sha256";
223 return false;
224 }
kaichieheef4cd72017-08-31 22:07:19 +0800225
Tom Cherryc3170092017-08-10 12:22:44 -0700226 std::string precompiled_plat_id;
kaichieheef4cd72017-08-31 22:07:19 +0800227 std::string precompiled_sha256 = *file + ".plat_and_mapping.sha256";
228 if (!ReadFirstLine(precompiled_sha256.c_str(), &precompiled_plat_id)) {
229 PLOG(INFO) << "Failed to read " << precompiled_sha256;
230 file->clear();
Tom Cherryc3170092017-08-10 12:22:44 -0700231 return false;
232 }
233 if ((actual_plat_id.empty()) || (actual_plat_id != precompiled_plat_id)) {
kaichieheef4cd72017-08-31 22:07:19 +0800234 file->clear();
Tom Cherryc3170092017-08-10 12:22:44 -0700235 return false;
236 }
Tom Cherryc3170092017-08-10 12:22:44 -0700237 return true;
238}
239
240bool GetVendorMappingVersion(std::string* plat_vers) {
241 if (!ReadFirstLine("/vendor/etc/selinux/plat_sepolicy_vers.txt", plat_vers)) {
242 PLOG(ERROR) << "Failed to read /vendor/etc/selinux/plat_sepolicy_vers.txt";
243 return false;
244 }
245 if (plat_vers->empty()) {
246 LOG(ERROR) << "No version present in plat_sepolicy_vers.txt";
247 return false;
248 }
249 return true;
250}
251
252constexpr const char plat_policy_cil_file[] = "/system/etc/selinux/plat_sepolicy.cil";
253
254bool IsSplitPolicyDevice() {
255 return access(plat_policy_cil_file, R_OK) != -1;
256}
257
258bool LoadSplitPolicy() {
259 // IMPLEMENTATION NOTE: Split policy consists of three CIL files:
260 // * platform -- policy needed due to logic contained in the system image,
261 // * non-platform -- policy needed due to logic contained in the vendor image,
262 // * mapping -- mapping policy which helps preserve forward-compatibility of non-platform policy
263 // with newer versions of platform policy.
264 //
265 // secilc is invoked to compile the above three policy files into a single monolithic policy
266 // file. This file is then loaded into the kernel.
267
268 // Load precompiled policy from vendor image, if a matching policy is found there. The policy
269 // must match the platform policy on the system image.
270 std::string precompiled_sepolicy_file;
271 if (FindPrecompiledSplitPolicy(&precompiled_sepolicy_file)) {
272 unique_fd fd(open(precompiled_sepolicy_file.c_str(), O_RDONLY | O_CLOEXEC | O_BINARY));
273 if (fd != -1) {
274 if (selinux_android_load_policy_from_fd(fd, precompiled_sepolicy_file.c_str()) < 0) {
275 LOG(ERROR) << "Failed to load SELinux policy from " << precompiled_sepolicy_file;
276 return false;
277 }
278 return true;
279 }
280 }
281 // No suitable precompiled policy could be loaded
282
283 LOG(INFO) << "Compiling SELinux policy";
284
285 // Determine the highest policy language version supported by the kernel
286 set_selinuxmnt("/sys/fs/selinux");
287 int max_policy_version = security_policyvers();
288 if (max_policy_version == -1) {
289 PLOG(ERROR) << "Failed to determine highest policy version supported by kernel";
290 return false;
291 }
292
293 // We store the output of the compilation on /dev because this is the most convenient tmpfs
294 // storage mount available this early in the boot sequence.
295 char compiled_sepolicy[] = "/dev/sepolicy.XXXXXX";
296 unique_fd compiled_sepolicy_fd(mkostemp(compiled_sepolicy, O_CLOEXEC));
297 if (compiled_sepolicy_fd < 0) {
298 PLOG(ERROR) << "Failed to create temporary file " << compiled_sepolicy;
299 return false;
300 }
301
302 // Determine which mapping file to include
303 std::string vend_plat_vers;
304 if (!GetVendorMappingVersion(&vend_plat_vers)) {
305 return false;
306 }
307 std::string mapping_file("/system/etc/selinux/mapping/" + vend_plat_vers + ".cil");
kaichieheef4cd72017-08-31 22:07:19 +0800308
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800309 // vendor_sepolicy.cil and plat_pub_versioned.cil are the new design to replace
kaichieheef4cd72017-08-31 22:07:19 +0800310 // nonplat_sepolicy.cil.
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800311 std::string plat_pub_versioned_cil_file("/vendor/etc/selinux/plat_pub_versioned.cil");
kaichieheef4cd72017-08-31 22:07:19 +0800312 std::string vendor_policy_cil_file("/vendor/etc/selinux/vendor_sepolicy.cil");
313
314 if (access(vendor_policy_cil_file.c_str(), F_OK) == -1) {
315 // For backward compatibility.
316 // TODO: remove this after no device is using nonplat_sepolicy.cil.
317 vendor_policy_cil_file = "/vendor/etc/selinux/nonplat_sepolicy.cil";
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800318 plat_pub_versioned_cil_file.clear();
319 } else if (access(plat_pub_versioned_cil_file.c_str(), F_OK) == -1) {
320 LOG(ERROR) << "Missing " << plat_pub_versioned_cil_file;
kaichieheef4cd72017-08-31 22:07:19 +0800321 return false;
322 }
323
324 // odm_sepolicy.cil is default but optional.
325 std::string odm_policy_cil_file("/odm/etc/selinux/odm_sepolicy.cil");
326 if (access(odm_policy_cil_file.c_str(), F_OK) == -1) {
327 odm_policy_cil_file.clear();
328 }
Andreas Huberc41b8382017-08-18 14:43:52 -0700329 const std::string version_as_string = std::to_string(max_policy_version);
330
Tom Cherryc3170092017-08-10 12:22:44 -0700331 // clang-format off
kaichieheef4cd72017-08-31 22:07:19 +0800332 std::vector<const char*> compile_args {
Tom Cherryc3170092017-08-10 12:22:44 -0700333 "/system/bin/secilc",
334 plat_policy_cil_file,
Jeff Vander Stoep5e9ba3c2017-10-06 17:03:45 -0700335 "-m", "-M", "true", "-G", "-N",
Tom Cherryc3170092017-08-10 12:22:44 -0700336 // Target the highest policy language version supported by the kernel
Andreas Huberc41b8382017-08-18 14:43:52 -0700337 "-c", version_as_string.c_str(),
Tom Cherryc3170092017-08-10 12:22:44 -0700338 mapping_file.c_str(),
Tom Cherryc3170092017-08-10 12:22:44 -0700339 "-o", compiled_sepolicy,
340 // We don't care about file_contexts output by the compiler
341 "-f", "/sys/fs/selinux/null", // /dev/null is not yet available
kaichieheef4cd72017-08-31 22:07:19 +0800342 };
Tom Cherryc3170092017-08-10 12:22:44 -0700343 // clang-format on
344
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800345 if (!plat_pub_versioned_cil_file.empty()) {
346 compile_args.push_back(plat_pub_versioned_cil_file.c_str());
kaichieheef4cd72017-08-31 22:07:19 +0800347 }
348 if (!vendor_policy_cil_file.empty()) {
349 compile_args.push_back(vendor_policy_cil_file.c_str());
350 }
351 if (!odm_policy_cil_file.empty()) {
352 compile_args.push_back(odm_policy_cil_file.c_str());
353 }
354 compile_args.push_back(nullptr);
355
356 if (!ForkExecveAndWaitForCompletion(compile_args[0], (char**)compile_args.data())) {
Tom Cherryc3170092017-08-10 12:22:44 -0700357 unlink(compiled_sepolicy);
358 return false;
359 }
360 unlink(compiled_sepolicy);
361
362 LOG(INFO) << "Loading compiled SELinux policy";
363 if (selinux_android_load_policy_from_fd(compiled_sepolicy_fd, compiled_sepolicy) < 0) {
364 LOG(ERROR) << "Failed to load SELinux policy from " << compiled_sepolicy;
365 return false;
366 }
367
368 return true;
369}
370
371bool LoadMonolithicPolicy() {
372 LOG(VERBOSE) << "Loading SELinux policy from monolithic file";
373 if (selinux_android_load_policy() < 0) {
374 PLOG(ERROR) << "Failed to load monolithic SELinux policy";
375 return false;
376 }
377 return true;
378}
379
380bool LoadPolicy() {
381 return IsSplitPolicyDevice() ? LoadSplitPolicy() : LoadMonolithicPolicy();
382}
383
Tom Cherryc3170092017-08-10 12:22:44 -0700384void SelinuxInitialize() {
385 Timer t;
386
387 LOG(INFO) << "Loading SELinux policy";
388 if (!LoadPolicy()) {
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700389 LOG(FATAL) << "Unable to load SELinux policy";
Tom Cherryc3170092017-08-10 12:22:44 -0700390 }
391
392 bool kernel_enforcing = (security_getenforce() == 1);
393 bool is_enforcing = IsEnforcing();
394 if (kernel_enforcing != is_enforcing) {
395 if (security_setenforce(is_enforcing)) {
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700396 PLOG(FATAL) << "security_setenforce(%s) failed" << (is_enforcing ? "true" : "false");
Tom Cherryc3170092017-08-10 12:22:44 -0700397 }
398 }
399
Tom Cherry11a3aee2017-08-03 12:54:07 -0700400 if (auto result = WriteFile("/sys/fs/selinux/checkreqprot", "0"); !result) {
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700401 LOG(FATAL) << "Unable to write to /sys/fs/selinux/checkreqprot: " << result.error();
Tom Cherryc3170092017-08-10 12:22:44 -0700402 }
403
404 // init's first stage can't set properties, so pass the time to the second stage.
405 setenv("INIT_SELINUX_TOOK", std::to_string(t.duration().count()).c_str(), 1);
406}
407
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800408} // namespace
409
Tom Cherryc3170092017-08-10 12:22:44 -0700410// The files and directories that were created before initial sepolicy load or
411// files on ramdisk need to have their security context restored to the proper
412// value. This must happen before /dev is populated by ueventd.
413void SelinuxRestoreContext() {
414 LOG(INFO) << "Running restorecon...";
415 selinux_android_restorecon("/dev", 0);
416 selinux_android_restorecon("/dev/kmsg", 0);
417 if constexpr (WORLD_WRITABLE_KMSG) {
418 selinux_android_restorecon("/dev/kmsg_debug", 0);
419 }
Tom Cherry81ae0752018-07-30 16:23:49 -0700420 selinux_android_restorecon("/dev/null", 0);
421 selinux_android_restorecon("/dev/ptmx", 0);
Tom Cherryc3170092017-08-10 12:22:44 -0700422 selinux_android_restorecon("/dev/socket", 0);
423 selinux_android_restorecon("/dev/random", 0);
424 selinux_android_restorecon("/dev/urandom", 0);
425 selinux_android_restorecon("/dev/__properties__", 0);
426
Tom Cherryc3170092017-08-10 12:22:44 -0700427 selinux_android_restorecon("/plat_file_contexts", 0);
428 selinux_android_restorecon("/nonplat_file_contexts", 0);
Bowgo Tsai36cf3532017-12-07 16:05:25 +0800429 selinux_android_restorecon("/vendor_file_contexts", 0);
Tom Cherryc3170092017-08-10 12:22:44 -0700430 selinux_android_restorecon("/plat_property_contexts", 0);
431 selinux_android_restorecon("/nonplat_property_contexts", 0);
Bowgo Tsai36cf3532017-12-07 16:05:25 +0800432 selinux_android_restorecon("/vendor_property_contexts", 0);
Tom Cherryc3170092017-08-10 12:22:44 -0700433 selinux_android_restorecon("/plat_seapp_contexts", 0);
434 selinux_android_restorecon("/nonplat_seapp_contexts", 0);
Bowgo Tsai36cf3532017-12-07 16:05:25 +0800435 selinux_android_restorecon("/vendor_seapp_contexts", 0);
Tom Cherryc3170092017-08-10 12:22:44 -0700436 selinux_android_restorecon("/plat_service_contexts", 0);
437 selinux_android_restorecon("/nonplat_service_contexts", 0);
Bowgo Tsai36cf3532017-12-07 16:05:25 +0800438 selinux_android_restorecon("/vendor_service_contexts", 0);
Tom Cherryc3170092017-08-10 12:22:44 -0700439 selinux_android_restorecon("/plat_hwservice_contexts", 0);
440 selinux_android_restorecon("/nonplat_hwservice_contexts", 0);
Bowgo Tsai36cf3532017-12-07 16:05:25 +0800441 selinux_android_restorecon("/vendor_hwservice_contexts", 0);
Tom Cherryc3170092017-08-10 12:22:44 -0700442 selinux_android_restorecon("/sepolicy", 0);
443 selinux_android_restorecon("/vndservice_contexts", 0);
444
445 selinux_android_restorecon("/dev/block", SELINUX_ANDROID_RESTORECON_RECURSE);
446 selinux_android_restorecon("/dev/device-mapper", 0);
447
448 selinux_android_restorecon("/sbin/mke2fs_static", 0);
449 selinux_android_restorecon("/sbin/e2fsdroid_static", 0);
Jaegeuk Kim899ad552017-11-28 19:26:34 -0800450
451 selinux_android_restorecon("/sbin/mkfs.f2fs", 0);
452 selinux_android_restorecon("/sbin/sload.f2fs", 0);
Tom Cherryc3170092017-08-10 12:22:44 -0700453}
454
Tom Cherry74069d12018-07-20 15:26:25 -0700455int SelinuxKlogCallback(int type, const char* fmt, ...) {
456 android::base::LogSeverity severity = android::base::ERROR;
457 if (type == SELINUX_WARNING) {
458 severity = android::base::WARNING;
459 } else if (type == SELINUX_INFO) {
460 severity = android::base::INFO;
461 }
462 char buf[1024];
463 va_list ap;
464 va_start(ap, fmt);
465 vsnprintf(buf, sizeof(buf), fmt, ap);
466 va_end(ap);
467 android::base::KernelLogger(android::base::MAIN, severity, "selinux", nullptr, 0, buf);
468 return 0;
469}
470
Tom Cherryc3170092017-08-10 12:22:44 -0700471// This function sets up SELinux logging to be written to kmsg, to match init's logging.
472void SelinuxSetupKernelLogging() {
473 selinux_callback cb;
Tom Cherry74069d12018-07-20 15:26:25 -0700474 cb.func_log = SelinuxKlogCallback;
Tom Cherryc3170092017-08-10 12:22:44 -0700475 selinux_set_callback(SELINUX_CB_LOG, cb);
476}
477
Tom Cherry40acb372018-08-01 13:41:12 -0700478// This function returns the Android version with which the vendor SEPolicy was compiled.
479// It is used for version checks such as whether or not vendor_init should be used
480int SelinuxGetVendorAndroidVersion() {
Logan Chien837b2a42018-05-03 14:33:52 +0800481 if (!IsSplitPolicyDevice()) {
Tom Cherry40acb372018-08-01 13:41:12 -0700482 // If this device does not split sepolicy files, it's not a Treble device and therefore,
483 // we assume it's always on the latest platform.
484 return __ANDROID_API_FUTURE__;
Logan Chien837b2a42018-05-03 14:33:52 +0800485 }
486
487 std::string version;
488 if (!GetVendorMappingVersion(&version)) {
Tom Cherry40acb372018-08-01 13:41:12 -0700489 LOG(FATAL) << "Could not read vendor SELinux version";
Logan Chien837b2a42018-05-03 14:33:52 +0800490 }
491
492 int major_version;
493 std::string major_version_str(version, 0, version.find('.'));
494 if (!ParseInt(major_version_str, &major_version)) {
Tom Cherry40acb372018-08-01 13:41:12 -0700495 PLOG(FATAL) << "Failed to parse the vendor sepolicy major version " << major_version_str;
Logan Chien837b2a42018-05-03 14:33:52 +0800496 }
497
Tom Cherry40acb372018-08-01 13:41:12 -0700498 return major_version;
Logan Chien837b2a42018-05-03 14:33:52 +0800499}
500
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800501// This function initializes SELinux then execs init to run in the init SELinux context.
502int SetupSelinux(char** argv) {
503 android::base::InitLogging(argv, &android::base::KernelLogger, [](const char*) {
504 RebootSystem(ANDROID_RB_RESTART2, "bootloader");
505 });
506
507 if (REBOOT_BOOTLOADER_ON_PANIC) {
508 InstallRebootSignalHandlers();
509 }
510
511 // Set up SELinux, loading the SELinux policy.
512 SelinuxSetupKernelLogging();
513 SelinuxInitialize();
514
515 // We're in the kernel domain and want to transition to the init domain. File systems that
516 // store SELabels in their xattrs, such as ext4 do not need an explicit restorecon here,
517 // but other file systems do. In particular, this is needed for ramdisks such as the
518 // recovery image for A/B devices.
519 if (selinux_android_restorecon("/system/bin/init", 0) == -1) {
520 PLOG(FATAL) << "restorecon failed of /system/bin/init failed";
521 }
522
523 const char* path = "/system/bin/init";
524 const char* args[] = {path, "second_stage", nullptr};
525 execv(path, const_cast<char**>(args));
526
527 // execv() only returns if an error happened, in which case we
528 // panic and never return from this function.
529 PLOG(FATAL) << "execv(\"" << path << "\") failed";
530
531 return 1;
532}
533
Tom Cherryc3170092017-08-10 12:22:44 -0700534// selinux_android_file_context_handle() takes on the order of 10+ms to run, so we want to cache
535// its value. selinux_android_restorecon() also needs an sehandle for file context look up. It
536// will create and store its own copy, but selinux_android_set_sehandle() can be used to provide
537// one, thus eliminating an extra call to selinux_android_file_context_handle().
538void SelabelInitialize() {
539 sehandle = selinux_android_file_context_handle();
540 selinux_android_set_sehandle(sehandle);
541}
542
543// A C++ wrapper around selabel_lookup() using the cached sehandle.
544// If sehandle is null, this returns success with an empty context.
545bool SelabelLookupFileContext(const std::string& key, int type, std::string* result) {
546 result->clear();
547
548 if (!sehandle) return true;
549
550 char* context;
551 if (selabel_lookup(sehandle, &context, key.c_str(), type) != 0) {
552 return false;
553 }
554 *result = context;
555 free(context);
556 return true;
557}
558
559// A C++ wrapper around selabel_lookup_best_match() using the cached sehandle.
560// If sehandle is null, this returns success with an empty context.
561bool SelabelLookupFileContextBestMatch(const std::string& key,
562 const std::vector<std::string>& aliases, int type,
563 std::string* result) {
564 result->clear();
565
566 if (!sehandle) return true;
567
568 std::vector<const char*> c_aliases;
569 for (const auto& alias : aliases) {
570 c_aliases.emplace_back(alias.c_str());
571 }
572 c_aliases.emplace_back(nullptr);
573
574 char* context;
575 if (selabel_lookup_best_match(sehandle, &context, key.c_str(), &c_aliases[0], type) != 0) {
576 return false;
577 }
578 *result = context;
579 free(context);
580 return true;
581}
582
583} // namespace init
584} // namespace android