xref: /aosp_15_r20/system/core/init/selinux.cpp (revision 00c7fec1bb09f3284aad6a6f96d2f63dfc3650ad)
1 /*
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.
21 // 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.
23 
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 
29 // 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.
35 
36 // The split SEPolicy is loaded as described below:
37 // 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
39 //    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
43 //    precompiled_sepolicy directly if and only if the hashes along with the precompiled SEPolicy on
44 //    /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.
49 //    That function contains even more documentation with the specific implementation details of how
50 //    the SEPolicy is compiled if needed.
51 
52 #include "selinux.h"
53 
54 #include <android/api-level.h>
55 #include <fcntl.h>
56 #include <linux/audit.h>
57 #include <linux/netlink.h>
58 #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>
65 #include <android-base/parseint.h>
66 #include <android-base/result.h>
67 #include <android-base/strings.h>
68 #include <android-base/unique_fd.h>
69 #include <android/avf_cc_flags.h>
70 #include <fs_avb/fs_avb.h>
71 #include <fs_mgr.h>
72 #include <genfslabelsversion.h>
73 #include <libgsi/libgsi.h>
74 #include <libsnapshot/snapshot.h>
75 #include <selinux/android.h>
76 
77 #include "block_dev_initializer.h"
78 #include "debug_ramdisk.h"
79 #include "reboot_utils.h"
80 #include "snapuserd_transition.h"
81 #include "util.h"
82 
83 using namespace std::string_literals;
84 
85 using android::base::ParseInt;
86 using android::base::Timer;
87 using android::base::unique_fd;
88 using android::fs_mgr::AvbHandle;
89 using android::snapshot::SnapshotManager;
90 
91 namespace android {
92 namespace init {
93 
94 namespace {
95 
96 enum EnforcingStatus { SELINUX_PERMISSIVE, SELINUX_ENFORCING };
97 
StatusFromProperty()98 EnforcingStatus StatusFromProperty() {
99     std::string value;
100     if (android::fs_mgr::GetKernelCmdline("androidboot.selinux", &value) && value == "permissive") {
101         return SELINUX_PERMISSIVE;
102     }
103     if (android::fs_mgr::GetBootconfig("androidboot.selinux", &value) && value == "permissive") {
104         return SELINUX_PERMISSIVE;
105     }
106     return SELINUX_ENFORCING;
107 }
108 
IsEnforcing()109 bool IsEnforcing() {
110     if (ALLOW_PERMISSIVE_SELINUX) {
111         return StatusFromProperty() == SELINUX_ENFORCING;
112     }
113     return true;
114 }
115 
ReadFirstLine(const char * file,std::string * line)116 bool 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 
FindPrecompiledSplitPolicy()128 Result<std::string> FindPrecompiledSplitPolicy() {
129     std::string precompiled_sepolicy;
130     // 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[] =
133             "/vendor/etc/selinux/precompiled_sepolicy";
134     static constexpr const char odm_precompiled_sepolicy[] =
135             "/odm/etc/selinux/precompiled_sepolicy";
136     if (access(odm_precompiled_sepolicy, R_OK) == 0) {
137         precompiled_sepolicy = odm_precompiled_sepolicy;
138     } else if (access(vendor_precompiled_sepolicy, R_OK) == 0) {
139         precompiled_sepolicy = vendor_precompiled_sepolicy;
140     } else {
141         return ErrnoError() << "No precompiled sepolicy at " << vendor_precompiled_sepolicy;
142     }
143 
144     // Use precompiled sepolicy only when all corresponding hashes are equal.
145     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"},
148             {"/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"},
152     };
153 
154     for (const auto& [actual_id_path, precompiled_id_path] : sepolicy_hashes) {
155         // 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 
164         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         }
177     }
178 
179     return precompiled_sepolicy;
180 }
181 
GetVendorMappingVersion(std::string * plat_vers)182 bool 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 
194 constexpr const char plat_policy_cil_file[] = "/system/etc/selinux/plat_sepolicy.cil";
195 
IsSplitPolicyDevice()196 bool IsSplitPolicyDevice() {
197     return access(plat_policy_cil_file, R_OK) != -1;
198 }
199 
GetUserdebugPlatformPolicyFile()200 std::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 
219 struct PolicyFile {
220     unique_fd fd;
221     std::string path;
222 };
223 
OpenSplitPolicy(PolicyFile * policy_file)224 bool OpenSplitPolicy(PolicyFile* policy_file) {
225     // IMPLEMENTATION NOTE: Split policy consists of three or more CIL files:
226     // * platform -- policy needed due to logic contained in the system image,
227     // * vendor -- policy needed due to logic contained in the vendor image,
228     // * mapping -- mapping policy which helps preserve forward-compatibility of non-platform policy
229     //   with newer versions of platform policy.
230     // * (optional) policy needed due to logic on product, system_ext, or odm images.
231     // 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 
234     const auto userdebug_plat_sepolicy = GetUserdebugPlatformPolicyFile();
235     const bool use_userdebug_policy = userdebug_plat_sepolicy.has_value();
236     if (use_userdebug_policy) {
237         LOG(INFO) << "Using userdebug system sepolicy " << *userdebug_plat_sepolicy;
238     }
239 
240     // 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.
242     // use_userdebug_policy requires compiling sepolicy with userdebug_plat_sepolicy.cil.
243     // Thus it cannot use the precompiled policy from vendor image.
244     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();
254         }
255     }
256     // No suitable precompiled policy could be loaded
257 
258     LOG(INFO) << "Compiling SELinux policy";
259 
260     // 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     }
274     std::string plat_mapping_file("/system/etc/selinux/mapping/" + vend_plat_vers + ".cil");
275 
276     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 
282     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 
293     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 
299     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 
304     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 
309     std::string vendor_policy_cil_file("/vendor/etc/selinux/vendor_sepolicy.cil");
310     if (access(vendor_policy_cil_file.c_str(), F_OK) == -1) {
311         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) {
317         LOG(ERROR) << "Missing " << plat_pub_versioned_cil_file;
318         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     }
326     const std::string version_as_string = std::to_string(SEPOLICY_VERSION);
327 
328     std::vector<std::string> genfs_cil_files;
329 
330     int vendor_genfs_version = get_genfs_labels_version();
331     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) {
334         LOG(INFO) << "Missing " << genfs_cil_file << "; skipping";
335         genfs_cil_file.clear();
336     } else {
337         LOG(INFO) << "Using " << genfs_cil_file << " for genfs labels";
338     }
339 
340     // clang-format off
341     std::vector<const char*> compile_args {
342         "/system/bin/secilc",
343         use_userdebug_policy ? *userdebug_plat_sepolicy : plat_policy_cil_file,
344         "-m", "-M", "true", "-G", "-N",
345         "-c", version_as_string.c_str(),
346         plat_mapping_file.c_str(),
347         "-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
350     };
351     // clang-format on
352 
353     if (!plat_compat_cil_file.empty()) {
354         compile_args.push_back(plat_compat_cil_file.c_str());
355     }
356     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     }
362     if (!system_ext_compat_cil_file.empty()) {
363         compile_args.push_back(system_ext_compat_cil_file.c_str());
364     }
365     if (!product_policy_cil_file.empty()) {
366         compile_args.push_back(product_policy_cil_file.c_str());
367     }
368     if (!product_mapping_file.empty()) {
369         compile_args.push_back(product_mapping_file.c_str());
370     }
371     if (!plat_pub_versioned_cil_file.empty()) {
372         compile_args.push_back(plat_pub_versioned_cil_file.c_str());
373     }
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     }
380     if (!genfs_cil_file.empty()) {
381         compile_args.push_back(genfs_cil_file.c_str());
382     }
383     compile_args.push_back(nullptr);
384 
385     if (!ForkExecveAndWaitForCompletion(compile_args[0], (char**)compile_args.data())) {
386         unlink(compiled_sepolicy);
387         return false;
388     }
389     unlink(compiled_sepolicy);
390 
391     policy_file->fd = std::move(compiled_sepolicy_fd);
392     policy_file->path = compiled_sepolicy;
393     return true;
394 }
395 
OpenMonolithicPolicy(PolicyFile * policy_file)396 bool OpenMonolithicPolicy(PolicyFile* policy_file) {
397     static constexpr char kSepolicyFile[] = "/sepolicy";
398 
399     LOG(INFO) << "Opening SELinux policy from monolithic file " << kSepolicyFile;
400     policy_file->fd.reset(open(kSepolicyFile, O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
401     if (policy_file->fd < 0) {
402         PLOG(ERROR) << "Failed to open monolithic SELinux policy";
403         return false;
404     }
405     policy_file->path = kSepolicyFile;
406     return true;
407 }
408 
ReadPolicy(std::string * policy)409 void ReadPolicy(std::string* policy) {
410     PolicyFile policy_file;
411 
412     bool ok = IsSplitPolicyDevice() ? OpenSplitPolicy(&policy_file)
413                                     : OpenMonolithicPolicy(&policy_file);
414     if (!ok) {
415         LOG(FATAL) << "Unable to open SELinux policy";
416     }
417 
418     if (!android::base::ReadFdToString(policy_file.fd, policy)) {
419         PLOG(FATAL) << "Failed to read policy file: " << policy_file.path;
420     }
421 }
422 
SelinuxSetEnforcement()423 void SelinuxSetEnforcement() {
424     bool kernel_enforcing = (security_getenforce() == 1);
425     bool is_enforcing = IsEnforcing();
426     if (kernel_enforcing != is_enforcing) {
427         if (security_setenforce(is_enforcing)) {
428             PLOG(FATAL) << "security_setenforce(" << (is_enforcing ? "true" : "false")
429                         << ") failed";
430         }
431     }
432 }
433 
434 constexpr size_t kKlogMessageSize = 1024;
435 
SelinuxAvcLog(char * buf)436 void SelinuxAvcLog(char* buf) {
437     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 
452     TEMP_FAILURE_RETRY(send(fd.get(), &request, sizeof(request), 0));
453 }
454 
RestoreconIfExists(const char * path,unsigned int flags)455 int 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 
463 }  // namespace
464 
SelinuxRestoreContext()465 void SelinuxRestoreContext() {
466     LOG(INFO) << "Running restorecon...";
467     selinux_android_restorecon("/dev", 0);
468     selinux_android_restorecon("/dev/console", 0);
469     selinux_android_restorecon("/dev/kmsg", 0);
470     if constexpr (WORLD_WRITABLE_KMSG) {
471         selinux_android_restorecon("/dev/kmsg_debug", 0);
472     }
473     selinux_android_restorecon("/dev/null", 0);
474     selinux_android_restorecon("/dev/ptmx", 0);
475     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 
480     selinux_android_restorecon("/dev/block", SELINUX_ANDROID_RESTORECON_RECURSE);
481     selinux_android_restorecon("/dev/dm-user", SELINUX_ANDROID_RESTORECON_RECURSE);
482     selinux_android_restorecon("/dev/device-mapper", 0);
483 
484     selinux_android_restorecon("/apex", 0);
485     selinux_android_restorecon("/bootstrap-apex", 0);
486     selinux_android_restorecon("/linkerconfig", 0);
487 
488     // adb remount, snapshot-based updates, and DSUs all create files during
489     // first-stage init.
490     RestoreconIfExists(SnapshotManager::GetGlobalRollbackIndicatorPath().c_str(), 0);
491     RestoreconIfExists("/metadata/gsi",
492                        SELINUX_ANDROID_RESTORECON_RECURSE | SELINUX_ANDROID_RESTORECON_SKIP_SEHASH);
493 }
494 
SelinuxKlogCallback(int type,const char * fmt,...)495 int 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     }
502     char buf[kKlogMessageSize];
503     va_list ap;
504     va_start(ap, fmt);
505     int length_written = vsnprintf(buf, sizeof(buf), fmt, ap);
506     va_end(ap);
507     if (length_written <= 0) {
508         return 0;
509     }
510 
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 
519     if (type == SELINUX_AVC) {
520         SelinuxAvcLog(buf);
521     } else {
522         android::base::KernelLogger(android::base::MAIN, severity, "selinux", nullptr, 0, buf);
523     }
524     return 0;
525 }
526 
SelinuxSetupKernelLogging()527 void SelinuxSetupKernelLogging() {
528     selinux_callback cb;
529     cb.func_log = SelinuxKlogCallback;
530     selinux_set_callback(SELINUX_CB_LOG, cb);
531 }
532 
SelinuxGetVendorAndroidVersion()533 int SelinuxGetVendorAndroidVersion() {
534     if (IsMicrodroid()) {
535         // As of now Microdroid doesn't have any vendor code.
536         return __ANDROID_API_FUTURE__;
537     }
538     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         }
544 
545         std::string version;
546         if (!GetVendorMappingVersion(&version)) {
547             LOG(FATAL) << "Could not read vendor SELinux version";
548         }
549 
550         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         }
556 
557         return major_version;
558     }();
559     return vendor_android_version;
560 }
561 
562 // 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.
MountMissingSystemPartitions()565 void 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 
585         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             }
595 
596             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();
599 
600             entry.mount_point = "/"s + name;
601             entry.blk_device =
602                 android::base::StringReplace(entry.blk_device, replace_name, partition_name, false);
603             if (!fs_mgr_update_logical_partition(&entry)) {
604                 LOG(ERROR) << "Could not update logical partition";
605                 continue;
606             }
607 
608             extra_fstab.emplace_back(std::move(entry));
609         }
610     }
611 
612     SkipMountingPartitions(&extra_fstab, true /* verbose */);
613     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 
LoadSelinuxPolicy(std::string & policy)632 static 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 
641 // Encapsulates steps to load SELinux policy in Microdroid.
642 // So far the process is very straightforward - just load the precompiled policy from /system.
LoadSelinuxPolicyMicrodroid()643 void 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 
661 // 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.
LoadSelinuxPolicyAndroid()676 void LoadSelinuxPolicyAndroid() {
677     MountMissingSystemPartitions();
678 
679     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) {
687         // Kill the old snapused to avoid audit messages. After this we cannot read from /system
688         // (or other dynamic partitions) until we call FinishTransition().
689         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     }
699 }
700 
SetupSelinux(char ** argv)701 int 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     }
719 
720     SelinuxSetEnforcement();
721 
722     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 
731     // 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 
739     setenv(kEnvSelinuxStartedAt, std::to_string(start_time.time_since_epoch().count()).c_str(), 1);
740 
741     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 
752 }  // namespace init
753 }  // namespace android
754