blob: 852d6caace988dc5f31b5048224c1fdf14801d0a [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
Bowgo Tsaif016f252019-08-28 17:56:51 +080039// are the sha256 hashes of the parts of the SEPolicy on /system, /system_ext and /product that
40// were used to compile this precompiled policy. The system partition contains a similar sha256
41// of the parts of the SEPolicy that it currently contains. Symmetrically, system_ext and
42// product paritition contain sha256 hashes of their SEPolicy. The init loads this
43// precompiled_sepolicy directly if and only if the hashes along with the precompiled SEPolicy on
44// /vendor or /odm match the hashes for system, system_ext and product SEPolicy, respectively.
45// 2) If these hashes do not match, then either /system or /system_ext or /product (or some of them)
46// have been updated out of sync with /vendor (or /odm if it is present) and the init needs to
47// compile the SEPolicy. /system contains the SEPolicy compiler, secilc, and it is used by the
48// LoadSplitPolicy() function below to compile the SEPolicy to a temp directory and load it.
49// That function contains even more documentation with the specific implementation details of how
50// the SEPolicy is compiled if needed.
Tom Cherryc3170092017-08-10 12:22:44 -070051
52#include "selinux.h"
53
Tom Cherry40acb372018-08-01 13:41:12 -070054#include <android/api-level.h>
Tom Cherryc3170092017-08-10 12:22:44 -070055#include <fcntl.h>
Tom Cherry8180b482019-08-26 13:57:51 -070056#include <linux/audit.h>
57#include <linux/netlink.h>
Tom Cherryc3170092017-08-10 12:22:44 -070058#include <stdlib.h>
59#include <sys/wait.h>
60#include <unistd.h>
61
62#include <android-base/chrono_utils.h>
63#include <android-base/file.h>
64#include <android-base/logging.h>
Logan Chien837b2a42018-05-03 14:33:52 +080065#include <android-base/parseint.h>
Tom Cherryc3170092017-08-10 12:22:44 -070066#include <android-base/unique_fd.h>
Bowgo Tsai1dacd422019-03-04 17:53:34 +080067#include <fs_avb/fs_avb.h>
Tom Cherryc3170092017-08-10 12:22:44 -070068#include <selinux/android.h>
69
Bowgo Tsai30afda72019-04-11 23:57:24 +080070#include "debug_ramdisk.h"
Tom Cherry7bfea3d2018-11-06 14:12:05 -080071#include "reboot_utils.h"
Tom Cherryc3170092017-08-10 12:22:44 -070072#include "util.h"
73
Bowgo Tsai1dacd422019-03-04 17:53:34 +080074using namespace std::string_literals;
75
Logan Chien837b2a42018-05-03 14:33:52 +080076using android::base::ParseInt;
Tom Cherryc3170092017-08-10 12:22:44 -070077using android::base::Timer;
78using android::base::unique_fd;
Bowgo Tsai1dacd422019-03-04 17:53:34 +080079using android::fs_mgr::AvbHandle;
Tom Cherryc3170092017-08-10 12:22:44 -070080
81namespace android {
82namespace init {
83
Tom Cherryc3170092017-08-10 12:22:44 -070084namespace {
85
86enum EnforcingStatus { SELINUX_PERMISSIVE, SELINUX_ENFORCING };
87
88EnforcingStatus StatusFromCmdline() {
89 EnforcingStatus status = SELINUX_ENFORCING;
90
Tom Cherryc88d8f92019-08-19 15:21:25 -070091 ImportKernelCmdline([&](const std::string& key, const std::string& value) {
92 if (key == "androidboot.selinux" && value == "permissive") {
93 status = SELINUX_PERMISSIVE;
94 }
95 });
Tom Cherryc3170092017-08-10 12:22:44 -070096
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 }
Bowgo Tsaif016f252019-08-28 17:56:51 +0800232 std::string actual_system_ext_id;
233 if (!ReadFirstLine("/system_ext/etc/selinux/system_ext_sepolicy_and_mapping.sha256",
234 &actual_system_ext_id)) {
235 PLOG(INFO) << "Failed to read "
236 "/system_ext/etc/selinux/system_ext_sepolicy_and_mapping.sha256";
237 return false;
238 }
Tri Voc8137f92019-01-22 18:22:25 -0800239 std::string actual_product_id;
240 if (!ReadFirstLine("/product/etc/selinux/product_sepolicy_and_mapping.sha256",
241 &actual_product_id)) {
242 PLOG(INFO) << "Failed to read "
243 "/product/etc/selinux/product_sepolicy_and_mapping.sha256";
Tom Cherryc3170092017-08-10 12:22:44 -0700244 return false;
245 }
kaichieheef4cd72017-08-31 22:07:19 +0800246
Tom Cherryc3170092017-08-10 12:22:44 -0700247 std::string precompiled_plat_id;
Tri Voc8137f92019-01-22 18:22:25 -0800248 std::string precompiled_plat_sha256 = *file + ".plat_sepolicy_and_mapping.sha256";
249 if (!ReadFirstLine(precompiled_plat_sha256.c_str(), &precompiled_plat_id)) {
250 PLOG(INFO) << "Failed to read " << precompiled_plat_sha256;
kaichieheef4cd72017-08-31 22:07:19 +0800251 file->clear();
Tom Cherryc3170092017-08-10 12:22:44 -0700252 return false;
253 }
Bowgo Tsaif016f252019-08-28 17:56:51 +0800254 std::string precompiled_system_ext_id;
255 std::string precompiled_system_ext_sha256 = *file + ".system_ext_sepolicy_and_mapping.sha256";
256 if (!ReadFirstLine(precompiled_system_ext_sha256.c_str(), &precompiled_system_ext_id)) {
257 PLOG(INFO) << "Failed to read " << precompiled_system_ext_sha256;
258 file->clear();
259 return false;
260 }
Tri Voc8137f92019-01-22 18:22:25 -0800261 std::string precompiled_product_id;
262 std::string precompiled_product_sha256 = *file + ".product_sepolicy_and_mapping.sha256";
263 if (!ReadFirstLine(precompiled_product_sha256.c_str(), &precompiled_product_id)) {
264 PLOG(INFO) << "Failed to read " << precompiled_product_sha256;
265 file->clear();
266 return false;
267 }
268 if (actual_plat_id.empty() || actual_plat_id != precompiled_plat_id ||
Bowgo Tsaif016f252019-08-28 17:56:51 +0800269 actual_system_ext_id.empty() || actual_system_ext_id != precompiled_system_ext_id ||
Tri Voc8137f92019-01-22 18:22:25 -0800270 actual_product_id.empty() || actual_product_id != precompiled_product_id) {
kaichieheef4cd72017-08-31 22:07:19 +0800271 file->clear();
Tom Cherryc3170092017-08-10 12:22:44 -0700272 return false;
273 }
Tom Cherryc3170092017-08-10 12:22:44 -0700274 return true;
275}
276
277bool GetVendorMappingVersion(std::string* plat_vers) {
278 if (!ReadFirstLine("/vendor/etc/selinux/plat_sepolicy_vers.txt", plat_vers)) {
279 PLOG(ERROR) << "Failed to read /vendor/etc/selinux/plat_sepolicy_vers.txt";
280 return false;
281 }
282 if (plat_vers->empty()) {
283 LOG(ERROR) << "No version present in plat_sepolicy_vers.txt";
284 return false;
285 }
286 return true;
287}
288
289constexpr const char plat_policy_cil_file[] = "/system/etc/selinux/plat_sepolicy.cil";
290
291bool IsSplitPolicyDevice() {
292 return access(plat_policy_cil_file, R_OK) != -1;
293}
294
295bool LoadSplitPolicy() {
296 // IMPLEMENTATION NOTE: Split policy consists of three CIL files:
297 // * platform -- policy needed due to logic contained in the system image,
298 // * non-platform -- policy needed due to logic contained in the vendor image,
299 // * mapping -- mapping policy which helps preserve forward-compatibility of non-platform policy
300 // with newer versions of platform policy.
301 //
302 // secilc is invoked to compile the above three policy files into a single monolithic policy
303 // file. This file is then loaded into the kernel.
304
Bowgo Tsai1dacd422019-03-04 17:53:34 +0800305 // See if we need to load userdebug_plat_sepolicy.cil instead of plat_sepolicy.cil.
306 const char* force_debuggable_env = getenv("INIT_FORCE_DEBUGGABLE");
307 bool use_userdebug_policy =
308 ((force_debuggable_env && "true"s == force_debuggable_env) &&
Bowgo Tsai30afda72019-04-11 23:57:24 +0800309 AvbHandle::IsDeviceUnlocked() && access(kDebugRamdiskSEPolicy, F_OK) == 0);
Bowgo Tsai1dacd422019-03-04 17:53:34 +0800310 if (use_userdebug_policy) {
311 LOG(WARNING) << "Using userdebug system sepolicy";
312 }
313
Tom Cherryc3170092017-08-10 12:22:44 -0700314 // Load precompiled policy from vendor image, if a matching policy is found there. The policy
315 // must match the platform policy on the system image.
316 std::string precompiled_sepolicy_file;
Bowgo Tsai1dacd422019-03-04 17:53:34 +0800317 // use_userdebug_policy requires compiling sepolicy with userdebug_plat_sepolicy.cil.
318 // Thus it cannot use the precompiled policy from vendor image.
319 if (!use_userdebug_policy && FindPrecompiledSplitPolicy(&precompiled_sepolicy_file)) {
Tom Cherryc3170092017-08-10 12:22:44 -0700320 unique_fd fd(open(precompiled_sepolicy_file.c_str(), O_RDONLY | O_CLOEXEC | O_BINARY));
321 if (fd != -1) {
322 if (selinux_android_load_policy_from_fd(fd, precompiled_sepolicy_file.c_str()) < 0) {
323 LOG(ERROR) << "Failed to load SELinux policy from " << precompiled_sepolicy_file;
324 return false;
325 }
326 return true;
327 }
328 }
329 // No suitable precompiled policy could be loaded
330
331 LOG(INFO) << "Compiling SELinux policy";
332
Tom Cherryc3170092017-08-10 12:22:44 -0700333 // We store the output of the compilation on /dev because this is the most convenient tmpfs
334 // storage mount available this early in the boot sequence.
335 char compiled_sepolicy[] = "/dev/sepolicy.XXXXXX";
336 unique_fd compiled_sepolicy_fd(mkostemp(compiled_sepolicy, O_CLOEXEC));
337 if (compiled_sepolicy_fd < 0) {
338 PLOG(ERROR) << "Failed to create temporary file " << compiled_sepolicy;
339 return false;
340 }
341
342 // Determine which mapping file to include
343 std::string vend_plat_vers;
344 if (!GetVendorMappingVersion(&vend_plat_vers)) {
345 return false;
346 }
Tri Vo503f1852019-01-16 11:57:19 -0800347 std::string plat_mapping_file("/system/etc/selinux/mapping/" + vend_plat_vers + ".cil");
kaichieheef4cd72017-08-31 22:07:19 +0800348
Jeff Vander Stoep0ac51cf2019-05-02 14:05:18 -0700349 std::string plat_compat_cil_file("/system/etc/selinux/mapping/" + vend_plat_vers +
350 ".compat.cil");
351 if (access(plat_compat_cil_file.c_str(), F_OK) == -1) {
352 plat_compat_cil_file.clear();
353 }
354
Bowgo Tsaif016f252019-08-28 17:56:51 +0800355 std::string system_ext_policy_cil_file("/system_ext/etc/selinux/system_ext_sepolicy.cil");
356 if (access(system_ext_policy_cil_file.c_str(), F_OK) == -1) {
357 system_ext_policy_cil_file.clear();
358 }
359
360 std::string system_ext_mapping_file("/system_ext/etc/selinux/mapping/" + vend_plat_vers +
361 ".cil");
362 if (access(system_ext_mapping_file.c_str(), F_OK) == -1) {
363 system_ext_mapping_file.clear();
364 }
365
Tri Vod3518cf2018-12-14 14:25:08 -0800366 std::string product_policy_cil_file("/product/etc/selinux/product_sepolicy.cil");
367 if (access(product_policy_cil_file.c_str(), F_OK) == -1) {
368 product_policy_cil_file.clear();
369 }
370
Tri Vo503f1852019-01-16 11:57:19 -0800371 std::string product_mapping_file("/product/etc/selinux/mapping/" + vend_plat_vers + ".cil");
372 if (access(product_mapping_file.c_str(), F_OK) == -1) {
373 product_mapping_file.clear();
374 }
375
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800376 // vendor_sepolicy.cil and plat_pub_versioned.cil are the new design to replace
kaichieheef4cd72017-08-31 22:07:19 +0800377 // nonplat_sepolicy.cil.
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800378 std::string plat_pub_versioned_cil_file("/vendor/etc/selinux/plat_pub_versioned.cil");
kaichieheef4cd72017-08-31 22:07:19 +0800379 std::string vendor_policy_cil_file("/vendor/etc/selinux/vendor_sepolicy.cil");
380
381 if (access(vendor_policy_cil_file.c_str(), F_OK) == -1) {
382 // For backward compatibility.
383 // TODO: remove this after no device is using nonplat_sepolicy.cil.
384 vendor_policy_cil_file = "/vendor/etc/selinux/nonplat_sepolicy.cil";
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800385 plat_pub_versioned_cil_file.clear();
386 } else if (access(plat_pub_versioned_cil_file.c_str(), F_OK) == -1) {
387 LOG(ERROR) << "Missing " << plat_pub_versioned_cil_file;
kaichieheef4cd72017-08-31 22:07:19 +0800388 return false;
389 }
390
391 // odm_sepolicy.cil is default but optional.
392 std::string odm_policy_cil_file("/odm/etc/selinux/odm_sepolicy.cil");
393 if (access(odm_policy_cil_file.c_str(), F_OK) == -1) {
394 odm_policy_cil_file.clear();
395 }
Jeff Vander Stoep724eda52019-02-15 12:13:38 -0800396 const std::string version_as_string = std::to_string(SEPOLICY_VERSION);
Andreas Huberc41b8382017-08-18 14:43:52 -0700397
Tom Cherryc3170092017-08-10 12:22:44 -0700398 // clang-format off
kaichieheef4cd72017-08-31 22:07:19 +0800399 std::vector<const char*> compile_args {
Tom Cherryc3170092017-08-10 12:22:44 -0700400 "/system/bin/secilc",
Bowgo Tsai30afda72019-04-11 23:57:24 +0800401 use_userdebug_policy ? kDebugRamdiskSEPolicy: plat_policy_cil_file,
Jeff Vander Stoep5e9ba3c2017-10-06 17:03:45 -0700402 "-m", "-M", "true", "-G", "-N",
Andreas Huberc41b8382017-08-18 14:43:52 -0700403 "-c", version_as_string.c_str(),
Tri Vo503f1852019-01-16 11:57:19 -0800404 plat_mapping_file.c_str(),
Tom Cherryc3170092017-08-10 12:22:44 -0700405 "-o", compiled_sepolicy,
406 // We don't care about file_contexts output by the compiler
407 "-f", "/sys/fs/selinux/null", // /dev/null is not yet available
kaichieheef4cd72017-08-31 22:07:19 +0800408 };
Tom Cherryc3170092017-08-10 12:22:44 -0700409 // clang-format on
410
Jeff Vander Stoep0ac51cf2019-05-02 14:05:18 -0700411 if (!plat_compat_cil_file.empty()) {
412 compile_args.push_back(plat_compat_cil_file.c_str());
413 }
Bowgo Tsaif016f252019-08-28 17:56:51 +0800414 if (!system_ext_policy_cil_file.empty()) {
415 compile_args.push_back(system_ext_policy_cil_file.c_str());
416 }
417 if (!system_ext_mapping_file.empty()) {
418 compile_args.push_back(system_ext_mapping_file.c_str());
419 }
Tri Vod3518cf2018-12-14 14:25:08 -0800420 if (!product_policy_cil_file.empty()) {
421 compile_args.push_back(product_policy_cil_file.c_str());
422 }
Tri Vo503f1852019-01-16 11:57:19 -0800423 if (!product_mapping_file.empty()) {
424 compile_args.push_back(product_mapping_file.c_str());
425 }
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800426 if (!plat_pub_versioned_cil_file.empty()) {
427 compile_args.push_back(plat_pub_versioned_cil_file.c_str());
kaichieheef4cd72017-08-31 22:07:19 +0800428 }
429 if (!vendor_policy_cil_file.empty()) {
430 compile_args.push_back(vendor_policy_cil_file.c_str());
431 }
432 if (!odm_policy_cil_file.empty()) {
433 compile_args.push_back(odm_policy_cil_file.c_str());
434 }
435 compile_args.push_back(nullptr);
436
437 if (!ForkExecveAndWaitForCompletion(compile_args[0], (char**)compile_args.data())) {
Tom Cherryc3170092017-08-10 12:22:44 -0700438 unlink(compiled_sepolicy);
439 return false;
440 }
441 unlink(compiled_sepolicy);
442
443 LOG(INFO) << "Loading compiled SELinux policy";
444 if (selinux_android_load_policy_from_fd(compiled_sepolicy_fd, compiled_sepolicy) < 0) {
445 LOG(ERROR) << "Failed to load SELinux policy from " << compiled_sepolicy;
446 return false;
447 }
448
449 return true;
450}
451
452bool LoadMonolithicPolicy() {
453 LOG(VERBOSE) << "Loading SELinux policy from monolithic file";
454 if (selinux_android_load_policy() < 0) {
455 PLOG(ERROR) << "Failed to load monolithic SELinux policy";
456 return false;
457 }
458 return true;
459}
460
461bool LoadPolicy() {
462 return IsSplitPolicyDevice() ? LoadSplitPolicy() : LoadMonolithicPolicy();
463}
464
Tom Cherryc3170092017-08-10 12:22:44 -0700465void SelinuxInitialize() {
Tom Cherryc3170092017-08-10 12:22:44 -0700466 LOG(INFO) << "Loading SELinux policy";
467 if (!LoadPolicy()) {
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700468 LOG(FATAL) << "Unable to load SELinux policy";
Tom Cherryc3170092017-08-10 12:22:44 -0700469 }
470
471 bool kernel_enforcing = (security_getenforce() == 1);
472 bool is_enforcing = IsEnforcing();
473 if (kernel_enforcing != is_enforcing) {
474 if (security_setenforce(is_enforcing)) {
Paul Lawrenceb2c2d692019-08-30 11:11:44 -0700475 PLOG(FATAL) << "security_setenforce(" << (is_enforcing ? "true" : "false")
476 << ") failed";
Tom Cherryc3170092017-08-10 12:22:44 -0700477 }
478 }
479
Tom Cherry11a3aee2017-08-03 12:54:07 -0700480 if (auto result = WriteFile("/sys/fs/selinux/checkreqprot", "0"); !result) {
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700481 LOG(FATAL) << "Unable to write to /sys/fs/selinux/checkreqprot: " << result.error();
Tom Cherryc3170092017-08-10 12:22:44 -0700482 }
Tom Cherryc3170092017-08-10 12:22:44 -0700483}
484
Tom Cherry8180b482019-08-26 13:57:51 -0700485constexpr size_t kKlogMessageSize = 1024;
486
487void SelinuxAvcLog(char* buf, size_t buf_len) {
488 CHECK_GT(buf_len, 0u);
489
490 size_t str_len = strnlen(buf, buf_len);
491 // trim newline at end of string
492 if (buf[str_len - 1] == '\n') {
493 buf[str_len - 1] = '\0';
494 }
495
496 struct NetlinkMessage {
497 nlmsghdr hdr;
498 char buf[kKlogMessageSize];
499 } request = {};
500
501 request.hdr.nlmsg_flags = NLM_F_REQUEST;
502 request.hdr.nlmsg_type = AUDIT_USER_AVC;
503 request.hdr.nlmsg_len = sizeof(request);
504 strlcpy(request.buf, buf, sizeof(request.buf));
505
506 auto fd = unique_fd{socket(PF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_AUDIT)};
507 if (!fd.ok()) {
508 return;
509 }
510
511 TEMP_FAILURE_RETRY(send(fd, &request, sizeof(request), 0));
512}
513
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800514} // namespace
515
Tom Cherryc3170092017-08-10 12:22:44 -0700516void SelinuxRestoreContext() {
517 LOG(INFO) << "Running restorecon...";
518 selinux_android_restorecon("/dev", 0);
519 selinux_android_restorecon("/dev/kmsg", 0);
520 if constexpr (WORLD_WRITABLE_KMSG) {
521 selinux_android_restorecon("/dev/kmsg_debug", 0);
522 }
Tom Cherry81ae0752018-07-30 16:23:49 -0700523 selinux_android_restorecon("/dev/null", 0);
524 selinux_android_restorecon("/dev/ptmx", 0);
Tom Cherryc3170092017-08-10 12:22:44 -0700525 selinux_android_restorecon("/dev/socket", 0);
526 selinux_android_restorecon("/dev/random", 0);
527 selinux_android_restorecon("/dev/urandom", 0);
528 selinux_android_restorecon("/dev/__properties__", 0);
529
Tom Cherryc3170092017-08-10 12:22:44 -0700530 selinux_android_restorecon("/dev/block", SELINUX_ANDROID_RESTORECON_RECURSE);
531 selinux_android_restorecon("/dev/device-mapper", 0);
Jiyong Park4ba548d2019-02-22 16:04:35 +0900532
533 selinux_android_restorecon("/apex", 0);
Kiyoung Kim99df54b2019-11-22 16:14:10 +0900534
535 selinux_android_restorecon("/linkerconfig", 0);
Tom Cherryc3170092017-08-10 12:22:44 -0700536}
537
Tom Cherry74069d12018-07-20 15:26:25 -0700538int SelinuxKlogCallback(int type, const char* fmt, ...) {
539 android::base::LogSeverity severity = android::base::ERROR;
540 if (type == SELINUX_WARNING) {
541 severity = android::base::WARNING;
542 } else if (type == SELINUX_INFO) {
543 severity = android::base::INFO;
544 }
Tom Cherry8180b482019-08-26 13:57:51 -0700545 char buf[kKlogMessageSize];
Tom Cherry74069d12018-07-20 15:26:25 -0700546 va_list ap;
547 va_start(ap, fmt);
Tom Cherry8180b482019-08-26 13:57:51 -0700548 int length_written = vsnprintf(buf, sizeof(buf), fmt, ap);
Tom Cherry74069d12018-07-20 15:26:25 -0700549 va_end(ap);
Tom Cherry8180b482019-08-26 13:57:51 -0700550 if (length_written <= 0) {
551 return 0;
552 }
553 if (type == SELINUX_AVC) {
554 SelinuxAvcLog(buf, sizeof(buf));
555 } else {
556 android::base::KernelLogger(android::base::MAIN, severity, "selinux", nullptr, 0, buf);
557 }
Tom Cherry74069d12018-07-20 15:26:25 -0700558 return 0;
559}
560
Tom Cherryc3170092017-08-10 12:22:44 -0700561void SelinuxSetupKernelLogging() {
562 selinux_callback cb;
Tom Cherry74069d12018-07-20 15:26:25 -0700563 cb.func_log = SelinuxKlogCallback;
Tom Cherryc3170092017-08-10 12:22:44 -0700564 selinux_set_callback(SELINUX_CB_LOG, cb);
565}
566
Tom Cherry40acb372018-08-01 13:41:12 -0700567int SelinuxGetVendorAndroidVersion() {
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700568 static int vendor_android_version = [] {
569 if (!IsSplitPolicyDevice()) {
570 // If this device does not split sepolicy files, it's not a Treble device and therefore,
571 // we assume it's always on the latest platform.
572 return __ANDROID_API_FUTURE__;
573 }
Logan Chien837b2a42018-05-03 14:33:52 +0800574
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700575 std::string version;
576 if (!GetVendorMappingVersion(&version)) {
577 LOG(FATAL) << "Could not read vendor SELinux version";
578 }
Logan Chien837b2a42018-05-03 14:33:52 +0800579
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700580 int major_version;
581 std::string major_version_str(version, 0, version.find('.'));
582 if (!ParseInt(major_version_str, &major_version)) {
583 PLOG(FATAL) << "Failed to parse the vendor sepolicy major version "
584 << major_version_str;
585 }
Logan Chien837b2a42018-05-03 14:33:52 +0800586
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700587 return major_version;
588 }();
589 return vendor_android_version;
Logan Chien837b2a42018-05-03 14:33:52 +0800590}
591
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800592int SetupSelinux(char** argv) {
Mark Salyzynbeb6abe2019-07-29 09:35:18 -0700593 SetStdioToDevNull(argv);
Tom Cherry59656fb2019-05-28 10:19:44 -0700594 InitKernelLogging(argv);
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800595
596 if (REBOOT_BOOTLOADER_ON_PANIC) {
597 InstallRebootSignalHandlers();
598 }
599
Mark Salyzyn10377df2019-03-27 08:10:41 -0700600 boot_clock::time_point start_time = boot_clock::now();
601
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800602 // Set up SELinux, loading the SELinux policy.
603 SelinuxSetupKernelLogging();
604 SelinuxInitialize();
605
606 // We're in the kernel domain and want to transition to the init domain. File systems that
607 // store SELabels in their xattrs, such as ext4 do not need an explicit restorecon here,
608 // but other file systems do. In particular, this is needed for ramdisks such as the
609 // recovery image for A/B devices.
610 if (selinux_android_restorecon("/system/bin/init", 0) == -1) {
611 PLOG(FATAL) << "restorecon failed of /system/bin/init failed";
612 }
613
Mark Salyzyn44505ec2019-05-08 12:44:50 -0700614 setenv(kEnvSelinuxStartedAt, std::to_string(start_time.time_since_epoch().count()).c_str(), 1);
Mark Salyzyn10377df2019-03-27 08:10:41 -0700615
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800616 const char* path = "/system/bin/init";
617 const char* args[] = {path, "second_stage", nullptr};
618 execv(path, const_cast<char**>(args));
619
620 // execv() only returns if an error happened, in which case we
621 // panic and never return from this function.
622 PLOG(FATAL) << "execv(\"" << path << "\") failed";
623
624 return 1;
625}
626
Tom Cherryc3170092017-08-10 12:22:44 -0700627} // namespace init
628} // namespace android