blob: 081cf6e2a9ad556ce8f3c72290d564626370a6e3 [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
Thiébaud Weksteen50f03fd2023-09-06 10:52:49 +100029// 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 'vendor'
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.
Tom Cherryc3170092017-08-10 12:22:44 -070035
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
Thiébaud Weksteen50f03fd2023-09-06 10:52:49 +100039// 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
Bowgo Tsaif016f252019-08-28 17:56:51 +080043// precompiled_sepolicy directly if and only if the hashes along with the precompiled SEPolicy on
Thiébaud Weksteen50f03fd2023-09-06 10:52:49 +100044// /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// 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>
Paul Lawrence7e2b0cd2025-03-05 09:55:25 -080059#include <sys/mount.h>
Tom Cherryc3170092017-08-10 12:22:44 -070060#include <sys/wait.h>
61#include <unistd.h>
62
63#include <android-base/chrono_utils.h>
64#include <android-base/file.h>
65#include <android-base/logging.h>
Logan Chien837b2a42018-05-03 14:33:52 +080066#include <android-base/parseint.h>
Inseob Kimd99d9772021-03-11 17:58:26 +090067#include <android-base/result.h>
David Andersond0ce5302020-03-20 21:47:10 -070068#include <android-base/strings.h>
Tom Cherryc3170092017-08-10 12:22:44 -070069#include <android-base/unique_fd.h>
Nikita Ioffefeb7e0e2024-03-28 00:32:36 +000070#include <android/avf_cc_flags.h>
Jooyung Hanebdd5bc2025-04-25 15:58:15 +090071#include <com_android_apex_flags.h>
Bowgo Tsai1dacd422019-03-04 17:53:34 +080072#include <fs_avb/fs_avb.h>
David Andersond0ce5302020-03-20 21:47:10 -070073#include <fs_mgr.h>
Paul Lawrence6bb52892025-01-29 19:43:48 -080074#include <fs_mgr_overlayfs.h>
Inseob Kime2efde32024-11-20 17:56:20 +090075#include <genfslabelsversion.h>
Bowgo Tsai196cc582020-01-20 18:03:58 +080076#include <libgsi/libgsi.h>
Yifan Hongd91998f2020-02-20 17:54:57 -080077#include <libsnapshot/snapshot.h>
Tom Cherryc3170092017-08-10 12:22:44 -070078#include <selinux/android.h>
79
David Andersond0ce5302020-03-20 21:47:10 -070080#include "block_dev_initializer.h"
Bowgo Tsai30afda72019-04-11 23:57:24 +080081#include "debug_ramdisk.h"
Tom Cherry7bfea3d2018-11-06 14:12:05 -080082#include "reboot_utils.h"
Paul Lawrence6bb52892025-01-29 19:43:48 -080083#include "second_stage_resources.h"
David Anderson491e4da2020-12-08 00:21:20 -080084#include "snapuserd_transition.h"
Tom Cherryc3170092017-08-10 12:22:44 -070085#include "util.h"
86
Bowgo Tsai1dacd422019-03-04 17:53:34 +080087using namespace std::string_literals;
88
Logan Chien837b2a42018-05-03 14:33:52 +080089using android::base::ParseInt;
Tom Cherryc3170092017-08-10 12:22:44 -070090using android::base::Timer;
91using android::base::unique_fd;
Bowgo Tsai1dacd422019-03-04 17:53:34 +080092using android::fs_mgr::AvbHandle;
Yifan Hongd91998f2020-02-20 17:54:57 -080093using android::snapshot::SnapshotManager;
Tom Cherryc3170092017-08-10 12:22:44 -070094
95namespace android {
96namespace init {
97
Tom Cherryc3170092017-08-10 12:22:44 -070098namespace {
99
100enum EnforcingStatus { SELINUX_PERMISSIVE, SELINUX_ENFORCING };
101
Alistair Delva63594a42021-03-09 11:04:23 -0800102EnforcingStatus StatusFromProperty() {
Yi-Yo Chiangda5323e2023-08-02 01:08:23 +0800103 std::string value;
104 if (android::fs_mgr::GetKernelCmdline("androidboot.selinux", &value) && value == "permissive") {
105 return SELINUX_PERMISSIVE;
Alistair Delva63594a42021-03-09 11:04:23 -0800106 }
Yi-Yo Chiangda5323e2023-08-02 01:08:23 +0800107 if (android::fs_mgr::GetBootconfig("androidboot.selinux", &value) && value == "permissive") {
108 return SELINUX_PERMISSIVE;
109 }
110 return SELINUX_ENFORCING;
Tom Cherryc3170092017-08-10 12:22:44 -0700111}
112
113bool IsEnforcing() {
114 if (ALLOW_PERMISSIVE_SELINUX) {
Alistair Delva63594a42021-03-09 11:04:23 -0800115 return StatusFromProperty() == SELINUX_ENFORCING;
Tom Cherryc3170092017-08-10 12:22:44 -0700116 }
117 return true;
118}
119
Tom Cherryc3170092017-08-10 12:22:44 -0700120bool ReadFirstLine(const char* file, std::string* line) {
121 line->clear();
122
123 std::string contents;
124 if (!android::base::ReadFileToString(file, &contents, true /* follow symlinks */)) {
125 return false;
126 }
127 std::istringstream in(contents);
128 std::getline(in, *line);
129 return true;
130}
131
Inseob Kimd99d9772021-03-11 17:58:26 +0900132Result<std::string> FindPrecompiledSplitPolicy() {
133 std::string precompiled_sepolicy;
kaichieheef4cd72017-08-31 22:07:19 +0800134 // If there is an odm partition, precompiled_sepolicy will be in
135 // odm/etc/selinux. Otherwise it will be in vendor/etc/selinux.
136 static constexpr const char vendor_precompiled_sepolicy[] =
Sandro1120f7f2022-09-05 15:56:38 +0000137 "/vendor/etc/selinux/precompiled_sepolicy";
kaichieheef4cd72017-08-31 22:07:19 +0800138 static constexpr const char odm_precompiled_sepolicy[] =
Sandro1120f7f2022-09-05 15:56:38 +0000139 "/odm/etc/selinux/precompiled_sepolicy";
kaichieheef4cd72017-08-31 22:07:19 +0800140 if (access(odm_precompiled_sepolicy, R_OK) == 0) {
Inseob Kimd99d9772021-03-11 17:58:26 +0900141 precompiled_sepolicy = odm_precompiled_sepolicy;
kaichieheef4cd72017-08-31 22:07:19 +0800142 } else if (access(vendor_precompiled_sepolicy, R_OK) == 0) {
Inseob Kimd99d9772021-03-11 17:58:26 +0900143 precompiled_sepolicy = vendor_precompiled_sepolicy;
kaichieheef4cd72017-08-31 22:07:19 +0800144 } else {
Inseob Kimd99d9772021-03-11 17:58:26 +0900145 return ErrnoError() << "No precompiled sepolicy at " << vendor_precompiled_sepolicy;
Tom Cherryc3170092017-08-10 12:22:44 -0700146 }
kaichieheef4cd72017-08-31 22:07:19 +0800147
Inseob Kimd99d9772021-03-11 17:58:26 +0900148 // Use precompiled sepolicy only when all corresponding hashes are equal.
Inseob Kimd99d9772021-03-11 17:58:26 +0900149 std::vector<std::pair<std::string, std::string>> sepolicy_hashes{
150 {"/system/etc/selinux/plat_sepolicy_and_mapping.sha256",
151 precompiled_sepolicy + ".plat_sepolicy_and_mapping.sha256"},
Inseob Kim28fdb672021-04-29 19:48:27 +0900152 {"/system_ext/etc/selinux/system_ext_sepolicy_and_mapping.sha256",
153 precompiled_sepolicy + ".system_ext_sepolicy_and_mapping.sha256"},
154 {"/product/etc/selinux/product_sepolicy_and_mapping.sha256",
155 precompiled_sepolicy + ".product_sepolicy_and_mapping.sha256"},
Inseob Kimd99d9772021-03-11 17:58:26 +0900156 };
157
Inseob Kimd99d9772021-03-11 17:58:26 +0900158 for (const auto& [actual_id_path, precompiled_id_path] : sepolicy_hashes) {
Inseob Kim28fdb672021-04-29 19:48:27 +0900159 // Both of them should exist or both of them shouldn't exist.
160 if (access(actual_id_path.c_str(), R_OK) != 0) {
161 if (access(precompiled_id_path.c_str(), R_OK) == 0) {
162 return Error() << precompiled_id_path << " exists but " << actual_id_path
163 << " doesn't";
164 }
165 continue;
166 }
167
Inseob Kimd99d9772021-03-11 17:58:26 +0900168 std::string actual_id;
169 if (!ReadFirstLine(actual_id_path.c_str(), &actual_id)) {
170 return ErrnoError() << "Failed to read " << actual_id_path;
171 }
172
173 std::string precompiled_id;
174 if (!ReadFirstLine(precompiled_id_path.c_str(), &precompiled_id)) {
175 return ErrnoError() << "Failed to read " << precompiled_id_path;
176 }
177
178 if (actual_id.empty() || actual_id != precompiled_id) {
179 return Error() << actual_id_path << " and " << precompiled_id_path << " differ";
180 }
Tri Voc8137f92019-01-22 18:22:25 -0800181 }
Inseob Kimd99d9772021-03-11 17:58:26 +0900182
183 return precompiled_sepolicy;
Tom Cherryc3170092017-08-10 12:22:44 -0700184}
185
186bool GetVendorMappingVersion(std::string* plat_vers) {
187 if (!ReadFirstLine("/vendor/etc/selinux/plat_sepolicy_vers.txt", plat_vers)) {
188 PLOG(ERROR) << "Failed to read /vendor/etc/selinux/plat_sepolicy_vers.txt";
189 return false;
190 }
191 if (plat_vers->empty()) {
192 LOG(ERROR) << "No version present in plat_sepolicy_vers.txt";
193 return false;
194 }
195 return true;
196}
197
198constexpr const char plat_policy_cil_file[] = "/system/etc/selinux/plat_sepolicy.cil";
199
200bool IsSplitPolicyDevice() {
201 return access(plat_policy_cil_file, R_OK) != -1;
202}
203
Yi-Yo Chiangbb77c542021-09-23 14:14:16 +0000204std::optional<const char*> GetUserdebugPlatformPolicyFile() {
205 // See if we need to load userdebug_plat_sepolicy.cil instead of plat_sepolicy.cil.
206 const char* force_debuggable_env = getenv("INIT_FORCE_DEBUGGABLE");
207 if (force_debuggable_env && "true"s == force_debuggable_env && AvbHandle::IsDeviceUnlocked()) {
208 const std::vector<const char*> debug_policy_candidates = {
209#if INSTALL_DEBUG_POLICY_TO_SYSTEM_EXT == 1
210 "/system_ext/etc/selinux/userdebug_plat_sepolicy.cil",
211#endif
212 kDebugRamdiskSEPolicy,
213 };
214 for (const char* debug_policy : debug_policy_candidates) {
215 if (access(debug_policy, F_OK) == 0) {
216 return debug_policy;
217 }
218 }
219 }
220 return std::nullopt;
221}
222
David Anderson491e4da2020-12-08 00:21:20 -0800223struct PolicyFile {
224 unique_fd fd;
225 std::string path;
226};
227
228bool OpenSplitPolicy(PolicyFile* policy_file) {
Jeff Vander Stoep5effda42021-11-05 09:03:11 +0100229 // IMPLEMENTATION NOTE: Split policy consists of three or more CIL files:
Tom Cherryc3170092017-08-10 12:22:44 -0700230 // * platform -- policy needed due to logic contained in the system image,
Jeff Vander Stoep5effda42021-11-05 09:03:11 +0100231 // * vendor -- policy needed due to logic contained in the vendor image,
Tom Cherryc3170092017-08-10 12:22:44 -0700232 // * mapping -- mapping policy which helps preserve forward-compatibility of non-platform policy
233 // with newer versions of platform policy.
Thiébaud Weksteen50f03fd2023-09-06 10:52:49 +1000234 // * (optional) policy needed due to logic on product, system_ext, or odm images.
Tom Cherryc3170092017-08-10 12:22:44 -0700235 // secilc is invoked to compile the above three policy files into a single monolithic policy
236 // file. This file is then loaded into the kernel.
237
Yi-Yo Chiangbb77c542021-09-23 14:14:16 +0000238 const auto userdebug_plat_sepolicy = GetUserdebugPlatformPolicyFile();
239 const bool use_userdebug_policy = userdebug_plat_sepolicy.has_value();
Bowgo Tsai1dacd422019-03-04 17:53:34 +0800240 if (use_userdebug_policy) {
Yi-Yo Chiangbb77c542021-09-23 14:14:16 +0000241 LOG(INFO) << "Using userdebug system sepolicy " << *userdebug_plat_sepolicy;
Bowgo Tsai1dacd422019-03-04 17:53:34 +0800242 }
243
Tom Cherryc3170092017-08-10 12:22:44 -0700244 // Load precompiled policy from vendor image, if a matching policy is found there. The policy
245 // must match the platform policy on the system image.
Bowgo Tsai1dacd422019-03-04 17:53:34 +0800246 // use_userdebug_policy requires compiling sepolicy with userdebug_plat_sepolicy.cil.
247 // Thus it cannot use the precompiled policy from vendor image.
Inseob Kimd99d9772021-03-11 17:58:26 +0900248 if (!use_userdebug_policy) {
249 if (auto res = FindPrecompiledSplitPolicy(); res.ok()) {
250 unique_fd fd(open(res->c_str(), O_RDONLY | O_CLOEXEC | O_BINARY));
251 if (fd != -1) {
252 policy_file->fd = std::move(fd);
253 policy_file->path = std::move(*res);
254 return true;
255 }
256 } else {
257 LOG(INFO) << res.error();
Tom Cherryc3170092017-08-10 12:22:44 -0700258 }
259 }
260 // No suitable precompiled policy could be loaded
261
262 LOG(INFO) << "Compiling SELinux policy";
263
Tom Cherryc3170092017-08-10 12:22:44 -0700264 // We store the output of the compilation on /dev because this is the most convenient tmpfs
265 // storage mount available this early in the boot sequence.
266 char compiled_sepolicy[] = "/dev/sepolicy.XXXXXX";
267 unique_fd compiled_sepolicy_fd(mkostemp(compiled_sepolicy, O_CLOEXEC));
268 if (compiled_sepolicy_fd < 0) {
269 PLOG(ERROR) << "Failed to create temporary file " << compiled_sepolicy;
270 return false;
271 }
272
273 // Determine which mapping file to include
274 std::string vend_plat_vers;
275 if (!GetVendorMappingVersion(&vend_plat_vers)) {
276 return false;
277 }
Tri Vo503f1852019-01-16 11:57:19 -0800278 std::string plat_mapping_file("/system/etc/selinux/mapping/" + vend_plat_vers + ".cil");
kaichieheef4cd72017-08-31 22:07:19 +0800279
Jeff Vander Stoep0ac51cf2019-05-02 14:05:18 -0700280 std::string plat_compat_cil_file("/system/etc/selinux/mapping/" + vend_plat_vers +
281 ".compat.cil");
282 if (access(plat_compat_cil_file.c_str(), F_OK) == -1) {
283 plat_compat_cil_file.clear();
284 }
285
Bowgo Tsaif016f252019-08-28 17:56:51 +0800286 std::string system_ext_policy_cil_file("/system_ext/etc/selinux/system_ext_sepolicy.cil");
287 if (access(system_ext_policy_cil_file.c_str(), F_OK) == -1) {
288 system_ext_policy_cil_file.clear();
289 }
290
291 std::string system_ext_mapping_file("/system_ext/etc/selinux/mapping/" + vend_plat_vers +
292 ".cil");
293 if (access(system_ext_mapping_file.c_str(), F_OK) == -1) {
294 system_ext_mapping_file.clear();
295 }
296
Yi-Yo Chiang731d2472021-03-23 22:11:13 +0800297 std::string system_ext_compat_cil_file("/system_ext/etc/selinux/mapping/" + vend_plat_vers +
298 ".compat.cil");
299 if (access(system_ext_compat_cil_file.c_str(), F_OK) == -1) {
300 system_ext_compat_cil_file.clear();
301 }
302
Tri Vod3518cf2018-12-14 14:25:08 -0800303 std::string product_policy_cil_file("/product/etc/selinux/product_sepolicy.cil");
304 if (access(product_policy_cil_file.c_str(), F_OK) == -1) {
305 product_policy_cil_file.clear();
306 }
307
Tri Vo503f1852019-01-16 11:57:19 -0800308 std::string product_mapping_file("/product/etc/selinux/mapping/" + vend_plat_vers + ".cil");
309 if (access(product_mapping_file.c_str(), F_OK) == -1) {
310 product_mapping_file.clear();
311 }
312
kaichieheef4cd72017-08-31 22:07:19 +0800313 std::string vendor_policy_cil_file("/vendor/etc/selinux/vendor_sepolicy.cil");
kaichieheef4cd72017-08-31 22:07:19 +0800314 if (access(vendor_policy_cil_file.c_str(), F_OK) == -1) {
Jeff Vander Stoep5effda42021-11-05 09:03:11 +0100315 LOG(ERROR) << "Missing " << vendor_policy_cil_file;
316 return false;
317 }
318
319 std::string plat_pub_versioned_cil_file("/vendor/etc/selinux/plat_pub_versioned.cil");
320 if (access(plat_pub_versioned_cil_file.c_str(), F_OK) == -1) {
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800321 LOG(ERROR) << "Missing " << plat_pub_versioned_cil_file;
kaichieheef4cd72017-08-31 22:07:19 +0800322 return false;
323 }
324
325 // odm_sepolicy.cil is default but optional.
326 std::string odm_policy_cil_file("/odm/etc/selinux/odm_sepolicy.cil");
327 if (access(odm_policy_cil_file.c_str(), F_OK) == -1) {
328 odm_policy_cil_file.clear();
329 }
Jeff Vander Stoep724eda52019-02-15 12:13:38 -0800330 const std::string version_as_string = std::to_string(SEPOLICY_VERSION);
Andreas Huberc41b8382017-08-18 14:43:52 -0700331
Inseob Kim76afb4a2024-11-06 17:07:04 +0900332 std::vector<std::string> genfs_cil_files;
333
Inseob Kime2efde32024-11-20 17:56:20 +0900334 int vendor_genfs_version = get_genfs_labels_version();
Inseob Kim76afb4a2024-11-06 17:07:04 +0900335 std::string genfs_cil_file =
336 std::format("/system/etc/selinux/plat_sepolicy_genfs_{}.cil", vendor_genfs_version);
337 if (access(genfs_cil_file.c_str(), F_OK) != 0) {
Inseob Kime2efde32024-11-20 17:56:20 +0900338 LOG(INFO) << "Missing " << genfs_cil_file << "; skipping";
Inseob Kim76afb4a2024-11-06 17:07:04 +0900339 genfs_cil_file.clear();
Inseob Kime2efde32024-11-20 17:56:20 +0900340 } else {
341 LOG(INFO) << "Using " << genfs_cil_file << " for genfs labels";
Inseob Kim76afb4a2024-11-06 17:07:04 +0900342 }
343
Tom Cherryc3170092017-08-10 12:22:44 -0700344 // clang-format off
kaichieheef4cd72017-08-31 22:07:19 +0800345 std::vector<const char*> compile_args {
Tom Cherryc3170092017-08-10 12:22:44 -0700346 "/system/bin/secilc",
Yi-Yo Chiangbb77c542021-09-23 14:14:16 +0000347 use_userdebug_policy ? *userdebug_plat_sepolicy : plat_policy_cil_file,
Jeff Vander Stoep5e9ba3c2017-10-06 17:03:45 -0700348 "-m", "-M", "true", "-G", "-N",
Andreas Huberc41b8382017-08-18 14:43:52 -0700349 "-c", version_as_string.c_str(),
Tri Vo503f1852019-01-16 11:57:19 -0800350 plat_mapping_file.c_str(),
Tom Cherryc3170092017-08-10 12:22:44 -0700351 "-o", compiled_sepolicy,
352 // We don't care about file_contexts output by the compiler
353 "-f", "/sys/fs/selinux/null", // /dev/null is not yet available
kaichieheef4cd72017-08-31 22:07:19 +0800354 };
Tom Cherryc3170092017-08-10 12:22:44 -0700355 // clang-format on
356
Jeff Vander Stoep0ac51cf2019-05-02 14:05:18 -0700357 if (!plat_compat_cil_file.empty()) {
358 compile_args.push_back(plat_compat_cil_file.c_str());
359 }
Bowgo Tsaif016f252019-08-28 17:56:51 +0800360 if (!system_ext_policy_cil_file.empty()) {
361 compile_args.push_back(system_ext_policy_cil_file.c_str());
362 }
363 if (!system_ext_mapping_file.empty()) {
364 compile_args.push_back(system_ext_mapping_file.c_str());
365 }
Yi-Yo Chiang731d2472021-03-23 22:11:13 +0800366 if (!system_ext_compat_cil_file.empty()) {
367 compile_args.push_back(system_ext_compat_cil_file.c_str());
368 }
Tri Vod3518cf2018-12-14 14:25:08 -0800369 if (!product_policy_cil_file.empty()) {
370 compile_args.push_back(product_policy_cil_file.c_str());
371 }
Tri Vo503f1852019-01-16 11:57:19 -0800372 if (!product_mapping_file.empty()) {
373 compile_args.push_back(product_mapping_file.c_str());
374 }
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800375 if (!plat_pub_versioned_cil_file.empty()) {
376 compile_args.push_back(plat_pub_versioned_cil_file.c_str());
kaichieheef4cd72017-08-31 22:07:19 +0800377 }
378 if (!vendor_policy_cil_file.empty()) {
379 compile_args.push_back(vendor_policy_cil_file.c_str());
380 }
381 if (!odm_policy_cil_file.empty()) {
382 compile_args.push_back(odm_policy_cil_file.c_str());
383 }
Inseob Kim76afb4a2024-11-06 17:07:04 +0900384 if (!genfs_cil_file.empty()) {
385 compile_args.push_back(genfs_cil_file.c_str());
386 }
kaichieheef4cd72017-08-31 22:07:19 +0800387 compile_args.push_back(nullptr);
388
389 if (!ForkExecveAndWaitForCompletion(compile_args[0], (char**)compile_args.data())) {
Tom Cherryc3170092017-08-10 12:22:44 -0700390 unlink(compiled_sepolicy);
391 return false;
392 }
393 unlink(compiled_sepolicy);
394
David Anderson491e4da2020-12-08 00:21:20 -0800395 policy_file->fd = std::move(compiled_sepolicy_fd);
396 policy_file->path = compiled_sepolicy;
Tom Cherryc3170092017-08-10 12:22:44 -0700397 return true;
398}
399
David Anderson491e4da2020-12-08 00:21:20 -0800400bool OpenMonolithicPolicy(PolicyFile* policy_file) {
401 static constexpr char kSepolicyFile[] = "/sepolicy";
402
Nikita Ioffea66adf42023-06-26 14:55:31 +0100403 LOG(INFO) << "Opening SELinux policy from monolithic file " << kSepolicyFile;
404 policy_file->fd.reset(open(kSepolicyFile, O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
David Anderson491e4da2020-12-08 00:21:20 -0800405 if (policy_file->fd < 0) {
406 PLOG(ERROR) << "Failed to open monolithic SELinux policy";
Tom Cherryc3170092017-08-10 12:22:44 -0700407 return false;
408 }
Nikita Ioffea66adf42023-06-26 14:55:31 +0100409 policy_file->path = kSepolicyFile;
Tom Cherryc3170092017-08-10 12:22:44 -0700410 return true;
411}
412
David Anderson491e4da2020-12-08 00:21:20 -0800413void ReadPolicy(std::string* policy) {
414 PolicyFile policy_file;
Tom Cherryc3170092017-08-10 12:22:44 -0700415
David Anderson491e4da2020-12-08 00:21:20 -0800416 bool ok = IsSplitPolicyDevice() ? OpenSplitPolicy(&policy_file)
417 : OpenMonolithicPolicy(&policy_file);
418 if (!ok) {
419 LOG(FATAL) << "Unable to open SELinux policy";
Tom Cherryc3170092017-08-10 12:22:44 -0700420 }
421
David Anderson491e4da2020-12-08 00:21:20 -0800422 if (!android::base::ReadFdToString(policy_file.fd, policy)) {
423 PLOG(FATAL) << "Failed to read policy file: " << policy_file.path;
424 }
425}
426
427void SelinuxSetEnforcement() {
Tom Cherryc3170092017-08-10 12:22:44 -0700428 bool kernel_enforcing = (security_getenforce() == 1);
429 bool is_enforcing = IsEnforcing();
430 if (kernel_enforcing != is_enforcing) {
431 if (security_setenforce(is_enforcing)) {
Paul Lawrenceb2c2d692019-08-30 11:11:44 -0700432 PLOG(FATAL) << "security_setenforce(" << (is_enforcing ? "true" : "false")
433 << ") failed";
Tom Cherryc3170092017-08-10 12:22:44 -0700434 }
435 }
Tom Cherryc3170092017-08-10 12:22:44 -0700436}
437
Tom Cherry8180b482019-08-26 13:57:51 -0700438constexpr size_t kKlogMessageSize = 1024;
439
Thiébaud Weksteenf03dde82023-04-03 16:53:12 +1000440void SelinuxAvcLog(char* buf) {
Tom Cherry8180b482019-08-26 13:57:51 -0700441 struct NetlinkMessage {
442 nlmsghdr hdr;
443 char buf[kKlogMessageSize];
444 } request = {};
445
446 request.hdr.nlmsg_flags = NLM_F_REQUEST;
447 request.hdr.nlmsg_type = AUDIT_USER_AVC;
448 request.hdr.nlmsg_len = sizeof(request);
449 strlcpy(request.buf, buf, sizeof(request.buf));
450
451 auto fd = unique_fd{socket(PF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_AUDIT)};
452 if (!fd.ok()) {
453 return;
454 }
455
Bart Van Asscheaee2ec82022-12-02 18:48:15 -0800456 TEMP_FAILURE_RETRY(send(fd.get(), &request, sizeof(request), 0));
Tom Cherry8180b482019-08-26 13:57:51 -0700457}
458
Eric Biggers141c6a82023-08-11 21:05:14 +0000459int RestoreconIfExists(const char* path, unsigned int flags) {
460 if (access(path, F_OK) != 0 && errno == ENOENT) {
461 // Avoid error message for path that is expected to not always exist.
462 return 0;
463 }
464 return selinux_android_restorecon(path, flags);
465}
466
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800467} // namespace
468
Tom Cherryc3170092017-08-10 12:22:44 -0700469void SelinuxRestoreContext() {
470 LOG(INFO) << "Running restorecon...";
471 selinux_android_restorecon("/dev", 0);
Inseob Kim89d69132022-03-22 21:51:07 +0900472 selinux_android_restorecon("/dev/console", 0);
Tom Cherryc3170092017-08-10 12:22:44 -0700473 selinux_android_restorecon("/dev/kmsg", 0);
474 if constexpr (WORLD_WRITABLE_KMSG) {
475 selinux_android_restorecon("/dev/kmsg_debug", 0);
476 }
Tom Cherry81ae0752018-07-30 16:23:49 -0700477 selinux_android_restorecon("/dev/null", 0);
478 selinux_android_restorecon("/dev/ptmx", 0);
Tom Cherryc3170092017-08-10 12:22:44 -0700479 selinux_android_restorecon("/dev/socket", 0);
480 selinux_android_restorecon("/dev/random", 0);
481 selinux_android_restorecon("/dev/urandom", 0);
482 selinux_android_restorecon("/dev/__properties__", 0);
483
Tom Cherryc3170092017-08-10 12:22:44 -0700484 selinux_android_restorecon("/dev/block", SELINUX_ANDROID_RESTORECON_RECURSE);
David Anderson1ff75812020-11-13 00:31:47 -0800485 selinux_android_restorecon("/dev/dm-user", SELINUX_ANDROID_RESTORECON_RECURSE);
Tom Cherryc3170092017-08-10 12:22:44 -0700486 selinux_android_restorecon("/dev/device-mapper", 0);
Jiyong Park4ba548d2019-02-22 16:04:35 +0900487
Jooyung Hanebdd5bc2025-04-25 15:58:15 +0900488 if constexpr (com::android::apex::flags::mount_before_data()) {
489 selinux_android_restorecon("/dev/loop-control", 0);
490 }
491
Jiyong Park4ba548d2019-02-22 16:04:35 +0900492 selinux_android_restorecon("/apex", 0);
Jooyung Han566c6522023-08-09 07:05:31 +0000493 selinux_android_restorecon("/bootstrap-apex", 0);
Kiyoung Kim99df54b2019-11-22 16:14:10 +0900494 selinux_android_restorecon("/linkerconfig", 0);
Bowgo Tsai196cc582020-01-20 18:03:58 +0800495
David Andersonc991f342020-02-21 17:11:07 -0800496 // adb remount, snapshot-based updates, and DSUs all create files during
497 // first-stage init.
Eric Biggers141c6a82023-08-11 21:05:14 +0000498 RestoreconIfExists(SnapshotManager::GetGlobalRollbackIndicatorPath().c_str(), 0);
499 RestoreconIfExists("/metadata/gsi",
500 SELINUX_ANDROID_RESTORECON_RECURSE | SELINUX_ANDROID_RESTORECON_SKIP_SEHASH);
Tom Cherryc3170092017-08-10 12:22:44 -0700501}
502
Tom Cherry74069d12018-07-20 15:26:25 -0700503int SelinuxKlogCallback(int type, const char* fmt, ...) {
504 android::base::LogSeverity severity = android::base::ERROR;
505 if (type == SELINUX_WARNING) {
506 severity = android::base::WARNING;
507 } else if (type == SELINUX_INFO) {
508 severity = android::base::INFO;
509 }
Tom Cherry8180b482019-08-26 13:57:51 -0700510 char buf[kKlogMessageSize];
Tom Cherry74069d12018-07-20 15:26:25 -0700511 va_list ap;
512 va_start(ap, fmt);
Tom Cherry8180b482019-08-26 13:57:51 -0700513 int length_written = vsnprintf(buf, sizeof(buf), fmt, ap);
Tom Cherry74069d12018-07-20 15:26:25 -0700514 va_end(ap);
Tom Cherry8180b482019-08-26 13:57:51 -0700515 if (length_written <= 0) {
516 return 0;
517 }
Thiébaud Weksteenf03dde82023-04-03 16:53:12 +1000518
519 // libselinux log messages usually contain a new line character, while
520 // Android LOG() does not expect it. Remove it to avoid empty lines in
521 // the log buffers.
522 size_t str_len = strlen(buf);
523 if (buf[str_len - 1] == '\n') {
524 buf[str_len - 1] = '\0';
525 }
526
Tom Cherry8180b482019-08-26 13:57:51 -0700527 if (type == SELINUX_AVC) {
Thiébaud Weksteenf03dde82023-04-03 16:53:12 +1000528 SelinuxAvcLog(buf);
Tom Cherry8180b482019-08-26 13:57:51 -0700529 } else {
530 android::base::KernelLogger(android::base::MAIN, severity, "selinux", nullptr, 0, buf);
531 }
Tom Cherry74069d12018-07-20 15:26:25 -0700532 return 0;
533}
534
Tom Cherryc3170092017-08-10 12:22:44 -0700535void SelinuxSetupKernelLogging() {
536 selinux_callback cb;
Tom Cherry74069d12018-07-20 15:26:25 -0700537 cb.func_log = SelinuxKlogCallback;
Tom Cherryc3170092017-08-10 12:22:44 -0700538 selinux_set_callback(SELINUX_CB_LOG, cb);
539}
540
Tom Cherry40acb372018-08-01 13:41:12 -0700541int SelinuxGetVendorAndroidVersion() {
Nikita Ioffea66adf42023-06-26 14:55:31 +0100542 if (IsMicrodroid()) {
543 // As of now Microdroid doesn't have any vendor code.
544 return __ANDROID_API_FUTURE__;
545 }
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700546 static int vendor_android_version = [] {
547 if (!IsSplitPolicyDevice()) {
548 // If this device does not split sepolicy files, it's not a Treble device and therefore,
549 // we assume it's always on the latest platform.
550 return __ANDROID_API_FUTURE__;
551 }
Logan Chien837b2a42018-05-03 14:33:52 +0800552
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700553 std::string version;
554 if (!GetVendorMappingVersion(&version)) {
555 LOG(FATAL) << "Could not read vendor SELinux version";
556 }
Logan Chien837b2a42018-05-03 14:33:52 +0800557
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700558 int major_version;
559 std::string major_version_str(version, 0, version.find('.'));
560 if (!ParseInt(major_version_str, &major_version)) {
561 PLOG(FATAL) << "Failed to parse the vendor sepolicy major version "
562 << major_version_str;
563 }
Logan Chien837b2a42018-05-03 14:33:52 +0800564
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700565 return major_version;
566 }();
567 return vendor_android_version;
Logan Chien837b2a42018-05-03 14:33:52 +0800568}
569
David Andersond0ce5302020-03-20 21:47:10 -0700570// This is for R system.img/system_ext.img to work on old vendor.img as system_ext.img
571// is introduced in R. We mount system_ext in second stage init because the first-stage
572// init in boot.img won't be updated in the system-only OTA scenario.
573void MountMissingSystemPartitions() {
574 android::fs_mgr::Fstab fstab;
575 if (!ReadDefaultFstab(&fstab)) {
576 LOG(ERROR) << "Could not read default fstab";
577 }
578
579 android::fs_mgr::Fstab mounts;
580 if (!ReadFstabFromFile("/proc/mounts", &mounts)) {
581 LOG(ERROR) << "Could not read /proc/mounts";
582 }
583
Frederick Mayle5e4d4a12025-04-09 16:42:32 -0700584 [[clang::no_destroy]] static const std::vector<std::string> kPartitionNames = {"system_ext",
585 "product"};
David Andersond0ce5302020-03-20 21:47:10 -0700586
587 android::fs_mgr::Fstab extra_fstab;
588 for (const auto& name : kPartitionNames) {
589 if (GetEntryForMountPoint(&mounts, "/"s + name)) {
590 // The partition is already mounted.
591 continue;
592 }
593
Lianjun Huangccd094c2023-02-17 20:22:37 +0800594 auto system_entries = GetEntriesForMountPoint(&fstab, "/system");
595 for (auto& system_entry : system_entries) {
596 if (!system_entry) {
597 LOG(ERROR) << "Could not find mount entry for /system";
598 break;
599 }
600 if (!system_entry->fs_mgr_flags.logical) {
601 LOG(INFO) << "Skipping mount of " << name << ", system is not dynamic.";
602 break;
603 }
David Andersond0ce5302020-03-20 21:47:10 -0700604
Lianjun Huangccd094c2023-02-17 20:22:37 +0800605 auto entry = *system_entry;
606 auto partition_name = name + fs_mgr_get_slot_suffix();
607 auto replace_name = "system"s + fs_mgr_get_slot_suffix();
David Andersond0ce5302020-03-20 21:47:10 -0700608
Lianjun Huangccd094c2023-02-17 20:22:37 +0800609 entry.mount_point = "/"s + name;
610 entry.blk_device =
David Andersond0ce5302020-03-20 21:47:10 -0700611 android::base::StringReplace(entry.blk_device, replace_name, partition_name, false);
Lianjun Huangccd094c2023-02-17 20:22:37 +0800612 if (!fs_mgr_update_logical_partition(&entry)) {
613 LOG(ERROR) << "Could not update logical partition";
614 continue;
615 }
David Andersond0ce5302020-03-20 21:47:10 -0700616
Lianjun Huangccd094c2023-02-17 20:22:37 +0800617 extra_fstab.emplace_back(std::move(entry));
618 }
David Andersond0ce5302020-03-20 21:47:10 -0700619 }
620
Yi-Yo Chiang20579012021-04-01 20:14:54 +0800621 SkipMountingPartitions(&extra_fstab, true /* verbose */);
David Andersond0ce5302020-03-20 21:47:10 -0700622 if (extra_fstab.empty()) {
623 return;
624 }
625
626 BlockDevInitializer block_dev_init;
627 for (auto& entry : extra_fstab) {
628 if (access(entry.blk_device.c_str(), F_OK) != 0) {
629 auto block_dev = android::base::Basename(entry.blk_device);
630 if (!block_dev_init.InitDmDevice(block_dev)) {
631 LOG(ERROR) << "Failed to find device-mapper node: " << block_dev;
632 continue;
633 }
634 }
635 if (fs_mgr_do_mount_one(entry)) {
636 LOG(ERROR) << "Could not mount " << entry.mount_point;
637 }
638 }
639}
640
David Anderson491e4da2020-12-08 00:21:20 -0800641static void LoadSelinuxPolicy(std::string& policy) {
642 LOG(INFO) << "Loading SELinux policy";
643
644 set_selinuxmnt("/sys/fs/selinux");
645 if (security_load_policy(policy.data(), policy.size()) < 0) {
646 PLOG(FATAL) << "SELinux: Could not load policy";
647 }
648}
649
Nikita Ioffea66adf42023-06-26 14:55:31 +0100650// Encapsulates steps to load SELinux policy in Microdroid.
651// So far the process is very straightforward - just load the precompiled policy from /system.
652void LoadSelinuxPolicyMicrodroid() {
653 constexpr const char kMicrodroidPrecompiledSepolicy[] =
654 "/system/etc/selinux/microdroid_precompiled_sepolicy";
655
656 LOG(INFO) << "Opening SELinux policy from " << kMicrodroidPrecompiledSepolicy;
657 unique_fd policy_fd(open(kMicrodroidPrecompiledSepolicy, O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
658 if (policy_fd < 0) {
659 PLOG(FATAL) << "Failed to open " << kMicrodroidPrecompiledSepolicy;
660 }
661
662 std::string policy;
663 if (!android::base::ReadFdToString(policy_fd, &policy)) {
664 PLOG(FATAL) << "Failed to read policy file: " << kMicrodroidPrecompiledSepolicy;
665 }
666
667 LoadSelinuxPolicy(policy);
668}
669
David Anderson491e4da2020-12-08 00:21:20 -0800670// The SELinux setup process is carefully orchestrated around snapuserd. Policy
671// must be loaded off dynamic partitions, and during an OTA, those partitions
672// cannot be read without snapuserd. But, with kernel-privileged snapuserd
673// running, loading the policy will immediately trigger audits.
674//
675// We use a five-step process to address this:
676// (1) Read the policy into a string, with snapuserd running.
677// (2) Rewrite the snapshot device-mapper tables, to generate new dm-user
678// devices and to flush I/O.
679// (3) Kill snapuserd, which no longer has any dm-user devices to attach to.
680// (4) Load the sepolicy and issue critical restorecons in /dev, carefully
681// avoiding anything that would read from /system.
682// (5) Re-launch snapuserd and attach it to the dm-user devices from step (2).
683//
684// After this sequence, it is safe to enable enforcing mode and continue booting.
Nikita Ioffea66adf42023-06-26 14:55:31 +0100685void LoadSelinuxPolicyAndroid() {
David Andersond0ce5302020-03-20 21:47:10 -0700686 MountMissingSystemPartitions();
687
David Anderson491e4da2020-12-08 00:21:20 -0800688 LOG(INFO) << "Opening SELinux policy";
689
690 // Read the policy before potentially killing snapuserd.
691 std::string policy;
692 ReadPolicy(&policy);
693
694 auto snapuserd_helper = SnapuserdSelinuxHelper::CreateIfNeeded();
695 if (snapuserd_helper) {
Nikita Ioffea66adf42023-06-26 14:55:31 +0100696 // Kill the old snapused to avoid audit messages. After this we cannot read from /system
697 // (or other dynamic partitions) until we call FinishTransition().
David Anderson491e4da2020-12-08 00:21:20 -0800698 snapuserd_helper->StartTransition();
699 }
700
701 LoadSelinuxPolicy(policy);
702
703 if (snapuserd_helper) {
704 // Before enforcing, finish the pending snapuserd transition.
705 snapuserd_helper->FinishTransition();
706 snapuserd_helper = nullptr;
707 }
Nikita Ioffea66adf42023-06-26 14:55:31 +0100708}
709
Paul Lawrence6bb52892025-01-29 19:43:48 -0800710#ifdef ALLOW_REMOUNT_OVERLAYS
Paul Lawrence7e2b0cd2025-03-05 09:55:25 -0800711bool EarlySetupOverlays() {
Paul Lawrence6bb52892025-01-29 19:43:48 -0800712 bool has_overlays = false;
713 std::string contents;
714 auto result = android::base::ReadFileToString("/proc/mounts", &contents, true);
715
716 auto lines = android::base::Split(contents, "\n");
717 for (auto const& line : lines)
718 if (android::base::StartsWith(line, "overlay")) {
719 has_overlays = true;
720 break;
721 }
722
Paul Lawrence7e2b0cd2025-03-05 09:55:25 -0800723 if (!has_overlays) return false;
724 if (mount("tmpfs", kSecondStageRes, "tmpfs", MS_REMOUNT | MS_NOSUID | MS_NODEV,
725 "mode=0755,uid=0,gid=0") == -1) {
726 PLOG(FATAL) << "Failed to remount tmpfs on " << kSecondStageRes << " to remove NO_EXEC";
727 }
Paul Lawrence6bb52892025-01-29 19:43:48 -0800728
Paul Lawrence7e2b0cd2025-03-05 09:55:25 -0800729 return true;
730}
731
732void SetupOverlays() {
Paul Lawrence6bb52892025-01-29 19:43:48 -0800733 // After adb remount, we mount all r/o volumes with overlayfs to allow writing.
734 // However, since overlayfs performs its file operations in the context of the
735 // mounting process, this will not work as is - init is in the kernel domain in
736 // first stage, which has very limited permissions.
737
738 // In order to fix this, we need to unmount remount all these volumes from a process
739 // with sufficient privileges to be able to perform these operations. The
740 // overlay_remounter domain has those privileges on debuggable devices.
741 // We will call overlay_remounter which will do the unmounts/mounts.
742 // But for that to work, the volumes must not be busy, so we need to copy
743 // overlay_remounter from system to a ramdisk and run it from there.
Paul Lawrence6bb52892025-01-29 19:43:48 -0800744 const char* kOverlayRemounter = "overlay_remounter";
745 auto or_src = std::filesystem::path("/system/xbin/") / kOverlayRemounter;
746 auto or_dest = std::filesystem::path(kSecondStageRes) / kOverlayRemounter;
747 std::error_code ec;
748 std::filesystem::copy(or_src, or_dest, ec);
749 if (ec) {
750 LOG(FATAL) << "Failed to copy " << or_src << " to " << or_dest << " " << ec.message();
751 }
752
753 if (selinux_android_restorecon(or_dest.c_str(), 0) == -1) {
754 PLOG(FATAL) << "restorecon of " << or_dest << " failed";
755 }
756 auto dest = unique_fd(open(or_dest.c_str(), O_RDONLY | O_CLOEXEC));
757 if (dest.get() == -1) {
758 PLOG(FATAL) << "Failed to reopen " << or_dest;
759 }
760 if (unlink(or_dest.c_str()) == -1) {
761 PLOG(FATAL) << "Failed to unlink " << or_dest;
762 }
763 const char* args[] = {or_dest.c_str(), nullptr};
Paul Lawrence7bcc1892025-02-21 06:31:48 -0800764 fexecve(dest.get(), const_cast<char**>(args), environ);
Paul Lawrence6bb52892025-01-29 19:43:48 -0800765
766 // execv() only returns if an error happened, in which case we
767 // panic and never return from this function.
768 PLOG(FATAL) << "execv(\"" << or_dest << "\") failed";
769}
770#else
Paul Lawrence7e2b0cd2025-03-05 09:55:25 -0800771bool EarlySetupOverlays() {
772 return false;
773}
Paul Lawrence6bb52892025-01-29 19:43:48 -0800774void SetupOverlays() {}
775#endif
776
Nikita Ioffea66adf42023-06-26 14:55:31 +0100777int SetupSelinux(char** argv) {
778 SetStdioToDevNull(argv);
779 InitKernelLogging(argv);
780
781 if (REBOOT_BOOTLOADER_ON_PANIC) {
782 InstallRebootSignalHandlers();
783 }
784
785 boot_clock::time_point start_time = boot_clock::now();
786
787 SelinuxSetupKernelLogging();
788
Paul Lawrence7e2b0cd2025-03-05 09:55:25 -0800789 // Test to see if we should use overlays, and if so remount tmpfs before selinux will block
790 bool use_overlays = EarlySetupOverlays();
791
Nikita Ioffea66adf42023-06-26 14:55:31 +0100792 // TODO(b/287206497): refactor into different headers to only include what we need.
793 if (IsMicrodroid()) {
794 LoadSelinuxPolicyMicrodroid();
795 } else {
796 LoadSelinuxPolicyAndroid();
797 }
Jeffrey Vander Stoepbaeece62022-02-08 12:42:33 +0000798
David Anderson491e4da2020-12-08 00:21:20 -0800799 SelinuxSetEnforcement();
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800800
Nikita Ioffefeb7e0e2024-03-28 00:32:36 +0000801 if (IsMicrodroid() && android::virtualization::IsOpenDiceChangesFlagEnabled()) {
802 // We run restorecon of /microdroid_resources while we are still in kernel context to avoid
803 // granting init `tmpfs:file relabelfrom` capability.
804 const int flags = SELINUX_ANDROID_RESTORECON_RECURSE;
805 if (selinux_android_restorecon("/microdroid_resources", flags) == -1) {
806 PLOG(FATAL) << "restorecon of /microdroid_resources failed";
807 }
808 }
809
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800810 // We're in the kernel domain and want to transition to the init domain. File systems that
811 // store SELabels in their xattrs, such as ext4 do not need an explicit restorecon here,
812 // but other file systems do. In particular, this is needed for ramdisks such as the
813 // recovery image for A/B devices.
814 if (selinux_android_restorecon("/system/bin/init", 0) == -1) {
815 PLOG(FATAL) << "restorecon failed of /system/bin/init failed";
816 }
817
Mark Salyzyn44505ec2019-05-08 12:44:50 -0700818 setenv(kEnvSelinuxStartedAt, std::to_string(start_time.time_since_epoch().count()).c_str(), 1);
Mark Salyzyn10377df2019-03-27 08:10:41 -0700819
Paul Lawrence6bb52892025-01-29 19:43:48 -0800820 // SetupOverlays does not return if overlays exist, instead it execs overlay_remounter
821 // which then execs second stage init
Paul Lawrence7e2b0cd2025-03-05 09:55:25 -0800822 if (use_overlays) SetupOverlays();
Paul Lawrence6bb52892025-01-29 19:43:48 -0800823
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800824 const char* path = "/system/bin/init";
825 const char* args[] = {path, "second_stage", nullptr};
826 execv(path, const_cast<char**>(args));
827
828 // execv() only returns if an error happened, in which case we
829 // panic and never return from this function.
830 PLOG(FATAL) << "execv(\"" << path << "\") failed";
831
832 return 1;
833}
834
Tom Cherryc3170092017-08-10 12:22:44 -0700835} // namespace init
836} // namespace android