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