blob: 5ced0b81ae3139f22ceeb795dcc4b387a757d8d5 [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>
Bowgo Tsai196cc582020-01-20 18:03:58 +080072#include <libgsi/libgsi.h>
Yifan Hongd91998f2020-02-20 17:54:57 -080073#include <libsnapshot/snapshot.h>
Tom Cherryc3170092017-08-10 12:22:44 -070074#include <selinux/android.h>
75
David Andersond0ce5302020-03-20 21:47:10 -070076#include "block_dev_initializer.h"
Bowgo Tsai30afda72019-04-11 23:57:24 +080077#include "debug_ramdisk.h"
Tom Cherry7bfea3d2018-11-06 14:12:05 -080078#include "reboot_utils.h"
David Anderson491e4da2020-12-08 00:21:20 -080079#include "snapuserd_transition.h"
Tom Cherryc3170092017-08-10 12:22:44 -070080#include "util.h"
81
Bowgo Tsai1dacd422019-03-04 17:53:34 +080082using namespace std::string_literals;
83
Logan Chien837b2a42018-05-03 14:33:52 +080084using android::base::ParseInt;
Tom Cherryc3170092017-08-10 12:22:44 -070085using android::base::Timer;
86using android::base::unique_fd;
Bowgo Tsai1dacd422019-03-04 17:53:34 +080087using android::fs_mgr::AvbHandle;
Yifan Hongd91998f2020-02-20 17:54:57 -080088using android::snapshot::SnapshotManager;
Tom Cherryc3170092017-08-10 12:22:44 -070089
90namespace android {
91namespace init {
92
Tom Cherryc3170092017-08-10 12:22:44 -070093namespace {
94
95enum EnforcingStatus { SELINUX_PERMISSIVE, SELINUX_ENFORCING };
96
Alistair Delva63594a42021-03-09 11:04:23 -080097EnforcingStatus StatusFromProperty() {
Yi-Yo Chiangda5323e2023-08-02 01:08:23 +080098 std::string value;
99 if (android::fs_mgr::GetKernelCmdline("androidboot.selinux", &value) && value == "permissive") {
100 return SELINUX_PERMISSIVE;
Alistair Delva63594a42021-03-09 11:04:23 -0800101 }
Yi-Yo Chiangda5323e2023-08-02 01:08:23 +0800102 if (android::fs_mgr::GetBootconfig("androidboot.selinux", &value) && value == "permissive") {
103 return SELINUX_PERMISSIVE;
104 }
105 return SELINUX_ENFORCING;
Tom Cherryc3170092017-08-10 12:22:44 -0700106}
107
108bool IsEnforcing() {
109 if (ALLOW_PERMISSIVE_SELINUX) {
Alistair Delva63594a42021-03-09 11:04:23 -0800110 return StatusFromProperty() == SELINUX_ENFORCING;
Tom Cherryc3170092017-08-10 12:22:44 -0700111 }
112 return true;
113}
114
Tom Cherryc3170092017-08-10 12:22:44 -0700115bool ReadFirstLine(const char* file, std::string* line) {
116 line->clear();
117
118 std::string contents;
119 if (!android::base::ReadFileToString(file, &contents, true /* follow symlinks */)) {
120 return false;
121 }
122 std::istringstream in(contents);
123 std::getline(in, *line);
124 return true;
125}
126
Inseob Kimd99d9772021-03-11 17:58:26 +0900127Result<std::string> FindPrecompiledSplitPolicy() {
128 std::string precompiled_sepolicy;
kaichieheef4cd72017-08-31 22:07:19 +0800129 // If there is an odm partition, precompiled_sepolicy will be in
130 // odm/etc/selinux. Otherwise it will be in vendor/etc/selinux.
131 static constexpr const char vendor_precompiled_sepolicy[] =
Sandro1120f7f2022-09-05 15:56:38 +0000132 "/vendor/etc/selinux/precompiled_sepolicy";
kaichieheef4cd72017-08-31 22:07:19 +0800133 static constexpr const char odm_precompiled_sepolicy[] =
Sandro1120f7f2022-09-05 15:56:38 +0000134 "/odm/etc/selinux/precompiled_sepolicy";
kaichieheef4cd72017-08-31 22:07:19 +0800135 if (access(odm_precompiled_sepolicy, R_OK) == 0) {
Inseob Kimd99d9772021-03-11 17:58:26 +0900136 precompiled_sepolicy = odm_precompiled_sepolicy;
kaichieheef4cd72017-08-31 22:07:19 +0800137 } else if (access(vendor_precompiled_sepolicy, R_OK) == 0) {
Inseob Kimd99d9772021-03-11 17:58:26 +0900138 precompiled_sepolicy = vendor_precompiled_sepolicy;
kaichieheef4cd72017-08-31 22:07:19 +0800139 } else {
Inseob Kimd99d9772021-03-11 17:58:26 +0900140 return ErrnoError() << "No precompiled sepolicy at " << vendor_precompiled_sepolicy;
Tom Cherryc3170092017-08-10 12:22:44 -0700141 }
kaichieheef4cd72017-08-31 22:07:19 +0800142
Inseob Kimd99d9772021-03-11 17:58:26 +0900143 // Use precompiled sepolicy only when all corresponding hashes are equal.
Inseob Kimd99d9772021-03-11 17:58:26 +0900144 std::vector<std::pair<std::string, std::string>> sepolicy_hashes{
145 {"/system/etc/selinux/plat_sepolicy_and_mapping.sha256",
146 precompiled_sepolicy + ".plat_sepolicy_and_mapping.sha256"},
Inseob Kim28fdb672021-04-29 19:48:27 +0900147 {"/system_ext/etc/selinux/system_ext_sepolicy_and_mapping.sha256",
148 precompiled_sepolicy + ".system_ext_sepolicy_and_mapping.sha256"},
149 {"/product/etc/selinux/product_sepolicy_and_mapping.sha256",
150 precompiled_sepolicy + ".product_sepolicy_and_mapping.sha256"},
Inseob Kimd99d9772021-03-11 17:58:26 +0900151 };
152
Inseob Kimd99d9772021-03-11 17:58:26 +0900153 for (const auto& [actual_id_path, precompiled_id_path] : sepolicy_hashes) {
Inseob Kim28fdb672021-04-29 19:48:27 +0900154 // Both of them should exist or both of them shouldn't exist.
155 if (access(actual_id_path.c_str(), R_OK) != 0) {
156 if (access(precompiled_id_path.c_str(), R_OK) == 0) {
157 return Error() << precompiled_id_path << " exists but " << actual_id_path
158 << " doesn't";
159 }
160 continue;
161 }
162
Inseob Kimd99d9772021-03-11 17:58:26 +0900163 std::string actual_id;
164 if (!ReadFirstLine(actual_id_path.c_str(), &actual_id)) {
165 return ErrnoError() << "Failed to read " << actual_id_path;
166 }
167
168 std::string precompiled_id;
169 if (!ReadFirstLine(precompiled_id_path.c_str(), &precompiled_id)) {
170 return ErrnoError() << "Failed to read " << precompiled_id_path;
171 }
172
173 if (actual_id.empty() || actual_id != precompiled_id) {
174 return Error() << actual_id_path << " and " << precompiled_id_path << " differ";
175 }
Tri Voc8137f92019-01-22 18:22:25 -0800176 }
Inseob Kimd99d9772021-03-11 17:58:26 +0900177
178 return precompiled_sepolicy;
Tom Cherryc3170092017-08-10 12:22:44 -0700179}
180
181bool GetVendorMappingVersion(std::string* plat_vers) {
182 if (!ReadFirstLine("/vendor/etc/selinux/plat_sepolicy_vers.txt", plat_vers)) {
183 PLOG(ERROR) << "Failed to read /vendor/etc/selinux/plat_sepolicy_vers.txt";
184 return false;
185 }
186 if (plat_vers->empty()) {
187 LOG(ERROR) << "No version present in plat_sepolicy_vers.txt";
188 return false;
189 }
190 return true;
191}
192
Inseob Kim76afb4a2024-11-06 17:07:04 +0900193int GetVendorGenfsVersion() {
194 std::string line;
195 if (!ReadFirstLine("/vendor/etc/selinux/genfs_labels_version.txt", &line)) {
196 PLOG(ERROR) << "Failed to read /vendor/etc/selinux/genfs_labels_version.txt; assuming it's "
197 "202404";
198 return 202404;
199 }
200 int version;
201 if (!ParseInt(line, &version)) {
202 PLOG(ERROR) << "Failed to parse the genfs labels version " << line
203 << "; assuming it's 202404";
204 return 202404;
205 }
206 return version;
207}
208
Tom Cherryc3170092017-08-10 12:22:44 -0700209constexpr const char plat_policy_cil_file[] = "/system/etc/selinux/plat_sepolicy.cil";
210
211bool IsSplitPolicyDevice() {
212 return access(plat_policy_cil_file, R_OK) != -1;
213}
214
Yi-Yo Chiangbb77c542021-09-23 14:14:16 +0000215std::optional<const char*> GetUserdebugPlatformPolicyFile() {
216 // See if we need to load userdebug_plat_sepolicy.cil instead of plat_sepolicy.cil.
217 const char* force_debuggable_env = getenv("INIT_FORCE_DEBUGGABLE");
218 if (force_debuggable_env && "true"s == force_debuggable_env && AvbHandle::IsDeviceUnlocked()) {
219 const std::vector<const char*> debug_policy_candidates = {
220#if INSTALL_DEBUG_POLICY_TO_SYSTEM_EXT == 1
221 "/system_ext/etc/selinux/userdebug_plat_sepolicy.cil",
222#endif
223 kDebugRamdiskSEPolicy,
224 };
225 for (const char* debug_policy : debug_policy_candidates) {
226 if (access(debug_policy, F_OK) == 0) {
227 return debug_policy;
228 }
229 }
230 }
231 return std::nullopt;
232}
233
David Anderson491e4da2020-12-08 00:21:20 -0800234struct PolicyFile {
235 unique_fd fd;
236 std::string path;
237};
238
239bool OpenSplitPolicy(PolicyFile* policy_file) {
Jeff Vander Stoep5effda42021-11-05 09:03:11 +0100240 // IMPLEMENTATION NOTE: Split policy consists of three or more CIL files:
Tom Cherryc3170092017-08-10 12:22:44 -0700241 // * platform -- policy needed due to logic contained in the system image,
Jeff Vander Stoep5effda42021-11-05 09:03:11 +0100242 // * vendor -- policy needed due to logic contained in the vendor image,
Tom Cherryc3170092017-08-10 12:22:44 -0700243 // * mapping -- mapping policy which helps preserve forward-compatibility of non-platform policy
244 // with newer versions of platform policy.
Thiébaud Weksteen50f03fd2023-09-06 10:52:49 +1000245 // * (optional) policy needed due to logic on product, system_ext, or odm images.
Tom Cherryc3170092017-08-10 12:22:44 -0700246 // secilc is invoked to compile the above three policy files into a single monolithic policy
247 // file. This file is then loaded into the kernel.
248
Yi-Yo Chiangbb77c542021-09-23 14:14:16 +0000249 const auto userdebug_plat_sepolicy = GetUserdebugPlatformPolicyFile();
250 const bool use_userdebug_policy = userdebug_plat_sepolicy.has_value();
Bowgo Tsai1dacd422019-03-04 17:53:34 +0800251 if (use_userdebug_policy) {
Yi-Yo Chiangbb77c542021-09-23 14:14:16 +0000252 LOG(INFO) << "Using userdebug system sepolicy " << *userdebug_plat_sepolicy;
Bowgo Tsai1dacd422019-03-04 17:53:34 +0800253 }
254
Tom Cherryc3170092017-08-10 12:22:44 -0700255 // Load precompiled policy from vendor image, if a matching policy is found there. The policy
256 // must match the platform policy on the system image.
Bowgo Tsai1dacd422019-03-04 17:53:34 +0800257 // use_userdebug_policy requires compiling sepolicy with userdebug_plat_sepolicy.cil.
258 // Thus it cannot use the precompiled policy from vendor image.
Inseob Kimd99d9772021-03-11 17:58:26 +0900259 if (!use_userdebug_policy) {
260 if (auto res = FindPrecompiledSplitPolicy(); res.ok()) {
261 unique_fd fd(open(res->c_str(), O_RDONLY | O_CLOEXEC | O_BINARY));
262 if (fd != -1) {
263 policy_file->fd = std::move(fd);
264 policy_file->path = std::move(*res);
265 return true;
266 }
267 } else {
268 LOG(INFO) << res.error();
Tom Cherryc3170092017-08-10 12:22:44 -0700269 }
270 }
271 // No suitable precompiled policy could be loaded
272
273 LOG(INFO) << "Compiling SELinux policy";
274
Tom Cherryc3170092017-08-10 12:22:44 -0700275 // We store the output of the compilation on /dev because this is the most convenient tmpfs
276 // storage mount available this early in the boot sequence.
277 char compiled_sepolicy[] = "/dev/sepolicy.XXXXXX";
278 unique_fd compiled_sepolicy_fd(mkostemp(compiled_sepolicy, O_CLOEXEC));
279 if (compiled_sepolicy_fd < 0) {
280 PLOG(ERROR) << "Failed to create temporary file " << compiled_sepolicy;
281 return false;
282 }
283
284 // Determine which mapping file to include
285 std::string vend_plat_vers;
286 if (!GetVendorMappingVersion(&vend_plat_vers)) {
287 return false;
288 }
Tri Vo503f1852019-01-16 11:57:19 -0800289 std::string plat_mapping_file("/system/etc/selinux/mapping/" + vend_plat_vers + ".cil");
kaichieheef4cd72017-08-31 22:07:19 +0800290
Jeff Vander Stoep0ac51cf2019-05-02 14:05:18 -0700291 std::string plat_compat_cil_file("/system/etc/selinux/mapping/" + vend_plat_vers +
292 ".compat.cil");
293 if (access(plat_compat_cil_file.c_str(), F_OK) == -1) {
294 plat_compat_cil_file.clear();
295 }
296
Bowgo Tsaif016f252019-08-28 17:56:51 +0800297 std::string system_ext_policy_cil_file("/system_ext/etc/selinux/system_ext_sepolicy.cil");
298 if (access(system_ext_policy_cil_file.c_str(), F_OK) == -1) {
299 system_ext_policy_cil_file.clear();
300 }
301
302 std::string system_ext_mapping_file("/system_ext/etc/selinux/mapping/" + vend_plat_vers +
303 ".cil");
304 if (access(system_ext_mapping_file.c_str(), F_OK) == -1) {
305 system_ext_mapping_file.clear();
306 }
307
Yi-Yo Chiang731d2472021-03-23 22:11:13 +0800308 std::string system_ext_compat_cil_file("/system_ext/etc/selinux/mapping/" + vend_plat_vers +
309 ".compat.cil");
310 if (access(system_ext_compat_cil_file.c_str(), F_OK) == -1) {
311 system_ext_compat_cil_file.clear();
312 }
313
Tri Vod3518cf2018-12-14 14:25:08 -0800314 std::string product_policy_cil_file("/product/etc/selinux/product_sepolicy.cil");
315 if (access(product_policy_cil_file.c_str(), F_OK) == -1) {
316 product_policy_cil_file.clear();
317 }
318
Tri Vo503f1852019-01-16 11:57:19 -0800319 std::string product_mapping_file("/product/etc/selinux/mapping/" + vend_plat_vers + ".cil");
320 if (access(product_mapping_file.c_str(), F_OK) == -1) {
321 product_mapping_file.clear();
322 }
323
kaichieheef4cd72017-08-31 22:07:19 +0800324 std::string vendor_policy_cil_file("/vendor/etc/selinux/vendor_sepolicy.cil");
kaichieheef4cd72017-08-31 22:07:19 +0800325 if (access(vendor_policy_cil_file.c_str(), F_OK) == -1) {
Jeff Vander Stoep5effda42021-11-05 09:03:11 +0100326 LOG(ERROR) << "Missing " << vendor_policy_cil_file;
327 return false;
328 }
329
330 std::string plat_pub_versioned_cil_file("/vendor/etc/selinux/plat_pub_versioned.cil");
331 if (access(plat_pub_versioned_cil_file.c_str(), F_OK) == -1) {
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800332 LOG(ERROR) << "Missing " << plat_pub_versioned_cil_file;
kaichieheef4cd72017-08-31 22:07:19 +0800333 return false;
334 }
335
336 // odm_sepolicy.cil is default but optional.
337 std::string odm_policy_cil_file("/odm/etc/selinux/odm_sepolicy.cil");
338 if (access(odm_policy_cil_file.c_str(), F_OK) == -1) {
339 odm_policy_cil_file.clear();
340 }
Jeff Vander Stoep724eda52019-02-15 12:13:38 -0800341 const std::string version_as_string = std::to_string(SEPOLICY_VERSION);
Andreas Huberc41b8382017-08-18 14:43:52 -0700342
Inseob Kim76afb4a2024-11-06 17:07:04 +0900343 std::vector<std::string> genfs_cil_files;
344
345 int vendor_genfs_version = GetVendorGenfsVersion();
346 std::string genfs_cil_file =
347 std::format("/system/etc/selinux/plat_sepolicy_genfs_{}.cil", vendor_genfs_version);
348 if (access(genfs_cil_file.c_str(), F_OK) != 0) {
349 genfs_cil_file.clear();
350 }
351
Tom Cherryc3170092017-08-10 12:22:44 -0700352 // clang-format off
kaichieheef4cd72017-08-31 22:07:19 +0800353 std::vector<const char*> compile_args {
Tom Cherryc3170092017-08-10 12:22:44 -0700354 "/system/bin/secilc",
Yi-Yo Chiangbb77c542021-09-23 14:14:16 +0000355 use_userdebug_policy ? *userdebug_plat_sepolicy : plat_policy_cil_file,
Jeff Vander Stoep5e9ba3c2017-10-06 17:03:45 -0700356 "-m", "-M", "true", "-G", "-N",
Andreas Huberc41b8382017-08-18 14:43:52 -0700357 "-c", version_as_string.c_str(),
Tri Vo503f1852019-01-16 11:57:19 -0800358 plat_mapping_file.c_str(),
Tom Cherryc3170092017-08-10 12:22:44 -0700359 "-o", compiled_sepolicy,
360 // We don't care about file_contexts output by the compiler
361 "-f", "/sys/fs/selinux/null", // /dev/null is not yet available
kaichieheef4cd72017-08-31 22:07:19 +0800362 };
Tom Cherryc3170092017-08-10 12:22:44 -0700363 // clang-format on
364
Jeff Vander Stoep0ac51cf2019-05-02 14:05:18 -0700365 if (!plat_compat_cil_file.empty()) {
366 compile_args.push_back(plat_compat_cil_file.c_str());
367 }
Bowgo Tsaif016f252019-08-28 17:56:51 +0800368 if (!system_ext_policy_cil_file.empty()) {
369 compile_args.push_back(system_ext_policy_cil_file.c_str());
370 }
371 if (!system_ext_mapping_file.empty()) {
372 compile_args.push_back(system_ext_mapping_file.c_str());
373 }
Yi-Yo Chiang731d2472021-03-23 22:11:13 +0800374 if (!system_ext_compat_cil_file.empty()) {
375 compile_args.push_back(system_ext_compat_cil_file.c_str());
376 }
Tri Vod3518cf2018-12-14 14:25:08 -0800377 if (!product_policy_cil_file.empty()) {
378 compile_args.push_back(product_policy_cil_file.c_str());
379 }
Tri Vo503f1852019-01-16 11:57:19 -0800380 if (!product_mapping_file.empty()) {
381 compile_args.push_back(product_mapping_file.c_str());
382 }
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800383 if (!plat_pub_versioned_cil_file.empty()) {
384 compile_args.push_back(plat_pub_versioned_cil_file.c_str());
kaichieheef4cd72017-08-31 22:07:19 +0800385 }
386 if (!vendor_policy_cil_file.empty()) {
387 compile_args.push_back(vendor_policy_cil_file.c_str());
388 }
389 if (!odm_policy_cil_file.empty()) {
390 compile_args.push_back(odm_policy_cil_file.c_str());
391 }
Inseob Kim76afb4a2024-11-06 17:07:04 +0900392 if (!genfs_cil_file.empty()) {
393 compile_args.push_back(genfs_cil_file.c_str());
394 }
kaichieheef4cd72017-08-31 22:07:19 +0800395 compile_args.push_back(nullptr);
396
397 if (!ForkExecveAndWaitForCompletion(compile_args[0], (char**)compile_args.data())) {
Tom Cherryc3170092017-08-10 12:22:44 -0700398 unlink(compiled_sepolicy);
399 return false;
400 }
401 unlink(compiled_sepolicy);
402
David Anderson491e4da2020-12-08 00:21:20 -0800403 policy_file->fd = std::move(compiled_sepolicy_fd);
404 policy_file->path = compiled_sepolicy;
Tom Cherryc3170092017-08-10 12:22:44 -0700405 return true;
406}
407
David Anderson491e4da2020-12-08 00:21:20 -0800408bool OpenMonolithicPolicy(PolicyFile* policy_file) {
409 static constexpr char kSepolicyFile[] = "/sepolicy";
410
Nikita Ioffea66adf42023-06-26 14:55:31 +0100411 LOG(INFO) << "Opening SELinux policy from monolithic file " << kSepolicyFile;
412 policy_file->fd.reset(open(kSepolicyFile, O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
David Anderson491e4da2020-12-08 00:21:20 -0800413 if (policy_file->fd < 0) {
414 PLOG(ERROR) << "Failed to open monolithic SELinux policy";
Tom Cherryc3170092017-08-10 12:22:44 -0700415 return false;
416 }
Nikita Ioffea66adf42023-06-26 14:55:31 +0100417 policy_file->path = kSepolicyFile;
Tom Cherryc3170092017-08-10 12:22:44 -0700418 return true;
419}
420
David Anderson491e4da2020-12-08 00:21:20 -0800421void ReadPolicy(std::string* policy) {
422 PolicyFile policy_file;
Tom Cherryc3170092017-08-10 12:22:44 -0700423
David Anderson491e4da2020-12-08 00:21:20 -0800424 bool ok = IsSplitPolicyDevice() ? OpenSplitPolicy(&policy_file)
425 : OpenMonolithicPolicy(&policy_file);
426 if (!ok) {
427 LOG(FATAL) << "Unable to open SELinux policy";
Tom Cherryc3170092017-08-10 12:22:44 -0700428 }
429
David Anderson491e4da2020-12-08 00:21:20 -0800430 if (!android::base::ReadFdToString(policy_file.fd, policy)) {
431 PLOG(FATAL) << "Failed to read policy file: " << policy_file.path;
432 }
433}
434
435void SelinuxSetEnforcement() {
Tom Cherryc3170092017-08-10 12:22:44 -0700436 bool kernel_enforcing = (security_getenforce() == 1);
437 bool is_enforcing = IsEnforcing();
438 if (kernel_enforcing != is_enforcing) {
439 if (security_setenforce(is_enforcing)) {
Paul Lawrenceb2c2d692019-08-30 11:11:44 -0700440 PLOG(FATAL) << "security_setenforce(" << (is_enforcing ? "true" : "false")
441 << ") failed";
Tom Cherryc3170092017-08-10 12:22:44 -0700442 }
443 }
Tom Cherryc3170092017-08-10 12:22:44 -0700444}
445
Tom Cherry8180b482019-08-26 13:57:51 -0700446constexpr size_t kKlogMessageSize = 1024;
447
Thiébaud Weksteenf03dde82023-04-03 16:53:12 +1000448void SelinuxAvcLog(char* buf) {
Tom Cherry8180b482019-08-26 13:57:51 -0700449 struct NetlinkMessage {
450 nlmsghdr hdr;
451 char buf[kKlogMessageSize];
452 } request = {};
453
454 request.hdr.nlmsg_flags = NLM_F_REQUEST;
455 request.hdr.nlmsg_type = AUDIT_USER_AVC;
456 request.hdr.nlmsg_len = sizeof(request);
457 strlcpy(request.buf, buf, sizeof(request.buf));
458
459 auto fd = unique_fd{socket(PF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_AUDIT)};
460 if (!fd.ok()) {
461 return;
462 }
463
Bart Van Asscheaee2ec82022-12-02 18:48:15 -0800464 TEMP_FAILURE_RETRY(send(fd.get(), &request, sizeof(request), 0));
Tom Cherry8180b482019-08-26 13:57:51 -0700465}
466
Eric Biggers141c6a82023-08-11 21:05:14 +0000467int RestoreconIfExists(const char* path, unsigned int flags) {
468 if (access(path, F_OK) != 0 && errno == ENOENT) {
469 // Avoid error message for path that is expected to not always exist.
470 return 0;
471 }
472 return selinux_android_restorecon(path, flags);
473}
474
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800475} // namespace
476
Tom Cherryc3170092017-08-10 12:22:44 -0700477void SelinuxRestoreContext() {
478 LOG(INFO) << "Running restorecon...";
479 selinux_android_restorecon("/dev", 0);
Inseob Kim89d69132022-03-22 21:51:07 +0900480 selinux_android_restorecon("/dev/console", 0);
Tom Cherryc3170092017-08-10 12:22:44 -0700481 selinux_android_restorecon("/dev/kmsg", 0);
482 if constexpr (WORLD_WRITABLE_KMSG) {
483 selinux_android_restorecon("/dev/kmsg_debug", 0);
484 }
Tom Cherry81ae0752018-07-30 16:23:49 -0700485 selinux_android_restorecon("/dev/null", 0);
486 selinux_android_restorecon("/dev/ptmx", 0);
Tom Cherryc3170092017-08-10 12:22:44 -0700487 selinux_android_restorecon("/dev/socket", 0);
488 selinux_android_restorecon("/dev/random", 0);
489 selinux_android_restorecon("/dev/urandom", 0);
490 selinux_android_restorecon("/dev/__properties__", 0);
491
Tom Cherryc3170092017-08-10 12:22:44 -0700492 selinux_android_restorecon("/dev/block", SELINUX_ANDROID_RESTORECON_RECURSE);
David Anderson1ff75812020-11-13 00:31:47 -0800493 selinux_android_restorecon("/dev/dm-user", SELINUX_ANDROID_RESTORECON_RECURSE);
Tom Cherryc3170092017-08-10 12:22:44 -0700494 selinux_android_restorecon("/dev/device-mapper", 0);
Jiyong Park4ba548d2019-02-22 16:04:35 +0900495
496 selinux_android_restorecon("/apex", 0);
Jooyung Han566c6522023-08-09 07:05:31 +0000497 selinux_android_restorecon("/bootstrap-apex", 0);
Kiyoung Kim99df54b2019-11-22 16:14:10 +0900498 selinux_android_restorecon("/linkerconfig", 0);
Bowgo Tsai196cc582020-01-20 18:03:58 +0800499
David Andersonc991f342020-02-21 17:11:07 -0800500 // adb remount, snapshot-based updates, and DSUs all create files during
501 // first-stage init.
Eric Biggers141c6a82023-08-11 21:05:14 +0000502 RestoreconIfExists(SnapshotManager::GetGlobalRollbackIndicatorPath().c_str(), 0);
503 RestoreconIfExists("/metadata/gsi",
504 SELINUX_ANDROID_RESTORECON_RECURSE | SELINUX_ANDROID_RESTORECON_SKIP_SEHASH);
Tom Cherryc3170092017-08-10 12:22:44 -0700505}
506
Tom Cherry74069d12018-07-20 15:26:25 -0700507int SelinuxKlogCallback(int type, const char* fmt, ...) {
508 android::base::LogSeverity severity = android::base::ERROR;
509 if (type == SELINUX_WARNING) {
510 severity = android::base::WARNING;
511 } else if (type == SELINUX_INFO) {
512 severity = android::base::INFO;
513 }
Tom Cherry8180b482019-08-26 13:57:51 -0700514 char buf[kKlogMessageSize];
Tom Cherry74069d12018-07-20 15:26:25 -0700515 va_list ap;
516 va_start(ap, fmt);
Tom Cherry8180b482019-08-26 13:57:51 -0700517 int length_written = vsnprintf(buf, sizeof(buf), fmt, ap);
Tom Cherry74069d12018-07-20 15:26:25 -0700518 va_end(ap);
Tom Cherry8180b482019-08-26 13:57:51 -0700519 if (length_written <= 0) {
520 return 0;
521 }
Thiébaud Weksteenf03dde82023-04-03 16:53:12 +1000522
523 // libselinux log messages usually contain a new line character, while
524 // Android LOG() does not expect it. Remove it to avoid empty lines in
525 // the log buffers.
526 size_t str_len = strlen(buf);
527 if (buf[str_len - 1] == '\n') {
528 buf[str_len - 1] = '\0';
529 }
530
Tom Cherry8180b482019-08-26 13:57:51 -0700531 if (type == SELINUX_AVC) {
Thiébaud Weksteenf03dde82023-04-03 16:53:12 +1000532 SelinuxAvcLog(buf);
Tom Cherry8180b482019-08-26 13:57:51 -0700533 } else {
534 android::base::KernelLogger(android::base::MAIN, severity, "selinux", nullptr, 0, buf);
535 }
Tom Cherry74069d12018-07-20 15:26:25 -0700536 return 0;
537}
538
Tom Cherryc3170092017-08-10 12:22:44 -0700539void SelinuxSetupKernelLogging() {
540 selinux_callback cb;
Tom Cherry74069d12018-07-20 15:26:25 -0700541 cb.func_log = SelinuxKlogCallback;
Tom Cherryc3170092017-08-10 12:22:44 -0700542 selinux_set_callback(SELINUX_CB_LOG, cb);
543}
544
Tom Cherry40acb372018-08-01 13:41:12 -0700545int SelinuxGetVendorAndroidVersion() {
Nikita Ioffea66adf42023-06-26 14:55:31 +0100546 if (IsMicrodroid()) {
547 // As of now Microdroid doesn't have any vendor code.
548 return __ANDROID_API_FUTURE__;
549 }
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700550 static int vendor_android_version = [] {
551 if (!IsSplitPolicyDevice()) {
552 // If this device does not split sepolicy files, it's not a Treble device and therefore,
553 // we assume it's always on the latest platform.
554 return __ANDROID_API_FUTURE__;
555 }
Logan Chien837b2a42018-05-03 14:33:52 +0800556
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700557 std::string version;
558 if (!GetVendorMappingVersion(&version)) {
559 LOG(FATAL) << "Could not read vendor SELinux version";
560 }
Logan Chien837b2a42018-05-03 14:33:52 +0800561
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700562 int major_version;
563 std::string major_version_str(version, 0, version.find('.'));
564 if (!ParseInt(major_version_str, &major_version)) {
565 PLOG(FATAL) << "Failed to parse the vendor sepolicy major version "
566 << major_version_str;
567 }
Logan Chien837b2a42018-05-03 14:33:52 +0800568
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700569 return major_version;
570 }();
571 return vendor_android_version;
Logan Chien837b2a42018-05-03 14:33:52 +0800572}
573
David Andersond0ce5302020-03-20 21:47:10 -0700574// This is for R system.img/system_ext.img to work on old vendor.img as system_ext.img
575// is introduced in R. We mount system_ext in second stage init because the first-stage
576// init in boot.img won't be updated in the system-only OTA scenario.
577void MountMissingSystemPartitions() {
578 android::fs_mgr::Fstab fstab;
579 if (!ReadDefaultFstab(&fstab)) {
580 LOG(ERROR) << "Could not read default fstab";
581 }
582
583 android::fs_mgr::Fstab mounts;
584 if (!ReadFstabFromFile("/proc/mounts", &mounts)) {
585 LOG(ERROR) << "Could not read /proc/mounts";
586 }
587
588 static const std::vector<std::string> kPartitionNames = {"system_ext", "product"};
589
590 android::fs_mgr::Fstab extra_fstab;
591 for (const auto& name : kPartitionNames) {
592 if (GetEntryForMountPoint(&mounts, "/"s + name)) {
593 // The partition is already mounted.
594 continue;
595 }
596
Lianjun Huangccd094c2023-02-17 20:22:37 +0800597 auto system_entries = GetEntriesForMountPoint(&fstab, "/system");
598 for (auto& system_entry : system_entries) {
599 if (!system_entry) {
600 LOG(ERROR) << "Could not find mount entry for /system";
601 break;
602 }
603 if (!system_entry->fs_mgr_flags.logical) {
604 LOG(INFO) << "Skipping mount of " << name << ", system is not dynamic.";
605 break;
606 }
David Andersond0ce5302020-03-20 21:47:10 -0700607
Lianjun Huangccd094c2023-02-17 20:22:37 +0800608 auto entry = *system_entry;
609 auto partition_name = name + fs_mgr_get_slot_suffix();
610 auto replace_name = "system"s + fs_mgr_get_slot_suffix();
David Andersond0ce5302020-03-20 21:47:10 -0700611
Lianjun Huangccd094c2023-02-17 20:22:37 +0800612 entry.mount_point = "/"s + name;
613 entry.blk_device =
David Andersond0ce5302020-03-20 21:47:10 -0700614 android::base::StringReplace(entry.blk_device, replace_name, partition_name, false);
Lianjun Huangccd094c2023-02-17 20:22:37 +0800615 if (!fs_mgr_update_logical_partition(&entry)) {
616 LOG(ERROR) << "Could not update logical partition";
617 continue;
618 }
David Andersond0ce5302020-03-20 21:47:10 -0700619
Lianjun Huangccd094c2023-02-17 20:22:37 +0800620 extra_fstab.emplace_back(std::move(entry));
621 }
David Andersond0ce5302020-03-20 21:47:10 -0700622 }
623
Yi-Yo Chiang20579012021-04-01 20:14:54 +0800624 SkipMountingPartitions(&extra_fstab, true /* verbose */);
David Andersond0ce5302020-03-20 21:47:10 -0700625 if (extra_fstab.empty()) {
626 return;
627 }
628
629 BlockDevInitializer block_dev_init;
630 for (auto& entry : extra_fstab) {
631 if (access(entry.blk_device.c_str(), F_OK) != 0) {
632 auto block_dev = android::base::Basename(entry.blk_device);
633 if (!block_dev_init.InitDmDevice(block_dev)) {
634 LOG(ERROR) << "Failed to find device-mapper node: " << block_dev;
635 continue;
636 }
637 }
638 if (fs_mgr_do_mount_one(entry)) {
639 LOG(ERROR) << "Could not mount " << entry.mount_point;
640 }
641 }
642}
643
David Anderson491e4da2020-12-08 00:21:20 -0800644static void LoadSelinuxPolicy(std::string& policy) {
645 LOG(INFO) << "Loading SELinux policy";
646
647 set_selinuxmnt("/sys/fs/selinux");
648 if (security_load_policy(policy.data(), policy.size()) < 0) {
649 PLOG(FATAL) << "SELinux: Could not load policy";
650 }
651}
652
Nikita Ioffea66adf42023-06-26 14:55:31 +0100653// Encapsulates steps to load SELinux policy in Microdroid.
654// So far the process is very straightforward - just load the precompiled policy from /system.
655void LoadSelinuxPolicyMicrodroid() {
656 constexpr const char kMicrodroidPrecompiledSepolicy[] =
657 "/system/etc/selinux/microdroid_precompiled_sepolicy";
658
659 LOG(INFO) << "Opening SELinux policy from " << kMicrodroidPrecompiledSepolicy;
660 unique_fd policy_fd(open(kMicrodroidPrecompiledSepolicy, O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
661 if (policy_fd < 0) {
662 PLOG(FATAL) << "Failed to open " << kMicrodroidPrecompiledSepolicy;
663 }
664
665 std::string policy;
666 if (!android::base::ReadFdToString(policy_fd, &policy)) {
667 PLOG(FATAL) << "Failed to read policy file: " << kMicrodroidPrecompiledSepolicy;
668 }
669
670 LoadSelinuxPolicy(policy);
671}
672
David Anderson491e4da2020-12-08 00:21:20 -0800673// The SELinux setup process is carefully orchestrated around snapuserd. Policy
674// must be loaded off dynamic partitions, and during an OTA, those partitions
675// cannot be read without snapuserd. But, with kernel-privileged snapuserd
676// running, loading the policy will immediately trigger audits.
677//
678// We use a five-step process to address this:
679// (1) Read the policy into a string, with snapuserd running.
680// (2) Rewrite the snapshot device-mapper tables, to generate new dm-user
681// devices and to flush I/O.
682// (3) Kill snapuserd, which no longer has any dm-user devices to attach to.
683// (4) Load the sepolicy and issue critical restorecons in /dev, carefully
684// avoiding anything that would read from /system.
685// (5) Re-launch snapuserd and attach it to the dm-user devices from step (2).
686//
687// After this sequence, it is safe to enable enforcing mode and continue booting.
Nikita Ioffea66adf42023-06-26 14:55:31 +0100688void LoadSelinuxPolicyAndroid() {
David Andersond0ce5302020-03-20 21:47:10 -0700689 MountMissingSystemPartitions();
690
David Anderson491e4da2020-12-08 00:21:20 -0800691 LOG(INFO) << "Opening SELinux policy";
692
693 // Read the policy before potentially killing snapuserd.
694 std::string policy;
695 ReadPolicy(&policy);
696
697 auto snapuserd_helper = SnapuserdSelinuxHelper::CreateIfNeeded();
698 if (snapuserd_helper) {
Nikita Ioffea66adf42023-06-26 14:55:31 +0100699 // Kill the old snapused to avoid audit messages. After this we cannot read from /system
700 // (or other dynamic partitions) until we call FinishTransition().
David Anderson491e4da2020-12-08 00:21:20 -0800701 snapuserd_helper->StartTransition();
702 }
703
704 LoadSelinuxPolicy(policy);
705
706 if (snapuserd_helper) {
707 // Before enforcing, finish the pending snapuserd transition.
708 snapuserd_helper->FinishTransition();
709 snapuserd_helper = nullptr;
710 }
Nikita Ioffea66adf42023-06-26 14:55:31 +0100711}
712
713int SetupSelinux(char** argv) {
714 SetStdioToDevNull(argv);
715 InitKernelLogging(argv);
716
717 if (REBOOT_BOOTLOADER_ON_PANIC) {
718 InstallRebootSignalHandlers();
719 }
720
721 boot_clock::time_point start_time = boot_clock::now();
722
723 SelinuxSetupKernelLogging();
724
725 // TODO(b/287206497): refactor into different headers to only include what we need.
726 if (IsMicrodroid()) {
727 LoadSelinuxPolicyMicrodroid();
728 } else {
729 LoadSelinuxPolicyAndroid();
730 }
Jeffrey Vander Stoepbaeece62022-02-08 12:42:33 +0000731
David Anderson491e4da2020-12-08 00:21:20 -0800732 SelinuxSetEnforcement();
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800733
Nikita Ioffefeb7e0e2024-03-28 00:32:36 +0000734 if (IsMicrodroid() && android::virtualization::IsOpenDiceChangesFlagEnabled()) {
735 // We run restorecon of /microdroid_resources while we are still in kernel context to avoid
736 // granting init `tmpfs:file relabelfrom` capability.
737 const int flags = SELINUX_ANDROID_RESTORECON_RECURSE;
738 if (selinux_android_restorecon("/microdroid_resources", flags) == -1) {
739 PLOG(FATAL) << "restorecon of /microdroid_resources failed";
740 }
741 }
742
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800743 // We're in the kernel domain and want to transition to the init domain. File systems that
744 // store SELabels in their xattrs, such as ext4 do not need an explicit restorecon here,
745 // but other file systems do. In particular, this is needed for ramdisks such as the
746 // recovery image for A/B devices.
747 if (selinux_android_restorecon("/system/bin/init", 0) == -1) {
748 PLOG(FATAL) << "restorecon failed of /system/bin/init failed";
749 }
750
Mark Salyzyn44505ec2019-05-08 12:44:50 -0700751 setenv(kEnvSelinuxStartedAt, std::to_string(start_time.time_since_epoch().count()).c_str(), 1);
Mark Salyzyn10377df2019-03-27 08:10:41 -0700752
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800753 const char* path = "/system/bin/init";
754 const char* args[] = {path, "second_stage", nullptr};
755 execv(path, const_cast<char**>(args));
756
757 // execv() only returns if an error happened, in which case we
758 // panic and never return from this function.
759 PLOG(FATAL) << "execv(\"" << path << "\") failed";
760
761 return 1;
762}
763
Tom Cherryc3170092017-08-10 12:22:44 -0700764} // namespace init
765} // namespace android