blob: acbcbd647437005b03740194280ddd2316756bd1 [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>
Bowgo Tsai196cc582020-01-20 18:03:58 +080068#include <libgsi/libgsi.h>
Yifan Hongd91998f2020-02-20 17:54:57 -080069#include <libsnapshot/snapshot.h>
Tom Cherryc3170092017-08-10 12:22:44 -070070#include <selinux/android.h>
71
Bowgo Tsai30afda72019-04-11 23:57:24 +080072#include "debug_ramdisk.h"
Tom Cherry7bfea3d2018-11-06 14:12:05 -080073#include "reboot_utils.h"
Tom Cherryc3170092017-08-10 12:22:44 -070074#include "util.h"
75
Bowgo Tsai1dacd422019-03-04 17:53:34 +080076using namespace std::string_literals;
77
Logan Chien837b2a42018-05-03 14:33:52 +080078using android::base::ParseInt;
Tom Cherryc3170092017-08-10 12:22:44 -070079using android::base::Timer;
80using android::base::unique_fd;
Bowgo Tsai1dacd422019-03-04 17:53:34 +080081using android::fs_mgr::AvbHandle;
Yifan Hongd91998f2020-02-20 17:54:57 -080082using android::snapshot::SnapshotManager;
Tom Cherryc3170092017-08-10 12:22:44 -070083
84namespace android {
85namespace init {
86
Tom Cherryc3170092017-08-10 12:22:44 -070087namespace {
88
89enum EnforcingStatus { SELINUX_PERMISSIVE, SELINUX_ENFORCING };
90
91EnforcingStatus StatusFromCmdline() {
92 EnforcingStatus status = SELINUX_ENFORCING;
93
Tom Cherryc88d8f92019-08-19 15:21:25 -070094 ImportKernelCmdline([&](const std::string& key, const std::string& value) {
95 if (key == "androidboot.selinux" && value == "permissive") {
96 status = SELINUX_PERMISSIVE;
97 }
98 });
Tom Cherryc3170092017-08-10 12:22:44 -070099
100 return status;
101}
102
103bool IsEnforcing() {
104 if (ALLOW_PERMISSIVE_SELINUX) {
105 return StatusFromCmdline() == SELINUX_ENFORCING;
106 }
107 return true;
108}
109
110// Forks, executes the provided program in the child, and waits for the completion in the parent.
111// Child's stderr is captured and logged using LOG(ERROR).
112bool ForkExecveAndWaitForCompletion(const char* filename, char* const argv[]) {
113 // Create a pipe used for redirecting child process's output.
114 // * pipe_fds[0] is the FD the parent will use for reading.
115 // * pipe_fds[1] is the FD the child will use for writing.
116 int pipe_fds[2];
117 if (pipe(pipe_fds) == -1) {
118 PLOG(ERROR) << "Failed to create pipe";
119 return false;
120 }
121
122 pid_t child_pid = fork();
123 if (child_pid == -1) {
124 PLOG(ERROR) << "Failed to fork for " << filename;
125 return false;
126 }
127
128 if (child_pid == 0) {
129 // fork succeeded -- this is executing in the child process
130
131 // Close the pipe FD not used by this process
Nick Kralevich3d118e72017-10-24 10:45:48 -0700132 close(pipe_fds[0]);
Tom Cherryc3170092017-08-10 12:22:44 -0700133
134 // Redirect stderr to the pipe FD provided by the parent
135 if (TEMP_FAILURE_RETRY(dup2(pipe_fds[1], STDERR_FILENO)) == -1) {
136 PLOG(ERROR) << "Failed to redirect stderr of " << filename;
137 _exit(127);
138 return false;
139 }
Nick Kralevich3d118e72017-10-24 10:45:48 -0700140 close(pipe_fds[1]);
Tom Cherryc3170092017-08-10 12:22:44 -0700141
Tom Cherry6de21f12017-08-22 15:41:03 -0700142 if (execv(filename, argv) == -1) {
Tom Cherryc3170092017-08-10 12:22:44 -0700143 PLOG(ERROR) << "Failed to execve " << filename;
144 return false;
145 }
146 // Unreachable because execve will have succeeded and replaced this code
147 // with child process's code.
148 _exit(127);
149 return false;
150 } else {
151 // fork succeeded -- this is executing in the original/parent process
152
153 // Close the pipe FD not used by this process
Nick Kralevich3d118e72017-10-24 10:45:48 -0700154 close(pipe_fds[1]);
Tom Cherryc3170092017-08-10 12:22:44 -0700155
156 // Log the redirected output of the child process.
157 // It's unfortunate that there's no standard way to obtain an istream for a file descriptor.
158 // As a result, we're buffering all output and logging it in one go at the end of the
159 // invocation, instead of logging it as it comes in.
160 const int child_out_fd = pipe_fds[0];
161 std::string child_output;
162 if (!android::base::ReadFdToString(child_out_fd, &child_output)) {
163 PLOG(ERROR) << "Failed to capture full output of " << filename;
164 }
Nick Kralevich3d118e72017-10-24 10:45:48 -0700165 close(child_out_fd);
Tom Cherryc3170092017-08-10 12:22:44 -0700166 if (!child_output.empty()) {
167 // Log captured output, line by line, because LOG expects to be invoked for each line
168 std::istringstream in(child_output);
169 std::string line;
170 while (std::getline(in, line)) {
171 LOG(ERROR) << filename << ": " << line;
172 }
173 }
174
175 // Wait for child to terminate
176 int status;
177 if (TEMP_FAILURE_RETRY(waitpid(child_pid, &status, 0)) != child_pid) {
178 PLOG(ERROR) << "Failed to wait for " << filename;
179 return false;
180 }
181
182 if (WIFEXITED(status)) {
183 int status_code = WEXITSTATUS(status);
184 if (status_code == 0) {
185 return true;
186 } else {
187 LOG(ERROR) << filename << " exited with status " << status_code;
188 }
189 } else if (WIFSIGNALED(status)) {
190 LOG(ERROR) << filename << " killed by signal " << WTERMSIG(status);
191 } else if (WIFSTOPPED(status)) {
192 LOG(ERROR) << filename << " stopped by signal " << WSTOPSIG(status);
193 } else {
194 LOG(ERROR) << "waitpid for " << filename << " returned unexpected status: " << status;
195 }
196
197 return false;
198 }
199}
200
201bool ReadFirstLine(const char* file, std::string* line) {
202 line->clear();
203
204 std::string contents;
205 if (!android::base::ReadFileToString(file, &contents, true /* follow symlinks */)) {
206 return false;
207 }
208 std::istringstream in(contents);
209 std::getline(in, *line);
210 return true;
211}
212
213bool FindPrecompiledSplitPolicy(std::string* file) {
214 file->clear();
kaichieheef4cd72017-08-31 22:07:19 +0800215 // If there is an odm partition, precompiled_sepolicy will be in
216 // odm/etc/selinux. Otherwise it will be in vendor/etc/selinux.
217 static constexpr const char vendor_precompiled_sepolicy[] =
218 "/vendor/etc/selinux/precompiled_sepolicy";
219 static constexpr const char odm_precompiled_sepolicy[] =
220 "/odm/etc/selinux/precompiled_sepolicy";
221 if (access(odm_precompiled_sepolicy, R_OK) == 0) {
222 *file = odm_precompiled_sepolicy;
223 } else if (access(vendor_precompiled_sepolicy, R_OK) == 0) {
224 *file = vendor_precompiled_sepolicy;
225 } else {
226 PLOG(INFO) << "No precompiled sepolicy";
Tom Cherryc3170092017-08-10 12:22:44 -0700227 return false;
228 }
229 std::string actual_plat_id;
Tri Voc8137f92019-01-22 18:22:25 -0800230 if (!ReadFirstLine("/system/etc/selinux/plat_sepolicy_and_mapping.sha256", &actual_plat_id)) {
Tom Cherryc3170092017-08-10 12:22:44 -0700231 PLOG(INFO) << "Failed to read "
Tri Voc8137f92019-01-22 18:22:25 -0800232 "/system/etc/selinux/plat_sepolicy_and_mapping.sha256";
233 return false;
234 }
Bowgo Tsaif016f252019-08-28 17:56:51 +0800235 std::string actual_system_ext_id;
236 if (!ReadFirstLine("/system_ext/etc/selinux/system_ext_sepolicy_and_mapping.sha256",
237 &actual_system_ext_id)) {
238 PLOG(INFO) << "Failed to read "
239 "/system_ext/etc/selinux/system_ext_sepolicy_and_mapping.sha256";
240 return false;
241 }
Tri Voc8137f92019-01-22 18:22:25 -0800242 std::string actual_product_id;
243 if (!ReadFirstLine("/product/etc/selinux/product_sepolicy_and_mapping.sha256",
244 &actual_product_id)) {
245 PLOG(INFO) << "Failed to read "
246 "/product/etc/selinux/product_sepolicy_and_mapping.sha256";
Tom Cherryc3170092017-08-10 12:22:44 -0700247 return false;
248 }
kaichieheef4cd72017-08-31 22:07:19 +0800249
Tom Cherryc3170092017-08-10 12:22:44 -0700250 std::string precompiled_plat_id;
Tri Voc8137f92019-01-22 18:22:25 -0800251 std::string precompiled_plat_sha256 = *file + ".plat_sepolicy_and_mapping.sha256";
252 if (!ReadFirstLine(precompiled_plat_sha256.c_str(), &precompiled_plat_id)) {
253 PLOG(INFO) << "Failed to read " << precompiled_plat_sha256;
kaichieheef4cd72017-08-31 22:07:19 +0800254 file->clear();
Tom Cherryc3170092017-08-10 12:22:44 -0700255 return false;
256 }
Bowgo Tsaif016f252019-08-28 17:56:51 +0800257 std::string precompiled_system_ext_id;
258 std::string precompiled_system_ext_sha256 = *file + ".system_ext_sepolicy_and_mapping.sha256";
259 if (!ReadFirstLine(precompiled_system_ext_sha256.c_str(), &precompiled_system_ext_id)) {
260 PLOG(INFO) << "Failed to read " << precompiled_system_ext_sha256;
261 file->clear();
262 return false;
263 }
Tri Voc8137f92019-01-22 18:22:25 -0800264 std::string precompiled_product_id;
265 std::string precompiled_product_sha256 = *file + ".product_sepolicy_and_mapping.sha256";
266 if (!ReadFirstLine(precompiled_product_sha256.c_str(), &precompiled_product_id)) {
267 PLOG(INFO) << "Failed to read " << precompiled_product_sha256;
268 file->clear();
269 return false;
270 }
271 if (actual_plat_id.empty() || actual_plat_id != precompiled_plat_id ||
Bowgo Tsaif016f252019-08-28 17:56:51 +0800272 actual_system_ext_id.empty() || actual_system_ext_id != precompiled_system_ext_id ||
Tri Voc8137f92019-01-22 18:22:25 -0800273 actual_product_id.empty() || actual_product_id != precompiled_product_id) {
kaichieheef4cd72017-08-31 22:07:19 +0800274 file->clear();
Tom Cherryc3170092017-08-10 12:22:44 -0700275 return false;
276 }
Tom Cherryc3170092017-08-10 12:22:44 -0700277 return true;
278}
279
280bool GetVendorMappingVersion(std::string* plat_vers) {
281 if (!ReadFirstLine("/vendor/etc/selinux/plat_sepolicy_vers.txt", plat_vers)) {
282 PLOG(ERROR) << "Failed to read /vendor/etc/selinux/plat_sepolicy_vers.txt";
283 return false;
284 }
285 if (plat_vers->empty()) {
286 LOG(ERROR) << "No version present in plat_sepolicy_vers.txt";
287 return false;
288 }
289 return true;
290}
291
292constexpr const char plat_policy_cil_file[] = "/system/etc/selinux/plat_sepolicy.cil";
293
294bool IsSplitPolicyDevice() {
295 return access(plat_policy_cil_file, R_OK) != -1;
296}
297
298bool LoadSplitPolicy() {
299 // IMPLEMENTATION NOTE: Split policy consists of three CIL files:
300 // * platform -- policy needed due to logic contained in the system image,
301 // * non-platform -- policy needed due to logic contained in the vendor image,
302 // * mapping -- mapping policy which helps preserve forward-compatibility of non-platform policy
303 // with newer versions of platform policy.
304 //
305 // secilc is invoked to compile the above three policy files into a single monolithic policy
306 // file. This file is then loaded into the kernel.
307
Bowgo Tsai1dacd422019-03-04 17:53:34 +0800308 // See if we need to load userdebug_plat_sepolicy.cil instead of plat_sepolicy.cil.
309 const char* force_debuggable_env = getenv("INIT_FORCE_DEBUGGABLE");
310 bool use_userdebug_policy =
311 ((force_debuggable_env && "true"s == force_debuggable_env) &&
Bowgo Tsai30afda72019-04-11 23:57:24 +0800312 AvbHandle::IsDeviceUnlocked() && access(kDebugRamdiskSEPolicy, F_OK) == 0);
Bowgo Tsai1dacd422019-03-04 17:53:34 +0800313 if (use_userdebug_policy) {
314 LOG(WARNING) << "Using userdebug system sepolicy";
315 }
316
Tom Cherryc3170092017-08-10 12:22:44 -0700317 // Load precompiled policy from vendor image, if a matching policy is found there. The policy
318 // must match the platform policy on the system image.
319 std::string precompiled_sepolicy_file;
Bowgo Tsai1dacd422019-03-04 17:53:34 +0800320 // use_userdebug_policy requires compiling sepolicy with userdebug_plat_sepolicy.cil.
321 // Thus it cannot use the precompiled policy from vendor image.
322 if (!use_userdebug_policy && FindPrecompiledSplitPolicy(&precompiled_sepolicy_file)) {
Tom Cherryc3170092017-08-10 12:22:44 -0700323 unique_fd fd(open(precompiled_sepolicy_file.c_str(), O_RDONLY | O_CLOEXEC | O_BINARY));
324 if (fd != -1) {
325 if (selinux_android_load_policy_from_fd(fd, precompiled_sepolicy_file.c_str()) < 0) {
326 LOG(ERROR) << "Failed to load SELinux policy from " << precompiled_sepolicy_file;
327 return false;
328 }
329 return true;
330 }
331 }
332 // No suitable precompiled policy could be loaded
333
334 LOG(INFO) << "Compiling SELinux policy";
335
Tom Cherryc3170092017-08-10 12:22:44 -0700336 // We store the output of the compilation on /dev because this is the most convenient tmpfs
337 // storage mount available this early in the boot sequence.
338 char compiled_sepolicy[] = "/dev/sepolicy.XXXXXX";
339 unique_fd compiled_sepolicy_fd(mkostemp(compiled_sepolicy, O_CLOEXEC));
340 if (compiled_sepolicy_fd < 0) {
341 PLOG(ERROR) << "Failed to create temporary file " << compiled_sepolicy;
342 return false;
343 }
344
345 // Determine which mapping file to include
346 std::string vend_plat_vers;
347 if (!GetVendorMappingVersion(&vend_plat_vers)) {
348 return false;
349 }
Tri Vo503f1852019-01-16 11:57:19 -0800350 std::string plat_mapping_file("/system/etc/selinux/mapping/" + vend_plat_vers + ".cil");
kaichieheef4cd72017-08-31 22:07:19 +0800351
Jeff Vander Stoep0ac51cf2019-05-02 14:05:18 -0700352 std::string plat_compat_cil_file("/system/etc/selinux/mapping/" + vend_plat_vers +
353 ".compat.cil");
354 if (access(plat_compat_cil_file.c_str(), F_OK) == -1) {
355 plat_compat_cil_file.clear();
356 }
357
Bowgo Tsaif016f252019-08-28 17:56:51 +0800358 std::string system_ext_policy_cil_file("/system_ext/etc/selinux/system_ext_sepolicy.cil");
359 if (access(system_ext_policy_cil_file.c_str(), F_OK) == -1) {
360 system_ext_policy_cil_file.clear();
361 }
362
363 std::string system_ext_mapping_file("/system_ext/etc/selinux/mapping/" + vend_plat_vers +
364 ".cil");
365 if (access(system_ext_mapping_file.c_str(), F_OK) == -1) {
366 system_ext_mapping_file.clear();
367 }
368
Tri Vod3518cf2018-12-14 14:25:08 -0800369 std::string product_policy_cil_file("/product/etc/selinux/product_sepolicy.cil");
370 if (access(product_policy_cil_file.c_str(), F_OK) == -1) {
371 product_policy_cil_file.clear();
372 }
373
Tri Vo503f1852019-01-16 11:57:19 -0800374 std::string product_mapping_file("/product/etc/selinux/mapping/" + vend_plat_vers + ".cil");
375 if (access(product_mapping_file.c_str(), F_OK) == -1) {
376 product_mapping_file.clear();
377 }
378
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800379 // vendor_sepolicy.cil and plat_pub_versioned.cil are the new design to replace
kaichieheef4cd72017-08-31 22:07:19 +0800380 // nonplat_sepolicy.cil.
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800381 std::string plat_pub_versioned_cil_file("/vendor/etc/selinux/plat_pub_versioned.cil");
kaichieheef4cd72017-08-31 22:07:19 +0800382 std::string vendor_policy_cil_file("/vendor/etc/selinux/vendor_sepolicy.cil");
383
384 if (access(vendor_policy_cil_file.c_str(), F_OK) == -1) {
385 // For backward compatibility.
386 // TODO: remove this after no device is using nonplat_sepolicy.cil.
387 vendor_policy_cil_file = "/vendor/etc/selinux/nonplat_sepolicy.cil";
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800388 plat_pub_versioned_cil_file.clear();
389 } else if (access(plat_pub_versioned_cil_file.c_str(), F_OK) == -1) {
390 LOG(ERROR) << "Missing " << plat_pub_versioned_cil_file;
kaichieheef4cd72017-08-31 22:07:19 +0800391 return false;
392 }
393
394 // odm_sepolicy.cil is default but optional.
395 std::string odm_policy_cil_file("/odm/etc/selinux/odm_sepolicy.cil");
396 if (access(odm_policy_cil_file.c_str(), F_OK) == -1) {
397 odm_policy_cil_file.clear();
398 }
Jeff Vander Stoep724eda52019-02-15 12:13:38 -0800399 const std::string version_as_string = std::to_string(SEPOLICY_VERSION);
Andreas Huberc41b8382017-08-18 14:43:52 -0700400
Tom Cherryc3170092017-08-10 12:22:44 -0700401 // clang-format off
kaichieheef4cd72017-08-31 22:07:19 +0800402 std::vector<const char*> compile_args {
Tom Cherryc3170092017-08-10 12:22:44 -0700403 "/system/bin/secilc",
Bowgo Tsai30afda72019-04-11 23:57:24 +0800404 use_userdebug_policy ? kDebugRamdiskSEPolicy: plat_policy_cil_file,
Jeff Vander Stoep5e9ba3c2017-10-06 17:03:45 -0700405 "-m", "-M", "true", "-G", "-N",
Andreas Huberc41b8382017-08-18 14:43:52 -0700406 "-c", version_as_string.c_str(),
Tri Vo503f1852019-01-16 11:57:19 -0800407 plat_mapping_file.c_str(),
Tom Cherryc3170092017-08-10 12:22:44 -0700408 "-o", compiled_sepolicy,
409 // We don't care about file_contexts output by the compiler
410 "-f", "/sys/fs/selinux/null", // /dev/null is not yet available
kaichieheef4cd72017-08-31 22:07:19 +0800411 };
Tom Cherryc3170092017-08-10 12:22:44 -0700412 // clang-format on
413
Jeff Vander Stoep0ac51cf2019-05-02 14:05:18 -0700414 if (!plat_compat_cil_file.empty()) {
415 compile_args.push_back(plat_compat_cil_file.c_str());
416 }
Bowgo Tsaif016f252019-08-28 17:56:51 +0800417 if (!system_ext_policy_cil_file.empty()) {
418 compile_args.push_back(system_ext_policy_cil_file.c_str());
419 }
420 if (!system_ext_mapping_file.empty()) {
421 compile_args.push_back(system_ext_mapping_file.c_str());
422 }
Tri Vod3518cf2018-12-14 14:25:08 -0800423 if (!product_policy_cil_file.empty()) {
424 compile_args.push_back(product_policy_cil_file.c_str());
425 }
Tri Vo503f1852019-01-16 11:57:19 -0800426 if (!product_mapping_file.empty()) {
427 compile_args.push_back(product_mapping_file.c_str());
428 }
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800429 if (!plat_pub_versioned_cil_file.empty()) {
430 compile_args.push_back(plat_pub_versioned_cil_file.c_str());
kaichieheef4cd72017-08-31 22:07:19 +0800431 }
432 if (!vendor_policy_cil_file.empty()) {
433 compile_args.push_back(vendor_policy_cil_file.c_str());
434 }
435 if (!odm_policy_cil_file.empty()) {
436 compile_args.push_back(odm_policy_cil_file.c_str());
437 }
438 compile_args.push_back(nullptr);
439
440 if (!ForkExecveAndWaitForCompletion(compile_args[0], (char**)compile_args.data())) {
Tom Cherryc3170092017-08-10 12:22:44 -0700441 unlink(compiled_sepolicy);
442 return false;
443 }
444 unlink(compiled_sepolicy);
445
446 LOG(INFO) << "Loading compiled SELinux policy";
447 if (selinux_android_load_policy_from_fd(compiled_sepolicy_fd, compiled_sepolicy) < 0) {
448 LOG(ERROR) << "Failed to load SELinux policy from " << compiled_sepolicy;
449 return false;
450 }
451
452 return true;
453}
454
455bool LoadMonolithicPolicy() {
456 LOG(VERBOSE) << "Loading SELinux policy from monolithic file";
457 if (selinux_android_load_policy() < 0) {
458 PLOG(ERROR) << "Failed to load monolithic SELinux policy";
459 return false;
460 }
461 return true;
462}
463
464bool LoadPolicy() {
465 return IsSplitPolicyDevice() ? LoadSplitPolicy() : LoadMonolithicPolicy();
466}
467
Tom Cherryc3170092017-08-10 12:22:44 -0700468void SelinuxInitialize() {
Tom Cherryc3170092017-08-10 12:22:44 -0700469 LOG(INFO) << "Loading SELinux policy";
470 if (!LoadPolicy()) {
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700471 LOG(FATAL) << "Unable to load SELinux policy";
Tom Cherryc3170092017-08-10 12:22:44 -0700472 }
473
474 bool kernel_enforcing = (security_getenforce() == 1);
475 bool is_enforcing = IsEnforcing();
476 if (kernel_enforcing != is_enforcing) {
477 if (security_setenforce(is_enforcing)) {
Paul Lawrenceb2c2d692019-08-30 11:11:44 -0700478 PLOG(FATAL) << "security_setenforce(" << (is_enforcing ? "true" : "false")
479 << ") failed";
Tom Cherryc3170092017-08-10 12:22:44 -0700480 }
481 }
482
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900483 if (auto result = WriteFile("/sys/fs/selinux/checkreqprot", "0"); !result.ok()) {
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700484 LOG(FATAL) << "Unable to write to /sys/fs/selinux/checkreqprot: " << result.error();
Tom Cherryc3170092017-08-10 12:22:44 -0700485 }
Tom Cherryc3170092017-08-10 12:22:44 -0700486}
487
Tom Cherry8180b482019-08-26 13:57:51 -0700488constexpr size_t kKlogMessageSize = 1024;
489
490void SelinuxAvcLog(char* buf, size_t buf_len) {
491 CHECK_GT(buf_len, 0u);
492
493 size_t str_len = strnlen(buf, buf_len);
494 // trim newline at end of string
495 if (buf[str_len - 1] == '\n') {
496 buf[str_len - 1] = '\0';
497 }
498
499 struct NetlinkMessage {
500 nlmsghdr hdr;
501 char buf[kKlogMessageSize];
502 } request = {};
503
504 request.hdr.nlmsg_flags = NLM_F_REQUEST;
505 request.hdr.nlmsg_type = AUDIT_USER_AVC;
506 request.hdr.nlmsg_len = sizeof(request);
507 strlcpy(request.buf, buf, sizeof(request.buf));
508
509 auto fd = unique_fd{socket(PF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_AUDIT)};
510 if (!fd.ok()) {
511 return;
512 }
513
514 TEMP_FAILURE_RETRY(send(fd, &request, sizeof(request), 0));
515}
516
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800517} // namespace
518
Tom Cherryc3170092017-08-10 12:22:44 -0700519void SelinuxRestoreContext() {
520 LOG(INFO) << "Running restorecon...";
521 selinux_android_restorecon("/dev", 0);
522 selinux_android_restorecon("/dev/kmsg", 0);
523 if constexpr (WORLD_WRITABLE_KMSG) {
524 selinux_android_restorecon("/dev/kmsg_debug", 0);
525 }
Tom Cherry81ae0752018-07-30 16:23:49 -0700526 selinux_android_restorecon("/dev/null", 0);
527 selinux_android_restorecon("/dev/ptmx", 0);
Tom Cherryc3170092017-08-10 12:22:44 -0700528 selinux_android_restorecon("/dev/socket", 0);
529 selinux_android_restorecon("/dev/random", 0);
530 selinux_android_restorecon("/dev/urandom", 0);
531 selinux_android_restorecon("/dev/__properties__", 0);
532
Tom Cherryc3170092017-08-10 12:22:44 -0700533 selinux_android_restorecon("/dev/block", SELINUX_ANDROID_RESTORECON_RECURSE);
534 selinux_android_restorecon("/dev/device-mapper", 0);
Jiyong Park4ba548d2019-02-22 16:04:35 +0900535
536 selinux_android_restorecon("/apex", 0);
Kiyoung Kim99df54b2019-11-22 16:14:10 +0900537
538 selinux_android_restorecon("/linkerconfig", 0);
Bowgo Tsai196cc582020-01-20 18:03:58 +0800539
David Andersonc991f342020-02-21 17:11:07 -0800540 // adb remount, snapshot-based updates, and DSUs all create files during
541 // first-stage init.
542 selinux_android_restorecon("/metadata", SELINUX_ANDROID_RESTORECON_RECURSE);
Yifan Hongd91998f2020-02-20 17:54:57 -0800543
544 selinux_android_restorecon(SnapshotManager::GetGlobalRollbackIndicatorPath().c_str(), 0);
Tom Cherryc3170092017-08-10 12:22:44 -0700545}
546
Tom Cherry74069d12018-07-20 15:26:25 -0700547int SelinuxKlogCallback(int type, const char* fmt, ...) {
548 android::base::LogSeverity severity = android::base::ERROR;
549 if (type == SELINUX_WARNING) {
550 severity = android::base::WARNING;
551 } else if (type == SELINUX_INFO) {
552 severity = android::base::INFO;
553 }
Tom Cherry8180b482019-08-26 13:57:51 -0700554 char buf[kKlogMessageSize];
Tom Cherry74069d12018-07-20 15:26:25 -0700555 va_list ap;
556 va_start(ap, fmt);
Tom Cherry8180b482019-08-26 13:57:51 -0700557 int length_written = vsnprintf(buf, sizeof(buf), fmt, ap);
Tom Cherry74069d12018-07-20 15:26:25 -0700558 va_end(ap);
Tom Cherry8180b482019-08-26 13:57:51 -0700559 if (length_written <= 0) {
560 return 0;
561 }
562 if (type == SELINUX_AVC) {
563 SelinuxAvcLog(buf, sizeof(buf));
564 } else {
565 android::base::KernelLogger(android::base::MAIN, severity, "selinux", nullptr, 0, buf);
566 }
Tom Cherry74069d12018-07-20 15:26:25 -0700567 return 0;
568}
569
Tom Cherryc3170092017-08-10 12:22:44 -0700570void SelinuxSetupKernelLogging() {
571 selinux_callback cb;
Tom Cherry74069d12018-07-20 15:26:25 -0700572 cb.func_log = SelinuxKlogCallback;
Tom Cherryc3170092017-08-10 12:22:44 -0700573 selinux_set_callback(SELINUX_CB_LOG, cb);
574}
575
Tom Cherry40acb372018-08-01 13:41:12 -0700576int SelinuxGetVendorAndroidVersion() {
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700577 static int vendor_android_version = [] {
578 if (!IsSplitPolicyDevice()) {
579 // If this device does not split sepolicy files, it's not a Treble device and therefore,
580 // we assume it's always on the latest platform.
581 return __ANDROID_API_FUTURE__;
582 }
Logan Chien837b2a42018-05-03 14:33:52 +0800583
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700584 std::string version;
585 if (!GetVendorMappingVersion(&version)) {
586 LOG(FATAL) << "Could not read vendor SELinux version";
587 }
Logan Chien837b2a42018-05-03 14:33:52 +0800588
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700589 int major_version;
590 std::string major_version_str(version, 0, version.find('.'));
591 if (!ParseInt(major_version_str, &major_version)) {
592 PLOG(FATAL) << "Failed to parse the vendor sepolicy major version "
593 << major_version_str;
594 }
Logan Chien837b2a42018-05-03 14:33:52 +0800595
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700596 return major_version;
597 }();
598 return vendor_android_version;
Logan Chien837b2a42018-05-03 14:33:52 +0800599}
600
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800601int SetupSelinux(char** argv) {
Mark Salyzynbeb6abe2019-07-29 09:35:18 -0700602 SetStdioToDevNull(argv);
Tom Cherry59656fb2019-05-28 10:19:44 -0700603 InitKernelLogging(argv);
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800604
605 if (REBOOT_BOOTLOADER_ON_PANIC) {
606 InstallRebootSignalHandlers();
607 }
608
Mark Salyzyn10377df2019-03-27 08:10:41 -0700609 boot_clock::time_point start_time = boot_clock::now();
610
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800611 // Set up SELinux, loading the SELinux policy.
612 SelinuxSetupKernelLogging();
613 SelinuxInitialize();
614
615 // We're in the kernel domain and want to transition to the init domain. File systems that
616 // store SELabels in their xattrs, such as ext4 do not need an explicit restorecon here,
617 // but other file systems do. In particular, this is needed for ramdisks such as the
618 // recovery image for A/B devices.
619 if (selinux_android_restorecon("/system/bin/init", 0) == -1) {
620 PLOG(FATAL) << "restorecon failed of /system/bin/init failed";
621 }
622
Mark Salyzyn44505ec2019-05-08 12:44:50 -0700623 setenv(kEnvSelinuxStartedAt, std::to_string(start_time.time_since_epoch().count()).c_str(), 1);
Mark Salyzyn10377df2019-03-27 08:10:41 -0700624
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800625 const char* path = "/system/bin/init";
626 const char* args[] = {path, "second_stage", nullptr};
627 execv(path, const_cast<char**>(args));
628
629 // execv() only returns if an error happened, in which case we
630 // panic and never return from this function.
631 PLOG(FATAL) << "execv(\"" << path << "\") failed";
632
633 return 1;
634}
635
Tom Cherryc3170092017-08-10 12:22:44 -0700636} // namespace init
637} // namespace android