blob: 0336936551ac9a9784a9dbfd57c93cf67776d106 [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
David Anderson491e4da2020-12-08 00:21:20 -080048// OpenSplitPolicy() function below to compile the SEPolicy to a temp directory and load it.
Bowgo Tsaif016f252019-08-28 17:56:51 +080049// 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>
David Andersond0ce5302020-03-20 21:47:10 -070066#include <android-base/strings.h>
Tom Cherryc3170092017-08-10 12:22:44 -070067#include <android-base/unique_fd.h>
Bowgo Tsai1dacd422019-03-04 17:53:34 +080068#include <fs_avb/fs_avb.h>
David Andersond0ce5302020-03-20 21:47:10 -070069#include <fs_mgr.h>
Bowgo Tsai196cc582020-01-20 18:03:58 +080070#include <libgsi/libgsi.h>
Yifan Hongd91998f2020-02-20 17:54:57 -080071#include <libsnapshot/snapshot.h>
Tom Cherryc3170092017-08-10 12:22:44 -070072#include <selinux/android.h>
73
David Andersond0ce5302020-03-20 21:47:10 -070074#include "block_dev_initializer.h"
Bowgo Tsai30afda72019-04-11 23:57:24 +080075#include "debug_ramdisk.h"
Tom Cherry7bfea3d2018-11-06 14:12:05 -080076#include "reboot_utils.h"
David Anderson491e4da2020-12-08 00:21:20 -080077#include "snapuserd_transition.h"
Tom Cherryc3170092017-08-10 12:22:44 -070078#include "util.h"
79
Bowgo Tsai1dacd422019-03-04 17:53:34 +080080using namespace std::string_literals;
81
Logan Chien837b2a42018-05-03 14:33:52 +080082using android::base::ParseInt;
Tom Cherryc3170092017-08-10 12:22:44 -070083using android::base::Timer;
84using android::base::unique_fd;
Bowgo Tsai1dacd422019-03-04 17:53:34 +080085using android::fs_mgr::AvbHandle;
Yifan Hongd91998f2020-02-20 17:54:57 -080086using android::snapshot::SnapshotManager;
Tom Cherryc3170092017-08-10 12:22:44 -070087
88namespace android {
89namespace init {
90
Tom Cherryc3170092017-08-10 12:22:44 -070091namespace {
92
93enum EnforcingStatus { SELINUX_PERMISSIVE, SELINUX_ENFORCING };
94
95EnforcingStatus StatusFromCmdline() {
96 EnforcingStatus status = SELINUX_ENFORCING;
97
Tom Cherryc88d8f92019-08-19 15:21:25 -070098 ImportKernelCmdline([&](const std::string& key, const std::string& value) {
99 if (key == "androidboot.selinux" && value == "permissive") {
100 status = SELINUX_PERMISSIVE;
101 }
102 });
Tom Cherryc3170092017-08-10 12:22:44 -0700103
104 return status;
105}
106
107bool IsEnforcing() {
108 if (ALLOW_PERMISSIVE_SELINUX) {
109 return StatusFromCmdline() == SELINUX_ENFORCING;
110 }
111 return true;
112}
113
114// Forks, executes the provided program in the child, and waits for the completion in the parent.
115// Child's stderr is captured and logged using LOG(ERROR).
116bool ForkExecveAndWaitForCompletion(const char* filename, char* const argv[]) {
117 // Create a pipe used for redirecting child process's output.
118 // * pipe_fds[0] is the FD the parent will use for reading.
119 // * pipe_fds[1] is the FD the child will use for writing.
120 int pipe_fds[2];
121 if (pipe(pipe_fds) == -1) {
122 PLOG(ERROR) << "Failed to create pipe";
123 return false;
124 }
125
126 pid_t child_pid = fork();
127 if (child_pid == -1) {
128 PLOG(ERROR) << "Failed to fork for " << filename;
129 return false;
130 }
131
132 if (child_pid == 0) {
133 // fork succeeded -- this is executing in the child process
134
135 // Close the pipe FD not used by this process
Nick Kralevich3d118e72017-10-24 10:45:48 -0700136 close(pipe_fds[0]);
Tom Cherryc3170092017-08-10 12:22:44 -0700137
138 // Redirect stderr to the pipe FD provided by the parent
139 if (TEMP_FAILURE_RETRY(dup2(pipe_fds[1], STDERR_FILENO)) == -1) {
140 PLOG(ERROR) << "Failed to redirect stderr of " << filename;
141 _exit(127);
142 return false;
143 }
Nick Kralevich3d118e72017-10-24 10:45:48 -0700144 close(pipe_fds[1]);
Tom Cherryc3170092017-08-10 12:22:44 -0700145
Tom Cherry6de21f12017-08-22 15:41:03 -0700146 if (execv(filename, argv) == -1) {
Tom Cherryc3170092017-08-10 12:22:44 -0700147 PLOG(ERROR) << "Failed to execve " << filename;
148 return false;
149 }
150 // Unreachable because execve will have succeeded and replaced this code
151 // with child process's code.
152 _exit(127);
153 return false;
154 } else {
155 // fork succeeded -- this is executing in the original/parent process
156
157 // Close the pipe FD not used by this process
Nick Kralevich3d118e72017-10-24 10:45:48 -0700158 close(pipe_fds[1]);
Tom Cherryc3170092017-08-10 12:22:44 -0700159
160 // Log the redirected output of the child process.
161 // It's unfortunate that there's no standard way to obtain an istream for a file descriptor.
162 // As a result, we're buffering all output and logging it in one go at the end of the
163 // invocation, instead of logging it as it comes in.
164 const int child_out_fd = pipe_fds[0];
165 std::string child_output;
166 if (!android::base::ReadFdToString(child_out_fd, &child_output)) {
167 PLOG(ERROR) << "Failed to capture full output of " << filename;
168 }
Nick Kralevich3d118e72017-10-24 10:45:48 -0700169 close(child_out_fd);
Tom Cherryc3170092017-08-10 12:22:44 -0700170 if (!child_output.empty()) {
171 // Log captured output, line by line, because LOG expects to be invoked for each line
172 std::istringstream in(child_output);
173 std::string line;
174 while (std::getline(in, line)) {
175 LOG(ERROR) << filename << ": " << line;
176 }
177 }
178
179 // Wait for child to terminate
180 int status;
181 if (TEMP_FAILURE_RETRY(waitpid(child_pid, &status, 0)) != child_pid) {
182 PLOG(ERROR) << "Failed to wait for " << filename;
183 return false;
184 }
185
186 if (WIFEXITED(status)) {
187 int status_code = WEXITSTATUS(status);
188 if (status_code == 0) {
189 return true;
190 } else {
191 LOG(ERROR) << filename << " exited with status " << status_code;
192 }
193 } else if (WIFSIGNALED(status)) {
194 LOG(ERROR) << filename << " killed by signal " << WTERMSIG(status);
195 } else if (WIFSTOPPED(status)) {
196 LOG(ERROR) << filename << " stopped by signal " << WSTOPSIG(status);
197 } else {
198 LOG(ERROR) << "waitpid for " << filename << " returned unexpected status: " << status;
199 }
200
201 return false;
202 }
203}
204
205bool ReadFirstLine(const char* file, std::string* line) {
206 line->clear();
207
208 std::string contents;
209 if (!android::base::ReadFileToString(file, &contents, true /* follow symlinks */)) {
210 return false;
211 }
212 std::istringstream in(contents);
213 std::getline(in, *line);
214 return true;
215}
216
217bool FindPrecompiledSplitPolicy(std::string* file) {
218 file->clear();
kaichieheef4cd72017-08-31 22:07:19 +0800219 // If there is an odm partition, precompiled_sepolicy will be in
220 // odm/etc/selinux. Otherwise it will be in vendor/etc/selinux.
221 static constexpr const char vendor_precompiled_sepolicy[] =
222 "/vendor/etc/selinux/precompiled_sepolicy";
223 static constexpr const char odm_precompiled_sepolicy[] =
224 "/odm/etc/selinux/precompiled_sepolicy";
225 if (access(odm_precompiled_sepolicy, R_OK) == 0) {
226 *file = odm_precompiled_sepolicy;
227 } else if (access(vendor_precompiled_sepolicy, R_OK) == 0) {
228 *file = vendor_precompiled_sepolicy;
229 } else {
230 PLOG(INFO) << "No precompiled sepolicy";
Tom Cherryc3170092017-08-10 12:22:44 -0700231 return false;
232 }
233 std::string actual_plat_id;
Tri Voc8137f92019-01-22 18:22:25 -0800234 if (!ReadFirstLine("/system/etc/selinux/plat_sepolicy_and_mapping.sha256", &actual_plat_id)) {
Tom Cherryc3170092017-08-10 12:22:44 -0700235 PLOG(INFO) << "Failed to read "
Tri Voc8137f92019-01-22 18:22:25 -0800236 "/system/etc/selinux/plat_sepolicy_and_mapping.sha256";
237 return false;
238 }
Bowgo Tsaif016f252019-08-28 17:56:51 +0800239 std::string actual_system_ext_id;
240 if (!ReadFirstLine("/system_ext/etc/selinux/system_ext_sepolicy_and_mapping.sha256",
241 &actual_system_ext_id)) {
242 PLOG(INFO) << "Failed to read "
243 "/system_ext/etc/selinux/system_ext_sepolicy_and_mapping.sha256";
244 return false;
245 }
Tri Voc8137f92019-01-22 18:22:25 -0800246 std::string actual_product_id;
247 if (!ReadFirstLine("/product/etc/selinux/product_sepolicy_and_mapping.sha256",
248 &actual_product_id)) {
249 PLOG(INFO) << "Failed to read "
250 "/product/etc/selinux/product_sepolicy_and_mapping.sha256";
Tom Cherryc3170092017-08-10 12:22:44 -0700251 return false;
252 }
kaichieheef4cd72017-08-31 22:07:19 +0800253
Tom Cherryc3170092017-08-10 12:22:44 -0700254 std::string precompiled_plat_id;
Tri Voc8137f92019-01-22 18:22:25 -0800255 std::string precompiled_plat_sha256 = *file + ".plat_sepolicy_and_mapping.sha256";
256 if (!ReadFirstLine(precompiled_plat_sha256.c_str(), &precompiled_plat_id)) {
257 PLOG(INFO) << "Failed to read " << precompiled_plat_sha256;
kaichieheef4cd72017-08-31 22:07:19 +0800258 file->clear();
Tom Cherryc3170092017-08-10 12:22:44 -0700259 return false;
260 }
Bowgo Tsaif016f252019-08-28 17:56:51 +0800261 std::string precompiled_system_ext_id;
262 std::string precompiled_system_ext_sha256 = *file + ".system_ext_sepolicy_and_mapping.sha256";
263 if (!ReadFirstLine(precompiled_system_ext_sha256.c_str(), &precompiled_system_ext_id)) {
264 PLOG(INFO) << "Failed to read " << precompiled_system_ext_sha256;
265 file->clear();
266 return false;
267 }
Tri Voc8137f92019-01-22 18:22:25 -0800268 std::string precompiled_product_id;
269 std::string precompiled_product_sha256 = *file + ".product_sepolicy_and_mapping.sha256";
270 if (!ReadFirstLine(precompiled_product_sha256.c_str(), &precompiled_product_id)) {
271 PLOG(INFO) << "Failed to read " << precompiled_product_sha256;
272 file->clear();
273 return false;
274 }
275 if (actual_plat_id.empty() || actual_plat_id != precompiled_plat_id ||
Bowgo Tsaif016f252019-08-28 17:56:51 +0800276 actual_system_ext_id.empty() || actual_system_ext_id != precompiled_system_ext_id ||
Tri Voc8137f92019-01-22 18:22:25 -0800277 actual_product_id.empty() || actual_product_id != precompiled_product_id) {
kaichieheef4cd72017-08-31 22:07:19 +0800278 file->clear();
Tom Cherryc3170092017-08-10 12:22:44 -0700279 return false;
280 }
Tom Cherryc3170092017-08-10 12:22:44 -0700281 return true;
282}
283
284bool GetVendorMappingVersion(std::string* plat_vers) {
285 if (!ReadFirstLine("/vendor/etc/selinux/plat_sepolicy_vers.txt", plat_vers)) {
286 PLOG(ERROR) << "Failed to read /vendor/etc/selinux/plat_sepolicy_vers.txt";
287 return false;
288 }
289 if (plat_vers->empty()) {
290 LOG(ERROR) << "No version present in plat_sepolicy_vers.txt";
291 return false;
292 }
293 return true;
294}
295
296constexpr const char plat_policy_cil_file[] = "/system/etc/selinux/plat_sepolicy.cil";
297
298bool IsSplitPolicyDevice() {
299 return access(plat_policy_cil_file, R_OK) != -1;
300}
301
David Anderson491e4da2020-12-08 00:21:20 -0800302struct PolicyFile {
303 unique_fd fd;
304 std::string path;
305};
306
307bool OpenSplitPolicy(PolicyFile* policy_file) {
Tom Cherryc3170092017-08-10 12:22:44 -0700308 // IMPLEMENTATION NOTE: Split policy consists of three CIL files:
309 // * platform -- policy needed due to logic contained in the system image,
310 // * non-platform -- policy needed due to logic contained in the vendor image,
311 // * mapping -- mapping policy which helps preserve forward-compatibility of non-platform policy
312 // with newer versions of platform policy.
313 //
314 // secilc is invoked to compile the above three policy files into a single monolithic policy
315 // file. This file is then loaded into the kernel.
316
Bowgo Tsai1dacd422019-03-04 17:53:34 +0800317 // See if we need to load userdebug_plat_sepolicy.cil instead of plat_sepolicy.cil.
318 const char* force_debuggable_env = getenv("INIT_FORCE_DEBUGGABLE");
319 bool use_userdebug_policy =
320 ((force_debuggable_env && "true"s == force_debuggable_env) &&
Bowgo Tsai30afda72019-04-11 23:57:24 +0800321 AvbHandle::IsDeviceUnlocked() && access(kDebugRamdiskSEPolicy, F_OK) == 0);
Bowgo Tsai1dacd422019-03-04 17:53:34 +0800322 if (use_userdebug_policy) {
323 LOG(WARNING) << "Using userdebug system sepolicy";
324 }
325
Tom Cherryc3170092017-08-10 12:22:44 -0700326 // Load precompiled policy from vendor image, if a matching policy is found there. The policy
327 // must match the platform policy on the system image.
328 std::string precompiled_sepolicy_file;
Bowgo Tsai1dacd422019-03-04 17:53:34 +0800329 // use_userdebug_policy requires compiling sepolicy with userdebug_plat_sepolicy.cil.
330 // Thus it cannot use the precompiled policy from vendor image.
331 if (!use_userdebug_policy && FindPrecompiledSplitPolicy(&precompiled_sepolicy_file)) {
Tom Cherryc3170092017-08-10 12:22:44 -0700332 unique_fd fd(open(precompiled_sepolicy_file.c_str(), O_RDONLY | O_CLOEXEC | O_BINARY));
333 if (fd != -1) {
David Anderson491e4da2020-12-08 00:21:20 -0800334 policy_file->fd = std::move(fd);
335 policy_file->path = std::move(precompiled_sepolicy_file);
Tom Cherryc3170092017-08-10 12:22:44 -0700336 return true;
337 }
338 }
339 // No suitable precompiled policy could be loaded
340
341 LOG(INFO) << "Compiling SELinux policy";
342
Tom Cherryc3170092017-08-10 12:22:44 -0700343 // We store the output of the compilation on /dev because this is the most convenient tmpfs
344 // storage mount available this early in the boot sequence.
345 char compiled_sepolicy[] = "/dev/sepolicy.XXXXXX";
346 unique_fd compiled_sepolicy_fd(mkostemp(compiled_sepolicy, O_CLOEXEC));
347 if (compiled_sepolicy_fd < 0) {
348 PLOG(ERROR) << "Failed to create temporary file " << compiled_sepolicy;
349 return false;
350 }
351
352 // Determine which mapping file to include
353 std::string vend_plat_vers;
354 if (!GetVendorMappingVersion(&vend_plat_vers)) {
355 return false;
356 }
Tri Vo503f1852019-01-16 11:57:19 -0800357 std::string plat_mapping_file("/system/etc/selinux/mapping/" + vend_plat_vers + ".cil");
kaichieheef4cd72017-08-31 22:07:19 +0800358
Jeff Vander Stoep0ac51cf2019-05-02 14:05:18 -0700359 std::string plat_compat_cil_file("/system/etc/selinux/mapping/" + vend_plat_vers +
360 ".compat.cil");
361 if (access(plat_compat_cil_file.c_str(), F_OK) == -1) {
362 plat_compat_cil_file.clear();
363 }
364
Bowgo Tsaif016f252019-08-28 17:56:51 +0800365 std::string system_ext_policy_cil_file("/system_ext/etc/selinux/system_ext_sepolicy.cil");
366 if (access(system_ext_policy_cil_file.c_str(), F_OK) == -1) {
367 system_ext_policy_cil_file.clear();
368 }
369
370 std::string system_ext_mapping_file("/system_ext/etc/selinux/mapping/" + vend_plat_vers +
371 ".cil");
372 if (access(system_ext_mapping_file.c_str(), F_OK) == -1) {
373 system_ext_mapping_file.clear();
374 }
375
Tri Vod3518cf2018-12-14 14:25:08 -0800376 std::string product_policy_cil_file("/product/etc/selinux/product_sepolicy.cil");
377 if (access(product_policy_cil_file.c_str(), F_OK) == -1) {
378 product_policy_cil_file.clear();
379 }
380
Tri Vo503f1852019-01-16 11:57:19 -0800381 std::string product_mapping_file("/product/etc/selinux/mapping/" + vend_plat_vers + ".cil");
382 if (access(product_mapping_file.c_str(), F_OK) == -1) {
383 product_mapping_file.clear();
384 }
385
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800386 // vendor_sepolicy.cil and plat_pub_versioned.cil are the new design to replace
kaichieheef4cd72017-08-31 22:07:19 +0800387 // nonplat_sepolicy.cil.
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800388 std::string plat_pub_versioned_cil_file("/vendor/etc/selinux/plat_pub_versioned.cil");
kaichieheef4cd72017-08-31 22:07:19 +0800389 std::string vendor_policy_cil_file("/vendor/etc/selinux/vendor_sepolicy.cil");
390
391 if (access(vendor_policy_cil_file.c_str(), F_OK) == -1) {
392 // For backward compatibility.
393 // TODO: remove this after no device is using nonplat_sepolicy.cil.
394 vendor_policy_cil_file = "/vendor/etc/selinux/nonplat_sepolicy.cil";
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800395 plat_pub_versioned_cil_file.clear();
396 } else if (access(plat_pub_versioned_cil_file.c_str(), F_OK) == -1) {
397 LOG(ERROR) << "Missing " << plat_pub_versioned_cil_file;
kaichieheef4cd72017-08-31 22:07:19 +0800398 return false;
399 }
400
401 // odm_sepolicy.cil is default but optional.
402 std::string odm_policy_cil_file("/odm/etc/selinux/odm_sepolicy.cil");
403 if (access(odm_policy_cil_file.c_str(), F_OK) == -1) {
404 odm_policy_cil_file.clear();
405 }
Jeff Vander Stoep724eda52019-02-15 12:13:38 -0800406 const std::string version_as_string = std::to_string(SEPOLICY_VERSION);
Andreas Huberc41b8382017-08-18 14:43:52 -0700407
Tom Cherryc3170092017-08-10 12:22:44 -0700408 // clang-format off
kaichieheef4cd72017-08-31 22:07:19 +0800409 std::vector<const char*> compile_args {
Tom Cherryc3170092017-08-10 12:22:44 -0700410 "/system/bin/secilc",
Bowgo Tsai30afda72019-04-11 23:57:24 +0800411 use_userdebug_policy ? kDebugRamdiskSEPolicy: plat_policy_cil_file,
Jeff Vander Stoep5e9ba3c2017-10-06 17:03:45 -0700412 "-m", "-M", "true", "-G", "-N",
Andreas Huberc41b8382017-08-18 14:43:52 -0700413 "-c", version_as_string.c_str(),
Tri Vo503f1852019-01-16 11:57:19 -0800414 plat_mapping_file.c_str(),
Tom Cherryc3170092017-08-10 12:22:44 -0700415 "-o", compiled_sepolicy,
416 // We don't care about file_contexts output by the compiler
417 "-f", "/sys/fs/selinux/null", // /dev/null is not yet available
kaichieheef4cd72017-08-31 22:07:19 +0800418 };
Tom Cherryc3170092017-08-10 12:22:44 -0700419 // clang-format on
420
Jeff Vander Stoep0ac51cf2019-05-02 14:05:18 -0700421 if (!plat_compat_cil_file.empty()) {
422 compile_args.push_back(plat_compat_cil_file.c_str());
423 }
Bowgo Tsaif016f252019-08-28 17:56:51 +0800424 if (!system_ext_policy_cil_file.empty()) {
425 compile_args.push_back(system_ext_policy_cil_file.c_str());
426 }
427 if (!system_ext_mapping_file.empty()) {
428 compile_args.push_back(system_ext_mapping_file.c_str());
429 }
Tri Vod3518cf2018-12-14 14:25:08 -0800430 if (!product_policy_cil_file.empty()) {
431 compile_args.push_back(product_policy_cil_file.c_str());
432 }
Tri Vo503f1852019-01-16 11:57:19 -0800433 if (!product_mapping_file.empty()) {
434 compile_args.push_back(product_mapping_file.c_str());
435 }
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800436 if (!plat_pub_versioned_cil_file.empty()) {
437 compile_args.push_back(plat_pub_versioned_cil_file.c_str());
kaichieheef4cd72017-08-31 22:07:19 +0800438 }
439 if (!vendor_policy_cil_file.empty()) {
440 compile_args.push_back(vendor_policy_cil_file.c_str());
441 }
442 if (!odm_policy_cil_file.empty()) {
443 compile_args.push_back(odm_policy_cil_file.c_str());
444 }
445 compile_args.push_back(nullptr);
446
447 if (!ForkExecveAndWaitForCompletion(compile_args[0], (char**)compile_args.data())) {
Tom Cherryc3170092017-08-10 12:22:44 -0700448 unlink(compiled_sepolicy);
449 return false;
450 }
451 unlink(compiled_sepolicy);
452
David Anderson491e4da2020-12-08 00:21:20 -0800453 policy_file->fd = std::move(compiled_sepolicy_fd);
454 policy_file->path = compiled_sepolicy;
Tom Cherryc3170092017-08-10 12:22:44 -0700455 return true;
456}
457
David Anderson491e4da2020-12-08 00:21:20 -0800458bool OpenMonolithicPolicy(PolicyFile* policy_file) {
459 static constexpr char kSepolicyFile[] = "/sepolicy";
460
461 LOG(VERBOSE) << "Opening SELinux policy from monolithic file";
462 policy_file->fd.reset(open(kSepolicyFile, O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
463 if (policy_file->fd < 0) {
464 PLOG(ERROR) << "Failed to open monolithic SELinux policy";
Tom Cherryc3170092017-08-10 12:22:44 -0700465 return false;
466 }
David Anderson491e4da2020-12-08 00:21:20 -0800467 policy_file->path = kSepolicyFile;
Tom Cherryc3170092017-08-10 12:22:44 -0700468 return true;
469}
470
David Anderson491e4da2020-12-08 00:21:20 -0800471void ReadPolicy(std::string* policy) {
472 PolicyFile policy_file;
Tom Cherryc3170092017-08-10 12:22:44 -0700473
David Anderson491e4da2020-12-08 00:21:20 -0800474 bool ok = IsSplitPolicyDevice() ? OpenSplitPolicy(&policy_file)
475 : OpenMonolithicPolicy(&policy_file);
476 if (!ok) {
477 LOG(FATAL) << "Unable to open SELinux policy";
Tom Cherryc3170092017-08-10 12:22:44 -0700478 }
479
David Anderson491e4da2020-12-08 00:21:20 -0800480 if (!android::base::ReadFdToString(policy_file.fd, policy)) {
481 PLOG(FATAL) << "Failed to read policy file: " << policy_file.path;
482 }
483}
484
485void SelinuxSetEnforcement() {
Tom Cherryc3170092017-08-10 12:22:44 -0700486 bool kernel_enforcing = (security_getenforce() == 1);
487 bool is_enforcing = IsEnforcing();
488 if (kernel_enforcing != is_enforcing) {
489 if (security_setenforce(is_enforcing)) {
Paul Lawrenceb2c2d692019-08-30 11:11:44 -0700490 PLOG(FATAL) << "security_setenforce(" << (is_enforcing ? "true" : "false")
491 << ") failed";
Tom Cherryc3170092017-08-10 12:22:44 -0700492 }
493 }
494
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900495 if (auto result = WriteFile("/sys/fs/selinux/checkreqprot", "0"); !result.ok()) {
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700496 LOG(FATAL) << "Unable to write to /sys/fs/selinux/checkreqprot: " << result.error();
Tom Cherryc3170092017-08-10 12:22:44 -0700497 }
Tom Cherryc3170092017-08-10 12:22:44 -0700498}
499
Tom Cherry8180b482019-08-26 13:57:51 -0700500constexpr size_t kKlogMessageSize = 1024;
501
502void SelinuxAvcLog(char* buf, size_t buf_len) {
503 CHECK_GT(buf_len, 0u);
504
505 size_t str_len = strnlen(buf, buf_len);
506 // trim newline at end of string
507 if (buf[str_len - 1] == '\n') {
508 buf[str_len - 1] = '\0';
509 }
510
511 struct NetlinkMessage {
512 nlmsghdr hdr;
513 char buf[kKlogMessageSize];
514 } request = {};
515
516 request.hdr.nlmsg_flags = NLM_F_REQUEST;
517 request.hdr.nlmsg_type = AUDIT_USER_AVC;
518 request.hdr.nlmsg_len = sizeof(request);
519 strlcpy(request.buf, buf, sizeof(request.buf));
520
521 auto fd = unique_fd{socket(PF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_AUDIT)};
522 if (!fd.ok()) {
523 return;
524 }
525
526 TEMP_FAILURE_RETRY(send(fd, &request, sizeof(request), 0));
527}
528
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800529} // namespace
530
Tom Cherryc3170092017-08-10 12:22:44 -0700531void SelinuxRestoreContext() {
532 LOG(INFO) << "Running restorecon...";
533 selinux_android_restorecon("/dev", 0);
534 selinux_android_restorecon("/dev/kmsg", 0);
535 if constexpr (WORLD_WRITABLE_KMSG) {
536 selinux_android_restorecon("/dev/kmsg_debug", 0);
537 }
Tom Cherry81ae0752018-07-30 16:23:49 -0700538 selinux_android_restorecon("/dev/null", 0);
539 selinux_android_restorecon("/dev/ptmx", 0);
Tom Cherryc3170092017-08-10 12:22:44 -0700540 selinux_android_restorecon("/dev/socket", 0);
541 selinux_android_restorecon("/dev/random", 0);
542 selinux_android_restorecon("/dev/urandom", 0);
543 selinux_android_restorecon("/dev/__properties__", 0);
544
Tom Cherryc3170092017-08-10 12:22:44 -0700545 selinux_android_restorecon("/dev/block", SELINUX_ANDROID_RESTORECON_RECURSE);
David Anderson1ff75812020-11-13 00:31:47 -0800546 selinux_android_restorecon("/dev/dm-user", SELINUX_ANDROID_RESTORECON_RECURSE);
Tom Cherryc3170092017-08-10 12:22:44 -0700547 selinux_android_restorecon("/dev/device-mapper", 0);
Jiyong Park4ba548d2019-02-22 16:04:35 +0900548
549 selinux_android_restorecon("/apex", 0);
Kiyoung Kim99df54b2019-11-22 16:14:10 +0900550
551 selinux_android_restorecon("/linkerconfig", 0);
Bowgo Tsai196cc582020-01-20 18:03:58 +0800552
David Andersonc991f342020-02-21 17:11:07 -0800553 // adb remount, snapshot-based updates, and DSUs all create files during
554 // first-stage init.
Yifan Hongd91998f2020-02-20 17:54:57 -0800555 selinux_android_restorecon(SnapshotManager::GetGlobalRollbackIndicatorPath().c_str(), 0);
David Anderson4bb500f2020-03-06 18:14:19 -0800556 selinux_android_restorecon("/metadata/gsi", SELINUX_ANDROID_RESTORECON_RECURSE |
557 SELINUX_ANDROID_RESTORECON_SKIP_SEHASH);
Tom Cherryc3170092017-08-10 12:22:44 -0700558}
559
Tom Cherry74069d12018-07-20 15:26:25 -0700560int SelinuxKlogCallback(int type, const char* fmt, ...) {
561 android::base::LogSeverity severity = android::base::ERROR;
562 if (type == SELINUX_WARNING) {
563 severity = android::base::WARNING;
564 } else if (type == SELINUX_INFO) {
565 severity = android::base::INFO;
566 }
Tom Cherry8180b482019-08-26 13:57:51 -0700567 char buf[kKlogMessageSize];
Tom Cherry74069d12018-07-20 15:26:25 -0700568 va_list ap;
569 va_start(ap, fmt);
Tom Cherry8180b482019-08-26 13:57:51 -0700570 int length_written = vsnprintf(buf, sizeof(buf), fmt, ap);
Tom Cherry74069d12018-07-20 15:26:25 -0700571 va_end(ap);
Tom Cherry8180b482019-08-26 13:57:51 -0700572 if (length_written <= 0) {
573 return 0;
574 }
575 if (type == SELINUX_AVC) {
576 SelinuxAvcLog(buf, sizeof(buf));
577 } else {
578 android::base::KernelLogger(android::base::MAIN, severity, "selinux", nullptr, 0, buf);
579 }
Tom Cherry74069d12018-07-20 15:26:25 -0700580 return 0;
581}
582
Tom Cherryc3170092017-08-10 12:22:44 -0700583void SelinuxSetupKernelLogging() {
584 selinux_callback cb;
Tom Cherry74069d12018-07-20 15:26:25 -0700585 cb.func_log = SelinuxKlogCallback;
Tom Cherryc3170092017-08-10 12:22:44 -0700586 selinux_set_callback(SELINUX_CB_LOG, cb);
587}
588
Tom Cherry40acb372018-08-01 13:41:12 -0700589int SelinuxGetVendorAndroidVersion() {
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700590 static int vendor_android_version = [] {
591 if (!IsSplitPolicyDevice()) {
592 // If this device does not split sepolicy files, it's not a Treble device and therefore,
593 // we assume it's always on the latest platform.
594 return __ANDROID_API_FUTURE__;
595 }
Logan Chien837b2a42018-05-03 14:33:52 +0800596
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700597 std::string version;
598 if (!GetVendorMappingVersion(&version)) {
599 LOG(FATAL) << "Could not read vendor SELinux version";
600 }
Logan Chien837b2a42018-05-03 14:33:52 +0800601
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700602 int major_version;
603 std::string major_version_str(version, 0, version.find('.'));
604 if (!ParseInt(major_version_str, &major_version)) {
605 PLOG(FATAL) << "Failed to parse the vendor sepolicy major version "
606 << major_version_str;
607 }
Logan Chien837b2a42018-05-03 14:33:52 +0800608
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700609 return major_version;
610 }();
611 return vendor_android_version;
Logan Chien837b2a42018-05-03 14:33:52 +0800612}
613
David Andersond0ce5302020-03-20 21:47:10 -0700614// This is for R system.img/system_ext.img to work on old vendor.img as system_ext.img
615// is introduced in R. We mount system_ext in second stage init because the first-stage
616// init in boot.img won't be updated in the system-only OTA scenario.
617void MountMissingSystemPartitions() {
618 android::fs_mgr::Fstab fstab;
619 if (!ReadDefaultFstab(&fstab)) {
620 LOG(ERROR) << "Could not read default fstab";
621 }
622
623 android::fs_mgr::Fstab mounts;
624 if (!ReadFstabFromFile("/proc/mounts", &mounts)) {
625 LOG(ERROR) << "Could not read /proc/mounts";
626 }
627
628 static const std::vector<std::string> kPartitionNames = {"system_ext", "product"};
629
630 android::fs_mgr::Fstab extra_fstab;
631 for (const auto& name : kPartitionNames) {
632 if (GetEntryForMountPoint(&mounts, "/"s + name)) {
633 // The partition is already mounted.
634 continue;
635 }
636
637 auto system_entry = GetEntryForMountPoint(&fstab, "/system");
638 if (!system_entry) {
639 LOG(ERROR) << "Could not find mount entry for /system";
640 break;
641 }
642 if (!system_entry->fs_mgr_flags.logical) {
643 LOG(INFO) << "Skipping mount of " << name << ", system is not dynamic.";
644 break;
645 }
646
647 auto entry = *system_entry;
648 auto partition_name = name + fs_mgr_get_slot_suffix();
649 auto replace_name = "system"s + fs_mgr_get_slot_suffix();
650
651 entry.mount_point = "/"s + name;
652 entry.blk_device =
653 android::base::StringReplace(entry.blk_device, replace_name, partition_name, false);
654 if (!fs_mgr_update_logical_partition(&entry)) {
655 LOG(ERROR) << "Could not update logical partition";
656 continue;
657 }
658
659 extra_fstab.emplace_back(std::move(entry));
660 }
661
662 SkipMountingPartitions(&extra_fstab);
663 if (extra_fstab.empty()) {
664 return;
665 }
666
667 BlockDevInitializer block_dev_init;
668 for (auto& entry : extra_fstab) {
669 if (access(entry.blk_device.c_str(), F_OK) != 0) {
670 auto block_dev = android::base::Basename(entry.blk_device);
671 if (!block_dev_init.InitDmDevice(block_dev)) {
672 LOG(ERROR) << "Failed to find device-mapper node: " << block_dev;
673 continue;
674 }
675 }
676 if (fs_mgr_do_mount_one(entry)) {
677 LOG(ERROR) << "Could not mount " << entry.mount_point;
678 }
679 }
680}
681
David Anderson491e4da2020-12-08 00:21:20 -0800682static void LoadSelinuxPolicy(std::string& policy) {
683 LOG(INFO) << "Loading SELinux policy";
684
685 set_selinuxmnt("/sys/fs/selinux");
686 if (security_load_policy(policy.data(), policy.size()) < 0) {
687 PLOG(FATAL) << "SELinux: Could not load policy";
688 }
689}
690
691// The SELinux setup process is carefully orchestrated around snapuserd. Policy
692// must be loaded off dynamic partitions, and during an OTA, those partitions
693// cannot be read without snapuserd. But, with kernel-privileged snapuserd
694// running, loading the policy will immediately trigger audits.
695//
696// We use a five-step process to address this:
697// (1) Read the policy into a string, with snapuserd running.
698// (2) Rewrite the snapshot device-mapper tables, to generate new dm-user
699// devices and to flush I/O.
700// (3) Kill snapuserd, which no longer has any dm-user devices to attach to.
701// (4) Load the sepolicy and issue critical restorecons in /dev, carefully
702// avoiding anything that would read from /system.
703// (5) Re-launch snapuserd and attach it to the dm-user devices from step (2).
704//
705// After this sequence, it is safe to enable enforcing mode and continue booting.
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800706int SetupSelinux(char** argv) {
Mark Salyzynbeb6abe2019-07-29 09:35:18 -0700707 SetStdioToDevNull(argv);
Tom Cherry59656fb2019-05-28 10:19:44 -0700708 InitKernelLogging(argv);
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800709
710 if (REBOOT_BOOTLOADER_ON_PANIC) {
711 InstallRebootSignalHandlers();
712 }
713
Mark Salyzyn10377df2019-03-27 08:10:41 -0700714 boot_clock::time_point start_time = boot_clock::now();
715
David Andersond0ce5302020-03-20 21:47:10 -0700716 MountMissingSystemPartitions();
717
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800718 SelinuxSetupKernelLogging();
David Anderson491e4da2020-12-08 00:21:20 -0800719
720 LOG(INFO) << "Opening SELinux policy";
721
722 // Read the policy before potentially killing snapuserd.
723 std::string policy;
724 ReadPolicy(&policy);
725
726 auto snapuserd_helper = SnapuserdSelinuxHelper::CreateIfNeeded();
727 if (snapuserd_helper) {
728 // Kill the old snapused to avoid audit messages. After this we cannot
729 // read from /system (or other dynamic partitions) until we call
730 // FinishTransition().
731 snapuserd_helper->StartTransition();
732 }
733
734 LoadSelinuxPolicy(policy);
735
736 if (snapuserd_helper) {
737 // Before enforcing, finish the pending snapuserd transition.
738 snapuserd_helper->FinishTransition();
739 snapuserd_helper = nullptr;
740 }
741
742 SelinuxSetEnforcement();
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800743
744 // We're in the kernel domain and want to transition to the init domain. File systems that
745 // store SELabels in their xattrs, such as ext4 do not need an explicit restorecon here,
746 // but other file systems do. In particular, this is needed for ramdisks such as the
747 // recovery image for A/B devices.
748 if (selinux_android_restorecon("/system/bin/init", 0) == -1) {
749 PLOG(FATAL) << "restorecon failed of /system/bin/init failed";
750 }
751
Mark Salyzyn44505ec2019-05-08 12:44:50 -0700752 setenv(kEnvSelinuxStartedAt, std::to_string(start_time.time_since_epoch().count()).c_str(), 1);
Mark Salyzyn10377df2019-03-27 08:10:41 -0700753
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800754 const char* path = "/system/bin/init";
755 const char* args[] = {path, "second_stage", nullptr};
756 execv(path, const_cast<char**>(args));
757
758 // execv() only returns if an error happened, in which case we
759 // panic and never return from this function.
760 PLOG(FATAL) << "execv(\"" << path << "\") failed";
761
762 return 1;
763}
764
Tom Cherryc3170092017-08-10 12:22:44 -0700765} // namespace init
766} // namespace android