blob: 6316b4deb3b5c6f9c21e38b23c69cc2258e8c1ec [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>
59#include <sys/wait.h>
60#include <unistd.h>
61
62#include <android-base/chrono_utils.h>
63#include <android-base/file.h>
64#include <android-base/logging.h>
Logan Chien837b2a42018-05-03 14:33:52 +080065#include <android-base/parseint.h>
Inseob Kimd99d9772021-03-11 17:58:26 +090066#include <android-base/result.h>
David Andersond0ce5302020-03-20 21:47:10 -070067#include <android-base/strings.h>
Tom Cherryc3170092017-08-10 12:22:44 -070068#include <android-base/unique_fd.h>
Nikita Ioffefeb7e0e2024-03-28 00:32:36 +000069#include <android/avf_cc_flags.h>
Bowgo Tsai1dacd422019-03-04 17:53:34 +080070#include <fs_avb/fs_avb.h>
David Andersond0ce5302020-03-20 21:47:10 -070071#include <fs_mgr.h>
Inseob Kime2efde32024-11-20 17:56:20 +090072#include <genfslabelsversion.h>
Bowgo Tsai196cc582020-01-20 18:03:58 +080073#include <libgsi/libgsi.h>
Yifan Hongd91998f2020-02-20 17:54:57 -080074#include <libsnapshot/snapshot.h>
Tom Cherryc3170092017-08-10 12:22:44 -070075#include <selinux/android.h>
76
David Andersond0ce5302020-03-20 21:47:10 -070077#include "block_dev_initializer.h"
Bowgo Tsai30afda72019-04-11 23:57:24 +080078#include "debug_ramdisk.h"
Tom Cherry7bfea3d2018-11-06 14:12:05 -080079#include "reboot_utils.h"
David Anderson491e4da2020-12-08 00:21:20 -080080#include "snapuserd_transition.h"
Tom Cherryc3170092017-08-10 12:22:44 -070081#include "util.h"
82
Bowgo Tsai1dacd422019-03-04 17:53:34 +080083using namespace std::string_literals;
84
Logan Chien837b2a42018-05-03 14:33:52 +080085using android::base::ParseInt;
Tom Cherryc3170092017-08-10 12:22:44 -070086using android::base::Timer;
87using android::base::unique_fd;
Bowgo Tsai1dacd422019-03-04 17:53:34 +080088using android::fs_mgr::AvbHandle;
Yifan Hongd91998f2020-02-20 17:54:57 -080089using android::snapshot::SnapshotManager;
Tom Cherryc3170092017-08-10 12:22:44 -070090
91namespace android {
92namespace init {
93
Tom Cherryc3170092017-08-10 12:22:44 -070094namespace {
95
96enum EnforcingStatus { SELINUX_PERMISSIVE, SELINUX_ENFORCING };
97
Alistair Delva63594a42021-03-09 11:04:23 -080098EnforcingStatus StatusFromProperty() {
Yi-Yo Chiangda5323e2023-08-02 01:08:23 +080099 std::string value;
100 if (android::fs_mgr::GetKernelCmdline("androidboot.selinux", &value) && value == "permissive") {
101 return SELINUX_PERMISSIVE;
Alistair Delva63594a42021-03-09 11:04:23 -0800102 }
Yi-Yo Chiangda5323e2023-08-02 01:08:23 +0800103 if (android::fs_mgr::GetBootconfig("androidboot.selinux", &value) && value == "permissive") {
104 return SELINUX_PERMISSIVE;
105 }
106 return SELINUX_ENFORCING;
Tom Cherryc3170092017-08-10 12:22:44 -0700107}
108
109bool IsEnforcing() {
110 if (ALLOW_PERMISSIVE_SELINUX) {
Alistair Delva63594a42021-03-09 11:04:23 -0800111 return StatusFromProperty() == SELINUX_ENFORCING;
Tom Cherryc3170092017-08-10 12:22:44 -0700112 }
113 return true;
114}
115
Tom Cherryc3170092017-08-10 12:22:44 -0700116bool ReadFirstLine(const char* file, std::string* line) {
117 line->clear();
118
119 std::string contents;
120 if (!android::base::ReadFileToString(file, &contents, true /* follow symlinks */)) {
121 return false;
122 }
123 std::istringstream in(contents);
124 std::getline(in, *line);
125 return true;
126}
127
Inseob Kimd99d9772021-03-11 17:58:26 +0900128Result<std::string> FindPrecompiledSplitPolicy() {
129 std::string precompiled_sepolicy;
kaichieheef4cd72017-08-31 22:07:19 +0800130 // If there is an odm partition, precompiled_sepolicy will be in
131 // odm/etc/selinux. Otherwise it will be in vendor/etc/selinux.
132 static constexpr const char vendor_precompiled_sepolicy[] =
Sandro1120f7f2022-09-05 15:56:38 +0000133 "/vendor/etc/selinux/precompiled_sepolicy";
kaichieheef4cd72017-08-31 22:07:19 +0800134 static constexpr const char odm_precompiled_sepolicy[] =
Sandro1120f7f2022-09-05 15:56:38 +0000135 "/odm/etc/selinux/precompiled_sepolicy";
kaichieheef4cd72017-08-31 22:07:19 +0800136 if (access(odm_precompiled_sepolicy, R_OK) == 0) {
Inseob Kimd99d9772021-03-11 17:58:26 +0900137 precompiled_sepolicy = odm_precompiled_sepolicy;
kaichieheef4cd72017-08-31 22:07:19 +0800138 } else if (access(vendor_precompiled_sepolicy, R_OK) == 0) {
Inseob Kimd99d9772021-03-11 17:58:26 +0900139 precompiled_sepolicy = vendor_precompiled_sepolicy;
kaichieheef4cd72017-08-31 22:07:19 +0800140 } else {
Inseob Kimd99d9772021-03-11 17:58:26 +0900141 return ErrnoError() << "No precompiled sepolicy at " << vendor_precompiled_sepolicy;
Tom Cherryc3170092017-08-10 12:22:44 -0700142 }
kaichieheef4cd72017-08-31 22:07:19 +0800143
Inseob Kimd99d9772021-03-11 17:58:26 +0900144 // Use precompiled sepolicy only when all corresponding hashes are equal.
Inseob Kimd99d9772021-03-11 17:58:26 +0900145 std::vector<std::pair<std::string, std::string>> sepolicy_hashes{
146 {"/system/etc/selinux/plat_sepolicy_and_mapping.sha256",
147 precompiled_sepolicy + ".plat_sepolicy_and_mapping.sha256"},
Inseob Kim28fdb672021-04-29 19:48:27 +0900148 {"/system_ext/etc/selinux/system_ext_sepolicy_and_mapping.sha256",
149 precompiled_sepolicy + ".system_ext_sepolicy_and_mapping.sha256"},
150 {"/product/etc/selinux/product_sepolicy_and_mapping.sha256",
151 precompiled_sepolicy + ".product_sepolicy_and_mapping.sha256"},
Inseob Kimd99d9772021-03-11 17:58:26 +0900152 };
153
Inseob Kimd99d9772021-03-11 17:58:26 +0900154 for (const auto& [actual_id_path, precompiled_id_path] : sepolicy_hashes) {
Inseob Kim28fdb672021-04-29 19:48:27 +0900155 // Both of them should exist or both of them shouldn't exist.
156 if (access(actual_id_path.c_str(), R_OK) != 0) {
157 if (access(precompiled_id_path.c_str(), R_OK) == 0) {
158 return Error() << precompiled_id_path << " exists but " << actual_id_path
159 << " doesn't";
160 }
161 continue;
162 }
163
Inseob Kimd99d9772021-03-11 17:58:26 +0900164 std::string actual_id;
165 if (!ReadFirstLine(actual_id_path.c_str(), &actual_id)) {
166 return ErrnoError() << "Failed to read " << actual_id_path;
167 }
168
169 std::string precompiled_id;
170 if (!ReadFirstLine(precompiled_id_path.c_str(), &precompiled_id)) {
171 return ErrnoError() << "Failed to read " << precompiled_id_path;
172 }
173
174 if (actual_id.empty() || actual_id != precompiled_id) {
175 return Error() << actual_id_path << " and " << precompiled_id_path << " differ";
176 }
Tri Voc8137f92019-01-22 18:22:25 -0800177 }
Inseob Kimd99d9772021-03-11 17:58:26 +0900178
179 return precompiled_sepolicy;
Tom Cherryc3170092017-08-10 12:22:44 -0700180}
181
182bool GetVendorMappingVersion(std::string* plat_vers) {
183 if (!ReadFirstLine("/vendor/etc/selinux/plat_sepolicy_vers.txt", plat_vers)) {
184 PLOG(ERROR) << "Failed to read /vendor/etc/selinux/plat_sepolicy_vers.txt";
185 return false;
186 }
187 if (plat_vers->empty()) {
188 LOG(ERROR) << "No version present in plat_sepolicy_vers.txt";
189 return false;
190 }
191 return true;
192}
193
194constexpr const char plat_policy_cil_file[] = "/system/etc/selinux/plat_sepolicy.cil";
195
196bool IsSplitPolicyDevice() {
197 return access(plat_policy_cil_file, R_OK) != -1;
198}
199
Yi-Yo Chiangbb77c542021-09-23 14:14:16 +0000200std::optional<const char*> GetUserdebugPlatformPolicyFile() {
201 // See if we need to load userdebug_plat_sepolicy.cil instead of plat_sepolicy.cil.
202 const char* force_debuggable_env = getenv("INIT_FORCE_DEBUGGABLE");
203 if (force_debuggable_env && "true"s == force_debuggable_env && AvbHandle::IsDeviceUnlocked()) {
204 const std::vector<const char*> debug_policy_candidates = {
205#if INSTALL_DEBUG_POLICY_TO_SYSTEM_EXT == 1
206 "/system_ext/etc/selinux/userdebug_plat_sepolicy.cil",
207#endif
208 kDebugRamdiskSEPolicy,
209 };
210 for (const char* debug_policy : debug_policy_candidates) {
211 if (access(debug_policy, F_OK) == 0) {
212 return debug_policy;
213 }
214 }
215 }
216 return std::nullopt;
217}
218
David Anderson491e4da2020-12-08 00:21:20 -0800219struct PolicyFile {
220 unique_fd fd;
221 std::string path;
222};
223
224bool OpenSplitPolicy(PolicyFile* policy_file) {
Jeff Vander Stoep5effda42021-11-05 09:03:11 +0100225 // IMPLEMENTATION NOTE: Split policy consists of three or more CIL files:
Tom Cherryc3170092017-08-10 12:22:44 -0700226 // * platform -- policy needed due to logic contained in the system image,
Jeff Vander Stoep5effda42021-11-05 09:03:11 +0100227 // * vendor -- policy needed due to logic contained in the vendor image,
Tom Cherryc3170092017-08-10 12:22:44 -0700228 // * mapping -- mapping policy which helps preserve forward-compatibility of non-platform policy
229 // with newer versions of platform policy.
Thiébaud Weksteen50f03fd2023-09-06 10:52:49 +1000230 // * (optional) policy needed due to logic on product, system_ext, or odm images.
Tom Cherryc3170092017-08-10 12:22:44 -0700231 // secilc is invoked to compile the above three policy files into a single monolithic policy
232 // file. This file is then loaded into the kernel.
233
Yi-Yo Chiangbb77c542021-09-23 14:14:16 +0000234 const auto userdebug_plat_sepolicy = GetUserdebugPlatformPolicyFile();
235 const bool use_userdebug_policy = userdebug_plat_sepolicy.has_value();
Bowgo Tsai1dacd422019-03-04 17:53:34 +0800236 if (use_userdebug_policy) {
Yi-Yo Chiangbb77c542021-09-23 14:14:16 +0000237 LOG(INFO) << "Using userdebug system sepolicy " << *userdebug_plat_sepolicy;
Bowgo Tsai1dacd422019-03-04 17:53:34 +0800238 }
239
Tom Cherryc3170092017-08-10 12:22:44 -0700240 // Load precompiled policy from vendor image, if a matching policy is found there. The policy
241 // must match the platform policy on the system image.
Bowgo Tsai1dacd422019-03-04 17:53:34 +0800242 // use_userdebug_policy requires compiling sepolicy with userdebug_plat_sepolicy.cil.
243 // Thus it cannot use the precompiled policy from vendor image.
Inseob Kimd99d9772021-03-11 17:58:26 +0900244 if (!use_userdebug_policy) {
245 if (auto res = FindPrecompiledSplitPolicy(); res.ok()) {
246 unique_fd fd(open(res->c_str(), O_RDONLY | O_CLOEXEC | O_BINARY));
247 if (fd != -1) {
248 policy_file->fd = std::move(fd);
249 policy_file->path = std::move(*res);
250 return true;
251 }
252 } else {
253 LOG(INFO) << res.error();
Tom Cherryc3170092017-08-10 12:22:44 -0700254 }
255 }
256 // No suitable precompiled policy could be loaded
257
258 LOG(INFO) << "Compiling SELinux policy";
259
Tom Cherryc3170092017-08-10 12:22:44 -0700260 // We store the output of the compilation on /dev because this is the most convenient tmpfs
261 // storage mount available this early in the boot sequence.
262 char compiled_sepolicy[] = "/dev/sepolicy.XXXXXX";
263 unique_fd compiled_sepolicy_fd(mkostemp(compiled_sepolicy, O_CLOEXEC));
264 if (compiled_sepolicy_fd < 0) {
265 PLOG(ERROR) << "Failed to create temporary file " << compiled_sepolicy;
266 return false;
267 }
268
269 // Determine which mapping file to include
270 std::string vend_plat_vers;
271 if (!GetVendorMappingVersion(&vend_plat_vers)) {
272 return false;
273 }
Tri Vo503f1852019-01-16 11:57:19 -0800274 std::string plat_mapping_file("/system/etc/selinux/mapping/" + vend_plat_vers + ".cil");
kaichieheef4cd72017-08-31 22:07:19 +0800275
Jeff Vander Stoep0ac51cf2019-05-02 14:05:18 -0700276 std::string plat_compat_cil_file("/system/etc/selinux/mapping/" + vend_plat_vers +
277 ".compat.cil");
278 if (access(plat_compat_cil_file.c_str(), F_OK) == -1) {
279 plat_compat_cil_file.clear();
280 }
281
Bowgo Tsaif016f252019-08-28 17:56:51 +0800282 std::string system_ext_policy_cil_file("/system_ext/etc/selinux/system_ext_sepolicy.cil");
283 if (access(system_ext_policy_cil_file.c_str(), F_OK) == -1) {
284 system_ext_policy_cil_file.clear();
285 }
286
287 std::string system_ext_mapping_file("/system_ext/etc/selinux/mapping/" + vend_plat_vers +
288 ".cil");
289 if (access(system_ext_mapping_file.c_str(), F_OK) == -1) {
290 system_ext_mapping_file.clear();
291 }
292
Yi-Yo Chiang731d2472021-03-23 22:11:13 +0800293 std::string system_ext_compat_cil_file("/system_ext/etc/selinux/mapping/" + vend_plat_vers +
294 ".compat.cil");
295 if (access(system_ext_compat_cil_file.c_str(), F_OK) == -1) {
296 system_ext_compat_cil_file.clear();
297 }
298
Tri Vod3518cf2018-12-14 14:25:08 -0800299 std::string product_policy_cil_file("/product/etc/selinux/product_sepolicy.cil");
300 if (access(product_policy_cil_file.c_str(), F_OK) == -1) {
301 product_policy_cil_file.clear();
302 }
303
Tri Vo503f1852019-01-16 11:57:19 -0800304 std::string product_mapping_file("/product/etc/selinux/mapping/" + vend_plat_vers + ".cil");
305 if (access(product_mapping_file.c_str(), F_OK) == -1) {
306 product_mapping_file.clear();
307 }
308
kaichieheef4cd72017-08-31 22:07:19 +0800309 std::string vendor_policy_cil_file("/vendor/etc/selinux/vendor_sepolicy.cil");
kaichieheef4cd72017-08-31 22:07:19 +0800310 if (access(vendor_policy_cil_file.c_str(), F_OK) == -1) {
Jeff Vander Stoep5effda42021-11-05 09:03:11 +0100311 LOG(ERROR) << "Missing " << vendor_policy_cil_file;
312 return false;
313 }
314
315 std::string plat_pub_versioned_cil_file("/vendor/etc/selinux/plat_pub_versioned.cil");
316 if (access(plat_pub_versioned_cil_file.c_str(), F_OK) == -1) {
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800317 LOG(ERROR) << "Missing " << plat_pub_versioned_cil_file;
kaichieheef4cd72017-08-31 22:07:19 +0800318 return false;
319 }
320
321 // odm_sepolicy.cil is default but optional.
322 std::string odm_policy_cil_file("/odm/etc/selinux/odm_sepolicy.cil");
323 if (access(odm_policy_cil_file.c_str(), F_OK) == -1) {
324 odm_policy_cil_file.clear();
325 }
Jeff Vander Stoep724eda52019-02-15 12:13:38 -0800326 const std::string version_as_string = std::to_string(SEPOLICY_VERSION);
Andreas Huberc41b8382017-08-18 14:43:52 -0700327
Inseob Kim76afb4a2024-11-06 17:07:04 +0900328 std::vector<std::string> genfs_cil_files;
329
Inseob Kime2efde32024-11-20 17:56:20 +0900330 int vendor_genfs_version = get_genfs_labels_version();
Inseob Kim76afb4a2024-11-06 17:07:04 +0900331 std::string genfs_cil_file =
332 std::format("/system/etc/selinux/plat_sepolicy_genfs_{}.cil", vendor_genfs_version);
333 if (access(genfs_cil_file.c_str(), F_OK) != 0) {
Inseob Kime2efde32024-11-20 17:56:20 +0900334 LOG(INFO) << "Missing " << genfs_cil_file << "; skipping";
Inseob Kim76afb4a2024-11-06 17:07:04 +0900335 genfs_cil_file.clear();
Inseob Kime2efde32024-11-20 17:56:20 +0900336 } else {
337 LOG(INFO) << "Using " << genfs_cil_file << " for genfs labels";
Inseob Kim76afb4a2024-11-06 17:07:04 +0900338 }
339
Tom Cherryc3170092017-08-10 12:22:44 -0700340 // clang-format off
kaichieheef4cd72017-08-31 22:07:19 +0800341 std::vector<const char*> compile_args {
Tom Cherryc3170092017-08-10 12:22:44 -0700342 "/system/bin/secilc",
Yi-Yo Chiangbb77c542021-09-23 14:14:16 +0000343 use_userdebug_policy ? *userdebug_plat_sepolicy : plat_policy_cil_file,
Jeff Vander Stoep5e9ba3c2017-10-06 17:03:45 -0700344 "-m", "-M", "true", "-G", "-N",
Andreas Huberc41b8382017-08-18 14:43:52 -0700345 "-c", version_as_string.c_str(),
Tri Vo503f1852019-01-16 11:57:19 -0800346 plat_mapping_file.c_str(),
Tom Cherryc3170092017-08-10 12:22:44 -0700347 "-o", compiled_sepolicy,
348 // We don't care about file_contexts output by the compiler
349 "-f", "/sys/fs/selinux/null", // /dev/null is not yet available
kaichieheef4cd72017-08-31 22:07:19 +0800350 };
Tom Cherryc3170092017-08-10 12:22:44 -0700351 // clang-format on
352
Jeff Vander Stoep0ac51cf2019-05-02 14:05:18 -0700353 if (!plat_compat_cil_file.empty()) {
354 compile_args.push_back(plat_compat_cil_file.c_str());
355 }
Bowgo Tsaif016f252019-08-28 17:56:51 +0800356 if (!system_ext_policy_cil_file.empty()) {
357 compile_args.push_back(system_ext_policy_cil_file.c_str());
358 }
359 if (!system_ext_mapping_file.empty()) {
360 compile_args.push_back(system_ext_mapping_file.c_str());
361 }
Yi-Yo Chiang731d2472021-03-23 22:11:13 +0800362 if (!system_ext_compat_cil_file.empty()) {
363 compile_args.push_back(system_ext_compat_cil_file.c_str());
364 }
Tri Vod3518cf2018-12-14 14:25:08 -0800365 if (!product_policy_cil_file.empty()) {
366 compile_args.push_back(product_policy_cil_file.c_str());
367 }
Tri Vo503f1852019-01-16 11:57:19 -0800368 if (!product_mapping_file.empty()) {
369 compile_args.push_back(product_mapping_file.c_str());
370 }
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800371 if (!plat_pub_versioned_cil_file.empty()) {
372 compile_args.push_back(plat_pub_versioned_cil_file.c_str());
kaichieheef4cd72017-08-31 22:07:19 +0800373 }
374 if (!vendor_policy_cil_file.empty()) {
375 compile_args.push_back(vendor_policy_cil_file.c_str());
376 }
377 if (!odm_policy_cil_file.empty()) {
378 compile_args.push_back(odm_policy_cil_file.c_str());
379 }
Inseob Kim76afb4a2024-11-06 17:07:04 +0900380 if (!genfs_cil_file.empty()) {
381 compile_args.push_back(genfs_cil_file.c_str());
382 }
kaichieheef4cd72017-08-31 22:07:19 +0800383 compile_args.push_back(nullptr);
384
385 if (!ForkExecveAndWaitForCompletion(compile_args[0], (char**)compile_args.data())) {
Tom Cherryc3170092017-08-10 12:22:44 -0700386 unlink(compiled_sepolicy);
387 return false;
388 }
389 unlink(compiled_sepolicy);
390
David Anderson491e4da2020-12-08 00:21:20 -0800391 policy_file->fd = std::move(compiled_sepolicy_fd);
392 policy_file->path = compiled_sepolicy;
Tom Cherryc3170092017-08-10 12:22:44 -0700393 return true;
394}
395
David Anderson491e4da2020-12-08 00:21:20 -0800396bool OpenMonolithicPolicy(PolicyFile* policy_file) {
397 static constexpr char kSepolicyFile[] = "/sepolicy";
398
Nikita Ioffea66adf42023-06-26 14:55:31 +0100399 LOG(INFO) << "Opening SELinux policy from monolithic file " << kSepolicyFile;
400 policy_file->fd.reset(open(kSepolicyFile, O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
David Anderson491e4da2020-12-08 00:21:20 -0800401 if (policy_file->fd < 0) {
402 PLOG(ERROR) << "Failed to open monolithic SELinux policy";
Tom Cherryc3170092017-08-10 12:22:44 -0700403 return false;
404 }
Nikita Ioffea66adf42023-06-26 14:55:31 +0100405 policy_file->path = kSepolicyFile;
Tom Cherryc3170092017-08-10 12:22:44 -0700406 return true;
407}
408
David Anderson491e4da2020-12-08 00:21:20 -0800409void ReadPolicy(std::string* policy) {
410 PolicyFile policy_file;
Tom Cherryc3170092017-08-10 12:22:44 -0700411
David Anderson491e4da2020-12-08 00:21:20 -0800412 bool ok = IsSplitPolicyDevice() ? OpenSplitPolicy(&policy_file)
413 : OpenMonolithicPolicy(&policy_file);
414 if (!ok) {
415 LOG(FATAL) << "Unable to open SELinux policy";
Tom Cherryc3170092017-08-10 12:22:44 -0700416 }
417
David Anderson491e4da2020-12-08 00:21:20 -0800418 if (!android::base::ReadFdToString(policy_file.fd, policy)) {
419 PLOG(FATAL) << "Failed to read policy file: " << policy_file.path;
420 }
421}
422
423void SelinuxSetEnforcement() {
Tom Cherryc3170092017-08-10 12:22:44 -0700424 bool kernel_enforcing = (security_getenforce() == 1);
425 bool is_enforcing = IsEnforcing();
426 if (kernel_enforcing != is_enforcing) {
427 if (security_setenforce(is_enforcing)) {
Paul Lawrenceb2c2d692019-08-30 11:11:44 -0700428 PLOG(FATAL) << "security_setenforce(" << (is_enforcing ? "true" : "false")
429 << ") failed";
Tom Cherryc3170092017-08-10 12:22:44 -0700430 }
431 }
Tom Cherryc3170092017-08-10 12:22:44 -0700432}
433
Tom Cherry8180b482019-08-26 13:57:51 -0700434constexpr size_t kKlogMessageSize = 1024;
435
Thiébaud Weksteenf03dde82023-04-03 16:53:12 +1000436void SelinuxAvcLog(char* buf) {
Tom Cherry8180b482019-08-26 13:57:51 -0700437 struct NetlinkMessage {
438 nlmsghdr hdr;
439 char buf[kKlogMessageSize];
440 } request = {};
441
442 request.hdr.nlmsg_flags = NLM_F_REQUEST;
443 request.hdr.nlmsg_type = AUDIT_USER_AVC;
444 request.hdr.nlmsg_len = sizeof(request);
445 strlcpy(request.buf, buf, sizeof(request.buf));
446
447 auto fd = unique_fd{socket(PF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_AUDIT)};
448 if (!fd.ok()) {
449 return;
450 }
451
Bart Van Asscheaee2ec82022-12-02 18:48:15 -0800452 TEMP_FAILURE_RETRY(send(fd.get(), &request, sizeof(request), 0));
Tom Cherry8180b482019-08-26 13:57:51 -0700453}
454
Eric Biggers141c6a82023-08-11 21:05:14 +0000455int RestoreconIfExists(const char* path, unsigned int flags) {
456 if (access(path, F_OK) != 0 && errno == ENOENT) {
457 // Avoid error message for path that is expected to not always exist.
458 return 0;
459 }
460 return selinux_android_restorecon(path, flags);
461}
462
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800463} // namespace
464
Tom Cherryc3170092017-08-10 12:22:44 -0700465void SelinuxRestoreContext() {
466 LOG(INFO) << "Running restorecon...";
467 selinux_android_restorecon("/dev", 0);
Inseob Kim89d69132022-03-22 21:51:07 +0900468 selinux_android_restorecon("/dev/console", 0);
Tom Cherryc3170092017-08-10 12:22:44 -0700469 selinux_android_restorecon("/dev/kmsg", 0);
470 if constexpr (WORLD_WRITABLE_KMSG) {
471 selinux_android_restorecon("/dev/kmsg_debug", 0);
472 }
Tom Cherry81ae0752018-07-30 16:23:49 -0700473 selinux_android_restorecon("/dev/null", 0);
474 selinux_android_restorecon("/dev/ptmx", 0);
Tom Cherryc3170092017-08-10 12:22:44 -0700475 selinux_android_restorecon("/dev/socket", 0);
476 selinux_android_restorecon("/dev/random", 0);
477 selinux_android_restorecon("/dev/urandom", 0);
478 selinux_android_restorecon("/dev/__properties__", 0);
479
Tom Cherryc3170092017-08-10 12:22:44 -0700480 selinux_android_restorecon("/dev/block", SELINUX_ANDROID_RESTORECON_RECURSE);
David Anderson1ff75812020-11-13 00:31:47 -0800481 selinux_android_restorecon("/dev/dm-user", SELINUX_ANDROID_RESTORECON_RECURSE);
Tom Cherryc3170092017-08-10 12:22:44 -0700482 selinux_android_restorecon("/dev/device-mapper", 0);
Jiyong Park4ba548d2019-02-22 16:04:35 +0900483
484 selinux_android_restorecon("/apex", 0);
Jooyung Han566c6522023-08-09 07:05:31 +0000485 selinux_android_restorecon("/bootstrap-apex", 0);
Kiyoung Kim99df54b2019-11-22 16:14:10 +0900486 selinux_android_restorecon("/linkerconfig", 0);
Bowgo Tsai196cc582020-01-20 18:03:58 +0800487
David Andersonc991f342020-02-21 17:11:07 -0800488 // adb remount, snapshot-based updates, and DSUs all create files during
489 // first-stage init.
Eric Biggers141c6a82023-08-11 21:05:14 +0000490 RestoreconIfExists(SnapshotManager::GetGlobalRollbackIndicatorPath().c_str(), 0);
491 RestoreconIfExists("/metadata/gsi",
492 SELINUX_ANDROID_RESTORECON_RECURSE | SELINUX_ANDROID_RESTORECON_SKIP_SEHASH);
Tom Cherryc3170092017-08-10 12:22:44 -0700493}
494
Tom Cherry74069d12018-07-20 15:26:25 -0700495int SelinuxKlogCallback(int type, const char* fmt, ...) {
496 android::base::LogSeverity severity = android::base::ERROR;
497 if (type == SELINUX_WARNING) {
498 severity = android::base::WARNING;
499 } else if (type == SELINUX_INFO) {
500 severity = android::base::INFO;
501 }
Tom Cherry8180b482019-08-26 13:57:51 -0700502 char buf[kKlogMessageSize];
Tom Cherry74069d12018-07-20 15:26:25 -0700503 va_list ap;
504 va_start(ap, fmt);
Tom Cherry8180b482019-08-26 13:57:51 -0700505 int length_written = vsnprintf(buf, sizeof(buf), fmt, ap);
Tom Cherry74069d12018-07-20 15:26:25 -0700506 va_end(ap);
Tom Cherry8180b482019-08-26 13:57:51 -0700507 if (length_written <= 0) {
508 return 0;
509 }
Thiébaud Weksteenf03dde82023-04-03 16:53:12 +1000510
511 // libselinux log messages usually contain a new line character, while
512 // Android LOG() does not expect it. Remove it to avoid empty lines in
513 // the log buffers.
514 size_t str_len = strlen(buf);
515 if (buf[str_len - 1] == '\n') {
516 buf[str_len - 1] = '\0';
517 }
518
Tom Cherry8180b482019-08-26 13:57:51 -0700519 if (type == SELINUX_AVC) {
Thiébaud Weksteenf03dde82023-04-03 16:53:12 +1000520 SelinuxAvcLog(buf);
Tom Cherry8180b482019-08-26 13:57:51 -0700521 } else {
522 android::base::KernelLogger(android::base::MAIN, severity, "selinux", nullptr, 0, buf);
523 }
Tom Cherry74069d12018-07-20 15:26:25 -0700524 return 0;
525}
526
Tom Cherryc3170092017-08-10 12:22:44 -0700527void SelinuxSetupKernelLogging() {
528 selinux_callback cb;
Tom Cherry74069d12018-07-20 15:26:25 -0700529 cb.func_log = SelinuxKlogCallback;
Tom Cherryc3170092017-08-10 12:22:44 -0700530 selinux_set_callback(SELINUX_CB_LOG, cb);
531}
532
Tom Cherry40acb372018-08-01 13:41:12 -0700533int SelinuxGetVendorAndroidVersion() {
Nikita Ioffea66adf42023-06-26 14:55:31 +0100534 if (IsMicrodroid()) {
535 // As of now Microdroid doesn't have any vendor code.
536 return __ANDROID_API_FUTURE__;
537 }
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700538 static int vendor_android_version = [] {
539 if (!IsSplitPolicyDevice()) {
540 // If this device does not split sepolicy files, it's not a Treble device and therefore,
541 // we assume it's always on the latest platform.
542 return __ANDROID_API_FUTURE__;
543 }
Logan Chien837b2a42018-05-03 14:33:52 +0800544
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700545 std::string version;
546 if (!GetVendorMappingVersion(&version)) {
547 LOG(FATAL) << "Could not read vendor SELinux version";
548 }
Logan Chien837b2a42018-05-03 14:33:52 +0800549
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700550 int major_version;
551 std::string major_version_str(version, 0, version.find('.'));
552 if (!ParseInt(major_version_str, &major_version)) {
553 PLOG(FATAL) << "Failed to parse the vendor sepolicy major version "
554 << major_version_str;
555 }
Logan Chien837b2a42018-05-03 14:33:52 +0800556
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700557 return major_version;
558 }();
559 return vendor_android_version;
Logan Chien837b2a42018-05-03 14:33:52 +0800560}
561
David Andersond0ce5302020-03-20 21:47:10 -0700562// This is for R system.img/system_ext.img to work on old vendor.img as system_ext.img
563// is introduced in R. We mount system_ext in second stage init because the first-stage
564// init in boot.img won't be updated in the system-only OTA scenario.
565void MountMissingSystemPartitions() {
566 android::fs_mgr::Fstab fstab;
567 if (!ReadDefaultFstab(&fstab)) {
568 LOG(ERROR) << "Could not read default fstab";
569 }
570
571 android::fs_mgr::Fstab mounts;
572 if (!ReadFstabFromFile("/proc/mounts", &mounts)) {
573 LOG(ERROR) << "Could not read /proc/mounts";
574 }
575
576 static const std::vector<std::string> kPartitionNames = {"system_ext", "product"};
577
578 android::fs_mgr::Fstab extra_fstab;
579 for (const auto& name : kPartitionNames) {
580 if (GetEntryForMountPoint(&mounts, "/"s + name)) {
581 // The partition is already mounted.
582 continue;
583 }
584
Lianjun Huangccd094c2023-02-17 20:22:37 +0800585 auto system_entries = GetEntriesForMountPoint(&fstab, "/system");
586 for (auto& system_entry : system_entries) {
587 if (!system_entry) {
588 LOG(ERROR) << "Could not find mount entry for /system";
589 break;
590 }
591 if (!system_entry->fs_mgr_flags.logical) {
592 LOG(INFO) << "Skipping mount of " << name << ", system is not dynamic.";
593 break;
594 }
David Andersond0ce5302020-03-20 21:47:10 -0700595
Lianjun Huangccd094c2023-02-17 20:22:37 +0800596 auto entry = *system_entry;
597 auto partition_name = name + fs_mgr_get_slot_suffix();
598 auto replace_name = "system"s + fs_mgr_get_slot_suffix();
David Andersond0ce5302020-03-20 21:47:10 -0700599
Lianjun Huangccd094c2023-02-17 20:22:37 +0800600 entry.mount_point = "/"s + name;
601 entry.blk_device =
David Andersond0ce5302020-03-20 21:47:10 -0700602 android::base::StringReplace(entry.blk_device, replace_name, partition_name, false);
Lianjun Huangccd094c2023-02-17 20:22:37 +0800603 if (!fs_mgr_update_logical_partition(&entry)) {
604 LOG(ERROR) << "Could not update logical partition";
605 continue;
606 }
David Andersond0ce5302020-03-20 21:47:10 -0700607
Lianjun Huangccd094c2023-02-17 20:22:37 +0800608 extra_fstab.emplace_back(std::move(entry));
609 }
David Andersond0ce5302020-03-20 21:47:10 -0700610 }
611
Yi-Yo Chiang20579012021-04-01 20:14:54 +0800612 SkipMountingPartitions(&extra_fstab, true /* verbose */);
David Andersond0ce5302020-03-20 21:47:10 -0700613 if (extra_fstab.empty()) {
614 return;
615 }
616
617 BlockDevInitializer block_dev_init;
618 for (auto& entry : extra_fstab) {
619 if (access(entry.blk_device.c_str(), F_OK) != 0) {
620 auto block_dev = android::base::Basename(entry.blk_device);
621 if (!block_dev_init.InitDmDevice(block_dev)) {
622 LOG(ERROR) << "Failed to find device-mapper node: " << block_dev;
623 continue;
624 }
625 }
626 if (fs_mgr_do_mount_one(entry)) {
627 LOG(ERROR) << "Could not mount " << entry.mount_point;
628 }
629 }
630}
631
David Anderson491e4da2020-12-08 00:21:20 -0800632static void LoadSelinuxPolicy(std::string& policy) {
633 LOG(INFO) << "Loading SELinux policy";
634
635 set_selinuxmnt("/sys/fs/selinux");
636 if (security_load_policy(policy.data(), policy.size()) < 0) {
637 PLOG(FATAL) << "SELinux: Could not load policy";
638 }
639}
640
Nikita Ioffea66adf42023-06-26 14:55:31 +0100641// Encapsulates steps to load SELinux policy in Microdroid.
642// So far the process is very straightforward - just load the precompiled policy from /system.
643void LoadSelinuxPolicyMicrodroid() {
644 constexpr const char kMicrodroidPrecompiledSepolicy[] =
645 "/system/etc/selinux/microdroid_precompiled_sepolicy";
646
647 LOG(INFO) << "Opening SELinux policy from " << kMicrodroidPrecompiledSepolicy;
648 unique_fd policy_fd(open(kMicrodroidPrecompiledSepolicy, O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
649 if (policy_fd < 0) {
650 PLOG(FATAL) << "Failed to open " << kMicrodroidPrecompiledSepolicy;
651 }
652
653 std::string policy;
654 if (!android::base::ReadFdToString(policy_fd, &policy)) {
655 PLOG(FATAL) << "Failed to read policy file: " << kMicrodroidPrecompiledSepolicy;
656 }
657
658 LoadSelinuxPolicy(policy);
659}
660
David Anderson491e4da2020-12-08 00:21:20 -0800661// The SELinux setup process is carefully orchestrated around snapuserd. Policy
662// must be loaded off dynamic partitions, and during an OTA, those partitions
663// cannot be read without snapuserd. But, with kernel-privileged snapuserd
664// running, loading the policy will immediately trigger audits.
665//
666// We use a five-step process to address this:
667// (1) Read the policy into a string, with snapuserd running.
668// (2) Rewrite the snapshot device-mapper tables, to generate new dm-user
669// devices and to flush I/O.
670// (3) Kill snapuserd, which no longer has any dm-user devices to attach to.
671// (4) Load the sepolicy and issue critical restorecons in /dev, carefully
672// avoiding anything that would read from /system.
673// (5) Re-launch snapuserd and attach it to the dm-user devices from step (2).
674//
675// After this sequence, it is safe to enable enforcing mode and continue booting.
Nikita Ioffea66adf42023-06-26 14:55:31 +0100676void LoadSelinuxPolicyAndroid() {
David Andersond0ce5302020-03-20 21:47:10 -0700677 MountMissingSystemPartitions();
678
David Anderson491e4da2020-12-08 00:21:20 -0800679 LOG(INFO) << "Opening SELinux policy";
680
681 // Read the policy before potentially killing snapuserd.
682 std::string policy;
683 ReadPolicy(&policy);
684
685 auto snapuserd_helper = SnapuserdSelinuxHelper::CreateIfNeeded();
686 if (snapuserd_helper) {
Nikita Ioffea66adf42023-06-26 14:55:31 +0100687 // Kill the old snapused to avoid audit messages. After this we cannot read from /system
688 // (or other dynamic partitions) until we call FinishTransition().
David Anderson491e4da2020-12-08 00:21:20 -0800689 snapuserd_helper->StartTransition();
690 }
691
692 LoadSelinuxPolicy(policy);
693
694 if (snapuserd_helper) {
695 // Before enforcing, finish the pending snapuserd transition.
696 snapuserd_helper->FinishTransition();
697 snapuserd_helper = nullptr;
698 }
Nikita Ioffea66adf42023-06-26 14:55:31 +0100699}
700
701int SetupSelinux(char** argv) {
702 SetStdioToDevNull(argv);
703 InitKernelLogging(argv);
704
705 if (REBOOT_BOOTLOADER_ON_PANIC) {
706 InstallRebootSignalHandlers();
707 }
708
709 boot_clock::time_point start_time = boot_clock::now();
710
711 SelinuxSetupKernelLogging();
712
713 // TODO(b/287206497): refactor into different headers to only include what we need.
714 if (IsMicrodroid()) {
715 LoadSelinuxPolicyMicrodroid();
716 } else {
717 LoadSelinuxPolicyAndroid();
718 }
Jeffrey Vander Stoepbaeece62022-02-08 12:42:33 +0000719
David Anderson491e4da2020-12-08 00:21:20 -0800720 SelinuxSetEnforcement();
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800721
Nikita Ioffefeb7e0e2024-03-28 00:32:36 +0000722 if (IsMicrodroid() && android::virtualization::IsOpenDiceChangesFlagEnabled()) {
723 // We run restorecon of /microdroid_resources while we are still in kernel context to avoid
724 // granting init `tmpfs:file relabelfrom` capability.
725 const int flags = SELINUX_ANDROID_RESTORECON_RECURSE;
726 if (selinux_android_restorecon("/microdroid_resources", flags) == -1) {
727 PLOG(FATAL) << "restorecon of /microdroid_resources failed";
728 }
729 }
730
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800731 // We're in the kernel domain and want to transition to the init domain. File systems that
732 // store SELabels in their xattrs, such as ext4 do not need an explicit restorecon here,
733 // but other file systems do. In particular, this is needed for ramdisks such as the
734 // recovery image for A/B devices.
735 if (selinux_android_restorecon("/system/bin/init", 0) == -1) {
736 PLOG(FATAL) << "restorecon failed of /system/bin/init failed";
737 }
738
Mark Salyzyn44505ec2019-05-08 12:44:50 -0700739 setenv(kEnvSelinuxStartedAt, std::to_string(start_time.time_since_epoch().count()).c_str(), 1);
Mark Salyzyn10377df2019-03-27 08:10:41 -0700740
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800741 const char* path = "/system/bin/init";
742 const char* args[] = {path, "second_stage", nullptr};
743 execv(path, const_cast<char**>(args));
744
745 // execv() only returns if an error happened, in which case we
746 // panic and never return from this function.
747 PLOG(FATAL) << "execv(\"" << path << "\") failed";
748
749 return 1;
750}
751
Tom Cherryc3170092017-08-10 12:22:44 -0700752} // namespace init
753} // namespace android