blob: 4a3a271a03f8565e84a4c87899b20ee02eddfeb5 [file] [log] [blame]
Tom Cherry16380362017-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.
21// Init loads the SEPolicy from the file system, restores the context of /init based on this
22// SEPolicy, and finally exec()'s itself to run in the proper domain.
23
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
50#include <fcntl.h>
Tom Cherry16380362017-08-10 12:22:44 -070051#include <stdlib.h>
52#include <sys/wait.h>
53#include <unistd.h>
54
55#include <android-base/chrono_utils.h>
56#include <android-base/file.h>
57#include <android-base/logging.h>
58#include <android-base/unique_fd.h>
59#include <selinux/android.h>
60
61#include "log.h"
62#include "util.h"
63
64using android::base::Timer;
65using android::base::unique_fd;
66
67namespace android {
68namespace init {
69
Tom Cherry16380362017-08-10 12:22:44 -070070namespace {
71
Tom Cherry94f3bcd2017-08-17 16:52:10 -070072selabel_handle* sehandle = nullptr;
73
Tom Cherry16380362017-08-10 12:22:44 -070074enum EnforcingStatus { SELINUX_PERMISSIVE, SELINUX_ENFORCING };
75
76EnforcingStatus StatusFromCmdline() {
77 EnforcingStatus status = SELINUX_ENFORCING;
78
79 import_kernel_cmdline(false,
80 [&](const std::string& key, const std::string& value, bool in_qemu) {
81 if (key == "androidboot.selinux" && value == "permissive") {
82 status = SELINUX_PERMISSIVE;
83 }
84 });
85
86 return status;
87}
88
89bool IsEnforcing() {
90 if (ALLOW_PERMISSIVE_SELINUX) {
91 return StatusFromCmdline() == SELINUX_ENFORCING;
92 }
93 return true;
94}
95
96// Forks, executes the provided program in the child, and waits for the completion in the parent.
97// Child's stderr is captured and logged using LOG(ERROR).
98bool ForkExecveAndWaitForCompletion(const char* filename, char* const argv[]) {
99 // Create a pipe used for redirecting child process's output.
100 // * pipe_fds[0] is the FD the parent will use for reading.
101 // * pipe_fds[1] is the FD the child will use for writing.
102 int pipe_fds[2];
103 if (pipe(pipe_fds) == -1) {
104 PLOG(ERROR) << "Failed to create pipe";
105 return false;
106 }
107
108 pid_t child_pid = fork();
109 if (child_pid == -1) {
110 PLOG(ERROR) << "Failed to fork for " << filename;
111 return false;
112 }
113
114 if (child_pid == 0) {
115 // fork succeeded -- this is executing in the child process
116
117 // Close the pipe FD not used by this process
118 TEMP_FAILURE_RETRY(close(pipe_fds[0]));
119
120 // Redirect stderr to the pipe FD provided by the parent
121 if (TEMP_FAILURE_RETRY(dup2(pipe_fds[1], STDERR_FILENO)) == -1) {
122 PLOG(ERROR) << "Failed to redirect stderr of " << filename;
123 _exit(127);
124 return false;
125 }
126 TEMP_FAILURE_RETRY(close(pipe_fds[1]));
127
Tom Cherry6de21f12017-08-22 15:41:03 -0700128 if (execv(filename, argv) == -1) {
Tom Cherry16380362017-08-10 12:22:44 -0700129 PLOG(ERROR) << "Failed to execve " << filename;
130 return false;
131 }
132 // Unreachable because execve will have succeeded and replaced this code
133 // with child process's code.
134 _exit(127);
135 return false;
136 } else {
137 // fork succeeded -- this is executing in the original/parent process
138
139 // Close the pipe FD not used by this process
140 TEMP_FAILURE_RETRY(close(pipe_fds[1]));
141
142 // Log the redirected output of the child process.
143 // It's unfortunate that there's no standard way to obtain an istream for a file descriptor.
144 // As a result, we're buffering all output and logging it in one go at the end of the
145 // invocation, instead of logging it as it comes in.
146 const int child_out_fd = pipe_fds[0];
147 std::string child_output;
148 if (!android::base::ReadFdToString(child_out_fd, &child_output)) {
149 PLOG(ERROR) << "Failed to capture full output of " << filename;
150 }
151 TEMP_FAILURE_RETRY(close(child_out_fd));
152 if (!child_output.empty()) {
153 // Log captured output, line by line, because LOG expects to be invoked for each line
154 std::istringstream in(child_output);
155 std::string line;
156 while (std::getline(in, line)) {
157 LOG(ERROR) << filename << ": " << line;
158 }
159 }
160
161 // Wait for child to terminate
162 int status;
163 if (TEMP_FAILURE_RETRY(waitpid(child_pid, &status, 0)) != child_pid) {
164 PLOG(ERROR) << "Failed to wait for " << filename;
165 return false;
166 }
167
168 if (WIFEXITED(status)) {
169 int status_code = WEXITSTATUS(status);
170 if (status_code == 0) {
171 return true;
172 } else {
173 LOG(ERROR) << filename << " exited with status " << status_code;
174 }
175 } else if (WIFSIGNALED(status)) {
176 LOG(ERROR) << filename << " killed by signal " << WTERMSIG(status);
177 } else if (WIFSTOPPED(status)) {
178 LOG(ERROR) << filename << " stopped by signal " << WSTOPSIG(status);
179 } else {
180 LOG(ERROR) << "waitpid for " << filename << " returned unexpected status: " << status;
181 }
182
183 return false;
184 }
185}
186
187bool ReadFirstLine(const char* file, std::string* line) {
188 line->clear();
189
190 std::string contents;
191 if (!android::base::ReadFileToString(file, &contents, true /* follow symlinks */)) {
192 return false;
193 }
194 std::istringstream in(contents);
195 std::getline(in, *line);
196 return true;
197}
198
199bool FindPrecompiledSplitPolicy(std::string* file) {
200 file->clear();
kaichieheef4cd72017-08-31 22:07:19 +0800201 // If there is an odm partition, precompiled_sepolicy will be in
202 // odm/etc/selinux. Otherwise it will be in vendor/etc/selinux.
203 static constexpr const char vendor_precompiled_sepolicy[] =
204 "/vendor/etc/selinux/precompiled_sepolicy";
205 static constexpr const char odm_precompiled_sepolicy[] =
206 "/odm/etc/selinux/precompiled_sepolicy";
207 if (access(odm_precompiled_sepolicy, R_OK) == 0) {
208 *file = odm_precompiled_sepolicy;
209 } else if (access(vendor_precompiled_sepolicy, R_OK) == 0) {
210 *file = vendor_precompiled_sepolicy;
211 } else {
212 PLOG(INFO) << "No precompiled sepolicy";
Tom Cherry16380362017-08-10 12:22:44 -0700213 return false;
214 }
215 std::string actual_plat_id;
216 if (!ReadFirstLine("/system/etc/selinux/plat_and_mapping_sepolicy.cil.sha256", &actual_plat_id)) {
217 PLOG(INFO) << "Failed to read "
218 "/system/etc/selinux/plat_and_mapping_sepolicy.cil.sha256";
219 return false;
220 }
kaichieheef4cd72017-08-31 22:07:19 +0800221
Tom Cherry16380362017-08-10 12:22:44 -0700222 std::string precompiled_plat_id;
kaichieheef4cd72017-08-31 22:07:19 +0800223 std::string precompiled_sha256 = *file + ".plat_and_mapping.sha256";
224 if (!ReadFirstLine(precompiled_sha256.c_str(), &precompiled_plat_id)) {
225 PLOG(INFO) << "Failed to read " << precompiled_sha256;
226 file->clear();
Tom Cherry16380362017-08-10 12:22:44 -0700227 return false;
228 }
229 if ((actual_plat_id.empty()) || (actual_plat_id != precompiled_plat_id)) {
kaichieheef4cd72017-08-31 22:07:19 +0800230 file->clear();
Tom Cherry16380362017-08-10 12:22:44 -0700231 return false;
232 }
Tom Cherry16380362017-08-10 12:22:44 -0700233 return true;
234}
235
236bool GetVendorMappingVersion(std::string* plat_vers) {
237 if (!ReadFirstLine("/vendor/etc/selinux/plat_sepolicy_vers.txt", plat_vers)) {
238 PLOG(ERROR) << "Failed to read /vendor/etc/selinux/plat_sepolicy_vers.txt";
239 return false;
240 }
241 if (plat_vers->empty()) {
242 LOG(ERROR) << "No version present in plat_sepolicy_vers.txt";
243 return false;
244 }
245 return true;
246}
247
248constexpr const char plat_policy_cil_file[] = "/system/etc/selinux/plat_sepolicy.cil";
249
250bool IsSplitPolicyDevice() {
251 return access(plat_policy_cil_file, R_OK) != -1;
252}
253
254bool LoadSplitPolicy() {
255 // IMPLEMENTATION NOTE: Split policy consists of three CIL files:
256 // * platform -- policy needed due to logic contained in the system image,
257 // * non-platform -- policy needed due to logic contained in the vendor image,
258 // * mapping -- mapping policy which helps preserve forward-compatibility of non-platform policy
259 // with newer versions of platform policy.
260 //
261 // secilc is invoked to compile the above three policy files into a single monolithic policy
262 // file. This file is then loaded into the kernel.
263
264 // Load precompiled policy from vendor image, if a matching policy is found there. The policy
265 // must match the platform policy on the system image.
266 std::string precompiled_sepolicy_file;
267 if (FindPrecompiledSplitPolicy(&precompiled_sepolicy_file)) {
268 unique_fd fd(open(precompiled_sepolicy_file.c_str(), O_RDONLY | O_CLOEXEC | O_BINARY));
269 if (fd != -1) {
270 if (selinux_android_load_policy_from_fd(fd, precompiled_sepolicy_file.c_str()) < 0) {
271 LOG(ERROR) << "Failed to load SELinux policy from " << precompiled_sepolicy_file;
272 return false;
273 }
274 return true;
275 }
276 }
277 // No suitable precompiled policy could be loaded
278
279 LOG(INFO) << "Compiling SELinux policy";
280
281 // Determine the highest policy language version supported by the kernel
282 set_selinuxmnt("/sys/fs/selinux");
283 int max_policy_version = security_policyvers();
284 if (max_policy_version == -1) {
285 PLOG(ERROR) << "Failed to determine highest policy version supported by kernel";
286 return false;
287 }
288
289 // We store the output of the compilation on /dev because this is the most convenient tmpfs
290 // storage mount available this early in the boot sequence.
291 char compiled_sepolicy[] = "/dev/sepolicy.XXXXXX";
292 unique_fd compiled_sepolicy_fd(mkostemp(compiled_sepolicy, O_CLOEXEC));
293 if (compiled_sepolicy_fd < 0) {
294 PLOG(ERROR) << "Failed to create temporary file " << compiled_sepolicy;
295 return false;
296 }
297
298 // Determine which mapping file to include
299 std::string vend_plat_vers;
300 if (!GetVendorMappingVersion(&vend_plat_vers)) {
301 return false;
302 }
303 std::string mapping_file("/system/etc/selinux/mapping/" + vend_plat_vers + ".cil");
kaichieheef4cd72017-08-31 22:07:19 +0800304
305 // vendor_sepolicy.cil and nonplat_declaration.cil are the new design to replace
306 // nonplat_sepolicy.cil.
307 std::string nonplat_declaration_cil_file("/vendor/etc/selinux/nonplat_declaration.cil");
308 std::string vendor_policy_cil_file("/vendor/etc/selinux/vendor_sepolicy.cil");
309
310 if (access(vendor_policy_cil_file.c_str(), F_OK) == -1) {
311 // For backward compatibility.
312 // TODO: remove this after no device is using nonplat_sepolicy.cil.
313 vendor_policy_cil_file = "/vendor/etc/selinux/nonplat_sepolicy.cil";
314 nonplat_declaration_cil_file.clear();
315 } else if (access(nonplat_declaration_cil_file.c_str(), F_OK) == -1) {
316 LOG(ERROR) << "Missing " << nonplat_declaration_cil_file;
317 return false;
318 }
319
320 // odm_sepolicy.cil is default but optional.
321 std::string odm_policy_cil_file("/odm/etc/selinux/odm_sepolicy.cil");
322 if (access(odm_policy_cil_file.c_str(), F_OK) == -1) {
323 odm_policy_cil_file.clear();
324 }
Andreas Huberc41b8382017-08-18 14:43:52 -0700325 const std::string version_as_string = std::to_string(max_policy_version);
326
Tom Cherry16380362017-08-10 12:22:44 -0700327 // clang-format off
kaichieheef4cd72017-08-31 22:07:19 +0800328 std::vector<const char*> compile_args {
Tom Cherry16380362017-08-10 12:22:44 -0700329 "/system/bin/secilc",
330 plat_policy_cil_file,
Jeff Vander Stoep5e9ba3c2017-10-06 17:03:45 -0700331 "-m", "-M", "true", "-G", "-N",
Tom Cherry16380362017-08-10 12:22:44 -0700332 // Target the highest policy language version supported by the kernel
Andreas Huberc41b8382017-08-18 14:43:52 -0700333 "-c", version_as_string.c_str(),
Tom Cherry16380362017-08-10 12:22:44 -0700334 mapping_file.c_str(),
Tom Cherry16380362017-08-10 12:22:44 -0700335 "-o", compiled_sepolicy,
336 // We don't care about file_contexts output by the compiler
337 "-f", "/sys/fs/selinux/null", // /dev/null is not yet available
kaichieheef4cd72017-08-31 22:07:19 +0800338 };
Tom Cherry16380362017-08-10 12:22:44 -0700339 // clang-format on
340
kaichieheef4cd72017-08-31 22:07:19 +0800341 if (!nonplat_declaration_cil_file.empty()) {
342 compile_args.push_back(nonplat_declaration_cil_file.c_str());
343 }
344 if (!vendor_policy_cil_file.empty()) {
345 compile_args.push_back(vendor_policy_cil_file.c_str());
346 }
347 if (!odm_policy_cil_file.empty()) {
348 compile_args.push_back(odm_policy_cil_file.c_str());
349 }
350 compile_args.push_back(nullptr);
351
352 if (!ForkExecveAndWaitForCompletion(compile_args[0], (char**)compile_args.data())) {
Tom Cherry16380362017-08-10 12:22:44 -0700353 unlink(compiled_sepolicy);
354 return false;
355 }
356 unlink(compiled_sepolicy);
357
358 LOG(INFO) << "Loading compiled SELinux policy";
359 if (selinux_android_load_policy_from_fd(compiled_sepolicy_fd, compiled_sepolicy) < 0) {
360 LOG(ERROR) << "Failed to load SELinux policy from " << compiled_sepolicy;
361 return false;
362 }
363
364 return true;
365}
366
367bool LoadMonolithicPolicy() {
368 LOG(VERBOSE) << "Loading SELinux policy from monolithic file";
369 if (selinux_android_load_policy() < 0) {
370 PLOG(ERROR) << "Failed to load monolithic SELinux policy";
371 return false;
372 }
373 return true;
374}
375
376bool LoadPolicy() {
377 return IsSplitPolicyDevice() ? LoadSplitPolicy() : LoadMonolithicPolicy();
378}
379
380} // namespace
381
382void SelinuxInitialize() {
383 Timer t;
384
385 LOG(INFO) << "Loading SELinux policy";
386 if (!LoadPolicy()) {
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700387 LOG(FATAL) << "Unable to load SELinux policy";
Tom Cherry16380362017-08-10 12:22:44 -0700388 }
389
390 bool kernel_enforcing = (security_getenforce() == 1);
391 bool is_enforcing = IsEnforcing();
392 if (kernel_enforcing != is_enforcing) {
393 if (security_setenforce(is_enforcing)) {
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700394 PLOG(FATAL) << "security_setenforce(%s) failed" << (is_enforcing ? "true" : "false");
Tom Cherry16380362017-08-10 12:22:44 -0700395 }
396 }
397
Tom Cherry62ca6632017-08-03 12:54:07 -0700398 if (auto result = WriteFile("/sys/fs/selinux/checkreqprot", "0"); !result) {
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700399 LOG(FATAL) << "Unable to write to /sys/fs/selinux/checkreqprot: " << result.error();
Tom Cherry16380362017-08-10 12:22:44 -0700400 }
401
402 // init's first stage can't set properties, so pass the time to the second stage.
403 setenv("INIT_SELINUX_TOOK", std::to_string(t.duration().count()).c_str(), 1);
404}
405
406// The files and directories that were created before initial sepolicy load or
407// files on ramdisk need to have their security context restored to the proper
408// value. This must happen before /dev is populated by ueventd.
409void SelinuxRestoreContext() {
410 LOG(INFO) << "Running restorecon...";
411 selinux_android_restorecon("/dev", 0);
412 selinux_android_restorecon("/dev/kmsg", 0);
413 if constexpr (WORLD_WRITABLE_KMSG) {
414 selinux_android_restorecon("/dev/kmsg_debug", 0);
415 }
416 selinux_android_restorecon("/dev/socket", 0);
417 selinux_android_restorecon("/dev/random", 0);
418 selinux_android_restorecon("/dev/urandom", 0);
419 selinux_android_restorecon("/dev/__properties__", 0);
420
421 selinux_android_restorecon("/plat_file_contexts", 0);
422 selinux_android_restorecon("/nonplat_file_contexts", 0);
423 selinux_android_restorecon("/plat_property_contexts", 0);
424 selinux_android_restorecon("/nonplat_property_contexts", 0);
425 selinux_android_restorecon("/plat_seapp_contexts", 0);
426 selinux_android_restorecon("/nonplat_seapp_contexts", 0);
427 selinux_android_restorecon("/plat_service_contexts", 0);
428 selinux_android_restorecon("/nonplat_service_contexts", 0);
429 selinux_android_restorecon("/plat_hwservice_contexts", 0);
430 selinux_android_restorecon("/nonplat_hwservice_contexts", 0);
431 selinux_android_restorecon("/sepolicy", 0);
432 selinux_android_restorecon("/vndservice_contexts", 0);
433
434 selinux_android_restorecon("/dev/block", SELINUX_ANDROID_RESTORECON_RECURSE);
435 selinux_android_restorecon("/dev/device-mapper", 0);
436
437 selinux_android_restorecon("/sbin/mke2fs_static", 0);
438 selinux_android_restorecon("/sbin/e2fsdroid_static", 0);
439}
440
441// This function sets up SELinux logging to be written to kmsg, to match init's logging.
442void SelinuxSetupKernelLogging() {
443 selinux_callback cb;
444 cb.func_log = selinux_klog_callback;
445 selinux_set_callback(SELINUX_CB_LOG, cb);
446}
447
448// selinux_android_file_context_handle() takes on the order of 10+ms to run, so we want to cache
449// its value. selinux_android_restorecon() also needs an sehandle for file context look up. It
450// will create and store its own copy, but selinux_android_set_sehandle() can be used to provide
451// one, thus eliminating an extra call to selinux_android_file_context_handle().
452void SelabelInitialize() {
453 sehandle = selinux_android_file_context_handle();
454 selinux_android_set_sehandle(sehandle);
455}
456
457// A C++ wrapper around selabel_lookup() using the cached sehandle.
458// If sehandle is null, this returns success with an empty context.
459bool SelabelLookupFileContext(const std::string& key, int type, std::string* result) {
460 result->clear();
461
462 if (!sehandle) return true;
463
464 char* context;
465 if (selabel_lookup(sehandle, &context, key.c_str(), type) != 0) {
466 return false;
467 }
468 *result = context;
469 free(context);
470 return true;
471}
472
473// A C++ wrapper around selabel_lookup_best_match() using the cached sehandle.
474// If sehandle is null, this returns success with an empty context.
475bool SelabelLookupFileContextBestMatch(const std::string& key,
476 const std::vector<std::string>& aliases, int type,
477 std::string* result) {
478 result->clear();
479
480 if (!sehandle) return true;
481
482 std::vector<const char*> c_aliases;
483 for (const auto& alias : aliases) {
484 c_aliases.emplace_back(alias.c_str());
485 }
486 c_aliases.emplace_back(nullptr);
487
488 char* context;
489 if (selabel_lookup_best_match(sehandle, &context, key.c_str(), &c_aliases[0], type) != 0) {
490 return false;
491 }
492 *result = context;
493 free(context);
494 return true;
495}
496
497} // namespace init
498} // namespace android