1 /*
2 * Copyright (C) 2019 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 #include "mount_namespace.h"
18
19 #include <sys/mount.h>
20
21 #include <string>
22 #include <vector>
23
24 #include <ApexProperties.sysprop.h>
25 #include <android-base/file.h>
26 #include <android-base/logging.h>
27 #include <android-base/properties.h>
28 #include <android-base/result.h>
29 #include <android-base/unique_fd.h>
30
31 #include "util.h"
32
33 #ifndef RECOVERY
34 #define ACTIVATE_FLATTENED_APEX 1
35 #endif
36
37 #ifdef ACTIVATE_FLATTENED_APEX
38 #include <apex_manifest.pb.h>
39 #include <com_android_apex.h>
40 #include <selinux/android.h>
41 #endif // ACTIVATE_FLATTENED_APEX
42
43 namespace android {
44 namespace init {
45 namespace {
46
BindMount(const std::string & source,const std::string & mount_point)47 static bool BindMount(const std::string& source, const std::string& mount_point) {
48 if (mount(source.c_str(), mount_point.c_str(), nullptr, MS_BIND | MS_REC, nullptr) == -1) {
49 PLOG(ERROR) << "Failed to bind mount " << source;
50 return false;
51 }
52 return true;
53 }
54
ChangeMount(const std::string & mount_point,unsigned long mountflags)55 static bool ChangeMount(const std::string& mount_point, unsigned long mountflags) {
56 if (mount(nullptr, mount_point.c_str(), nullptr, mountflags, nullptr) == -1) {
57 PLOG(ERROR) << "Failed to remount " << mount_point << " as " << std::hex << mountflags;
58 return false;
59 }
60 return true;
61 }
62
OpenMountNamespace()63 static int OpenMountNamespace() {
64 int fd = open("/proc/self/ns/mnt", O_RDONLY | O_CLOEXEC);
65 if (fd < 0) {
66 PLOG(ERROR) << "Cannot open fd for current mount namespace";
67 }
68 return fd;
69 }
70
GetMountNamespaceId()71 static std::string GetMountNamespaceId() {
72 std::string ret;
73 if (!android::base::Readlink("/proc/self/ns/mnt", &ret)) {
74 PLOG(ERROR) << "Failed to read namespace ID";
75 return "";
76 }
77 return ret;
78 }
79
IsApexUpdatable()80 static bool IsApexUpdatable() {
81 static bool updatable = android::sysprop::ApexProperties::updatable().value_or(false);
82 return updatable;
83 }
84
85 #ifdef ACTIVATE_FLATTENED_APEX
86
MountDir(const std::string & path,const std::string & mount_path)87 static Result<void> MountDir(const std::string& path, const std::string& mount_path) {
88 if (int ret = mkdir(mount_path.c_str(), 0755); ret != 0 && errno != EEXIST) {
89 return ErrnoError() << "Could not create mount point " << mount_path;
90 }
91 if (mount(path.c_str(), mount_path.c_str(), nullptr, MS_BIND, nullptr) != 0) {
92 return ErrnoError() << "Could not bind mount " << path << " to " << mount_path;
93 }
94 return {};
95 }
96
GetApexManifest(const std::string & apex_dir)97 static Result<apex::proto::ApexManifest> GetApexManifest(const std::string& apex_dir) {
98 const std::string manifest_path = apex_dir + "/apex_manifest.pb";
99 std::string content;
100 if (!android::base::ReadFileToString(manifest_path, &content)) {
101 return Error() << "Failed to read manifest file: " << manifest_path;
102 }
103 apex::proto::ApexManifest manifest;
104 if (!manifest.ParseFromString(content)) {
105 return Error() << "Can't parse manifest file: " << manifest_path;
106 }
107 return manifest;
108 }
109
110 template <typename Fn>
ActivateFlattenedApexesFrom(const std::string & from_dir,const std::string & to_dir,Fn on_activate)111 static Result<void> ActivateFlattenedApexesFrom(const std::string& from_dir,
112 const std::string& to_dir, Fn on_activate) {
113 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(from_dir.c_str()), closedir);
114 if (!dir) {
115 return {};
116 }
117 dirent* entry;
118 std::vector<std::string> entries;
119
120 while ((entry = readdir(dir.get())) != nullptr) {
121 if (entry->d_name[0] == '.') continue;
122 if (entry->d_type == DT_DIR) {
123 entries.push_back(entry->d_name);
124 }
125 }
126
127 std::sort(entries.begin(), entries.end());
128 for (const auto& name : entries) {
129 const std::string apex_path = from_dir + "/" + name;
130 const auto apex_manifest = GetApexManifest(apex_path);
131 if (!apex_manifest.ok()) {
132 LOG(ERROR) << apex_path << " is not an APEX directory: " << apex_manifest.error();
133 continue;
134 }
135 const std::string mount_path = to_dir + "/" + apex_manifest->name();
136 if (auto result = MountDir(apex_path, mount_path); !result.ok()) {
137 return result;
138 }
139 on_activate(apex_path, *apex_manifest);
140 }
141 return {};
142 }
143
ActivateFlattenedApexesIfPossible()144 static bool ActivateFlattenedApexesIfPossible() {
145 if (IsRecoveryMode() || IsApexUpdatable()) {
146 return true;
147 }
148
149 const std::string kApexTop = "/apex";
150 const std::vector<std::string> kBuiltinDirsForApexes = {
151 "/system/apex",
152 "/system_ext/apex",
153 "/product/apex",
154 "/vendor/apex",
155 };
156
157 std::vector<com::android::apex::ApexInfo> apex_infos;
158 auto on_activate = [&](const std::string& apex_path,
159 const apex::proto::ApexManifest& apex_manifest) {
160 apex_infos.emplace_back(apex_manifest.name(), apex_path, apex_path, apex_manifest.version(),
161 apex_manifest.versionname(), /*isFactory=*/true, /*isActive=*/true,
162 /* lastUpdateMillis= */ 0);
163 };
164
165 for (const auto& dir : kBuiltinDirsForApexes) {
166 if (auto result = ActivateFlattenedApexesFrom(dir, kApexTop, on_activate); !result.ok()) {
167 LOG(ERROR) << result.error();
168 return false;
169 }
170 }
171
172 std::ostringstream oss;
173 com::android::apex::ApexInfoList apex_info_list(apex_infos);
174 com::android::apex::write(oss, apex_info_list);
175 const std::string kApexInfoList = kApexTop + "/apex-info-list.xml";
176 if (!android::base::WriteStringToFile(oss.str(), kApexInfoList)) {
177 PLOG(ERROR) << "Failed to write " << kApexInfoList;
178 return false;
179 }
180 if (selinux_android_restorecon(kApexInfoList.c_str(), 0) != 0) {
181 PLOG(ERROR) << "selinux_android_restorecon(" << kApexInfoList << ") failed";
182 }
183
184 return true;
185 }
186
187 #endif // ACTIVATE_FLATTENED_APEX
188
189 static android::base::unique_fd bootstrap_ns_fd;
190 static android::base::unique_fd default_ns_fd;
191
192 static std::string bootstrap_ns_id;
193 static std::string default_ns_id;
194
195 } // namespace
196
SetupMountNamespaces()197 bool SetupMountNamespaces() {
198 // Set the propagation type of / as shared so that any mounting event (e.g.
199 // /data) is by default visible to all processes. When private mounting is
200 // needed for /foo/bar, then we will make /foo/bar as a mount point (by
201 // bind-mounting by to itself) and set the propagation type of the mount
202 // point to private.
203 if (!ChangeMount("/", MS_SHARED | MS_REC)) return false;
204
205 // /apex is a private mountpoint to give different sets of APEXes for
206 // the bootstrap and default mount namespaces. The processes running with
207 // the bootstrap namespace get APEXes from the read-only partition.
208 if (!(ChangeMount("/apex", MS_PRIVATE))) return false;
209
210 // /linkerconfig is a private mountpoint to give a different linker configuration
211 // based on the mount namespace. Subdirectory will be bind-mounted based on current mount
212 // namespace
213 if (!(ChangeMount("/linkerconfig", MS_PRIVATE))) return false;
214
215 // The two mount namespaces present challenges for scoped storage, because
216 // vold, which is responsible for most of the mounting, lives in the
217 // bootstrap mount namespace, whereas most other daemons and all apps live
218 // in the default namespace. Scoped storage has a need for a
219 // /mnt/installer view that is a slave bind mount of /mnt/user - in other
220 // words, all mounts under /mnt/user should automatically show up under
221 // /mnt/installer. However, additional mounts done under /mnt/installer
222 // should not propagate back to /mnt/user. In a single mount namespace
223 // this is easy to achieve, by simply marking the /mnt/installer a slave
224 // bind mount. Unfortunately, if /mnt/installer is only created and
225 // bind mounted after the two namespaces are created below, we end up
226 // with the following situation:
227 // /mnt/user and /mnt/installer share the same peer group in both the
228 // bootstrap and default namespaces. Marking /mnt/installer slave in either
229 // namespace means that it won't propagate events to the /mnt/installer in
230 // the other namespace, which is still something we require - vold is the
231 // one doing the mounting under /mnt/installer, and those mounts should
232 // show up in the default namespace as well.
233 //
234 // The simplest solution is to do the bind mount before the two namespaces
235 // are created: the effect is that in both namespaces, /mnt/installer is a
236 // slave to the /mnt/user mount, and at the same time /mnt/installer in the
237 // bootstrap namespace shares a peer group with /mnt/installer in the
238 // default namespace.
239 // /mnt/androidwritable is similar to /mnt/installer but serves for
240 // MOUNT_EXTERNAL_ANDROID_WRITABLE apps.
241 if (!mkdir_recursive("/mnt/user", 0755)) return false;
242 if (!mkdir_recursive("/mnt/installer", 0755)) return false;
243 if (!mkdir_recursive("/mnt/androidwritable", 0755)) return false;
244 if (!(BindMount("/mnt/user", "/mnt/installer"))) return false;
245 if (!(BindMount("/mnt/user", "/mnt/androidwritable"))) return false;
246 // First, make /mnt/installer and /mnt/androidwritable a slave bind mount
247 if (!(ChangeMount("/mnt/installer", MS_SLAVE))) return false;
248 if (!(ChangeMount("/mnt/androidwritable", MS_SLAVE))) return false;
249 // Then, make it shared again - effectively creating a new peer group, that
250 // will be inherited by new mount namespaces.
251 if (!(ChangeMount("/mnt/installer", MS_SHARED))) return false;
252 if (!(ChangeMount("/mnt/androidwritable", MS_SHARED))) return false;
253
254 bootstrap_ns_fd.reset(OpenMountNamespace());
255 bootstrap_ns_id = GetMountNamespaceId();
256
257 // When APEXes are updatable (e.g. not-flattened), we create separate mount
258 // namespaces for processes that are started before and after the APEX is
259 // activated by apexd. In the namespace for pre-apexd processes, small
260 // number of essential APEXes (e.g. com.android.runtime) are activated.
261 // In the namespace for post-apexd processes, all APEXes are activated.
262 bool success = true;
263 if (IsApexUpdatable() && !IsRecoveryMode()) {
264 // Creating a new namespace by cloning, saving, and switching back to
265 // the original namespace.
266 if (unshare(CLONE_NEWNS) == -1) {
267 PLOG(ERROR) << "Cannot create mount namespace";
268 return false;
269 }
270 default_ns_fd.reset(OpenMountNamespace());
271 default_ns_id = GetMountNamespaceId();
272
273 if (setns(bootstrap_ns_fd.get(), CLONE_NEWNS) == -1) {
274 PLOG(ERROR) << "Cannot switch back to bootstrap mount namespace";
275 return false;
276 }
277 } else {
278 // Otherwise, default == bootstrap
279 default_ns_fd.reset(OpenMountNamespace());
280 default_ns_id = GetMountNamespaceId();
281 }
282 #ifdef ACTIVATE_FLATTENED_APEX
283 success &= ActivateFlattenedApexesIfPossible();
284 #endif
285 LOG(INFO) << "SetupMountNamespaces done";
286 return success;
287 }
288
SwitchToMountNamespaceIfNeeded(MountNamespace target_mount_namespace)289 Result<void> SwitchToMountNamespaceIfNeeded(MountNamespace target_mount_namespace) {
290 if (IsRecoveryMode() || !IsApexUpdatable()) {
291 // we don't have multiple namespaces in recovery mode or if apex is not updatable
292 return {};
293 }
294 const auto& ns_id = target_mount_namespace == NS_BOOTSTRAP ? bootstrap_ns_id : default_ns_id;
295 const auto& ns_fd = target_mount_namespace == NS_BOOTSTRAP ? bootstrap_ns_fd : default_ns_fd;
296 const auto& ns_name = target_mount_namespace == NS_BOOTSTRAP ? "bootstrap" : "default";
297 if (ns_id != GetMountNamespaceId() && ns_fd.get() != -1) {
298 if (setns(ns_fd.get(), CLONE_NEWNS) == -1) {
299 return ErrnoError() << "Failed to switch to " << ns_name << " mount namespace.";
300 }
301 }
302 return {};
303 }
304
GetCurrentMountNamespace()305 base::Result<MountNamespace> GetCurrentMountNamespace() {
306 std::string current_namespace_id = GetMountNamespaceId();
307 if (current_namespace_id == "") {
308 return Error() << "Failed to get current mount namespace ID";
309 }
310
311 if (current_namespace_id == bootstrap_ns_id) {
312 return NS_BOOTSTRAP;
313 } else if (current_namespace_id == default_ns_id) {
314 return NS_DEFAULT;
315 }
316
317 return Error() << "Failed to find current mount namespace";
318 }
319
320 } // namespace init
321 } // namespace android
322