blob: 9095b854eb18b4dfeefa95fb5f6c9cdca5742bce [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>
Bowgo Tsai1dacd422019-03-04 17:53:34 +080069#include <fs_avb/fs_avb.h>
David Andersond0ce5302020-03-20 21:47:10 -070070#include <fs_mgr.h>
Bowgo Tsai196cc582020-01-20 18:03:58 +080071#include <libgsi/libgsi.h>
Yifan Hongd91998f2020-02-20 17:54:57 -080072#include <libsnapshot/snapshot.h>
Tom Cherryc3170092017-08-10 12:22:44 -070073#include <selinux/android.h>
74
David Andersond0ce5302020-03-20 21:47:10 -070075#include "block_dev_initializer.h"
Bowgo Tsai30afda72019-04-11 23:57:24 +080076#include "debug_ramdisk.h"
Tom Cherry7bfea3d2018-11-06 14:12:05 -080077#include "reboot_utils.h"
David Anderson491e4da2020-12-08 00:21:20 -080078#include "snapuserd_transition.h"
Tom Cherryc3170092017-08-10 12:22:44 -070079#include "util.h"
80
Bowgo Tsai1dacd422019-03-04 17:53:34 +080081using namespace std::string_literals;
82
Logan Chien837b2a42018-05-03 14:33:52 +080083using android::base::ParseInt;
Tom Cherryc3170092017-08-10 12:22:44 -070084using android::base::Timer;
85using android::base::unique_fd;
Bowgo Tsai1dacd422019-03-04 17:53:34 +080086using android::fs_mgr::AvbHandle;
Yifan Hongd91998f2020-02-20 17:54:57 -080087using android::snapshot::SnapshotManager;
Tom Cherryc3170092017-08-10 12:22:44 -070088
89namespace android {
90namespace init {
91
Tom Cherryc3170092017-08-10 12:22:44 -070092namespace {
93
94enum EnforcingStatus { SELINUX_PERMISSIVE, SELINUX_ENFORCING };
95
Alistair Delva63594a42021-03-09 11:04:23 -080096EnforcingStatus StatusFromProperty() {
Yi-Yo Chiangda5323e2023-08-02 01:08:23 +080097 std::string value;
98 if (android::fs_mgr::GetKernelCmdline("androidboot.selinux", &value) && value == "permissive") {
99 return SELINUX_PERMISSIVE;
Alistair Delva63594a42021-03-09 11:04:23 -0800100 }
Yi-Yo Chiangda5323e2023-08-02 01:08:23 +0800101 if (android::fs_mgr::GetBootconfig("androidboot.selinux", &value) && value == "permissive") {
102 return SELINUX_PERMISSIVE;
103 }
104 return SELINUX_ENFORCING;
Tom Cherryc3170092017-08-10 12:22:44 -0700105}
106
107bool IsEnforcing() {
108 if (ALLOW_PERMISSIVE_SELINUX) {
Alistair Delva63594a42021-03-09 11:04:23 -0800109 return StatusFromProperty() == SELINUX_ENFORCING;
Tom Cherryc3170092017-08-10 12:22:44 -0700110 }
111 return true;
112}
113
114// Forks, executes the provided program in the child, and waits for the completion in the parent.
115// Child's stderr is captured and logged using LOG(ERROR).
116bool ForkExecveAndWaitForCompletion(const char* filename, char* const argv[]) {
117 // Create a pipe used for redirecting child process's output.
118 // * pipe_fds[0] is the FD the parent will use for reading.
119 // * pipe_fds[1] is the FD the child will use for writing.
120 int pipe_fds[2];
121 if (pipe(pipe_fds) == -1) {
122 PLOG(ERROR) << "Failed to create pipe";
123 return false;
124 }
125
126 pid_t child_pid = fork();
127 if (child_pid == -1) {
128 PLOG(ERROR) << "Failed to fork for " << filename;
129 return false;
130 }
131
132 if (child_pid == 0) {
133 // fork succeeded -- this is executing in the child process
134
135 // Close the pipe FD not used by this process
Nick Kralevich3d118e72017-10-24 10:45:48 -0700136 close(pipe_fds[0]);
Tom Cherryc3170092017-08-10 12:22:44 -0700137
138 // Redirect stderr to the pipe FD provided by the parent
139 if (TEMP_FAILURE_RETRY(dup2(pipe_fds[1], STDERR_FILENO)) == -1) {
140 PLOG(ERROR) << "Failed to redirect stderr of " << filename;
141 _exit(127);
142 return false;
143 }
Nick Kralevich3d118e72017-10-24 10:45:48 -0700144 close(pipe_fds[1]);
Tom Cherryc3170092017-08-10 12:22:44 -0700145
Tom Cherry6de21f12017-08-22 15:41:03 -0700146 if (execv(filename, argv) == -1) {
Tom Cherryc3170092017-08-10 12:22:44 -0700147 PLOG(ERROR) << "Failed to execve " << filename;
148 return false;
149 }
150 // Unreachable because execve will have succeeded and replaced this code
151 // with child process's code.
152 _exit(127);
153 return false;
154 } else {
155 // fork succeeded -- this is executing in the original/parent process
156
157 // Close the pipe FD not used by this process
Nick Kralevich3d118e72017-10-24 10:45:48 -0700158 close(pipe_fds[1]);
Tom Cherryc3170092017-08-10 12:22:44 -0700159
160 // Log the redirected output of the child process.
161 // It's unfortunate that there's no standard way to obtain an istream for a file descriptor.
162 // As a result, we're buffering all output and logging it in one go at the end of the
163 // invocation, instead of logging it as it comes in.
164 const int child_out_fd = pipe_fds[0];
165 std::string child_output;
166 if (!android::base::ReadFdToString(child_out_fd, &child_output)) {
167 PLOG(ERROR) << "Failed to capture full output of " << filename;
168 }
Nick Kralevich3d118e72017-10-24 10:45:48 -0700169 close(child_out_fd);
Tom Cherryc3170092017-08-10 12:22:44 -0700170 if (!child_output.empty()) {
171 // Log captured output, line by line, because LOG expects to be invoked for each line
172 std::istringstream in(child_output);
173 std::string line;
174 while (std::getline(in, line)) {
175 LOG(ERROR) << filename << ": " << line;
176 }
177 }
178
179 // Wait for child to terminate
180 int status;
181 if (TEMP_FAILURE_RETRY(waitpid(child_pid, &status, 0)) != child_pid) {
182 PLOG(ERROR) << "Failed to wait for " << filename;
183 return false;
184 }
185
186 if (WIFEXITED(status)) {
187 int status_code = WEXITSTATUS(status);
188 if (status_code == 0) {
189 return true;
190 } else {
191 LOG(ERROR) << filename << " exited with status " << status_code;
192 }
193 } else if (WIFSIGNALED(status)) {
194 LOG(ERROR) << filename << " killed by signal " << WTERMSIG(status);
195 } else if (WIFSTOPPED(status)) {
196 LOG(ERROR) << filename << " stopped by signal " << WSTOPSIG(status);
197 } else {
198 LOG(ERROR) << "waitpid for " << filename << " returned unexpected status: " << status;
199 }
200
201 return false;
202 }
203}
204
205bool ReadFirstLine(const char* file, std::string* line) {
206 line->clear();
207
208 std::string contents;
209 if (!android::base::ReadFileToString(file, &contents, true /* follow symlinks */)) {
210 return false;
211 }
212 std::istringstream in(contents);
213 std::getline(in, *line);
214 return true;
215}
216
Inseob Kimd99d9772021-03-11 17:58:26 +0900217Result<std::string> FindPrecompiledSplitPolicy() {
218 std::string precompiled_sepolicy;
kaichieheef4cd72017-08-31 22:07:19 +0800219 // If there is an odm partition, precompiled_sepolicy will be in
220 // odm/etc/selinux. Otherwise it will be in vendor/etc/selinux.
221 static constexpr const char vendor_precompiled_sepolicy[] =
Sandro1120f7f2022-09-05 15:56:38 +0000222 "/vendor/etc/selinux/precompiled_sepolicy";
kaichieheef4cd72017-08-31 22:07:19 +0800223 static constexpr const char odm_precompiled_sepolicy[] =
Sandro1120f7f2022-09-05 15:56:38 +0000224 "/odm/etc/selinux/precompiled_sepolicy";
kaichieheef4cd72017-08-31 22:07:19 +0800225 if (access(odm_precompiled_sepolicy, R_OK) == 0) {
Inseob Kimd99d9772021-03-11 17:58:26 +0900226 precompiled_sepolicy = odm_precompiled_sepolicy;
kaichieheef4cd72017-08-31 22:07:19 +0800227 } else if (access(vendor_precompiled_sepolicy, R_OK) == 0) {
Inseob Kimd99d9772021-03-11 17:58:26 +0900228 precompiled_sepolicy = vendor_precompiled_sepolicy;
kaichieheef4cd72017-08-31 22:07:19 +0800229 } else {
Inseob Kimd99d9772021-03-11 17:58:26 +0900230 return ErrnoError() << "No precompiled sepolicy at " << vendor_precompiled_sepolicy;
Tom Cherryc3170092017-08-10 12:22:44 -0700231 }
kaichieheef4cd72017-08-31 22:07:19 +0800232
Inseob Kimd99d9772021-03-11 17:58:26 +0900233 // Use precompiled sepolicy only when all corresponding hashes are equal.
Inseob Kimd99d9772021-03-11 17:58:26 +0900234 std::vector<std::pair<std::string, std::string>> sepolicy_hashes{
235 {"/system/etc/selinux/plat_sepolicy_and_mapping.sha256",
236 precompiled_sepolicy + ".plat_sepolicy_and_mapping.sha256"},
Inseob Kim28fdb672021-04-29 19:48:27 +0900237 {"/system_ext/etc/selinux/system_ext_sepolicy_and_mapping.sha256",
238 precompiled_sepolicy + ".system_ext_sepolicy_and_mapping.sha256"},
239 {"/product/etc/selinux/product_sepolicy_and_mapping.sha256",
240 precompiled_sepolicy + ".product_sepolicy_and_mapping.sha256"},
Inseob Kimd99d9772021-03-11 17:58:26 +0900241 };
242
Inseob Kimd99d9772021-03-11 17:58:26 +0900243 for (const auto& [actual_id_path, precompiled_id_path] : sepolicy_hashes) {
Inseob Kim28fdb672021-04-29 19:48:27 +0900244 // Both of them should exist or both of them shouldn't exist.
245 if (access(actual_id_path.c_str(), R_OK) != 0) {
246 if (access(precompiled_id_path.c_str(), R_OK) == 0) {
247 return Error() << precompiled_id_path << " exists but " << actual_id_path
248 << " doesn't";
249 }
250 continue;
251 }
252
Inseob Kimd99d9772021-03-11 17:58:26 +0900253 std::string actual_id;
254 if (!ReadFirstLine(actual_id_path.c_str(), &actual_id)) {
255 return ErrnoError() << "Failed to read " << actual_id_path;
256 }
257
258 std::string precompiled_id;
259 if (!ReadFirstLine(precompiled_id_path.c_str(), &precompiled_id)) {
260 return ErrnoError() << "Failed to read " << precompiled_id_path;
261 }
262
263 if (actual_id.empty() || actual_id != precompiled_id) {
264 return Error() << actual_id_path << " and " << precompiled_id_path << " differ";
265 }
Tri Voc8137f92019-01-22 18:22:25 -0800266 }
Inseob Kimd99d9772021-03-11 17:58:26 +0900267
268 return precompiled_sepolicy;
Tom Cherryc3170092017-08-10 12:22:44 -0700269}
270
271bool GetVendorMappingVersion(std::string* plat_vers) {
272 if (!ReadFirstLine("/vendor/etc/selinux/plat_sepolicy_vers.txt", plat_vers)) {
273 PLOG(ERROR) << "Failed to read /vendor/etc/selinux/plat_sepolicy_vers.txt";
274 return false;
275 }
276 if (plat_vers->empty()) {
277 LOG(ERROR) << "No version present in plat_sepolicy_vers.txt";
278 return false;
279 }
280 return true;
281}
282
283constexpr const char plat_policy_cil_file[] = "/system/etc/selinux/plat_sepolicy.cil";
284
285bool IsSplitPolicyDevice() {
286 return access(plat_policy_cil_file, R_OK) != -1;
287}
288
Yi-Yo Chiangbb77c542021-09-23 14:14:16 +0000289std::optional<const char*> GetUserdebugPlatformPolicyFile() {
290 // See if we need to load userdebug_plat_sepolicy.cil instead of plat_sepolicy.cil.
291 const char* force_debuggable_env = getenv("INIT_FORCE_DEBUGGABLE");
292 if (force_debuggable_env && "true"s == force_debuggable_env && AvbHandle::IsDeviceUnlocked()) {
293 const std::vector<const char*> debug_policy_candidates = {
294#if INSTALL_DEBUG_POLICY_TO_SYSTEM_EXT == 1
295 "/system_ext/etc/selinux/userdebug_plat_sepolicy.cil",
296#endif
297 kDebugRamdiskSEPolicy,
298 };
299 for (const char* debug_policy : debug_policy_candidates) {
300 if (access(debug_policy, F_OK) == 0) {
301 return debug_policy;
302 }
303 }
304 }
305 return std::nullopt;
306}
307
David Anderson491e4da2020-12-08 00:21:20 -0800308struct PolicyFile {
309 unique_fd fd;
310 std::string path;
311};
312
313bool OpenSplitPolicy(PolicyFile* policy_file) {
Jeff Vander Stoep5effda42021-11-05 09:03:11 +0100314 // IMPLEMENTATION NOTE: Split policy consists of three or more CIL files:
Tom Cherryc3170092017-08-10 12:22:44 -0700315 // * platform -- policy needed due to logic contained in the system image,
Jeff Vander Stoep5effda42021-11-05 09:03:11 +0100316 // * vendor -- policy needed due to logic contained in the vendor image,
Tom Cherryc3170092017-08-10 12:22:44 -0700317 // * mapping -- mapping policy which helps preserve forward-compatibility of non-platform policy
318 // with newer versions of platform policy.
Thiébaud Weksteen50f03fd2023-09-06 10:52:49 +1000319 // * (optional) policy needed due to logic on product, system_ext, or odm images.
Tom Cherryc3170092017-08-10 12:22:44 -0700320 // secilc is invoked to compile the above three policy files into a single monolithic policy
321 // file. This file is then loaded into the kernel.
322
Yi-Yo Chiangbb77c542021-09-23 14:14:16 +0000323 const auto userdebug_plat_sepolicy = GetUserdebugPlatformPolicyFile();
324 const bool use_userdebug_policy = userdebug_plat_sepolicy.has_value();
Bowgo Tsai1dacd422019-03-04 17:53:34 +0800325 if (use_userdebug_policy) {
Yi-Yo Chiangbb77c542021-09-23 14:14:16 +0000326 LOG(INFO) << "Using userdebug system sepolicy " << *userdebug_plat_sepolicy;
Bowgo Tsai1dacd422019-03-04 17:53:34 +0800327 }
328
Tom Cherryc3170092017-08-10 12:22:44 -0700329 // Load precompiled policy from vendor image, if a matching policy is found there. The policy
330 // must match the platform policy on the system image.
Bowgo Tsai1dacd422019-03-04 17:53:34 +0800331 // use_userdebug_policy requires compiling sepolicy with userdebug_plat_sepolicy.cil.
332 // Thus it cannot use the precompiled policy from vendor image.
Inseob Kimd99d9772021-03-11 17:58:26 +0900333 if (!use_userdebug_policy) {
334 if (auto res = FindPrecompiledSplitPolicy(); res.ok()) {
335 unique_fd fd(open(res->c_str(), O_RDONLY | O_CLOEXEC | O_BINARY));
336 if (fd != -1) {
337 policy_file->fd = std::move(fd);
338 policy_file->path = std::move(*res);
339 return true;
340 }
341 } else {
342 LOG(INFO) << res.error();
Tom Cherryc3170092017-08-10 12:22:44 -0700343 }
344 }
345 // No suitable precompiled policy could be loaded
346
347 LOG(INFO) << "Compiling SELinux policy";
348
Tom Cherryc3170092017-08-10 12:22:44 -0700349 // We store the output of the compilation on /dev because this is the most convenient tmpfs
350 // storage mount available this early in the boot sequence.
351 char compiled_sepolicy[] = "/dev/sepolicy.XXXXXX";
352 unique_fd compiled_sepolicy_fd(mkostemp(compiled_sepolicy, O_CLOEXEC));
353 if (compiled_sepolicy_fd < 0) {
354 PLOG(ERROR) << "Failed to create temporary file " << compiled_sepolicy;
355 return false;
356 }
357
358 // Determine which mapping file to include
359 std::string vend_plat_vers;
360 if (!GetVendorMappingVersion(&vend_plat_vers)) {
361 return false;
362 }
Tri Vo503f1852019-01-16 11:57:19 -0800363 std::string plat_mapping_file("/system/etc/selinux/mapping/" + vend_plat_vers + ".cil");
kaichieheef4cd72017-08-31 22:07:19 +0800364
Jeff Vander Stoep0ac51cf2019-05-02 14:05:18 -0700365 std::string plat_compat_cil_file("/system/etc/selinux/mapping/" + vend_plat_vers +
366 ".compat.cil");
367 if (access(plat_compat_cil_file.c_str(), F_OK) == -1) {
368 plat_compat_cil_file.clear();
369 }
370
Bowgo Tsaif016f252019-08-28 17:56:51 +0800371 std::string system_ext_policy_cil_file("/system_ext/etc/selinux/system_ext_sepolicy.cil");
372 if (access(system_ext_policy_cil_file.c_str(), F_OK) == -1) {
373 system_ext_policy_cil_file.clear();
374 }
375
376 std::string system_ext_mapping_file("/system_ext/etc/selinux/mapping/" + vend_plat_vers +
377 ".cil");
378 if (access(system_ext_mapping_file.c_str(), F_OK) == -1) {
379 system_ext_mapping_file.clear();
380 }
381
Yi-Yo Chiang731d2472021-03-23 22:11:13 +0800382 std::string system_ext_compat_cil_file("/system_ext/etc/selinux/mapping/" + vend_plat_vers +
383 ".compat.cil");
384 if (access(system_ext_compat_cil_file.c_str(), F_OK) == -1) {
385 system_ext_compat_cil_file.clear();
386 }
387
Tri Vod3518cf2018-12-14 14:25:08 -0800388 std::string product_policy_cil_file("/product/etc/selinux/product_sepolicy.cil");
389 if (access(product_policy_cil_file.c_str(), F_OK) == -1) {
390 product_policy_cil_file.clear();
391 }
392
Tri Vo503f1852019-01-16 11:57:19 -0800393 std::string product_mapping_file("/product/etc/selinux/mapping/" + vend_plat_vers + ".cil");
394 if (access(product_mapping_file.c_str(), F_OK) == -1) {
395 product_mapping_file.clear();
396 }
397
kaichieheef4cd72017-08-31 22:07:19 +0800398 std::string vendor_policy_cil_file("/vendor/etc/selinux/vendor_sepolicy.cil");
kaichieheef4cd72017-08-31 22:07:19 +0800399 if (access(vendor_policy_cil_file.c_str(), F_OK) == -1) {
Jeff Vander Stoep5effda42021-11-05 09:03:11 +0100400 LOG(ERROR) << "Missing " << vendor_policy_cil_file;
401 return false;
402 }
403
404 std::string plat_pub_versioned_cil_file("/vendor/etc/selinux/plat_pub_versioned.cil");
405 if (access(plat_pub_versioned_cil_file.c_str(), F_OK) == -1) {
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800406 LOG(ERROR) << "Missing " << plat_pub_versioned_cil_file;
kaichieheef4cd72017-08-31 22:07:19 +0800407 return false;
408 }
409
410 // odm_sepolicy.cil is default but optional.
411 std::string odm_policy_cil_file("/odm/etc/selinux/odm_sepolicy.cil");
412 if (access(odm_policy_cil_file.c_str(), F_OK) == -1) {
413 odm_policy_cil_file.clear();
414 }
Jeff Vander Stoep724eda52019-02-15 12:13:38 -0800415 const std::string version_as_string = std::to_string(SEPOLICY_VERSION);
Andreas Huberc41b8382017-08-18 14:43:52 -0700416
Tom Cherryc3170092017-08-10 12:22:44 -0700417 // clang-format off
kaichieheef4cd72017-08-31 22:07:19 +0800418 std::vector<const char*> compile_args {
Tom Cherryc3170092017-08-10 12:22:44 -0700419 "/system/bin/secilc",
Yi-Yo Chiangbb77c542021-09-23 14:14:16 +0000420 use_userdebug_policy ? *userdebug_plat_sepolicy : plat_policy_cil_file,
Jeff Vander Stoep5e9ba3c2017-10-06 17:03:45 -0700421 "-m", "-M", "true", "-G", "-N",
Andreas Huberc41b8382017-08-18 14:43:52 -0700422 "-c", version_as_string.c_str(),
Tri Vo503f1852019-01-16 11:57:19 -0800423 plat_mapping_file.c_str(),
Tom Cherryc3170092017-08-10 12:22:44 -0700424 "-o", compiled_sepolicy,
425 // We don't care about file_contexts output by the compiler
426 "-f", "/sys/fs/selinux/null", // /dev/null is not yet available
kaichieheef4cd72017-08-31 22:07:19 +0800427 };
Tom Cherryc3170092017-08-10 12:22:44 -0700428 // clang-format on
429
Jeff Vander Stoep0ac51cf2019-05-02 14:05:18 -0700430 if (!plat_compat_cil_file.empty()) {
431 compile_args.push_back(plat_compat_cil_file.c_str());
432 }
Bowgo Tsaif016f252019-08-28 17:56:51 +0800433 if (!system_ext_policy_cil_file.empty()) {
434 compile_args.push_back(system_ext_policy_cil_file.c_str());
435 }
436 if (!system_ext_mapping_file.empty()) {
437 compile_args.push_back(system_ext_mapping_file.c_str());
438 }
Yi-Yo Chiang731d2472021-03-23 22:11:13 +0800439 if (!system_ext_compat_cil_file.empty()) {
440 compile_args.push_back(system_ext_compat_cil_file.c_str());
441 }
Tri Vod3518cf2018-12-14 14:25:08 -0800442 if (!product_policy_cil_file.empty()) {
443 compile_args.push_back(product_policy_cil_file.c_str());
444 }
Tri Vo503f1852019-01-16 11:57:19 -0800445 if (!product_mapping_file.empty()) {
446 compile_args.push_back(product_mapping_file.c_str());
447 }
Bowgo Tsai069ab5b2017-10-18 17:03:20 +0800448 if (!plat_pub_versioned_cil_file.empty()) {
449 compile_args.push_back(plat_pub_versioned_cil_file.c_str());
kaichieheef4cd72017-08-31 22:07:19 +0800450 }
451 if (!vendor_policy_cil_file.empty()) {
452 compile_args.push_back(vendor_policy_cil_file.c_str());
453 }
454 if (!odm_policy_cil_file.empty()) {
455 compile_args.push_back(odm_policy_cil_file.c_str());
456 }
457 compile_args.push_back(nullptr);
458
459 if (!ForkExecveAndWaitForCompletion(compile_args[0], (char**)compile_args.data())) {
Tom Cherryc3170092017-08-10 12:22:44 -0700460 unlink(compiled_sepolicy);
461 return false;
462 }
463 unlink(compiled_sepolicy);
464
David Anderson491e4da2020-12-08 00:21:20 -0800465 policy_file->fd = std::move(compiled_sepolicy_fd);
466 policy_file->path = compiled_sepolicy;
Tom Cherryc3170092017-08-10 12:22:44 -0700467 return true;
468}
469
David Anderson491e4da2020-12-08 00:21:20 -0800470bool OpenMonolithicPolicy(PolicyFile* policy_file) {
471 static constexpr char kSepolicyFile[] = "/sepolicy";
472
Nikita Ioffea66adf42023-06-26 14:55:31 +0100473 LOG(INFO) << "Opening SELinux policy from monolithic file " << kSepolicyFile;
474 policy_file->fd.reset(open(kSepolicyFile, O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
David Anderson491e4da2020-12-08 00:21:20 -0800475 if (policy_file->fd < 0) {
476 PLOG(ERROR) << "Failed to open monolithic SELinux policy";
Tom Cherryc3170092017-08-10 12:22:44 -0700477 return false;
478 }
Nikita Ioffea66adf42023-06-26 14:55:31 +0100479 policy_file->path = kSepolicyFile;
Tom Cherryc3170092017-08-10 12:22:44 -0700480 return true;
481}
482
David Anderson491e4da2020-12-08 00:21:20 -0800483void ReadPolicy(std::string* policy) {
484 PolicyFile policy_file;
Tom Cherryc3170092017-08-10 12:22:44 -0700485
David Anderson491e4da2020-12-08 00:21:20 -0800486 bool ok = IsSplitPolicyDevice() ? OpenSplitPolicy(&policy_file)
487 : OpenMonolithicPolicy(&policy_file);
488 if (!ok) {
489 LOG(FATAL) << "Unable to open SELinux policy";
Tom Cherryc3170092017-08-10 12:22:44 -0700490 }
491
David Anderson491e4da2020-12-08 00:21:20 -0800492 if (!android::base::ReadFdToString(policy_file.fd, policy)) {
493 PLOG(FATAL) << "Failed to read policy file: " << policy_file.path;
494 }
495}
496
497void SelinuxSetEnforcement() {
Tom Cherryc3170092017-08-10 12:22:44 -0700498 bool kernel_enforcing = (security_getenforce() == 1);
499 bool is_enforcing = IsEnforcing();
500 if (kernel_enforcing != is_enforcing) {
501 if (security_setenforce(is_enforcing)) {
Paul Lawrenceb2c2d692019-08-30 11:11:44 -0700502 PLOG(FATAL) << "security_setenforce(" << (is_enforcing ? "true" : "false")
503 << ") failed";
Tom Cherryc3170092017-08-10 12:22:44 -0700504 }
505 }
506
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900507 if (auto result = WriteFile("/sys/fs/selinux/checkreqprot", "0"); !result.ok()) {
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700508 LOG(FATAL) << "Unable to write to /sys/fs/selinux/checkreqprot: " << result.error();
Tom Cherryc3170092017-08-10 12:22:44 -0700509 }
Tom Cherryc3170092017-08-10 12:22:44 -0700510}
511
Tom Cherry8180b482019-08-26 13:57:51 -0700512constexpr size_t kKlogMessageSize = 1024;
513
Thiébaud Weksteenf03dde82023-04-03 16:53:12 +1000514void SelinuxAvcLog(char* buf) {
Tom Cherry8180b482019-08-26 13:57:51 -0700515 struct NetlinkMessage {
516 nlmsghdr hdr;
517 char buf[kKlogMessageSize];
518 } request = {};
519
520 request.hdr.nlmsg_flags = NLM_F_REQUEST;
521 request.hdr.nlmsg_type = AUDIT_USER_AVC;
522 request.hdr.nlmsg_len = sizeof(request);
523 strlcpy(request.buf, buf, sizeof(request.buf));
524
525 auto fd = unique_fd{socket(PF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_AUDIT)};
526 if (!fd.ok()) {
527 return;
528 }
529
Bart Van Asscheaee2ec82022-12-02 18:48:15 -0800530 TEMP_FAILURE_RETRY(send(fd.get(), &request, sizeof(request), 0));
Tom Cherry8180b482019-08-26 13:57:51 -0700531}
532
Eric Biggers141c6a82023-08-11 21:05:14 +0000533int RestoreconIfExists(const char* path, unsigned int flags) {
534 if (access(path, F_OK) != 0 && errno == ENOENT) {
535 // Avoid error message for path that is expected to not always exist.
536 return 0;
537 }
538 return selinux_android_restorecon(path, flags);
539}
540
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800541} // namespace
542
Tom Cherryc3170092017-08-10 12:22:44 -0700543void SelinuxRestoreContext() {
544 LOG(INFO) << "Running restorecon...";
545 selinux_android_restorecon("/dev", 0);
Inseob Kim89d69132022-03-22 21:51:07 +0900546 selinux_android_restorecon("/dev/console", 0);
Tom Cherryc3170092017-08-10 12:22:44 -0700547 selinux_android_restorecon("/dev/kmsg", 0);
548 if constexpr (WORLD_WRITABLE_KMSG) {
549 selinux_android_restorecon("/dev/kmsg_debug", 0);
550 }
Tom Cherry81ae0752018-07-30 16:23:49 -0700551 selinux_android_restorecon("/dev/null", 0);
552 selinux_android_restorecon("/dev/ptmx", 0);
Tom Cherryc3170092017-08-10 12:22:44 -0700553 selinux_android_restorecon("/dev/socket", 0);
554 selinux_android_restorecon("/dev/random", 0);
555 selinux_android_restorecon("/dev/urandom", 0);
556 selinux_android_restorecon("/dev/__properties__", 0);
557
Tom Cherryc3170092017-08-10 12:22:44 -0700558 selinux_android_restorecon("/dev/block", SELINUX_ANDROID_RESTORECON_RECURSE);
David Anderson1ff75812020-11-13 00:31:47 -0800559 selinux_android_restorecon("/dev/dm-user", SELINUX_ANDROID_RESTORECON_RECURSE);
Tom Cherryc3170092017-08-10 12:22:44 -0700560 selinux_android_restorecon("/dev/device-mapper", 0);
Jiyong Park4ba548d2019-02-22 16:04:35 +0900561
562 selinux_android_restorecon("/apex", 0);
Jooyung Han566c6522023-08-09 07:05:31 +0000563 selinux_android_restorecon("/bootstrap-apex", 0);
Kiyoung Kim99df54b2019-11-22 16:14:10 +0900564 selinux_android_restorecon("/linkerconfig", 0);
Bowgo Tsai196cc582020-01-20 18:03:58 +0800565
David Andersonc991f342020-02-21 17:11:07 -0800566 // adb remount, snapshot-based updates, and DSUs all create files during
567 // first-stage init.
Eric Biggers141c6a82023-08-11 21:05:14 +0000568 RestoreconIfExists(SnapshotManager::GetGlobalRollbackIndicatorPath().c_str(), 0);
569 RestoreconIfExists("/metadata/gsi",
570 SELINUX_ANDROID_RESTORECON_RECURSE | SELINUX_ANDROID_RESTORECON_SKIP_SEHASH);
Tom Cherryc3170092017-08-10 12:22:44 -0700571}
572
Tom Cherry74069d12018-07-20 15:26:25 -0700573int SelinuxKlogCallback(int type, const char* fmt, ...) {
574 android::base::LogSeverity severity = android::base::ERROR;
575 if (type == SELINUX_WARNING) {
576 severity = android::base::WARNING;
577 } else if (type == SELINUX_INFO) {
578 severity = android::base::INFO;
579 }
Tom Cherry8180b482019-08-26 13:57:51 -0700580 char buf[kKlogMessageSize];
Tom Cherry74069d12018-07-20 15:26:25 -0700581 va_list ap;
582 va_start(ap, fmt);
Tom Cherry8180b482019-08-26 13:57:51 -0700583 int length_written = vsnprintf(buf, sizeof(buf), fmt, ap);
Tom Cherry74069d12018-07-20 15:26:25 -0700584 va_end(ap);
Tom Cherry8180b482019-08-26 13:57:51 -0700585 if (length_written <= 0) {
586 return 0;
587 }
Thiébaud Weksteenf03dde82023-04-03 16:53:12 +1000588
589 // libselinux log messages usually contain a new line character, while
590 // Android LOG() does not expect it. Remove it to avoid empty lines in
591 // the log buffers.
592 size_t str_len = strlen(buf);
593 if (buf[str_len - 1] == '\n') {
594 buf[str_len - 1] = '\0';
595 }
596
Tom Cherry8180b482019-08-26 13:57:51 -0700597 if (type == SELINUX_AVC) {
Thiébaud Weksteenf03dde82023-04-03 16:53:12 +1000598 SelinuxAvcLog(buf);
Tom Cherry8180b482019-08-26 13:57:51 -0700599 } else {
600 android::base::KernelLogger(android::base::MAIN, severity, "selinux", nullptr, 0, buf);
601 }
Tom Cherry74069d12018-07-20 15:26:25 -0700602 return 0;
603}
604
Tom Cherryc3170092017-08-10 12:22:44 -0700605void SelinuxSetupKernelLogging() {
606 selinux_callback cb;
Tom Cherry74069d12018-07-20 15:26:25 -0700607 cb.func_log = SelinuxKlogCallback;
Tom Cherryc3170092017-08-10 12:22:44 -0700608 selinux_set_callback(SELINUX_CB_LOG, cb);
609}
610
Tom Cherry40acb372018-08-01 13:41:12 -0700611int SelinuxGetVendorAndroidVersion() {
Nikita Ioffea66adf42023-06-26 14:55:31 +0100612 if (IsMicrodroid()) {
613 // As of now Microdroid doesn't have any vendor code.
614 return __ANDROID_API_FUTURE__;
615 }
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700616 static int vendor_android_version = [] {
617 if (!IsSplitPolicyDevice()) {
618 // If this device does not split sepolicy files, it's not a Treble device and therefore,
619 // we assume it's always on the latest platform.
620 return __ANDROID_API_FUTURE__;
621 }
Logan Chien837b2a42018-05-03 14:33:52 +0800622
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700623 std::string version;
624 if (!GetVendorMappingVersion(&version)) {
625 LOG(FATAL) << "Could not read vendor SELinux version";
626 }
Logan Chien837b2a42018-05-03 14:33:52 +0800627
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700628 int major_version;
629 std::string major_version_str(version, 0, version.find('.'));
630 if (!ParseInt(major_version_str, &major_version)) {
631 PLOG(FATAL) << "Failed to parse the vendor sepolicy major version "
632 << major_version_str;
633 }
Logan Chien837b2a42018-05-03 14:33:52 +0800634
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700635 return major_version;
636 }();
637 return vendor_android_version;
Logan Chien837b2a42018-05-03 14:33:52 +0800638}
639
David Andersond0ce5302020-03-20 21:47:10 -0700640// This is for R system.img/system_ext.img to work on old vendor.img as system_ext.img
641// is introduced in R. We mount system_ext in second stage init because the first-stage
642// init in boot.img won't be updated in the system-only OTA scenario.
643void MountMissingSystemPartitions() {
644 android::fs_mgr::Fstab fstab;
645 if (!ReadDefaultFstab(&fstab)) {
646 LOG(ERROR) << "Could not read default fstab";
647 }
648
649 android::fs_mgr::Fstab mounts;
650 if (!ReadFstabFromFile("/proc/mounts", &mounts)) {
651 LOG(ERROR) << "Could not read /proc/mounts";
652 }
653
654 static const std::vector<std::string> kPartitionNames = {"system_ext", "product"};
655
656 android::fs_mgr::Fstab extra_fstab;
657 for (const auto& name : kPartitionNames) {
658 if (GetEntryForMountPoint(&mounts, "/"s + name)) {
659 // The partition is already mounted.
660 continue;
661 }
662
Lianjun Huangccd094c2023-02-17 20:22:37 +0800663 auto system_entries = GetEntriesForMountPoint(&fstab, "/system");
664 for (auto& system_entry : system_entries) {
665 if (!system_entry) {
666 LOG(ERROR) << "Could not find mount entry for /system";
667 break;
668 }
669 if (!system_entry->fs_mgr_flags.logical) {
670 LOG(INFO) << "Skipping mount of " << name << ", system is not dynamic.";
671 break;
672 }
David Andersond0ce5302020-03-20 21:47:10 -0700673
Lianjun Huangccd094c2023-02-17 20:22:37 +0800674 auto entry = *system_entry;
675 auto partition_name = name + fs_mgr_get_slot_suffix();
676 auto replace_name = "system"s + fs_mgr_get_slot_suffix();
David Andersond0ce5302020-03-20 21:47:10 -0700677
Lianjun Huangccd094c2023-02-17 20:22:37 +0800678 entry.mount_point = "/"s + name;
679 entry.blk_device =
David Andersond0ce5302020-03-20 21:47:10 -0700680 android::base::StringReplace(entry.blk_device, replace_name, partition_name, false);
Lianjun Huangccd094c2023-02-17 20:22:37 +0800681 if (!fs_mgr_update_logical_partition(&entry)) {
682 LOG(ERROR) << "Could not update logical partition";
683 continue;
684 }
David Andersond0ce5302020-03-20 21:47:10 -0700685
Lianjun Huangccd094c2023-02-17 20:22:37 +0800686 extra_fstab.emplace_back(std::move(entry));
687 }
David Andersond0ce5302020-03-20 21:47:10 -0700688 }
689
Yi-Yo Chiang20579012021-04-01 20:14:54 +0800690 SkipMountingPartitions(&extra_fstab, true /* verbose */);
David Andersond0ce5302020-03-20 21:47:10 -0700691 if (extra_fstab.empty()) {
692 return;
693 }
694
695 BlockDevInitializer block_dev_init;
696 for (auto& entry : extra_fstab) {
697 if (access(entry.blk_device.c_str(), F_OK) != 0) {
698 auto block_dev = android::base::Basename(entry.blk_device);
699 if (!block_dev_init.InitDmDevice(block_dev)) {
700 LOG(ERROR) << "Failed to find device-mapper node: " << block_dev;
701 continue;
702 }
703 }
704 if (fs_mgr_do_mount_one(entry)) {
705 LOG(ERROR) << "Could not mount " << entry.mount_point;
706 }
707 }
708}
709
David Anderson491e4da2020-12-08 00:21:20 -0800710static void LoadSelinuxPolicy(std::string& policy) {
711 LOG(INFO) << "Loading SELinux policy";
712
713 set_selinuxmnt("/sys/fs/selinux");
714 if (security_load_policy(policy.data(), policy.size()) < 0) {
715 PLOG(FATAL) << "SELinux: Could not load policy";
716 }
717}
718
Nikita Ioffea66adf42023-06-26 14:55:31 +0100719// Encapsulates steps to load SELinux policy in Microdroid.
720// So far the process is very straightforward - just load the precompiled policy from /system.
721void LoadSelinuxPolicyMicrodroid() {
722 constexpr const char kMicrodroidPrecompiledSepolicy[] =
723 "/system/etc/selinux/microdroid_precompiled_sepolicy";
724
725 LOG(INFO) << "Opening SELinux policy from " << kMicrodroidPrecompiledSepolicy;
726 unique_fd policy_fd(open(kMicrodroidPrecompiledSepolicy, O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
727 if (policy_fd < 0) {
728 PLOG(FATAL) << "Failed to open " << kMicrodroidPrecompiledSepolicy;
729 }
730
731 std::string policy;
732 if (!android::base::ReadFdToString(policy_fd, &policy)) {
733 PLOG(FATAL) << "Failed to read policy file: " << kMicrodroidPrecompiledSepolicy;
734 }
735
736 LoadSelinuxPolicy(policy);
737}
738
David Anderson491e4da2020-12-08 00:21:20 -0800739// The SELinux setup process is carefully orchestrated around snapuserd. Policy
740// must be loaded off dynamic partitions, and during an OTA, those partitions
741// cannot be read without snapuserd. But, with kernel-privileged snapuserd
742// running, loading the policy will immediately trigger audits.
743//
744// We use a five-step process to address this:
745// (1) Read the policy into a string, with snapuserd running.
746// (2) Rewrite the snapshot device-mapper tables, to generate new dm-user
747// devices and to flush I/O.
748// (3) Kill snapuserd, which no longer has any dm-user devices to attach to.
749// (4) Load the sepolicy and issue critical restorecons in /dev, carefully
750// avoiding anything that would read from /system.
751// (5) Re-launch snapuserd and attach it to the dm-user devices from step (2).
752//
753// After this sequence, it is safe to enable enforcing mode and continue booting.
Nikita Ioffea66adf42023-06-26 14:55:31 +0100754void LoadSelinuxPolicyAndroid() {
David Andersond0ce5302020-03-20 21:47:10 -0700755 MountMissingSystemPartitions();
756
David Anderson491e4da2020-12-08 00:21:20 -0800757 LOG(INFO) << "Opening SELinux policy";
758
759 // Read the policy before potentially killing snapuserd.
760 std::string policy;
761 ReadPolicy(&policy);
762
763 auto snapuserd_helper = SnapuserdSelinuxHelper::CreateIfNeeded();
764 if (snapuserd_helper) {
Nikita Ioffea66adf42023-06-26 14:55:31 +0100765 // Kill the old snapused to avoid audit messages. After this we cannot read from /system
766 // (or other dynamic partitions) until we call FinishTransition().
David Anderson491e4da2020-12-08 00:21:20 -0800767 snapuserd_helper->StartTransition();
768 }
769
770 LoadSelinuxPolicy(policy);
771
772 if (snapuserd_helper) {
773 // Before enforcing, finish the pending snapuserd transition.
774 snapuserd_helper->FinishTransition();
775 snapuserd_helper = nullptr;
776 }
Nikita Ioffea66adf42023-06-26 14:55:31 +0100777}
778
779int SetupSelinux(char** argv) {
780 SetStdioToDevNull(argv);
781 InitKernelLogging(argv);
782
783 if (REBOOT_BOOTLOADER_ON_PANIC) {
784 InstallRebootSignalHandlers();
785 }
786
787 boot_clock::time_point start_time = boot_clock::now();
788
789 SelinuxSetupKernelLogging();
790
791 // TODO(b/287206497): refactor into different headers to only include what we need.
792 if (IsMicrodroid()) {
793 LoadSelinuxPolicyMicrodroid();
794 } else {
795 LoadSelinuxPolicyAndroid();
796 }
Jeffrey Vander Stoepbaeece62022-02-08 12:42:33 +0000797
David Anderson491e4da2020-12-08 00:21:20 -0800798 SelinuxSetEnforcement();
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800799
800 // We're in the kernel domain and want to transition to the init domain. File systems that
801 // store SELabels in their xattrs, such as ext4 do not need an explicit restorecon here,
802 // but other file systems do. In particular, this is needed for ramdisks such as the
803 // recovery image for A/B devices.
804 if (selinux_android_restorecon("/system/bin/init", 0) == -1) {
805 PLOG(FATAL) << "restorecon failed of /system/bin/init failed";
806 }
807
Mark Salyzyn44505ec2019-05-08 12:44:50 -0700808 setenv(kEnvSelinuxStartedAt, std::to_string(start_time.time_since_epoch().count()).c_str(), 1);
Mark Salyzyn10377df2019-03-27 08:10:41 -0700809
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800810 const char* path = "/system/bin/init";
811 const char* args[] = {path, "second_stage", nullptr};
812 execv(path, const_cast<char**>(args));
813
814 // execv() only returns if an error happened, in which case we
815 // panic and never return from this function.
816 PLOG(FATAL) << "execv(\"" << path << "\") failed";
817
818 return 1;
819}
820
Tom Cherryc3170092017-08-10 12:22:44 -0700821} // namespace init
822} // namespace android