blob: a9365323362f0d6ad1061afaa82df834f78fe9db [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
Jeffrey Vander Stoepbaeece62022-02-08 12:42:33 +000029// The split policy is for supporting treble devices and updateable apexes. It splits the SEPolicy
30// across files on /system/etc/selinux (the 'plat' portion of the policy), /vendor/etc/selinux
31// (the 'vendor' portion of the policy), /system_ext/etc/selinux, /product/etc/selinux,
32// /odm/etc/selinux, and /dev/selinux (the apex portion of policy). This is necessary to allow
33// images to be updated independently of the vendor image, while maintaining contributions from
34// multiple partitions in the SEPolicy. This is especially important for VTS testing, where the
35// SEPolicy on the Google System Image may not be identical to the system image shipped on a
36// vendor's device.
Tom Cherryc3170092017-08-10 12:22:44 -070037
38// The split SEPolicy is loaded as described below:
Tri Voc8137f92019-01-22 18:22:25 -080039// 1) There is a precompiled SEPolicy located at either /vendor/etc/selinux/precompiled_sepolicy or
40// /odm/etc/selinux/precompiled_sepolicy if odm parition is present. Stored along with this file
Jeffrey Vander Stoepbaeece62022-02-08 12:42:33 +000041// are the sha256 hashes of the parts of the SEPolicy on /system, /system_ext, /product, and apex
42// that were used to compile this precompiled policy. The system partition contains a similar
43// sha256 of the parts of the SEPolicy that it currently contains. Symmetrically, system_ext,
44// product, and apex contain sha256 hashes of their SEPolicy. Init loads this
Bowgo Tsaif016f252019-08-28 17:56:51 +080045// precompiled_sepolicy directly if and only if the hashes along with the precompiled SEPolicy on
Jeffrey Vander Stoepbaeece62022-02-08 12:42:33 +000046// /vendor or /odm match the hashes for system, system_ext, product, and apex SEPolicy,
47// respectively.
48// 2) If these hashes do not match, then either /system or /system_ext /product, or apex (or some of
49// them) have been updated out of sync with /vendor (or /odm if it is present) and the init needs
50// to compile the SEPolicy. /system contains the SEPolicy compiler, secilc, and it is used by
51// the OpenSplitPolicy() function below to compile the SEPolicy to a temp directory and load it.
Bowgo Tsaif016f252019-08-28 17:56:51 +080052// That function contains even more documentation with the specific implementation details of how
53// the SEPolicy is compiled if needed.
Tom Cherryc3170092017-08-10 12:22:44 -070054
55#include "selinux.h"
56
Tom Cherry40acb372018-08-01 13:41:12 -070057#include <android/api-level.h>
Tom Cherryc3170092017-08-10 12:22:44 -070058#include <fcntl.h>
Tom Cherry8180b482019-08-26 13:57:51 -070059#include <linux/audit.h>
60#include <linux/netlink.h>
Tom Cherryc3170092017-08-10 12:22:44 -070061#include <stdlib.h>
62#include <sys/wait.h>
63#include <unistd.h>
Jeffrey Vander Stoepbaeece62022-02-08 12:42:33 +000064#include <fstream>
Tom Cherryc3170092017-08-10 12:22:44 -070065
Jeffrey Vander Stoepbaeece62022-02-08 12:42:33 +000066#include <CertUtils.h>
Tom Cherryc3170092017-08-10 12:22:44 -070067#include <android-base/chrono_utils.h>
68#include <android-base/file.h>
69#include <android-base/logging.h>
Logan Chien837b2a42018-05-03 14:33:52 +080070#include <android-base/parseint.h>
Inseob Kimd99d9772021-03-11 17:58:26 +090071#include <android-base/result.h>
Jeffrey Vander Stoepbaeece62022-02-08 12:42:33 +000072#include <android-base/scopeguard.h>
David Andersond0ce5302020-03-20 21:47:10 -070073#include <android-base/strings.h>
Tom Cherryc3170092017-08-10 12:22:44 -070074#include <android-base/unique_fd.h>
Bowgo Tsai1dacd422019-03-04 17:53:34 +080075#include <fs_avb/fs_avb.h>
David Andersond0ce5302020-03-20 21:47:10 -070076#include <fs_mgr.h>
Jeffrey Vander Stoepbaeece62022-02-08 12:42:33 +000077#include <fsverity_init.h>
Bowgo Tsai196cc582020-01-20 18:03:58 +080078#include <libgsi/libgsi.h>
Yifan Hongd91998f2020-02-20 17:54:57 -080079#include <libsnapshot/snapshot.h>
Jeffrey Vander Stoepbaeece62022-02-08 12:42:33 +000080#include <mini_keyctl_utils.h>
Tom Cherryc3170092017-08-10 12:22:44 -070081#include <selinux/android.h>
Jeffrey Vander Stoepbaeece62022-02-08 12:42:33 +000082#include <ziparchive/zip_archive.h>
Tom Cherryc3170092017-08-10 12:22:44 -070083
David Andersond0ce5302020-03-20 21:47:10 -070084#include "block_dev_initializer.h"
Bowgo Tsai30afda72019-04-11 23:57:24 +080085#include "debug_ramdisk.h"
Tom Cherry7bfea3d2018-11-06 14:12:05 -080086#include "reboot_utils.h"
David Anderson491e4da2020-12-08 00:21:20 -080087#include "snapuserd_transition.h"
Tom Cherryc3170092017-08-10 12:22:44 -070088#include "util.h"
89
Bowgo Tsai1dacd422019-03-04 17:53:34 +080090using namespace std::string_literals;
91
Logan Chien837b2a42018-05-03 14:33:52 +080092using android::base::ParseInt;
Tom Cherryc3170092017-08-10 12:22:44 -070093using android::base::Timer;
94using android::base::unique_fd;
Bowgo Tsai1dacd422019-03-04 17:53:34 +080095using android::fs_mgr::AvbHandle;
Yifan Hongd91998f2020-02-20 17:54:57 -080096using android::snapshot::SnapshotManager;
Tom Cherryc3170092017-08-10 12:22:44 -070097
98namespace android {
99namespace init {
100
Tom Cherryc3170092017-08-10 12:22:44 -0700101namespace {
102
103enum EnforcingStatus { SELINUX_PERMISSIVE, SELINUX_ENFORCING };
104
Alistair Delva63594a42021-03-09 11:04:23 -0800105EnforcingStatus StatusFromProperty() {
Tom Cherryc3170092017-08-10 12:22:44 -0700106 EnforcingStatus status = SELINUX_ENFORCING;
107
Tom Cherryc88d8f92019-08-19 15:21:25 -0700108 ImportKernelCmdline([&](const std::string& key, const std::string& value) {
109 if (key == "androidboot.selinux" && value == "permissive") {
110 status = SELINUX_PERMISSIVE;
111 }
112 });
Tom Cherryc3170092017-08-10 12:22:44 -0700113
Alistair Delva63594a42021-03-09 11:04:23 -0800114 if (status == SELINUX_ENFORCING) {
115 ImportBootconfig([&](const std::string& key, const std::string& value) {
116 if (key == "androidboot.selinux" && value == "permissive") {
117 status = SELINUX_PERMISSIVE;
118 }
119 });
120 }
121
Tom Cherryc3170092017-08-10 12:22:44 -0700122 return status;
123}
124
125bool IsEnforcing() {
126 if (ALLOW_PERMISSIVE_SELINUX) {
Alistair Delva63594a42021-03-09 11:04:23 -0800127 return StatusFromProperty() == SELINUX_ENFORCING;
Tom Cherryc3170092017-08-10 12:22:44 -0700128 }
129 return true;
130}
131
132// Forks, executes the provided program in the child, and waits for the completion in the parent.
133// Child's stderr is captured and logged using LOG(ERROR).
134bool ForkExecveAndWaitForCompletion(const char* filename, char* const argv[]) {
135 // Create a pipe used for redirecting child process's output.
136 // * pipe_fds[0] is the FD the parent will use for reading.
137 // * pipe_fds[1] is the FD the child will use for writing.
138 int pipe_fds[2];
139 if (pipe(pipe_fds) == -1) {
140 PLOG(ERROR) << "Failed to create pipe";
141 return false;
142 }
143
144 pid_t child_pid = fork();
145 if (child_pid == -1) {
146 PLOG(ERROR) << "Failed to fork for " << filename;
147 return false;
148 }
149
150 if (child_pid == 0) {
151 // fork succeeded -- this is executing in the child process
152
153 // Close the pipe FD not used by this process
Nick Kralevich3d118e72017-10-24 10:45:48 -0700154 close(pipe_fds[0]);
Tom Cherryc3170092017-08-10 12:22:44 -0700155
156 // Redirect stderr to the pipe FD provided by the parent
157 if (TEMP_FAILURE_RETRY(dup2(pipe_fds[1], STDERR_FILENO)) == -1) {
158 PLOG(ERROR) << "Failed to redirect stderr of " << filename;
159 _exit(127);
160 return false;
161 }
Nick Kralevich3d118e72017-10-24 10:45:48 -0700162 close(pipe_fds[1]);
Tom Cherryc3170092017-08-10 12:22:44 -0700163
Tom Cherry6de21f12017-08-22 15:41:03 -0700164 if (execv(filename, argv) == -1) {
Tom Cherryc3170092017-08-10 12:22:44 -0700165 PLOG(ERROR) << "Failed to execve " << filename;
166 return false;
167 }
168 // Unreachable because execve will have succeeded and replaced this code
169 // with child process's code.
170 _exit(127);
171 return false;
172 } else {
173 // fork succeeded -- this is executing in the original/parent process
174
175 // Close the pipe FD not used by this process
Nick Kralevich3d118e72017-10-24 10:45:48 -0700176 close(pipe_fds[1]);
Tom Cherryc3170092017-08-10 12:22:44 -0700177
178 // Log the redirected output of the child process.
179 // It's unfortunate that there's no standard way to obtain an istream for a file descriptor.
180 // As a result, we're buffering all output and logging it in one go at the end of the
181 // invocation, instead of logging it as it comes in.
182 const int child_out_fd = pipe_fds[0];
183 std::string child_output;
184 if (!android::base::ReadFdToString(child_out_fd, &child_output)) {
185 PLOG(ERROR) << "Failed to capture full output of " << filename;
186 }
Nick Kralevich3d118e72017-10-24 10:45:48 -0700187 close(child_out_fd);
Tom Cherryc3170092017-08-10 12:22:44 -0700188 if (!child_output.empty()) {
189 // Log captured output, line by line, because LOG expects to be invoked for each line
190 std::istringstream in(child_output);
191 std::string line;
192 while (std::getline(in, line)) {
193 LOG(ERROR) << filename << ": " << line;
194 }
195 }
196
197 // Wait for child to terminate
198 int status;
199 if (TEMP_FAILURE_RETRY(waitpid(child_pid, &status, 0)) != child_pid) {
200 PLOG(ERROR) << "Failed to wait for " << filename;
201 return false;
202 }
203
204 if (WIFEXITED(status)) {
205 int status_code = WEXITSTATUS(status);
206 if (status_code == 0) {
207 return true;
208 } else {
209 LOG(ERROR) << filename << " exited with status " << status_code;
210 }
211 } else if (WIFSIGNALED(status)) {
212 LOG(ERROR) << filename << " killed by signal " << WTERMSIG(status);
213 } else if (WIFSTOPPED(status)) {
214 LOG(ERROR) << filename << " stopped by signal " << WSTOPSIG(status);
215 } else {
216 LOG(ERROR) << "waitpid for " << filename << " returned unexpected status: " << status;
217 }
218
219 return false;
220 }
221}
222
223bool ReadFirstLine(const char* file, std::string* line) {
224 line->clear();
225
226 std::string contents;
227 if (!android::base::ReadFileToString(file, &contents, true /* follow symlinks */)) {
228 return false;
229 }
230 std::istringstream in(contents);
231 std::getline(in, *line);
232 return true;
233}
234
Inseob Kimd99d9772021-03-11 17:58:26 +0900235Result<std::string> FindPrecompiledSplitPolicy() {
236 std::string precompiled_sepolicy;
kaichieheef4cd72017-08-31 22:07:19 +0800237 // If there is an odm partition, precompiled_sepolicy will be in
238 // odm/etc/selinux. Otherwise it will be in vendor/etc/selinux.
239 static constexpr const char vendor_precompiled_sepolicy[] =
Sandro1120f7f2022-09-05 15:56:38 +0000240 "/vendor/etc/selinux/precompiled_sepolicy";
kaichieheef4cd72017-08-31 22:07:19 +0800241 static constexpr const char odm_precompiled_sepolicy[] =
Sandro1120f7f2022-09-05 15:56:38 +0000242 "/odm/etc/selinux/precompiled_sepolicy";
kaichieheef4cd72017-08-31 22:07:19 +0800243 if (access(odm_precompiled_sepolicy, R_OK) == 0) {
Inseob Kimd99d9772021-03-11 17:58:26 +0900244 precompiled_sepolicy = odm_precompiled_sepolicy;
kaichieheef4cd72017-08-31 22:07:19 +0800245 } else if (access(vendor_precompiled_sepolicy, R_OK) == 0) {
Inseob Kimd99d9772021-03-11 17:58:26 +0900246 precompiled_sepolicy = vendor_precompiled_sepolicy;
kaichieheef4cd72017-08-31 22:07:19 +0800247 } else {
Inseob Kimd99d9772021-03-11 17:58:26 +0900248 return ErrnoError() << "No precompiled sepolicy at " << vendor_precompiled_sepolicy;
Tom Cherryc3170092017-08-10 12:22:44 -0700249 }
kaichieheef4cd72017-08-31 22:07:19 +0800250
Inseob Kimd99d9772021-03-11 17:58:26 +0900251 // Use precompiled sepolicy only when all corresponding hashes are equal.
Inseob Kimd99d9772021-03-11 17:58:26 +0900252 std::vector<std::pair<std::string, std::string>> sepolicy_hashes{
253 {"/system/etc/selinux/plat_sepolicy_and_mapping.sha256",
254 precompiled_sepolicy + ".plat_sepolicy_and_mapping.sha256"},
Inseob Kim28fdb672021-04-29 19:48:27 +0900255 {"/system_ext/etc/selinux/system_ext_sepolicy_and_mapping.sha256",
256 precompiled_sepolicy + ".system_ext_sepolicy_and_mapping.sha256"},
257 {"/product/etc/selinux/product_sepolicy_and_mapping.sha256",
258 precompiled_sepolicy + ".product_sepolicy_and_mapping.sha256"},
Jeffrey Vander Stoepbaeece62022-02-08 12:42:33 +0000259 {"/dev/selinux/apex_sepolicy.sha256", precompiled_sepolicy + ".apex_sepolicy.sha256"},
Inseob Kimd99d9772021-03-11 17:58:26 +0900260 };
261
Inseob Kimd99d9772021-03-11 17:58:26 +0900262 for (const auto& [actual_id_path, precompiled_id_path] : sepolicy_hashes) {
Inseob Kim28fdb672021-04-29 19:48:27 +0900263 // Both of them should exist or both of them shouldn't exist.
264 if (access(actual_id_path.c_str(), R_OK) != 0) {
265 if (access(precompiled_id_path.c_str(), R_OK) == 0) {
266 return Error() << precompiled_id_path << " exists but " << actual_id_path
267 << " doesn't";
268 }
269 continue;
270 }
271
Inseob Kimd99d9772021-03-11 17:58:26 +0900272 std::string actual_id;
273 if (!ReadFirstLine(actual_id_path.c_str(), &actual_id)) {
274 return ErrnoError() << "Failed to read " << actual_id_path;
275 }
276
277 std::string precompiled_id;
278 if (!ReadFirstLine(precompiled_id_path.c_str(), &precompiled_id)) {
279 return ErrnoError() << "Failed to read " << precompiled_id_path;
280 }
281
282 if (actual_id.empty() || actual_id != precompiled_id) {
283 return Error() << actual_id_path << " and " << precompiled_id_path << " differ";
284 }
Tri Voc8137f92019-01-22 18:22:25 -0800285 }
Inseob Kimd99d9772021-03-11 17:58:26 +0900286
287 return precompiled_sepolicy;
Tom Cherryc3170092017-08-10 12:22:44 -0700288}
289
290bool GetVendorMappingVersion(std::string* plat_vers) {
291 if (!ReadFirstLine("/vendor/etc/selinux/plat_sepolicy_vers.txt", plat_vers)) {
292 PLOG(ERROR) << "Failed to read /vendor/etc/selinux/plat_sepolicy_vers.txt";
293 return false;
294 }
295 if (plat_vers->empty()) {
296 LOG(ERROR) << "No version present in plat_sepolicy_vers.txt";
297 return false;
298 }
299 return true;
300}
301
302constexpr const char plat_policy_cil_file[] = "/system/etc/selinux/plat_sepolicy.cil";
Nikita Ioffefa33f852023-06-14 20:29:37 +0000303constexpr const char kMicrodroidPrecompiledSepolicy[] =
304 "/system/etc/selinux/microdroid_precompiled_sepolicy";
Tom Cherryc3170092017-08-10 12:22:44 -0700305
306bool IsSplitPolicyDevice() {
307 return access(plat_policy_cil_file, R_OK) != -1;
308}
309
Yi-Yo Chiangbb77c542021-09-23 14:14:16 +0000310std::optional<const char*> GetUserdebugPlatformPolicyFile() {
311 // See if we need to load userdebug_plat_sepolicy.cil instead of plat_sepolicy.cil.
312 const char* force_debuggable_env = getenv("INIT_FORCE_DEBUGGABLE");
313 if (force_debuggable_env && "true"s == force_debuggable_env && AvbHandle::IsDeviceUnlocked()) {
314 const std::vector<const char*> debug_policy_candidates = {
315#if INSTALL_DEBUG_POLICY_TO_SYSTEM_EXT == 1
316 "/system_ext/etc/selinux/userdebug_plat_sepolicy.cil",
317#endif
318 kDebugRamdiskSEPolicy,
319 };
320 for (const char* debug_policy : debug_policy_candidates) {
321 if (access(debug_policy, F_OK) == 0) {
322 return debug_policy;
323 }
324 }
325 }
326 return std::nullopt;
327}
328
David Anderson491e4da2020-12-08 00:21:20 -0800329struct PolicyFile {
330 unique_fd fd;
331 std::string path;
332};
333
334bool OpenSplitPolicy(PolicyFile* policy_file) {
Jeff Vander Stoep5effda42021-11-05 09:03:11 +0100335 // IMPLEMENTATION NOTE: Split policy consists of three or more CIL files:
Tom Cherryc3170092017-08-10 12:22:44 -0700336 // * platform -- policy needed due to logic contained in the system image,
Jeff Vander Stoep5effda42021-11-05 09:03:11 +0100337 // * vendor -- policy needed due to logic contained in the vendor image,
Tom Cherryc3170092017-08-10 12:22:44 -0700338 // * mapping -- mapping policy which helps preserve forward-compatibility of non-platform policy
339 // with newer versions of platform policy.
Jeffrey Vander Stoepbaeece62022-02-08 12:42:33 +0000340 // * (optional) policy needed due to logic on product, system_ext, odm, or apex.
Tom Cherryc3170092017-08-10 12:22:44 -0700341 // secilc is invoked to compile the above three policy files into a single monolithic policy
342 // file. This file is then loaded into the kernel.
343
Yi-Yo Chiangbb77c542021-09-23 14:14:16 +0000344 const auto userdebug_plat_sepolicy = GetUserdebugPlatformPolicyFile();
345 const bool use_userdebug_policy = userdebug_plat_sepolicy.has_value();
Bowgo Tsai1dacd422019-03-04 17:53:34 +0800346 if (use_userdebug_policy) {
Yi-Yo Chiangbb77c542021-09-23 14:14:16 +0000347 LOG(INFO) << "Using userdebug system sepolicy " << *userdebug_plat_sepolicy;
Bowgo Tsai1dacd422019-03-04 17:53:34 +0800348 }
349
Tom Cherryc3170092017-08-10 12:22:44 -0700350 // Load precompiled policy from vendor image, if a matching policy is found there. The policy
351 // must match the platform policy on the system image.
Bowgo Tsai1dacd422019-03-04 17:53:34 +0800352 // use_userdebug_policy requires compiling sepolicy with userdebug_plat_sepolicy.cil.
353 // Thus it cannot use the precompiled policy from vendor image.
Inseob Kimd99d9772021-03-11 17:58:26 +0900354 if (!use_userdebug_policy) {
355 if (auto res = FindPrecompiledSplitPolicy(); res.ok()) {
356 unique_fd fd(open(res->c_str(), O_RDONLY | O_CLOEXEC | O_BINARY));
357 if (fd != -1) {
358 policy_file->fd = std::move(fd);
359 policy_file->path = std::move(*res);
360 return true;
361 }
362 } else {
363 LOG(INFO) << res.error();
Tom Cherryc3170092017-08-10 12:22:44 -0700364 }
365 }
366 // No suitable precompiled policy could be loaded
367
368 LOG(INFO) << "Compiling SELinux policy";
369
Tom Cherryc3170092017-08-10 12:22:44 -0700370 // We store the output of the compilation on /dev because this is the most convenient tmpfs
371 // storage mount available this early in the boot sequence.
372 char compiled_sepolicy[] = "/dev/sepolicy.XXXXXX";
373 unique_fd compiled_sepolicy_fd(mkostemp(compiled_sepolicy, O_CLOEXEC));
374 if (compiled_sepolicy_fd < 0) {
375 PLOG(ERROR) << "Failed to create temporary file " << compiled_sepolicy;
376 return false;
377 }
378
379 // Determine which mapping file to include
380 std::string vend_plat_vers;
381 if (!GetVendorMappingVersion(&vend_plat_vers)) {
382 return false;
383 }
Tri Vo503f1852019-01-16 11:57:19 -0800384 std::string plat_mapping_file("/system/etc/selinux/mapping/" + vend_plat_vers + ".cil");
kaichieheef4cd72017-08-31 22:07:19 +0800385
Jeff Vander Stoep0ac51cf2019-05-02 14:05:18 -0700386 std::string plat_compat_cil_file("/system/etc/selinux/mapping/" + vend_plat_vers +
387 ".compat.cil");
388 if (access(plat_compat_cil_file.c_str(), F_OK) == -1) {
389 plat_compat_cil_file.clear();
390 }
391
Bowgo Tsaif016f252019-08-28 17:56:51 +0800392 std::string system_ext_policy_cil_file("/system_ext/etc/selinux/system_ext_sepolicy.cil");
393 if (access(system_ext_policy_cil_file.c_str(), F_OK) == -1) {
394 system_ext_policy_cil_file.clear();
395 }
396
397 std::string system_ext_mapping_file("/system_ext/etc/selinux/mapping/" + vend_plat_vers +
398 ".cil");
399 if (access(system_ext_mapping_file.c_str(), F_OK) == -1) {
400 system_ext_mapping_file.clear();
401 }
402
Yi-Yo Chiang731d2472021-03-23 22:11:13 +0800403 std::string system_ext_compat_cil_file("/system_ext/etc/selinux/mapping/" + vend_plat_vers +
404 ".compat.cil");
405 if (access(system_ext_compat_cil_file.c_str(), F_OK) == -1) {
406 system_ext_compat_cil_file.clear();
407 }
408
Tri Vod3518cf2018-12-14 14:25:08 -0800409 std::string product_policy_cil_file("/product/etc/selinux/product_sepolicy.cil");
410 if (access(product_policy_cil_file.c_str(), F_OK) == -1) {
411 product_policy_cil_file.clear();
412 }
413
Tri Vo503f1852019-01-16 11:57:19 -0800414 std::string product_mapping_file("/product/etc/selinux/mapping/" + vend_plat_vers + ".cil");
415 if (access(product_mapping_file.c_str(), F_OK) == -1) {
416 product_mapping_file.clear();
417 }
418
kaichieheef4cd72017-08-31 22:07:19 +0800419 std::string vendor_policy_cil_file("/vendor/etc/selinux/vendor_sepolicy.cil");
kaichieheef4cd72017-08-31 22:07:19 +0800420 if (access(vendor_policy_cil_file.c_str(), F_OK) == -1) {
Jeff Vander Stoep5effda42021-11-05 09:03:11 +0100421 LOG(ERROR) << "Missing " << vendor_policy_cil_file;
422 return false;
423 }
424
425 std::string plat_pub_versioned_cil_file("/vendor/etc/selinux/plat_pub_versioned.cil");
426 if (access(plat_pub_versioned_cil_file.c_str(), F_OK) == -1) {
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800427 LOG(ERROR) << "Missing " << plat_pub_versioned_cil_file;
kaichieheef4cd72017-08-31 22:07:19 +0800428 return false;
429 }
430
431 // odm_sepolicy.cil is default but optional.
432 std::string odm_policy_cil_file("/odm/etc/selinux/odm_sepolicy.cil");
433 if (access(odm_policy_cil_file.c_str(), F_OK) == -1) {
434 odm_policy_cil_file.clear();
435 }
Jeffrey Vander Stoepbaeece62022-02-08 12:42:33 +0000436
437 // apex_sepolicy.cil is default but optional.
438 std::string apex_policy_cil_file("/dev/selinux/apex_sepolicy.cil");
439 if (access(apex_policy_cil_file.c_str(), F_OK) == -1) {
440 apex_policy_cil_file.clear();
441 }
Jeff Vander Stoep724eda52019-02-15 12:13:38 -0800442 const std::string version_as_string = std::to_string(SEPOLICY_VERSION);
Andreas Huberc41b8382017-08-18 14:43:52 -0700443
Tom Cherryc3170092017-08-10 12:22:44 -0700444 // clang-format off
kaichieheef4cd72017-08-31 22:07:19 +0800445 std::vector<const char*> compile_args {
Tom Cherryc3170092017-08-10 12:22:44 -0700446 "/system/bin/secilc",
Yi-Yo Chiangbb77c542021-09-23 14:14:16 +0000447 use_userdebug_policy ? *userdebug_plat_sepolicy : plat_policy_cil_file,
Jeff Vander Stoep5e9ba3c2017-10-06 17:03:45 -0700448 "-m", "-M", "true", "-G", "-N",
Andreas Huberc41b8382017-08-18 14:43:52 -0700449 "-c", version_as_string.c_str(),
Tri Vo503f1852019-01-16 11:57:19 -0800450 plat_mapping_file.c_str(),
Tom Cherryc3170092017-08-10 12:22:44 -0700451 "-o", compiled_sepolicy,
452 // We don't care about file_contexts output by the compiler
453 "-f", "/sys/fs/selinux/null", // /dev/null is not yet available
kaichieheef4cd72017-08-31 22:07:19 +0800454 };
Tom Cherryc3170092017-08-10 12:22:44 -0700455 // clang-format on
456
Jeff Vander Stoep0ac51cf2019-05-02 14:05:18 -0700457 if (!plat_compat_cil_file.empty()) {
458 compile_args.push_back(plat_compat_cil_file.c_str());
459 }
Bowgo Tsaif016f252019-08-28 17:56:51 +0800460 if (!system_ext_policy_cil_file.empty()) {
461 compile_args.push_back(system_ext_policy_cil_file.c_str());
462 }
463 if (!system_ext_mapping_file.empty()) {
464 compile_args.push_back(system_ext_mapping_file.c_str());
465 }
Yi-Yo Chiang731d2472021-03-23 22:11:13 +0800466 if (!system_ext_compat_cil_file.empty()) {
467 compile_args.push_back(system_ext_compat_cil_file.c_str());
468 }
Tri Vod3518cf2018-12-14 14:25:08 -0800469 if (!product_policy_cil_file.empty()) {
470 compile_args.push_back(product_policy_cil_file.c_str());
471 }
Tri Vo503f1852019-01-16 11:57:19 -0800472 if (!product_mapping_file.empty()) {
473 compile_args.push_back(product_mapping_file.c_str());
474 }
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800475 if (!plat_pub_versioned_cil_file.empty()) {
476 compile_args.push_back(plat_pub_versioned_cil_file.c_str());
kaichieheef4cd72017-08-31 22:07:19 +0800477 }
478 if (!vendor_policy_cil_file.empty()) {
479 compile_args.push_back(vendor_policy_cil_file.c_str());
480 }
481 if (!odm_policy_cil_file.empty()) {
482 compile_args.push_back(odm_policy_cil_file.c_str());
483 }
Jeffrey Vander Stoepbaeece62022-02-08 12:42:33 +0000484 if (!apex_policy_cil_file.empty()) {
485 compile_args.push_back(apex_policy_cil_file.c_str());
486 }
kaichieheef4cd72017-08-31 22:07:19 +0800487 compile_args.push_back(nullptr);
488
489 if (!ForkExecveAndWaitForCompletion(compile_args[0], (char**)compile_args.data())) {
Tom Cherryc3170092017-08-10 12:22:44 -0700490 unlink(compiled_sepolicy);
491 return false;
492 }
493 unlink(compiled_sepolicy);
494
David Anderson491e4da2020-12-08 00:21:20 -0800495 policy_file->fd = std::move(compiled_sepolicy_fd);
496 policy_file->path = compiled_sepolicy;
Tom Cherryc3170092017-08-10 12:22:44 -0700497 return true;
498}
499
David Anderson491e4da2020-12-08 00:21:20 -0800500bool OpenMonolithicPolicy(PolicyFile* policy_file) {
501 static constexpr char kSepolicyFile[] = "/sepolicy";
Nikita Ioffefa33f852023-06-14 20:29:37 +0000502 // In Microdroid the precompiled sepolicy is located on /system, since there is no vendor code.
503 // TODO(b/287206497): refactor once we start conditionally compiling init for Microdroid.
504 std::string monolithic_policy_file = access(kMicrodroidPrecompiledSepolicy, R_OK) == 0
505 ? kMicrodroidPrecompiledSepolicy
506 : kSepolicyFile;
David Anderson491e4da2020-12-08 00:21:20 -0800507
Nikita Ioffefa33f852023-06-14 20:29:37 +0000508 LOG(INFO) << "Opening SELinux policy from monolithic file " << monolithic_policy_file;
509 policy_file->fd.reset(open(monolithic_policy_file.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
David Anderson491e4da2020-12-08 00:21:20 -0800510 if (policy_file->fd < 0) {
511 PLOG(ERROR) << "Failed to open monolithic SELinux policy";
Tom Cherryc3170092017-08-10 12:22:44 -0700512 return false;
513 }
Nikita Ioffefa33f852023-06-14 20:29:37 +0000514 policy_file->path = monolithic_policy_file;
Tom Cherryc3170092017-08-10 12:22:44 -0700515 return true;
516}
517
Jeffrey Vander Stoepbaeece62022-02-08 12:42:33 +0000518constexpr const char* kSigningCertRelease =
519 "/system/etc/selinux/com.android.sepolicy.cert-release.der";
520constexpr const char* kFsVerityProcPath = "/proc/sys/fs/verity";
521const std::string kSepolicyApexMetadataDir = "/metadata/sepolicy/";
522const std::string kSepolicyApexSystemDir = "/system/etc/selinux/apex/";
523const std::string kSepolicyZip = "SEPolicy.zip";
524const std::string kSepolicySignature = "SEPolicy.zip.sig";
525
526const std::string kTmpfsDir = "/dev/selinux/";
527
528// Files that are deleted after policy is compiled/loaded.
529const std::vector<std::string> kApexSepolicyTmp{"apex_sepolicy.cil", "apex_sepolicy.sha256"};
530// Files that need to persist because they are used by userspace processes.
531const std::vector<std::string> kApexSepolicy{"apex_file_contexts", "apex_property_contexts",
532 "apex_service_contexts", "apex_seapp_contexts",
533 "apex_test"};
534
Sandrod0192102022-09-07 14:56:39 +0000535Result<void> CreateTmpfsDir() {
Sandro1120f7f2022-09-05 15:56:38 +0000536 mode_t mode = 0744;
537 struct stat stat_data;
538 if (stat(kTmpfsDir.c_str(), &stat_data) != 0) {
539 if (errno != ENOENT) {
540 return ErrnoError() << "Could not stat " << kTmpfsDir;
541 }
542 if (mkdir(kTmpfsDir.c_str(), mode) != 0) {
543 return ErrnoError() << "Could not mkdir " << kTmpfsDir;
544 }
545 } else {
546 if (!S_ISDIR(stat_data.st_mode)) {
547 return Error() << kTmpfsDir << " exists and is not a directory.";
548 }
Sandrod0192102022-09-07 14:56:39 +0000549 LOG(WARNING) << "Directory " << kTmpfsDir << " already exists";
Sandro1120f7f2022-09-05 15:56:38 +0000550 }
551
552 // Need to manually call chmod because mkdir will create a folder with
553 // permissions mode & ~umask.
554 if (chmod(kTmpfsDir.c_str(), mode) != 0) {
555 return ErrnoError() << "Could not chmod " << kTmpfsDir;
556 }
557
558 return {};
559}
560
Jeffrey Vander Stoepbaeece62022-02-08 12:42:33 +0000561Result<void> PutFileInTmpfs(ZipArchiveHandle archive, const std::string& fileName) {
562 ZipEntry entry;
563 std::string dstPath = kTmpfsDir + fileName;
564
565 int ret = FindEntry(archive, fileName, &entry);
566 if (ret != 0) {
567 // All files are optional. If a file doesn't exist, return without error.
568 return {};
569 }
570
571 unique_fd fd(TEMP_FAILURE_RETRY(
572 open(dstPath.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, S_IRUSR | S_IWUSR)));
573 if (fd == -1) {
Sandro1120f7f2022-09-05 15:56:38 +0000574 return ErrnoError() << "Failed to open " << dstPath;
Jeffrey Vander Stoepbaeece62022-02-08 12:42:33 +0000575 }
576
Bart Van Asscheaee2ec82022-12-02 18:48:15 -0800577 ret = ExtractEntryToFile(archive, &entry, fd.get());
Jeffrey Vander Stoepbaeece62022-02-08 12:42:33 +0000578 if (ret != 0) {
579 return Error() << "Failed to extract entry \"" << fileName << "\" ("
580 << entry.uncompressed_length << " bytes) to \"" << dstPath
581 << "\": " << ErrorCodeString(ret);
582 }
583
584 return {};
585}
586
587Result<void> GetPolicyFromApex(const std::string& dir) {
588 LOG(INFO) << "Loading APEX Sepolicy from " << dir + kSepolicyZip;
589 unique_fd fd(open((dir + kSepolicyZip).c_str(), O_RDONLY | O_BINARY | O_CLOEXEC));
590 if (fd < 0) {
591 return ErrnoError() << "Failed to open package " << dir + kSepolicyZip;
592 }
593
594 ZipArchiveHandle handle;
595 int ret = OpenArchiveFd(fd.get(), (dir + kSepolicyZip).c_str(), &handle,
596 /*assume_ownership=*/false);
597 if (ret < 0) {
598 return Error() << "Failed to open package " << dir + kSepolicyZip << ": "
599 << ErrorCodeString(ret);
600 }
601
602 auto handle_guard = android::base::make_scope_guard([&handle] { CloseArchive(handle); });
603
Sandrod0192102022-09-07 14:56:39 +0000604 auto create = CreateTmpfsDir();
Sandro1120f7f2022-09-05 15:56:38 +0000605 if (!create.ok()) {
606 return create.error();
607 }
608
Jeffrey Vander Stoepbaeece62022-02-08 12:42:33 +0000609 for (const auto& file : kApexSepolicy) {
610 auto extract = PutFileInTmpfs(handle, file);
611 if (!extract.ok()) {
612 return extract.error();
613 }
614 }
615 for (const auto& file : kApexSepolicyTmp) {
616 auto extract = PutFileInTmpfs(handle, file);
617 if (!extract.ok()) {
618 return extract.error();
619 }
620 }
621 return {};
622}
623
624Result<void> LoadSepolicyApexCerts() {
625 key_serial_t keyring_id = android::GetKeyringId(".fs-verity");
626 if (keyring_id < 0) {
627 return Error() << "Failed to find .fs-verity keyring id";
628 }
629
630 // TODO(b/199914227) the release key should always exist. Once it's checked in, start
631 // throwing an error here if it doesn't exist.
632 if (access(kSigningCertRelease, F_OK) == 0) {
633 LoadKeyFromFile(keyring_id, "fsv_sepolicy_apex_release", kSigningCertRelease);
634 }
635 return {};
636}
637
638Result<void> SepolicyFsVerityCheck() {
Bart Van Asschedcc208f2023-01-30 18:49:41 -0800639 return Error() << "TODO implement support for fsverity SEPolicy.";
Jeffrey Vander Stoepbaeece62022-02-08 12:42:33 +0000640}
641
642Result<void> SepolicyCheckSignature(const std::string& dir) {
643 std::string signature;
644 if (!android::base::ReadFileToString(dir + kSepolicySignature, &signature)) {
645 return ErrnoError() << "Failed to read " << kSepolicySignature;
646 }
647
648 std::fstream sepolicyZip(dir + kSepolicyZip, std::ios::in | std::ios::binary);
649 if (!sepolicyZip) {
650 return Error() << "Failed to open " << kSepolicyZip;
651 }
652 sepolicyZip.seekg(0);
653 std::string sepolicyStr((std::istreambuf_iterator<char>(sepolicyZip)),
654 std::istreambuf_iterator<char>());
655
656 auto releaseKey = extractPublicKeyFromX509(kSigningCertRelease);
657 if (!releaseKey.ok()) {
658 return releaseKey.error();
659 }
660
661 return verifySignature(sepolicyStr, signature, *releaseKey);
662}
663
664Result<void> SepolicyVerify(const std::string& dir, bool supportsFsVerity) {
665 if (supportsFsVerity) {
666 auto fsVerityCheck = SepolicyFsVerityCheck();
667 if (fsVerityCheck.ok()) {
668 return fsVerityCheck;
669 }
670 // TODO(b/199914227) If the device supports fsverity, but we fail here, we should fail to
671 // boot and not carry on. For now, fallback to a signature checkuntil the fsverity
672 // logic is implemented.
673 LOG(INFO) << "Falling back to standard signature check. " << fsVerityCheck.error();
674 }
675
676 auto sepolicySignature = SepolicyCheckSignature(dir);
677 if (!sepolicySignature.ok()) {
678 return Error() << "Apex SEPolicy failed signature check";
679 }
680 return {};
681}
682
683void CleanupApexSepolicy() {
684 for (const auto& file : kApexSepolicyTmp) {
685 std::string path = kTmpfsDir + file;
686 unlink(path.c_str());
687 }
688}
689
690// Updatable sepolicy is shipped within an zip within an APEX. Because
691// it needs to be available before Apexes are mounted, apexd copies
692// the zip from the APEX and stores it in /metadata/sepolicy. If there is
693// no updatable sepolicy in /metadata/sepolicy, then the updatable policy is
694// loaded from /system/etc/selinux/apex. Init performs the following
695// steps on boot:
696//
697// 1. Validates the zip by checking its signature against a public key that is
698// stored in /system/etc/selinux.
699// 2. Extracts files from zip and stores them in /dev/selinux.
700// 3. Checks if the apex_sepolicy.sha256 matches the sha256 of precompiled_sepolicy.
701// if so, the precompiled sepolicy is used. Otherwise, an on-device compile of the policy
702// is used. This is the same flow as on-device compilation of policy for Treble.
703// 4. Cleans up files in /dev/selinux which are no longer needed.
704// 5. Restorecons the remaining files in /dev/selinux.
705// 6. Sets selinux into enforcing mode and continues normal booting.
706//
707void PrepareApexSepolicy() {
708 bool supportsFsVerity = access(kFsVerityProcPath, F_OK) == 0;
709 if (supportsFsVerity) {
710 auto loadSepolicyApexCerts = LoadSepolicyApexCerts();
711 if (!loadSepolicyApexCerts.ok()) {
712 // TODO(b/199914227) If the device supports fsverity, but we fail here, we should fail
713 // to boot and not carry on. For now, fallback to a signature checkuntil the fsverity
714 // logic is implemented.
715 LOG(INFO) << loadSepolicyApexCerts.error();
716 }
717 }
718 // If apex sepolicy zip exists in /metadata/sepolicy, use that, otherwise use version on
719 // /system.
720 auto dir = (access((kSepolicyApexMetadataDir + kSepolicyZip).c_str(), F_OK) == 0)
721 ? kSepolicyApexMetadataDir
722 : kSepolicyApexSystemDir;
723
724 auto sepolicyVerify = SepolicyVerify(dir, supportsFsVerity);
725 if (!sepolicyVerify.ok()) {
726 LOG(INFO) << "Error: " << sepolicyVerify.error();
727 // If signature verification fails, fall back to version on /system.
728 // This file doesn't need to be verified because it lives on the system partition which
729 // is signed and protected by verified boot.
730 dir = kSepolicyApexSystemDir;
731 }
732
733 auto apex = GetPolicyFromApex(dir);
734 if (!apex.ok()) {
735 // TODO(b/199914227) Make failure fatal. For now continue booting with non-apex sepolicy.
736 LOG(ERROR) << apex.error();
737 }
738}
739
David Anderson491e4da2020-12-08 00:21:20 -0800740void ReadPolicy(std::string* policy) {
741 PolicyFile policy_file;
Tom Cherryc3170092017-08-10 12:22:44 -0700742
David Anderson491e4da2020-12-08 00:21:20 -0800743 bool ok = IsSplitPolicyDevice() ? OpenSplitPolicy(&policy_file)
744 : OpenMonolithicPolicy(&policy_file);
745 if (!ok) {
746 LOG(FATAL) << "Unable to open SELinux policy";
Tom Cherryc3170092017-08-10 12:22:44 -0700747 }
748
David Anderson491e4da2020-12-08 00:21:20 -0800749 if (!android::base::ReadFdToString(policy_file.fd, policy)) {
750 PLOG(FATAL) << "Failed to read policy file: " << policy_file.path;
751 }
752}
753
754void SelinuxSetEnforcement() {
Tom Cherryc3170092017-08-10 12:22:44 -0700755 bool kernel_enforcing = (security_getenforce() == 1);
756 bool is_enforcing = IsEnforcing();
757 if (kernel_enforcing != is_enforcing) {
758 if (security_setenforce(is_enforcing)) {
Paul Lawrenceb2c2d692019-08-30 11:11:44 -0700759 PLOG(FATAL) << "security_setenforce(" << (is_enforcing ? "true" : "false")
760 << ") failed";
Tom Cherryc3170092017-08-10 12:22:44 -0700761 }
762 }
763
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900764 if (auto result = WriteFile("/sys/fs/selinux/checkreqprot", "0"); !result.ok()) {
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700765 LOG(FATAL) << "Unable to write to /sys/fs/selinux/checkreqprot: " << result.error();
Tom Cherryc3170092017-08-10 12:22:44 -0700766 }
Tom Cherryc3170092017-08-10 12:22:44 -0700767}
768
Tom Cherry8180b482019-08-26 13:57:51 -0700769constexpr size_t kKlogMessageSize = 1024;
770
Thiébaud Weksteenf03dde82023-04-03 16:53:12 +1000771void SelinuxAvcLog(char* buf) {
Tom Cherry8180b482019-08-26 13:57:51 -0700772 struct NetlinkMessage {
773 nlmsghdr hdr;
774 char buf[kKlogMessageSize];
775 } request = {};
776
777 request.hdr.nlmsg_flags = NLM_F_REQUEST;
778 request.hdr.nlmsg_type = AUDIT_USER_AVC;
779 request.hdr.nlmsg_len = sizeof(request);
780 strlcpy(request.buf, buf, sizeof(request.buf));
781
782 auto fd = unique_fd{socket(PF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_AUDIT)};
783 if (!fd.ok()) {
784 return;
785 }
786
Bart Van Asscheaee2ec82022-12-02 18:48:15 -0800787 TEMP_FAILURE_RETRY(send(fd.get(), &request, sizeof(request), 0));
Tom Cherry8180b482019-08-26 13:57:51 -0700788}
789
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800790} // namespace
791
Tom Cherryc3170092017-08-10 12:22:44 -0700792void SelinuxRestoreContext() {
793 LOG(INFO) << "Running restorecon...";
794 selinux_android_restorecon("/dev", 0);
Inseob Kim89d69132022-03-22 21:51:07 +0900795 selinux_android_restorecon("/dev/console", 0);
Tom Cherryc3170092017-08-10 12:22:44 -0700796 selinux_android_restorecon("/dev/kmsg", 0);
797 if constexpr (WORLD_WRITABLE_KMSG) {
798 selinux_android_restorecon("/dev/kmsg_debug", 0);
799 }
Tom Cherry81ae0752018-07-30 16:23:49 -0700800 selinux_android_restorecon("/dev/null", 0);
801 selinux_android_restorecon("/dev/ptmx", 0);
Tom Cherryc3170092017-08-10 12:22:44 -0700802 selinux_android_restorecon("/dev/socket", 0);
803 selinux_android_restorecon("/dev/random", 0);
804 selinux_android_restorecon("/dev/urandom", 0);
805 selinux_android_restorecon("/dev/__properties__", 0);
806
Tom Cherryc3170092017-08-10 12:22:44 -0700807 selinux_android_restorecon("/dev/block", SELINUX_ANDROID_RESTORECON_RECURSE);
David Anderson1ff75812020-11-13 00:31:47 -0800808 selinux_android_restorecon("/dev/dm-user", SELINUX_ANDROID_RESTORECON_RECURSE);
Tom Cherryc3170092017-08-10 12:22:44 -0700809 selinux_android_restorecon("/dev/device-mapper", 0);
Jiyong Park4ba548d2019-02-22 16:04:35 +0900810
811 selinux_android_restorecon("/apex", 0);
Kiyoung Kim99df54b2019-11-22 16:14:10 +0900812
813 selinux_android_restorecon("/linkerconfig", 0);
Bowgo Tsai196cc582020-01-20 18:03:58 +0800814
David Andersonc991f342020-02-21 17:11:07 -0800815 // adb remount, snapshot-based updates, and DSUs all create files during
816 // first-stage init.
Yifan Hongd91998f2020-02-20 17:54:57 -0800817 selinux_android_restorecon(SnapshotManager::GetGlobalRollbackIndicatorPath().c_str(), 0);
David Anderson4bb500f2020-03-06 18:14:19 -0800818 selinux_android_restorecon("/metadata/gsi", SELINUX_ANDROID_RESTORECON_RECURSE |
819 SELINUX_ANDROID_RESTORECON_SKIP_SEHASH);
Tom Cherryc3170092017-08-10 12:22:44 -0700820}
821
Tom Cherry74069d12018-07-20 15:26:25 -0700822int SelinuxKlogCallback(int type, const char* fmt, ...) {
823 android::base::LogSeverity severity = android::base::ERROR;
824 if (type == SELINUX_WARNING) {
825 severity = android::base::WARNING;
826 } else if (type == SELINUX_INFO) {
827 severity = android::base::INFO;
828 }
Tom Cherry8180b482019-08-26 13:57:51 -0700829 char buf[kKlogMessageSize];
Tom Cherry74069d12018-07-20 15:26:25 -0700830 va_list ap;
831 va_start(ap, fmt);
Tom Cherry8180b482019-08-26 13:57:51 -0700832 int length_written = vsnprintf(buf, sizeof(buf), fmt, ap);
Tom Cherry74069d12018-07-20 15:26:25 -0700833 va_end(ap);
Tom Cherry8180b482019-08-26 13:57:51 -0700834 if (length_written <= 0) {
835 return 0;
836 }
Thiébaud Weksteenf03dde82023-04-03 16:53:12 +1000837
838 // libselinux log messages usually contain a new line character, while
839 // Android LOG() does not expect it. Remove it to avoid empty lines in
840 // the log buffers.
841 size_t str_len = strlen(buf);
842 if (buf[str_len - 1] == '\n') {
843 buf[str_len - 1] = '\0';
844 }
845
Tom Cherry8180b482019-08-26 13:57:51 -0700846 if (type == SELINUX_AVC) {
Thiébaud Weksteenf03dde82023-04-03 16:53:12 +1000847 SelinuxAvcLog(buf);
Tom Cherry8180b482019-08-26 13:57:51 -0700848 } else {
849 android::base::KernelLogger(android::base::MAIN, severity, "selinux", nullptr, 0, buf);
850 }
Tom Cherry74069d12018-07-20 15:26:25 -0700851 return 0;
852}
853
Tom Cherryc3170092017-08-10 12:22:44 -0700854void SelinuxSetupKernelLogging() {
855 selinux_callback cb;
Tom Cherry74069d12018-07-20 15:26:25 -0700856 cb.func_log = SelinuxKlogCallback;
Tom Cherryc3170092017-08-10 12:22:44 -0700857 selinux_set_callback(SELINUX_CB_LOG, cb);
858}
859
Tom Cherry40acb372018-08-01 13:41:12 -0700860int SelinuxGetVendorAndroidVersion() {
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700861 static int vendor_android_version = [] {
862 if (!IsSplitPolicyDevice()) {
863 // If this device does not split sepolicy files, it's not a Treble device and therefore,
864 // we assume it's always on the latest platform.
865 return __ANDROID_API_FUTURE__;
866 }
Logan Chien837b2a42018-05-03 14:33:52 +0800867
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700868 std::string version;
869 if (!GetVendorMappingVersion(&version)) {
870 LOG(FATAL) << "Could not read vendor SELinux version";
871 }
Logan Chien837b2a42018-05-03 14:33:52 +0800872
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700873 int major_version;
874 std::string major_version_str(version, 0, version.find('.'));
875 if (!ParseInt(major_version_str, &major_version)) {
876 PLOG(FATAL) << "Failed to parse the vendor sepolicy major version "
877 << major_version_str;
878 }
Logan Chien837b2a42018-05-03 14:33:52 +0800879
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700880 return major_version;
881 }();
882 return vendor_android_version;
Logan Chien837b2a42018-05-03 14:33:52 +0800883}
884
David Andersond0ce5302020-03-20 21:47:10 -0700885// This is for R system.img/system_ext.img to work on old vendor.img as system_ext.img
886// is introduced in R. We mount system_ext in second stage init because the first-stage
887// init in boot.img won't be updated in the system-only OTA scenario.
888void MountMissingSystemPartitions() {
889 android::fs_mgr::Fstab fstab;
890 if (!ReadDefaultFstab(&fstab)) {
891 LOG(ERROR) << "Could not read default fstab";
892 }
893
894 android::fs_mgr::Fstab mounts;
895 if (!ReadFstabFromFile("/proc/mounts", &mounts)) {
896 LOG(ERROR) << "Could not read /proc/mounts";
897 }
898
899 static const std::vector<std::string> kPartitionNames = {"system_ext", "product"};
900
901 android::fs_mgr::Fstab extra_fstab;
902 for (const auto& name : kPartitionNames) {
903 if (GetEntryForMountPoint(&mounts, "/"s + name)) {
904 // The partition is already mounted.
905 continue;
906 }
907
Lianjun Huangccd094c2023-02-17 20:22:37 +0800908 auto system_entries = GetEntriesForMountPoint(&fstab, "/system");
909 for (auto& system_entry : system_entries) {
910 if (!system_entry) {
911 LOG(ERROR) << "Could not find mount entry for /system";
912 break;
913 }
914 if (!system_entry->fs_mgr_flags.logical) {
915 LOG(INFO) << "Skipping mount of " << name << ", system is not dynamic.";
916 break;
917 }
David Andersond0ce5302020-03-20 21:47:10 -0700918
Lianjun Huangccd094c2023-02-17 20:22:37 +0800919 auto entry = *system_entry;
920 auto partition_name = name + fs_mgr_get_slot_suffix();
921 auto replace_name = "system"s + fs_mgr_get_slot_suffix();
David Andersond0ce5302020-03-20 21:47:10 -0700922
Lianjun Huangccd094c2023-02-17 20:22:37 +0800923 entry.mount_point = "/"s + name;
924 entry.blk_device =
David Andersond0ce5302020-03-20 21:47:10 -0700925 android::base::StringReplace(entry.blk_device, replace_name, partition_name, false);
Lianjun Huangccd094c2023-02-17 20:22:37 +0800926 if (!fs_mgr_update_logical_partition(&entry)) {
927 LOG(ERROR) << "Could not update logical partition";
928 continue;
929 }
David Andersond0ce5302020-03-20 21:47:10 -0700930
Lianjun Huangccd094c2023-02-17 20:22:37 +0800931 extra_fstab.emplace_back(std::move(entry));
932 }
David Andersond0ce5302020-03-20 21:47:10 -0700933 }
934
Yi-Yo Chiang20579012021-04-01 20:14:54 +0800935 SkipMountingPartitions(&extra_fstab, true /* verbose */);
David Andersond0ce5302020-03-20 21:47:10 -0700936 if (extra_fstab.empty()) {
937 return;
938 }
939
940 BlockDevInitializer block_dev_init;
941 for (auto& entry : extra_fstab) {
942 if (access(entry.blk_device.c_str(), F_OK) != 0) {
943 auto block_dev = android::base::Basename(entry.blk_device);
944 if (!block_dev_init.InitDmDevice(block_dev)) {
945 LOG(ERROR) << "Failed to find device-mapper node: " << block_dev;
946 continue;
947 }
948 }
949 if (fs_mgr_do_mount_one(entry)) {
950 LOG(ERROR) << "Could not mount " << entry.mount_point;
951 }
952 }
953}
954
David Anderson491e4da2020-12-08 00:21:20 -0800955static void LoadSelinuxPolicy(std::string& policy) {
956 LOG(INFO) << "Loading SELinux policy";
957
958 set_selinuxmnt("/sys/fs/selinux");
959 if (security_load_policy(policy.data(), policy.size()) < 0) {
960 PLOG(FATAL) << "SELinux: Could not load policy";
961 }
962}
963
964// The SELinux setup process is carefully orchestrated around snapuserd. Policy
965// must be loaded off dynamic partitions, and during an OTA, those partitions
966// cannot be read without snapuserd. But, with kernel-privileged snapuserd
967// running, loading the policy will immediately trigger audits.
968//
969// We use a five-step process to address this:
970// (1) Read the policy into a string, with snapuserd running.
971// (2) Rewrite the snapshot device-mapper tables, to generate new dm-user
972// devices and to flush I/O.
973// (3) Kill snapuserd, which no longer has any dm-user devices to attach to.
974// (4) Load the sepolicy and issue critical restorecons in /dev, carefully
975// avoiding anything that would read from /system.
976// (5) Re-launch snapuserd and attach it to the dm-user devices from step (2).
977//
978// After this sequence, it is safe to enable enforcing mode and continue booting.
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800979int SetupSelinux(char** argv) {
Mark Salyzynbeb6abe2019-07-29 09:35:18 -0700980 SetStdioToDevNull(argv);
Tom Cherry59656fb2019-05-28 10:19:44 -0700981 InitKernelLogging(argv);
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800982
983 if (REBOOT_BOOTLOADER_ON_PANIC) {
984 InstallRebootSignalHandlers();
985 }
986
Mark Salyzyn10377df2019-03-27 08:10:41 -0700987 boot_clock::time_point start_time = boot_clock::now();
988
David Andersond0ce5302020-03-20 21:47:10 -0700989 MountMissingSystemPartitions();
990
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800991 SelinuxSetupKernelLogging();
David Anderson491e4da2020-12-08 00:21:20 -0800992
993 LOG(INFO) << "Opening SELinux policy";
994
Jeffrey Vander Stoepbaeece62022-02-08 12:42:33 +0000995 PrepareApexSepolicy();
996
David Anderson491e4da2020-12-08 00:21:20 -0800997 // Read the policy before potentially killing snapuserd.
998 std::string policy;
999 ReadPolicy(&policy);
Jeffrey Vander Stoepbaeece62022-02-08 12:42:33 +00001000 CleanupApexSepolicy();
David Anderson491e4da2020-12-08 00:21:20 -08001001
1002 auto snapuserd_helper = SnapuserdSelinuxHelper::CreateIfNeeded();
1003 if (snapuserd_helper) {
1004 // Kill the old snapused to avoid audit messages. After this we cannot
1005 // read from /system (or other dynamic partitions) until we call
1006 // FinishTransition().
1007 snapuserd_helper->StartTransition();
1008 }
1009
1010 LoadSelinuxPolicy(policy);
1011
1012 if (snapuserd_helper) {
1013 // Before enforcing, finish the pending snapuserd transition.
1014 snapuserd_helper->FinishTransition();
1015 snapuserd_helper = nullptr;
1016 }
1017
Jeffrey Vander Stoepbaeece62022-02-08 12:42:33 +00001018 // This restorecon is intentionally done before SelinuxSetEnforcement because the permissions
1019 // needed to transition files from tmpfs to *_contexts_file context should not be granted to
1020 // any process after selinux is set into enforcing mode.
1021 if (selinux_android_restorecon("/dev/selinux/", SELINUX_ANDROID_RESTORECON_RECURSE) == -1) {
1022 PLOG(FATAL) << "restorecon failed of /dev/selinux failed";
1023 }
1024
David Anderson491e4da2020-12-08 00:21:20 -08001025 SelinuxSetEnforcement();
Tom Cherry7bfea3d2018-11-06 14:12:05 -08001026
1027 // We're in the kernel domain and want to transition to the init domain. File systems that
1028 // store SELabels in their xattrs, such as ext4 do not need an explicit restorecon here,
1029 // but other file systems do. In particular, this is needed for ramdisks such as the
1030 // recovery image for A/B devices.
1031 if (selinux_android_restorecon("/system/bin/init", 0) == -1) {
1032 PLOG(FATAL) << "restorecon failed of /system/bin/init failed";
1033 }
1034
Mark Salyzyn44505ec2019-05-08 12:44:50 -07001035 setenv(kEnvSelinuxStartedAt, std::to_string(start_time.time_since_epoch().count()).c_str(), 1);
Mark Salyzyn10377df2019-03-27 08:10:41 -07001036
Tom Cherry7bfea3d2018-11-06 14:12:05 -08001037 const char* path = "/system/bin/init";
1038 const char* args[] = {path, "second_stage", nullptr};
1039 execv(path, const_cast<char**>(args));
1040
1041 // execv() only returns if an error happened, in which case we
1042 // panic and never return from this function.
1043 PLOG(FATAL) << "execv(\"" << path << "\") failed";
1044
1045 return 1;
1046}
1047
Tom Cherryc3170092017-08-10 12:22:44 -07001048} // namespace init
1049} // namespace android