blob: 132fc137d8926af53e6476695a02d3ed553246dc [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
Tri Vod3518cf2018-12-14 14:25:08 -0800334 std::string product_policy_cil_file("/product/etc/selinux/product_sepolicy.cil");
335 if (access(product_policy_cil_file.c_str(), F_OK) == -1) {
336 product_policy_cil_file.clear();
337 }
338
Tri Vo503f1852019-01-16 11:57:19 -0800339 std::string product_mapping_file("/product/etc/selinux/mapping/" + vend_plat_vers + ".cil");
340 if (access(product_mapping_file.c_str(), F_OK) == -1) {
341 product_mapping_file.clear();
342 }
343
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800344 // vendor_sepolicy.cil and plat_pub_versioned.cil are the new design to replace
kaichieheef4cd72017-08-31 22:07:19 +0800345 // nonplat_sepolicy.cil.
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800346 std::string plat_pub_versioned_cil_file("/vendor/etc/selinux/plat_pub_versioned.cil");
kaichieheef4cd72017-08-31 22:07:19 +0800347 std::string vendor_policy_cil_file("/vendor/etc/selinux/vendor_sepolicy.cil");
348
349 if (access(vendor_policy_cil_file.c_str(), F_OK) == -1) {
350 // For backward compatibility.
351 // TODO: remove this after no device is using nonplat_sepolicy.cil.
352 vendor_policy_cil_file = "/vendor/etc/selinux/nonplat_sepolicy.cil";
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800353 plat_pub_versioned_cil_file.clear();
354 } else if (access(plat_pub_versioned_cil_file.c_str(), F_OK) == -1) {
355 LOG(ERROR) << "Missing " << plat_pub_versioned_cil_file;
kaichieheef4cd72017-08-31 22:07:19 +0800356 return false;
357 }
358
359 // odm_sepolicy.cil is default but optional.
360 std::string odm_policy_cil_file("/odm/etc/selinux/odm_sepolicy.cil");
361 if (access(odm_policy_cil_file.c_str(), F_OK) == -1) {
362 odm_policy_cil_file.clear();
363 }
Jeff Vander Stoep724eda52019-02-15 12:13:38 -0800364 const std::string version_as_string = std::to_string(SEPOLICY_VERSION);
Andreas Huberc41b8382017-08-18 14:43:52 -0700365
Tom Cherryc3170092017-08-10 12:22:44 -0700366 // clang-format off
kaichieheef4cd72017-08-31 22:07:19 +0800367 std::vector<const char*> compile_args {
Tom Cherryc3170092017-08-10 12:22:44 -0700368 "/system/bin/secilc",
Bowgo Tsai30afda72019-04-11 23:57:24 +0800369 use_userdebug_policy ? kDebugRamdiskSEPolicy: plat_policy_cil_file,
Jeff Vander Stoep5e9ba3c2017-10-06 17:03:45 -0700370 "-m", "-M", "true", "-G", "-N",
Andreas Huberc41b8382017-08-18 14:43:52 -0700371 "-c", version_as_string.c_str(),
Tri Vo503f1852019-01-16 11:57:19 -0800372 plat_mapping_file.c_str(),
Tom Cherryc3170092017-08-10 12:22:44 -0700373 "-o", compiled_sepolicy,
374 // We don't care about file_contexts output by the compiler
375 "-f", "/sys/fs/selinux/null", // /dev/null is not yet available
kaichieheef4cd72017-08-31 22:07:19 +0800376 };
Tom Cherryc3170092017-08-10 12:22:44 -0700377 // clang-format on
378
Tri Vod3518cf2018-12-14 14:25:08 -0800379 if (!product_policy_cil_file.empty()) {
380 compile_args.push_back(product_policy_cil_file.c_str());
381 }
Tri Vo503f1852019-01-16 11:57:19 -0800382 if (!product_mapping_file.empty()) {
383 compile_args.push_back(product_mapping_file.c_str());
384 }
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800385 if (!plat_pub_versioned_cil_file.empty()) {
386 compile_args.push_back(plat_pub_versioned_cil_file.c_str());
kaichieheef4cd72017-08-31 22:07:19 +0800387 }
388 if (!vendor_policy_cil_file.empty()) {
389 compile_args.push_back(vendor_policy_cil_file.c_str());
390 }
391 if (!odm_policy_cil_file.empty()) {
392 compile_args.push_back(odm_policy_cil_file.c_str());
393 }
394 compile_args.push_back(nullptr);
395
396 if (!ForkExecveAndWaitForCompletion(compile_args[0], (char**)compile_args.data())) {
Tom Cherryc3170092017-08-10 12:22:44 -0700397 unlink(compiled_sepolicy);
398 return false;
399 }
400 unlink(compiled_sepolicy);
401
402 LOG(INFO) << "Loading compiled SELinux policy";
403 if (selinux_android_load_policy_from_fd(compiled_sepolicy_fd, compiled_sepolicy) < 0) {
404 LOG(ERROR) << "Failed to load SELinux policy from " << compiled_sepolicy;
405 return false;
406 }
407
408 return true;
409}
410
411bool LoadMonolithicPolicy() {
412 LOG(VERBOSE) << "Loading SELinux policy from monolithic file";
413 if (selinux_android_load_policy() < 0) {
414 PLOG(ERROR) << "Failed to load monolithic SELinux policy";
415 return false;
416 }
417 return true;
418}
419
420bool LoadPolicy() {
421 return IsSplitPolicyDevice() ? LoadSplitPolicy() : LoadMonolithicPolicy();
422}
423
Tom Cherryc3170092017-08-10 12:22:44 -0700424void SelinuxInitialize() {
425 Timer t;
426
427 LOG(INFO) << "Loading SELinux policy";
428 if (!LoadPolicy()) {
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700429 LOG(FATAL) << "Unable to load SELinux policy";
Tom Cherryc3170092017-08-10 12:22:44 -0700430 }
431
432 bool kernel_enforcing = (security_getenforce() == 1);
433 bool is_enforcing = IsEnforcing();
434 if (kernel_enforcing != is_enforcing) {
435 if (security_setenforce(is_enforcing)) {
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700436 PLOG(FATAL) << "security_setenforce(%s) failed" << (is_enforcing ? "true" : "false");
Tom Cherryc3170092017-08-10 12:22:44 -0700437 }
438 }
439
Tom Cherry11a3aee2017-08-03 12:54:07 -0700440 if (auto result = WriteFile("/sys/fs/selinux/checkreqprot", "0"); !result) {
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700441 LOG(FATAL) << "Unable to write to /sys/fs/selinux/checkreqprot: " << result.error();
Tom Cherryc3170092017-08-10 12:22:44 -0700442 }
443
444 // init's first stage can't set properties, so pass the time to the second stage.
445 setenv("INIT_SELINUX_TOOK", std::to_string(t.duration().count()).c_str(), 1);
446}
447
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800448} // namespace
449
Tom Cherryc3170092017-08-10 12:22:44 -0700450// The files and directories that were created before initial sepolicy load or
451// files on ramdisk need to have their security context restored to the proper
452// value. This must happen before /dev is populated by ueventd.
453void SelinuxRestoreContext() {
454 LOG(INFO) << "Running restorecon...";
455 selinux_android_restorecon("/dev", 0);
456 selinux_android_restorecon("/dev/kmsg", 0);
457 if constexpr (WORLD_WRITABLE_KMSG) {
458 selinux_android_restorecon("/dev/kmsg_debug", 0);
459 }
Tom Cherry81ae0752018-07-30 16:23:49 -0700460 selinux_android_restorecon("/dev/null", 0);
461 selinux_android_restorecon("/dev/ptmx", 0);
Tom Cherryc3170092017-08-10 12:22:44 -0700462 selinux_android_restorecon("/dev/socket", 0);
463 selinux_android_restorecon("/dev/random", 0);
464 selinux_android_restorecon("/dev/urandom", 0);
465 selinux_android_restorecon("/dev/__properties__", 0);
466
Tom Cherryc3170092017-08-10 12:22:44 -0700467 selinux_android_restorecon("/dev/block", SELINUX_ANDROID_RESTORECON_RECURSE);
468 selinux_android_restorecon("/dev/device-mapper", 0);
Jiyong Park4ba548d2019-02-22 16:04:35 +0900469
470 selinux_android_restorecon("/apex", 0);
Tom Cherryc3170092017-08-10 12:22:44 -0700471}
472
Tom Cherry74069d12018-07-20 15:26:25 -0700473int SelinuxKlogCallback(int type, const char* fmt, ...) {
474 android::base::LogSeverity severity = android::base::ERROR;
475 if (type == SELINUX_WARNING) {
476 severity = android::base::WARNING;
477 } else if (type == SELINUX_INFO) {
478 severity = android::base::INFO;
479 }
480 char buf[1024];
481 va_list ap;
482 va_start(ap, fmt);
483 vsnprintf(buf, sizeof(buf), fmt, ap);
484 va_end(ap);
485 android::base::KernelLogger(android::base::MAIN, severity, "selinux", nullptr, 0, buf);
486 return 0;
487}
488
Tom Cherryc3170092017-08-10 12:22:44 -0700489// This function sets up SELinux logging to be written to kmsg, to match init's logging.
490void SelinuxSetupKernelLogging() {
491 selinux_callback cb;
Tom Cherry74069d12018-07-20 15:26:25 -0700492 cb.func_log = SelinuxKlogCallback;
Tom Cherryc3170092017-08-10 12:22:44 -0700493 selinux_set_callback(SELINUX_CB_LOG, cb);
494}
495
Tom Cherry40acb372018-08-01 13:41:12 -0700496// This function returns the Android version with which the vendor SEPolicy was compiled.
497// It is used for version checks such as whether or not vendor_init should be used
498int SelinuxGetVendorAndroidVersion() {
Logan Chien837b2a42018-05-03 14:33:52 +0800499 if (!IsSplitPolicyDevice()) {
Tom Cherry40acb372018-08-01 13:41:12 -0700500 // If this device does not split sepolicy files, it's not a Treble device and therefore,
501 // we assume it's always on the latest platform.
502 return __ANDROID_API_FUTURE__;
Logan Chien837b2a42018-05-03 14:33:52 +0800503 }
504
505 std::string version;
506 if (!GetVendorMappingVersion(&version)) {
Tom Cherry40acb372018-08-01 13:41:12 -0700507 LOG(FATAL) << "Could not read vendor SELinux version";
Logan Chien837b2a42018-05-03 14:33:52 +0800508 }
509
510 int major_version;
511 std::string major_version_str(version, 0, version.find('.'));
512 if (!ParseInt(major_version_str, &major_version)) {
Tom Cherry40acb372018-08-01 13:41:12 -0700513 PLOG(FATAL) << "Failed to parse the vendor sepolicy major version " << major_version_str;
Logan Chien837b2a42018-05-03 14:33:52 +0800514 }
515
Tom Cherry40acb372018-08-01 13:41:12 -0700516 return major_version;
Logan Chien837b2a42018-05-03 14:33:52 +0800517}
518
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800519// This function initializes SELinux then execs init to run in the init SELinux context.
520int SetupSelinux(char** argv) {
521 android::base::InitLogging(argv, &android::base::KernelLogger, [](const char*) {
522 RebootSystem(ANDROID_RB_RESTART2, "bootloader");
523 });
524
525 if (REBOOT_BOOTLOADER_ON_PANIC) {
526 InstallRebootSignalHandlers();
527 }
528
529 // Set up SELinux, loading the SELinux policy.
530 SelinuxSetupKernelLogging();
531 SelinuxInitialize();
532
533 // We're in the kernel domain and want to transition to the init domain. File systems that
534 // store SELabels in their xattrs, such as ext4 do not need an explicit restorecon here,
535 // but other file systems do. In particular, this is needed for ramdisks such as the
536 // recovery image for A/B devices.
537 if (selinux_android_restorecon("/system/bin/init", 0) == -1) {
538 PLOG(FATAL) << "restorecon failed of /system/bin/init failed";
539 }
540
541 const char* path = "/system/bin/init";
542 const char* args[] = {path, "second_stage", nullptr};
543 execv(path, const_cast<char**>(args));
544
545 // execv() only returns if an error happened, in which case we
546 // panic and never return from this function.
547 PLOG(FATAL) << "execv(\"" << path << "\") failed";
548
549 return 1;
550}
551
Tom Cherryc3170092017-08-10 12:22:44 -0700552// selinux_android_file_context_handle() takes on the order of 10+ms to run, so we want to cache
553// its value. selinux_android_restorecon() also needs an sehandle for file context look up. It
554// will create and store its own copy, but selinux_android_set_sehandle() can be used to provide
555// one, thus eliminating an extra call to selinux_android_file_context_handle().
556void SelabelInitialize() {
557 sehandle = selinux_android_file_context_handle();
558 selinux_android_set_sehandle(sehandle);
559}
560
561// A C++ wrapper around selabel_lookup() using the cached sehandle.
562// If sehandle is null, this returns success with an empty context.
563bool SelabelLookupFileContext(const std::string& key, int type, std::string* result) {
564 result->clear();
565
566 if (!sehandle) return true;
567
568 char* context;
569 if (selabel_lookup(sehandle, &context, key.c_str(), type) != 0) {
570 return false;
571 }
572 *result = context;
573 free(context);
574 return true;
575}
576
577// A C++ wrapper around selabel_lookup_best_match() using the cached sehandle.
578// If sehandle is null, this returns success with an empty context.
579bool SelabelLookupFileContextBestMatch(const std::string& key,
580 const std::vector<std::string>& aliases, int type,
581 std::string* result) {
582 result->clear();
583
584 if (!sehandle) return true;
585
586 std::vector<const char*> c_aliases;
587 for (const auto& alias : aliases) {
588 c_aliases.emplace_back(alias.c_str());
589 }
590 c_aliases.emplace_back(nullptr);
591
592 char* context;
593 if (selabel_lookup_best_match(sehandle, &context, key.c_str(), &c_aliases[0], type) != 0) {
594 return false;
595 }
596 *result = context;
597 free(context);
598 return true;
599}
600
601} // namespace init
602} // namespace android