xref: /linux/fs/namespace.c (revision 32e940f2bd3b16551f23ea44be47f6f5d1746d64)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  linux/fs/namespace.c
4  *
5  * (C) Copyright Al Viro 2000, 2001
6  *
7  * Based on code from fs/super.c, copyright Linus Torvalds and others.
8  * Heavily rewritten.
9  */
10 
11 #include <linux/syscalls.h>
12 #include <linux/export.h>
13 #include <linux/capability.h>
14 #include <linux/mnt_namespace.h>
15 #include <linux/user_namespace.h>
16 #include <linux/namei.h>
17 #include <linux/security.h>
18 #include <linux/cred.h>
19 #include <linux/idr.h>
20 #include <linux/init.h>		/* init_rootfs */
21 #include <linux/fs_struct.h>	/* get_fs_root et.al. */
22 #include <linux/fsnotify.h>	/* fsnotify_vfsmount_delete */
23 #include <linux/file.h>
24 #include <linux/uaccess.h>
25 #include <linux/proc_ns.h>
26 #include <linux/magic.h>
27 #include <linux/memblock.h>
28 #include <linux/proc_fs.h>
29 #include <linux/task_work.h>
30 #include <linux/sched/task.h>
31 #include <uapi/linux/mount.h>
32 #include <linux/fs_context.h>
33 #include <linux/shmem_fs.h>
34 #include <linux/mnt_idmapping.h>
35 #include <linux/pidfs.h>
36 #include <linux/nstree.h>
37 
38 #include "pnode.h"
39 #include "internal.h"
40 
41 /* Maximum number of mounts in a mount namespace */
42 static unsigned int sysctl_mount_max __read_mostly = 100000;
43 
44 static unsigned int m_hash_mask __ro_after_init;
45 static unsigned int m_hash_shift __ro_after_init;
46 static unsigned int mp_hash_mask __ro_after_init;
47 static unsigned int mp_hash_shift __ro_after_init;
48 
49 static __initdata unsigned long mhash_entries;
set_mhash_entries(char * str)50 static int __init set_mhash_entries(char *str)
51 {
52 	return kstrtoul(str, 0, &mhash_entries) == 0;
53 }
54 __setup("mhash_entries=", set_mhash_entries);
55 
56 static __initdata unsigned long mphash_entries;
set_mphash_entries(char * str)57 static int __init set_mphash_entries(char *str)
58 {
59 	return kstrtoul(str, 0, &mphash_entries) == 0;
60 }
61 __setup("mphash_entries=", set_mphash_entries);
62 
63 static char * __initdata initramfs_options;
initramfs_options_setup(char * str)64 static int __init initramfs_options_setup(char *str)
65 {
66 	initramfs_options = str;
67 	return 1;
68 }
69 
70 __setup("initramfs_options=", initramfs_options_setup);
71 
72 static u64 event;
73 static DEFINE_XARRAY_FLAGS(mnt_id_xa, XA_FLAGS_ALLOC);
74 static DEFINE_IDA(mnt_group_ida);
75 
76 /* Don't allow confusion with old 32bit mount ID */
77 #define MNT_UNIQUE_ID_OFFSET (1ULL << 31)
78 static u64 mnt_id_ctr = MNT_UNIQUE_ID_OFFSET;
79 
80 static struct hlist_head *mount_hashtable __ro_after_init;
81 static struct hlist_head *mountpoint_hashtable __ro_after_init;
82 static struct kmem_cache *mnt_cache __ro_after_init;
83 static DECLARE_RWSEM(namespace_sem);
84 static HLIST_HEAD(unmounted);	/* protected by namespace_sem */
85 static LIST_HEAD(ex_mountpoints); /* protected by namespace_sem */
86 static struct mnt_namespace *emptied_ns; /* protected by namespace_sem */
87 
88 static inline void namespace_lock(void);
89 static void namespace_unlock(void);
90 DEFINE_LOCK_GUARD_0(namespace_excl, namespace_lock(), namespace_unlock())
91 DEFINE_LOCK_GUARD_0(namespace_shared, down_read(&namespace_sem),
92 				      up_read(&namespace_sem))
93 
94 DEFINE_FREE(mntput, struct vfsmount *, if (!IS_ERR(_T)) mntput(_T))
95 
96 #ifdef CONFIG_FSNOTIFY
97 LIST_HEAD(notify_list); /* protected by namespace_sem */
98 #endif
99 
100 enum mount_kattr_flags_t {
101 	MOUNT_KATTR_RECURSE		= (1 << 0),
102 	MOUNT_KATTR_IDMAP_REPLACE	= (1 << 1),
103 };
104 
105 struct mount_kattr {
106 	unsigned int attr_set;
107 	unsigned int attr_clr;
108 	unsigned int propagation;
109 	unsigned int lookup_flags;
110 	enum mount_kattr_flags_t kflags;
111 	struct user_namespace *mnt_userns;
112 	struct mnt_idmap *mnt_idmap;
113 };
114 
115 /* /sys/fs */
116 struct kobject *fs_kobj __ro_after_init;
117 EXPORT_SYMBOL_GPL(fs_kobj);
118 
119 /*
120  * vfsmount lock may be taken for read to prevent changes to the
121  * vfsmount hash, ie. during mountpoint lookups or walking back
122  * up the tree.
123  *
124  * It should be taken for write in all cases where the vfsmount
125  * tree or hash is modified or when a vfsmount structure is modified.
126  */
127 __cacheline_aligned_in_smp DEFINE_SEQLOCK(mount_lock);
128 
mnt_ns_release(struct mnt_namespace * ns)129 static void mnt_ns_release(struct mnt_namespace *ns)
130 {
131 	/* keep alive for {list,stat}mount() */
132 	if (ns && refcount_dec_and_test(&ns->passive)) {
133 		fsnotify_mntns_delete(ns);
134 		put_user_ns(ns->user_ns);
135 		kfree(ns);
136 	}
137 }
138 DEFINE_FREE(mnt_ns_release, struct mnt_namespace *,
139 	    if (!IS_ERR(_T)) mnt_ns_release(_T))
140 
mnt_ns_release_rcu(struct rcu_head * rcu)141 static void mnt_ns_release_rcu(struct rcu_head *rcu)
142 {
143 	mnt_ns_release(container_of(rcu, struct mnt_namespace, ns.ns_rcu));
144 }
145 
mnt_ns_tree_remove(struct mnt_namespace * ns)146 static void mnt_ns_tree_remove(struct mnt_namespace *ns)
147 {
148 	/* remove from global mount namespace list */
149 	if (ns_tree_active(ns))
150 		ns_tree_remove(ns);
151 
152 	call_rcu(&ns->ns.ns_rcu, mnt_ns_release_rcu);
153 }
154 
155 /*
156  * Lookup a mount namespace by id and take a passive reference count. Taking a
157  * passive reference means the mount namespace can be emptied if e.g., the last
158  * task holding an active reference exits. To access the mounts of the
159  * namespace the @namespace_sem must first be acquired. If the namespace has
160  * already shut down before acquiring @namespace_sem, {list,stat}mount() will
161  * see that the mount rbtree of the namespace is empty.
162  *
163  * Note the lookup is lockless protected by a sequence counter. We only
164  * need to guard against false negatives as false positives aren't
165  * possible. So if we didn't find a mount namespace and the sequence
166  * counter has changed we need to retry. If the sequence counter is
167  * still the same we know the search actually failed.
168  */
lookup_mnt_ns(u64 mnt_ns_id)169 static struct mnt_namespace *lookup_mnt_ns(u64 mnt_ns_id)
170 {
171 	struct mnt_namespace *mnt_ns;
172 	struct ns_common *ns;
173 
174 	guard(rcu)();
175 	ns = ns_tree_lookup_rcu(mnt_ns_id, CLONE_NEWNS);
176 	if (!ns)
177 		return NULL;
178 
179 	/*
180 	 * The last reference count is put with RCU delay so we can
181 	 * unconditonally acquire a reference here.
182 	 */
183 	mnt_ns = container_of(ns, struct mnt_namespace, ns);
184 	refcount_inc(&mnt_ns->passive);
185 	return mnt_ns;
186 }
187 
lock_mount_hash(void)188 static inline void lock_mount_hash(void)
189 {
190 	write_seqlock(&mount_lock);
191 }
192 
unlock_mount_hash(void)193 static inline void unlock_mount_hash(void)
194 {
195 	write_sequnlock(&mount_lock);
196 }
197 
m_hash(struct vfsmount * mnt,struct dentry * dentry)198 static inline struct hlist_head *m_hash(struct vfsmount *mnt, struct dentry *dentry)
199 {
200 	unsigned long tmp = ((unsigned long)mnt / L1_CACHE_BYTES);
201 	tmp += ((unsigned long)dentry / L1_CACHE_BYTES);
202 	tmp = tmp + (tmp >> m_hash_shift);
203 	return &mount_hashtable[tmp & m_hash_mask];
204 }
205 
mp_hash(struct dentry * dentry)206 static inline struct hlist_head *mp_hash(struct dentry *dentry)
207 {
208 	unsigned long tmp = ((unsigned long)dentry / L1_CACHE_BYTES);
209 	tmp = tmp + (tmp >> mp_hash_shift);
210 	return &mountpoint_hashtable[tmp & mp_hash_mask];
211 }
212 
mnt_alloc_id(struct mount * mnt)213 static int mnt_alloc_id(struct mount *mnt)
214 {
215 	int res;
216 
217 	xa_lock(&mnt_id_xa);
218 	res = __xa_alloc(&mnt_id_xa, &mnt->mnt_id, mnt, xa_limit_31b, GFP_KERNEL);
219 	if (!res)
220 		mnt->mnt_id_unique = ++mnt_id_ctr;
221 	xa_unlock(&mnt_id_xa);
222 	return res;
223 }
224 
mnt_free_id(struct mount * mnt)225 static void mnt_free_id(struct mount *mnt)
226 {
227 	xa_erase(&mnt_id_xa, mnt->mnt_id);
228 }
229 
230 /*
231  * Allocate a new peer group ID
232  */
mnt_alloc_group_id(struct mount * mnt)233 static int mnt_alloc_group_id(struct mount *mnt)
234 {
235 	int res = ida_alloc_min(&mnt_group_ida, 1, GFP_KERNEL);
236 
237 	if (res < 0)
238 		return res;
239 	mnt->mnt_group_id = res;
240 	return 0;
241 }
242 
243 /*
244  * Release a peer group ID
245  */
mnt_release_group_id(struct mount * mnt)246 void mnt_release_group_id(struct mount *mnt)
247 {
248 	ida_free(&mnt_group_ida, mnt->mnt_group_id);
249 	mnt->mnt_group_id = 0;
250 }
251 
252 /*
253  * vfsmount lock must be held for read
254  */
mnt_add_count(struct mount * mnt,int n)255 static inline void mnt_add_count(struct mount *mnt, int n)
256 {
257 #ifdef CONFIG_SMP
258 	this_cpu_add(mnt->mnt_pcp->mnt_count, n);
259 #else
260 	preempt_disable();
261 	mnt->mnt_count += n;
262 	preempt_enable();
263 #endif
264 }
265 
266 /*
267  * vfsmount lock must be held for write
268  */
mnt_get_count(struct mount * mnt)269 int mnt_get_count(struct mount *mnt)
270 {
271 #ifdef CONFIG_SMP
272 	int count = 0;
273 	int cpu;
274 
275 	for_each_possible_cpu(cpu) {
276 		count += per_cpu_ptr(mnt->mnt_pcp, cpu)->mnt_count;
277 	}
278 
279 	return count;
280 #else
281 	return mnt->mnt_count;
282 #endif
283 }
284 
alloc_vfsmnt(const char * name)285 static struct mount *alloc_vfsmnt(const char *name)
286 {
287 	struct mount *mnt = kmem_cache_zalloc(mnt_cache, GFP_KERNEL);
288 	if (mnt) {
289 		int err;
290 
291 		err = mnt_alloc_id(mnt);
292 		if (err)
293 			goto out_free_cache;
294 
295 		if (name)
296 			mnt->mnt_devname = kstrdup_const(name,
297 							 GFP_KERNEL_ACCOUNT);
298 		else
299 			mnt->mnt_devname = "none";
300 		if (!mnt->mnt_devname)
301 			goto out_free_id;
302 
303 #ifdef CONFIG_SMP
304 		mnt->mnt_pcp = alloc_percpu(struct mnt_pcp);
305 		if (!mnt->mnt_pcp)
306 			goto out_free_devname;
307 
308 		this_cpu_add(mnt->mnt_pcp->mnt_count, 1);
309 #else
310 		mnt->mnt_count = 1;
311 		mnt->mnt_writers = 0;
312 #endif
313 
314 		INIT_HLIST_NODE(&mnt->mnt_hash);
315 		INIT_LIST_HEAD(&mnt->mnt_child);
316 		INIT_LIST_HEAD(&mnt->mnt_mounts);
317 		INIT_LIST_HEAD(&mnt->mnt_list);
318 		INIT_LIST_HEAD(&mnt->mnt_expire);
319 		INIT_LIST_HEAD(&mnt->mnt_share);
320 		INIT_HLIST_HEAD(&mnt->mnt_slave_list);
321 		INIT_HLIST_NODE(&mnt->mnt_slave);
322 		INIT_HLIST_NODE(&mnt->mnt_mp_list);
323 		INIT_HLIST_HEAD(&mnt->mnt_stuck_children);
324 		RB_CLEAR_NODE(&mnt->mnt_node);
325 		mnt->mnt.mnt_idmap = &nop_mnt_idmap;
326 	}
327 	return mnt;
328 
329 #ifdef CONFIG_SMP
330 out_free_devname:
331 	kfree_const(mnt->mnt_devname);
332 #endif
333 out_free_id:
334 	mnt_free_id(mnt);
335 out_free_cache:
336 	kmem_cache_free(mnt_cache, mnt);
337 	return NULL;
338 }
339 
340 /*
341  * Most r/o checks on a fs are for operations that take
342  * discrete amounts of time, like a write() or unlink().
343  * We must keep track of when those operations start
344  * (for permission checks) and when they end, so that
345  * we can determine when writes are able to occur to
346  * a filesystem.
347  */
348 /*
349  * __mnt_is_readonly: check whether a mount is read-only
350  * @mnt: the mount to check for its write status
351  *
352  * This shouldn't be used directly ouside of the VFS.
353  * It does not guarantee that the filesystem will stay
354  * r/w, just that it is right *now*.  This can not and
355  * should not be used in place of IS_RDONLY(inode).
356  * mnt_want/drop_write() will _keep_ the filesystem
357  * r/w.
358  */
__mnt_is_readonly(const struct vfsmount * mnt)359 bool __mnt_is_readonly(const struct vfsmount *mnt)
360 {
361 	return (mnt->mnt_flags & MNT_READONLY) || sb_rdonly(mnt->mnt_sb);
362 }
363 EXPORT_SYMBOL_GPL(__mnt_is_readonly);
364 
mnt_inc_writers(struct mount * mnt)365 static inline void mnt_inc_writers(struct mount *mnt)
366 {
367 #ifdef CONFIG_SMP
368 	this_cpu_inc(mnt->mnt_pcp->mnt_writers);
369 #else
370 	mnt->mnt_writers++;
371 #endif
372 }
373 
mnt_dec_writers(struct mount * mnt)374 static inline void mnt_dec_writers(struct mount *mnt)
375 {
376 #ifdef CONFIG_SMP
377 	this_cpu_dec(mnt->mnt_pcp->mnt_writers);
378 #else
379 	mnt->mnt_writers--;
380 #endif
381 }
382 
mnt_get_writers(struct mount * mnt)383 static unsigned int mnt_get_writers(struct mount *mnt)
384 {
385 #ifdef CONFIG_SMP
386 	unsigned int count = 0;
387 	int cpu;
388 
389 	for_each_possible_cpu(cpu) {
390 		count += per_cpu_ptr(mnt->mnt_pcp, cpu)->mnt_writers;
391 	}
392 
393 	return count;
394 #else
395 	return mnt->mnt_writers;
396 #endif
397 }
398 
mnt_is_readonly(const struct vfsmount * mnt)399 static int mnt_is_readonly(const struct vfsmount *mnt)
400 {
401 	if (READ_ONCE(mnt->mnt_sb->s_readonly_remount))
402 		return 1;
403 	/*
404 	 * The barrier pairs with the barrier in sb_start_ro_state_change()
405 	 * making sure if we don't see s_readonly_remount set yet, we also will
406 	 * not see any superblock / mount flag changes done by remount.
407 	 * It also pairs with the barrier in sb_end_ro_state_change()
408 	 * assuring that if we see s_readonly_remount already cleared, we will
409 	 * see the values of superblock / mount flags updated by remount.
410 	 */
411 	smp_rmb();
412 	return __mnt_is_readonly(mnt);
413 }
414 
415 /*
416  * Most r/o & frozen checks on a fs are for operations that take discrete
417  * amounts of time, like a write() or unlink().  We must keep track of when
418  * those operations start (for permission checks) and when they end, so that we
419  * can determine when writes are able to occur to a filesystem.
420  */
421 /**
422  * mnt_get_write_access - get write access to a mount without freeze protection
423  * @m: the mount on which to take a write
424  *
425  * This tells the low-level filesystem that a write is about to be performed to
426  * it, and makes sure that writes are allowed (mnt it read-write) before
427  * returning success. This operation does not protect against filesystem being
428  * frozen. When the write operation is finished, mnt_put_write_access() must be
429  * called. This is effectively a refcount.
430  */
mnt_get_write_access(struct vfsmount * m)431 int mnt_get_write_access(struct vfsmount *m)
432 {
433 	struct mount *mnt = real_mount(m);
434 	int ret = 0;
435 
436 	preempt_disable();
437 	mnt_inc_writers(mnt);
438 	/*
439 	 * The store to mnt_inc_writers must be visible before we pass
440 	 * WRITE_HOLD loop below, so that the slowpath can see our
441 	 * incremented count after it has set WRITE_HOLD.
442 	 */
443 	smp_mb();
444 	might_lock(&mount_lock.lock);
445 	while (__test_write_hold(READ_ONCE(mnt->mnt_pprev_for_sb))) {
446 		if (!IS_ENABLED(CONFIG_PREEMPT_RT)) {
447 			cpu_relax();
448 		} else {
449 			/*
450 			 * This prevents priority inversion, if the task
451 			 * setting WRITE_HOLD got preempted on a remote
452 			 * CPU, and it prevents life lock if the task setting
453 			 * WRITE_HOLD has a lower priority and is bound to
454 			 * the same CPU as the task that is spinning here.
455 			 */
456 			preempt_enable();
457 			read_seqlock_excl(&mount_lock);
458 			read_sequnlock_excl(&mount_lock);
459 			preempt_disable();
460 		}
461 	}
462 	/*
463 	 * The barrier pairs with the barrier sb_start_ro_state_change() making
464 	 * sure that if we see WRITE_HOLD cleared, we will also see
465 	 * s_readonly_remount set (or even SB_RDONLY / MNT_READONLY flags) in
466 	 * mnt_is_readonly() and bail in case we are racing with remount
467 	 * read-only.
468 	 */
469 	smp_rmb();
470 	if (mnt_is_readonly(m)) {
471 		mnt_dec_writers(mnt);
472 		ret = -EROFS;
473 	}
474 	preempt_enable();
475 
476 	return ret;
477 }
478 EXPORT_SYMBOL_GPL(mnt_get_write_access);
479 
480 /**
481  * mnt_want_write - get write access to a mount
482  * @m: the mount on which to take a write
483  *
484  * This tells the low-level filesystem that a write is about to be performed to
485  * it, and makes sure that writes are allowed (mount is read-write, filesystem
486  * is not frozen) before returning success.  When the write operation is
487  * finished, mnt_drop_write() must be called.  This is effectively a refcount.
488  */
mnt_want_write(struct vfsmount * m)489 int mnt_want_write(struct vfsmount *m)
490 {
491 	int ret;
492 
493 	sb_start_write(m->mnt_sb);
494 	ret = mnt_get_write_access(m);
495 	if (ret)
496 		sb_end_write(m->mnt_sb);
497 	return ret;
498 }
499 EXPORT_SYMBOL_GPL(mnt_want_write);
500 
501 /**
502  * mnt_get_write_access_file - get write access to a file's mount
503  * @file: the file who's mount on which to take a write
504  *
505  * This is like mnt_get_write_access, but if @file is already open for write it
506  * skips incrementing mnt_writers (since the open file already has a reference)
507  * and instead only does the check for emergency r/o remounts.  This must be
508  * paired with mnt_put_write_access_file.
509  */
mnt_get_write_access_file(struct file * file)510 int mnt_get_write_access_file(struct file *file)
511 {
512 	if (file->f_mode & FMODE_WRITER) {
513 		/*
514 		 * Superblock may have become readonly while there are still
515 		 * writable fd's, e.g. due to a fs error with errors=remount-ro
516 		 */
517 		if (__mnt_is_readonly(file->f_path.mnt))
518 			return -EROFS;
519 		return 0;
520 	}
521 	return mnt_get_write_access(file->f_path.mnt);
522 }
523 
524 /**
525  * mnt_want_write_file - get write access to a file's mount
526  * @file: the file who's mount on which to take a write
527  *
528  * This is like mnt_want_write, but if the file is already open for writing it
529  * skips incrementing mnt_writers (since the open file already has a reference)
530  * and instead only does the freeze protection and the check for emergency r/o
531  * remounts.  This must be paired with mnt_drop_write_file.
532  */
mnt_want_write_file(struct file * file)533 int mnt_want_write_file(struct file *file)
534 {
535 	int ret;
536 
537 	sb_start_write(file_inode(file)->i_sb);
538 	ret = mnt_get_write_access_file(file);
539 	if (ret)
540 		sb_end_write(file_inode(file)->i_sb);
541 	return ret;
542 }
543 EXPORT_SYMBOL_GPL(mnt_want_write_file);
544 
545 /**
546  * mnt_put_write_access - give up write access to a mount
547  * @mnt: the mount on which to give up write access
548  *
549  * Tells the low-level filesystem that we are done
550  * performing writes to it.  Must be matched with
551  * mnt_get_write_access() call above.
552  */
mnt_put_write_access(struct vfsmount * mnt)553 void mnt_put_write_access(struct vfsmount *mnt)
554 {
555 	preempt_disable();
556 	mnt_dec_writers(real_mount(mnt));
557 	preempt_enable();
558 }
559 EXPORT_SYMBOL_GPL(mnt_put_write_access);
560 
561 /**
562  * mnt_drop_write - give up write access to a mount
563  * @mnt: the mount on which to give up write access
564  *
565  * Tells the low-level filesystem that we are done performing writes to it and
566  * also allows filesystem to be frozen again.  Must be matched with
567  * mnt_want_write() call above.
568  */
mnt_drop_write(struct vfsmount * mnt)569 void mnt_drop_write(struct vfsmount *mnt)
570 {
571 	mnt_put_write_access(mnt);
572 	sb_end_write(mnt->mnt_sb);
573 }
574 EXPORT_SYMBOL_GPL(mnt_drop_write);
575 
mnt_put_write_access_file(struct file * file)576 void mnt_put_write_access_file(struct file *file)
577 {
578 	if (!(file->f_mode & FMODE_WRITER))
579 		mnt_put_write_access(file->f_path.mnt);
580 }
581 
mnt_drop_write_file(struct file * file)582 void mnt_drop_write_file(struct file *file)
583 {
584 	mnt_put_write_access_file(file);
585 	sb_end_write(file_inode(file)->i_sb);
586 }
587 EXPORT_SYMBOL(mnt_drop_write_file);
588 
589 /**
590  * mnt_hold_writers - prevent write access to the given mount
591  * @mnt: mnt to prevent write access to
592  *
593  * Prevents write access to @mnt if there are no active writers for @mnt.
594  * This function needs to be called and return successfully before changing
595  * properties of @mnt that need to remain stable for callers with write access
596  * to @mnt.
597  *
598  * After this functions has been called successfully callers must pair it with
599  * a call to mnt_unhold_writers() in order to stop preventing write access to
600  * @mnt.
601  *
602  * Context: This function expects to be in mount_locked_reader scope serializing
603  *          setting WRITE_HOLD.
604  * Return: On success 0 is returned.
605  *	   On error, -EBUSY is returned.
606  */
mnt_hold_writers(struct mount * mnt)607 static inline int mnt_hold_writers(struct mount *mnt)
608 {
609 	set_write_hold(mnt);
610 	/*
611 	 * After storing WRITE_HOLD, we'll read the counters. This store
612 	 * should be visible before we do.
613 	 */
614 	smp_mb();
615 
616 	/*
617 	 * With writers on hold, if this value is zero, then there are
618 	 * definitely no active writers (although held writers may subsequently
619 	 * increment the count, they'll have to wait, and decrement it after
620 	 * seeing MNT_READONLY).
621 	 *
622 	 * It is OK to have counter incremented on one CPU and decremented on
623 	 * another: the sum will add up correctly. The danger would be when we
624 	 * sum up each counter, if we read a counter before it is incremented,
625 	 * but then read another CPU's count which it has been subsequently
626 	 * decremented from -- we would see more decrements than we should.
627 	 * WRITE_HOLD protects against this scenario, because
628 	 * mnt_want_write first increments count, then smp_mb, then spins on
629 	 * WRITE_HOLD, so it can't be decremented by another CPU while
630 	 * we're counting up here.
631 	 */
632 	if (mnt_get_writers(mnt) > 0)
633 		return -EBUSY;
634 
635 	return 0;
636 }
637 
638 /**
639  * mnt_unhold_writers - stop preventing write access to the given mount
640  * @mnt: mnt to stop preventing write access to
641  *
642  * Stop preventing write access to @mnt allowing callers to gain write access
643  * to @mnt again.
644  *
645  * This function can only be called after a call to mnt_hold_writers().
646  *
647  * Context: This function expects to be in the same mount_locked_reader scope
648  * as the matching mnt_hold_writers().
649  */
mnt_unhold_writers(struct mount * mnt)650 static inline void mnt_unhold_writers(struct mount *mnt)
651 {
652 	if (!test_write_hold(mnt))
653 		return;
654 	/*
655 	 * MNT_READONLY must become visible before ~WRITE_HOLD, so writers
656 	 * that become unheld will see MNT_READONLY.
657 	 */
658 	smp_wmb();
659 	clear_write_hold(mnt);
660 }
661 
mnt_del_instance(struct mount * m)662 static inline void mnt_del_instance(struct mount *m)
663 {
664 	struct mount **p = m->mnt_pprev_for_sb;
665 	struct mount *next = m->mnt_next_for_sb;
666 
667 	if (next)
668 		next->mnt_pprev_for_sb = p;
669 	*p = next;
670 }
671 
mnt_add_instance(struct mount * m,struct super_block * s)672 static inline void mnt_add_instance(struct mount *m, struct super_block *s)
673 {
674 	struct mount *first = s->s_mounts;
675 
676 	if (first)
677 		first->mnt_pprev_for_sb = &m->mnt_next_for_sb;
678 	m->mnt_next_for_sb = first;
679 	m->mnt_pprev_for_sb = &s->s_mounts;
680 	s->s_mounts = m;
681 }
682 
mnt_make_readonly(struct mount * mnt)683 static int mnt_make_readonly(struct mount *mnt)
684 {
685 	int ret;
686 
687 	ret = mnt_hold_writers(mnt);
688 	if (!ret)
689 		mnt->mnt.mnt_flags |= MNT_READONLY;
690 	mnt_unhold_writers(mnt);
691 	return ret;
692 }
693 
sb_prepare_remount_readonly(struct super_block * sb)694 int sb_prepare_remount_readonly(struct super_block *sb)
695 {
696 	int err = 0;
697 
698 	/* Racy optimization.  Recheck the counter under WRITE_HOLD */
699 	if (atomic_long_read(&sb->s_remove_count))
700 		return -EBUSY;
701 
702 	guard(mount_locked_reader)();
703 
704 	for (struct mount *m = sb->s_mounts; m; m = m->mnt_next_for_sb) {
705 		if (!(m->mnt.mnt_flags & MNT_READONLY)) {
706 			err = mnt_hold_writers(m);
707 			if (err)
708 				break;
709 		}
710 	}
711 	if (!err && atomic_long_read(&sb->s_remove_count))
712 		err = -EBUSY;
713 
714 	if (!err)
715 		sb_start_ro_state_change(sb);
716 	for (struct mount *m = sb->s_mounts; m; m = m->mnt_next_for_sb) {
717 		if (test_write_hold(m))
718 			clear_write_hold(m);
719 	}
720 
721 	return err;
722 }
723 
free_vfsmnt(struct mount * mnt)724 static void free_vfsmnt(struct mount *mnt)
725 {
726 	mnt_idmap_put(mnt_idmap(&mnt->mnt));
727 	kfree_const(mnt->mnt_devname);
728 #ifdef CONFIG_SMP
729 	free_percpu(mnt->mnt_pcp);
730 #endif
731 	kmem_cache_free(mnt_cache, mnt);
732 }
733 
delayed_free_vfsmnt(struct rcu_head * head)734 static void delayed_free_vfsmnt(struct rcu_head *head)
735 {
736 	free_vfsmnt(container_of(head, struct mount, mnt_rcu));
737 }
738 
739 /* call under rcu_read_lock */
__legitimize_mnt(struct vfsmount * bastard,unsigned seq)740 int __legitimize_mnt(struct vfsmount *bastard, unsigned seq)
741 {
742 	struct mount *mnt;
743 	if (read_seqretry(&mount_lock, seq))
744 		return 1;
745 	if (bastard == NULL)
746 		return 0;
747 	mnt = real_mount(bastard);
748 	mnt_add_count(mnt, 1);
749 	smp_mb();		// see mntput_no_expire() and do_umount()
750 	if (likely(!read_seqretry(&mount_lock, seq)))
751 		return 0;
752 	lock_mount_hash();
753 	if (unlikely(bastard->mnt_flags & (MNT_SYNC_UMOUNT | MNT_DOOMED))) {
754 		mnt_add_count(mnt, -1);
755 		unlock_mount_hash();
756 		return 1;
757 	}
758 	unlock_mount_hash();
759 	/* caller will mntput() */
760 	return -1;
761 }
762 
763 /* call under rcu_read_lock */
legitimize_mnt(struct vfsmount * bastard,unsigned seq)764 static bool legitimize_mnt(struct vfsmount *bastard, unsigned seq)
765 {
766 	int res = __legitimize_mnt(bastard, seq);
767 	if (likely(!res))
768 		return true;
769 	if (unlikely(res < 0)) {
770 		rcu_read_unlock();
771 		mntput(bastard);
772 		rcu_read_lock();
773 	}
774 	return false;
775 }
776 
777 /**
778  * __lookup_mnt - mount hash lookup
779  * @mnt:	parent mount
780  * @dentry:	dentry of mountpoint
781  *
782  * If @mnt has a child mount @c mounted on @dentry find and return it.
783  * Caller must either hold the spinlock component of @mount_lock or
784  * hold rcu_read_lock(), sample the seqcount component before the call
785  * and recheck it afterwards.
786  *
787  * Return: The child of @mnt mounted on @dentry or %NULL.
788  */
__lookup_mnt(struct vfsmount * mnt,struct dentry * dentry)789 struct mount *__lookup_mnt(struct vfsmount *mnt, struct dentry *dentry)
790 {
791 	struct hlist_head *head = m_hash(mnt, dentry);
792 	struct mount *p;
793 
794 	hlist_for_each_entry_rcu(p, head, mnt_hash)
795 		if (&p->mnt_parent->mnt == mnt && p->mnt_mountpoint == dentry)
796 			return p;
797 	return NULL;
798 }
799 
800 /**
801  * lookup_mnt - Return the child mount mounted at given location
802  * @path:	location in the namespace
803  *
804  * Acquires and returns a new reference to mount at given location
805  * or %NULL if nothing is mounted there.
806  */
lookup_mnt(const struct path * path)807 struct vfsmount *lookup_mnt(const struct path *path)
808 {
809 	struct mount *child_mnt;
810 	struct vfsmount *m;
811 	unsigned seq;
812 
813 	rcu_read_lock();
814 	do {
815 		seq = read_seqbegin(&mount_lock);
816 		child_mnt = __lookup_mnt(path->mnt, path->dentry);
817 		m = child_mnt ? &child_mnt->mnt : NULL;
818 	} while (!legitimize_mnt(m, seq));
819 	rcu_read_unlock();
820 	return m;
821 }
822 
823 /*
824  * __is_local_mountpoint - Test to see if dentry is a mountpoint in the
825  *                         current mount namespace.
826  *
827  * The common case is dentries are not mountpoints at all and that
828  * test is handled inline.  For the slow case when we are actually
829  * dealing with a mountpoint of some kind, walk through all of the
830  * mounts in the current mount namespace and test to see if the dentry
831  * is a mountpoint.
832  *
833  * The mount_hashtable is not usable in the context because we
834  * need to identify all mounts that may be in the current mount
835  * namespace not just a mount that happens to have some specified
836  * parent mount.
837  */
__is_local_mountpoint(const struct dentry * dentry)838 bool __is_local_mountpoint(const struct dentry *dentry)
839 {
840 	struct mnt_namespace *ns = current->nsproxy->mnt_ns;
841 	struct mount *mnt, *n;
842 
843 	guard(namespace_shared)();
844 
845 	rbtree_postorder_for_each_entry_safe(mnt, n, &ns->mounts, mnt_node)
846 		if (mnt->mnt_mountpoint == dentry)
847 			return true;
848 
849 	return false;
850 }
851 
852 struct pinned_mountpoint {
853 	struct hlist_node node;
854 	struct mountpoint *mp;
855 	struct mount *parent;
856 };
857 
lookup_mountpoint(struct dentry * dentry,struct pinned_mountpoint * m)858 static bool lookup_mountpoint(struct dentry *dentry, struct pinned_mountpoint *m)
859 {
860 	struct hlist_head *chain = mp_hash(dentry);
861 	struct mountpoint *mp;
862 
863 	hlist_for_each_entry(mp, chain, m_hash) {
864 		if (mp->m_dentry == dentry) {
865 			hlist_add_head(&m->node, &mp->m_list);
866 			m->mp = mp;
867 			return true;
868 		}
869 	}
870 	return false;
871 }
872 
get_mountpoint(struct dentry * dentry,struct pinned_mountpoint * m)873 static int get_mountpoint(struct dentry *dentry, struct pinned_mountpoint *m)
874 {
875 	struct mountpoint *mp __free(kfree) = NULL;
876 	bool found;
877 	int ret;
878 
879 	if (d_mountpoint(dentry)) {
880 		/* might be worth a WARN_ON() */
881 		if (d_unlinked(dentry))
882 			return -ENOENT;
883 mountpoint:
884 		read_seqlock_excl(&mount_lock);
885 		found = lookup_mountpoint(dentry, m);
886 		read_sequnlock_excl(&mount_lock);
887 		if (found)
888 			return 0;
889 	}
890 
891 	if (!mp)
892 		mp = kmalloc_obj(struct mountpoint);
893 	if (!mp)
894 		return -ENOMEM;
895 
896 	/* Exactly one processes may set d_mounted */
897 	ret = d_set_mounted(dentry);
898 
899 	/* Someone else set d_mounted? */
900 	if (ret == -EBUSY)
901 		goto mountpoint;
902 
903 	/* The dentry is not available as a mountpoint? */
904 	if (ret)
905 		return ret;
906 
907 	/* Add the new mountpoint to the hash table */
908 	read_seqlock_excl(&mount_lock);
909 	mp->m_dentry = dget(dentry);
910 	hlist_add_head(&mp->m_hash, mp_hash(dentry));
911 	INIT_HLIST_HEAD(&mp->m_list);
912 	hlist_add_head(&m->node, &mp->m_list);
913 	m->mp = no_free_ptr(mp);
914 	read_sequnlock_excl(&mount_lock);
915 	return 0;
916 }
917 
918 /*
919  * vfsmount lock must be held.  Additionally, the caller is responsible
920  * for serializing calls for given disposal list.
921  */
maybe_free_mountpoint(struct mountpoint * mp,struct list_head * list)922 static void maybe_free_mountpoint(struct mountpoint *mp, struct list_head *list)
923 {
924 	if (hlist_empty(&mp->m_list)) {
925 		struct dentry *dentry = mp->m_dentry;
926 		spin_lock(&dentry->d_lock);
927 		dentry->d_flags &= ~DCACHE_MOUNTED;
928 		spin_unlock(&dentry->d_lock);
929 		dput_to_list(dentry, list);
930 		hlist_del(&mp->m_hash);
931 		kfree(mp);
932 	}
933 }
934 
935 /*
936  * locks: mount_lock [read_seqlock_excl], namespace_sem [excl]
937  */
unpin_mountpoint(struct pinned_mountpoint * m)938 static void unpin_mountpoint(struct pinned_mountpoint *m)
939 {
940 	if (m->mp) {
941 		hlist_del(&m->node);
942 		maybe_free_mountpoint(m->mp, &ex_mountpoints);
943 	}
944 }
945 
check_mnt(const struct mount * mnt)946 static inline int check_mnt(const struct mount *mnt)
947 {
948 	return mnt->mnt_ns == current->nsproxy->mnt_ns;
949 }
950 
check_anonymous_mnt(struct mount * mnt)951 static inline bool check_anonymous_mnt(struct mount *mnt)
952 {
953 	u64 seq;
954 
955 	if (!is_anon_ns(mnt->mnt_ns))
956 		return false;
957 
958 	seq = mnt->mnt_ns->seq_origin;
959 	return !seq || (seq == current->nsproxy->mnt_ns->ns.ns_id);
960 }
961 
962 /*
963  * vfsmount lock must be held for write
964  */
touch_mnt_namespace(struct mnt_namespace * ns)965 static void touch_mnt_namespace(struct mnt_namespace *ns)
966 {
967 	if (ns) {
968 		ns->event = ++event;
969 		wake_up_interruptible(&ns->poll);
970 	}
971 }
972 
973 /*
974  * vfsmount lock must be held for write
975  */
__touch_mnt_namespace(struct mnt_namespace * ns)976 static void __touch_mnt_namespace(struct mnt_namespace *ns)
977 {
978 	if (ns && ns->event != event) {
979 		ns->event = event;
980 		wake_up_interruptible(&ns->poll);
981 	}
982 }
983 
984 /*
985  * locks: mount_lock[write_seqlock]
986  */
__umount_mnt(struct mount * mnt,struct list_head * shrink_list)987 static void __umount_mnt(struct mount *mnt, struct list_head *shrink_list)
988 {
989 	struct mountpoint *mp;
990 	struct mount *parent = mnt->mnt_parent;
991 	if (unlikely(parent->overmount == mnt))
992 		parent->overmount = NULL;
993 	mnt->mnt_parent = mnt;
994 	mnt->mnt_mountpoint = mnt->mnt.mnt_root;
995 	list_del_init(&mnt->mnt_child);
996 	hlist_del_init_rcu(&mnt->mnt_hash);
997 	hlist_del_init(&mnt->mnt_mp_list);
998 	mp = mnt->mnt_mp;
999 	mnt->mnt_mp = NULL;
1000 	maybe_free_mountpoint(mp, shrink_list);
1001 }
1002 
1003 /*
1004  * locks: mount_lock[write_seqlock], namespace_sem[excl] (for ex_mountpoints)
1005  */
umount_mnt(struct mount * mnt)1006 static void umount_mnt(struct mount *mnt)
1007 {
1008 	__umount_mnt(mnt, &ex_mountpoints);
1009 }
1010 
1011 /*
1012  * vfsmount lock must be held for write
1013  */
mnt_set_mountpoint(struct mount * mnt,struct mountpoint * mp,struct mount * child_mnt)1014 void mnt_set_mountpoint(struct mount *mnt,
1015 			struct mountpoint *mp,
1016 			struct mount *child_mnt)
1017 {
1018 	child_mnt->mnt_mountpoint = mp->m_dentry;
1019 	child_mnt->mnt_parent = mnt;
1020 	child_mnt->mnt_mp = mp;
1021 	hlist_add_head(&child_mnt->mnt_mp_list, &mp->m_list);
1022 }
1023 
make_visible(struct mount * mnt)1024 static void make_visible(struct mount *mnt)
1025 {
1026 	struct mount *parent = mnt->mnt_parent;
1027 	if (unlikely(mnt->mnt_mountpoint == parent->mnt.mnt_root))
1028 		parent->overmount = mnt;
1029 	hlist_add_head_rcu(&mnt->mnt_hash,
1030 			   m_hash(&parent->mnt, mnt->mnt_mountpoint));
1031 	list_add_tail(&mnt->mnt_child, &parent->mnt_mounts);
1032 }
1033 
1034 /**
1035  * attach_mnt - mount a mount, attach to @mount_hashtable and parent's
1036  *              list of child mounts
1037  * @parent:  the parent
1038  * @mnt:     the new mount
1039  * @mp:      the new mountpoint
1040  *
1041  * Mount @mnt at @mp on @parent. Then attach @mnt
1042  * to @parent's child mount list and to @mount_hashtable.
1043  *
1044  * Note, when make_visible() is called @mnt->mnt_parent already points
1045  * to the correct parent.
1046  *
1047  * Context: This function expects namespace_lock() and lock_mount_hash()
1048  *          to have been acquired in that order.
1049  */
attach_mnt(struct mount * mnt,struct mount * parent,struct mountpoint * mp)1050 static void attach_mnt(struct mount *mnt, struct mount *parent,
1051 		       struct mountpoint *mp)
1052 {
1053 	mnt_set_mountpoint(parent, mp, mnt);
1054 	make_visible(mnt);
1055 }
1056 
mnt_change_mountpoint(struct mount * parent,struct mountpoint * mp,struct mount * mnt)1057 void mnt_change_mountpoint(struct mount *parent, struct mountpoint *mp, struct mount *mnt)
1058 {
1059 	struct mountpoint *old_mp = mnt->mnt_mp;
1060 
1061 	list_del_init(&mnt->mnt_child);
1062 	hlist_del_init(&mnt->mnt_mp_list);
1063 	hlist_del_init_rcu(&mnt->mnt_hash);
1064 
1065 	attach_mnt(mnt, parent, mp);
1066 
1067 	maybe_free_mountpoint(old_mp, &ex_mountpoints);
1068 }
1069 
node_to_mount(struct rb_node * node)1070 static inline struct mount *node_to_mount(struct rb_node *node)
1071 {
1072 	return node ? rb_entry(node, struct mount, mnt_node) : NULL;
1073 }
1074 
mnt_add_to_ns(struct mnt_namespace * ns,struct mount * mnt)1075 static void mnt_add_to_ns(struct mnt_namespace *ns, struct mount *mnt)
1076 {
1077 	struct rb_node **link = &ns->mounts.rb_node;
1078 	struct rb_node *parent = NULL;
1079 	bool mnt_first_node = true, mnt_last_node = true;
1080 
1081 	WARN_ON(mnt_ns_attached(mnt));
1082 	mnt->mnt_ns = ns;
1083 	while (*link) {
1084 		parent = *link;
1085 		if (mnt->mnt_id_unique < node_to_mount(parent)->mnt_id_unique) {
1086 			link = &parent->rb_left;
1087 			mnt_last_node = false;
1088 		} else {
1089 			link = &parent->rb_right;
1090 			mnt_first_node = false;
1091 		}
1092 	}
1093 
1094 	if (mnt_last_node)
1095 		ns->mnt_last_node = &mnt->mnt_node;
1096 	if (mnt_first_node)
1097 		ns->mnt_first_node = &mnt->mnt_node;
1098 	rb_link_node(&mnt->mnt_node, parent, link);
1099 	rb_insert_color(&mnt->mnt_node, &ns->mounts);
1100 
1101 	mnt_notify_add(mnt);
1102 }
1103 
next_mnt(struct mount * p,struct mount * root)1104 static struct mount *next_mnt(struct mount *p, struct mount *root)
1105 {
1106 	struct list_head *next = p->mnt_mounts.next;
1107 	if (next == &p->mnt_mounts) {
1108 		while (1) {
1109 			if (p == root)
1110 				return NULL;
1111 			next = p->mnt_child.next;
1112 			if (next != &p->mnt_parent->mnt_mounts)
1113 				break;
1114 			p = p->mnt_parent;
1115 		}
1116 	}
1117 	return list_entry(next, struct mount, mnt_child);
1118 }
1119 
skip_mnt_tree(struct mount * p)1120 static struct mount *skip_mnt_tree(struct mount *p)
1121 {
1122 	struct list_head *prev = p->mnt_mounts.prev;
1123 	while (prev != &p->mnt_mounts) {
1124 		p = list_entry(prev, struct mount, mnt_child);
1125 		prev = p->mnt_mounts.prev;
1126 	}
1127 	return p;
1128 }
1129 
1130 /*
1131  * vfsmount lock must be held for write
1132  */
commit_tree(struct mount * mnt)1133 static void commit_tree(struct mount *mnt)
1134 {
1135 	struct mnt_namespace *n = mnt->mnt_parent->mnt_ns;
1136 
1137 	if (!mnt_ns_attached(mnt)) {
1138 		for (struct mount *m = mnt; m; m = next_mnt(m, mnt))
1139 			mnt_add_to_ns(n, m);
1140 		n->nr_mounts += n->pending_mounts;
1141 		n->pending_mounts = 0;
1142 	}
1143 
1144 	make_visible(mnt);
1145 	touch_mnt_namespace(n);
1146 }
1147 
setup_mnt(struct mount * m,struct dentry * root)1148 static void setup_mnt(struct mount *m, struct dentry *root)
1149 {
1150 	struct super_block *s = root->d_sb;
1151 
1152 	atomic_inc(&s->s_active);
1153 	m->mnt.mnt_sb = s;
1154 	m->mnt.mnt_root = dget(root);
1155 	m->mnt_mountpoint = m->mnt.mnt_root;
1156 	m->mnt_parent = m;
1157 
1158 	guard(mount_locked_reader)();
1159 	mnt_add_instance(m, s);
1160 }
1161 
1162 /**
1163  * vfs_create_mount - Create a mount for a configured superblock
1164  * @fc: The configuration context with the superblock attached
1165  *
1166  * Create a mount to an already configured superblock.  If necessary, the
1167  * caller should invoke vfs_get_tree() before calling this.
1168  *
1169  * Note that this does not attach the mount to anything.
1170  */
vfs_create_mount(struct fs_context * fc)1171 struct vfsmount *vfs_create_mount(struct fs_context *fc)
1172 {
1173 	struct mount *mnt;
1174 
1175 	if (!fc->root)
1176 		return ERR_PTR(-EINVAL);
1177 
1178 	mnt = alloc_vfsmnt(fc->source);
1179 	if (!mnt)
1180 		return ERR_PTR(-ENOMEM);
1181 
1182 	if (fc->sb_flags & SB_KERNMOUNT)
1183 		mnt->mnt.mnt_flags = MNT_INTERNAL;
1184 
1185 	setup_mnt(mnt, fc->root);
1186 
1187 	return &mnt->mnt;
1188 }
1189 EXPORT_SYMBOL(vfs_create_mount);
1190 
fc_mount(struct fs_context * fc)1191 struct vfsmount *fc_mount(struct fs_context *fc)
1192 {
1193 	int err = vfs_get_tree(fc);
1194 	if (!err) {
1195 		up_write(&fc->root->d_sb->s_umount);
1196 		return vfs_create_mount(fc);
1197 	}
1198 	return ERR_PTR(err);
1199 }
1200 EXPORT_SYMBOL(fc_mount);
1201 
fc_mount_longterm(struct fs_context * fc)1202 struct vfsmount *fc_mount_longterm(struct fs_context *fc)
1203 {
1204 	struct vfsmount *mnt = fc_mount(fc);
1205 	if (!IS_ERR(mnt))
1206 		real_mount(mnt)->mnt_ns = MNT_NS_INTERNAL;
1207 	return mnt;
1208 }
1209 EXPORT_SYMBOL(fc_mount_longterm);
1210 
vfs_kern_mount(struct file_system_type * type,int flags,const char * name,void * data)1211 struct vfsmount *vfs_kern_mount(struct file_system_type *type,
1212 				int flags, const char *name,
1213 				void *data)
1214 {
1215 	struct fs_context *fc;
1216 	struct vfsmount *mnt;
1217 	int ret = 0;
1218 
1219 	if (!type)
1220 		return ERR_PTR(-EINVAL);
1221 
1222 	fc = fs_context_for_mount(type, flags);
1223 	if (IS_ERR(fc))
1224 		return ERR_CAST(fc);
1225 
1226 	if (name)
1227 		ret = vfs_parse_fs_string(fc, "source", name);
1228 	if (!ret)
1229 		ret = parse_monolithic_mount_data(fc, data);
1230 	if (!ret)
1231 		mnt = fc_mount(fc);
1232 	else
1233 		mnt = ERR_PTR(ret);
1234 
1235 	put_fs_context(fc);
1236 	return mnt;
1237 }
1238 EXPORT_SYMBOL_GPL(vfs_kern_mount);
1239 
clone_mnt(struct mount * old,struct dentry * root,int flag)1240 static struct mount *clone_mnt(struct mount *old, struct dentry *root,
1241 					int flag)
1242 {
1243 	struct mount *mnt;
1244 	int err;
1245 
1246 	mnt = alloc_vfsmnt(old->mnt_devname);
1247 	if (!mnt)
1248 		return ERR_PTR(-ENOMEM);
1249 
1250 	mnt->mnt.mnt_flags = READ_ONCE(old->mnt.mnt_flags) &
1251 			     ~MNT_INTERNAL_FLAGS;
1252 
1253 	if (flag & (CL_SLAVE | CL_PRIVATE))
1254 		mnt->mnt_group_id = 0; /* not a peer of original */
1255 	else
1256 		mnt->mnt_group_id = old->mnt_group_id;
1257 
1258 	if ((flag & CL_MAKE_SHARED) && !mnt->mnt_group_id) {
1259 		err = mnt_alloc_group_id(mnt);
1260 		if (err)
1261 			goto out_free;
1262 	}
1263 
1264 	if (mnt->mnt_group_id)
1265 		set_mnt_shared(mnt);
1266 
1267 	mnt->mnt.mnt_idmap = mnt_idmap_get(mnt_idmap(&old->mnt));
1268 
1269 	setup_mnt(mnt, root);
1270 
1271 	if (flag & CL_PRIVATE)	// we are done with it
1272 		return mnt;
1273 
1274 	if (peers(mnt, old))
1275 		list_add(&mnt->mnt_share, &old->mnt_share);
1276 
1277 	if ((flag & CL_SLAVE) && old->mnt_group_id) {
1278 		hlist_add_head(&mnt->mnt_slave, &old->mnt_slave_list);
1279 		mnt->mnt_master = old;
1280 	} else if (IS_MNT_SLAVE(old)) {
1281 		hlist_add_behind(&mnt->mnt_slave, &old->mnt_slave);
1282 		mnt->mnt_master = old->mnt_master;
1283 	}
1284 	return mnt;
1285 
1286  out_free:
1287 	mnt_free_id(mnt);
1288 	free_vfsmnt(mnt);
1289 	return ERR_PTR(err);
1290 }
1291 
cleanup_mnt(struct mount * mnt)1292 static void cleanup_mnt(struct mount *mnt)
1293 {
1294 	struct hlist_node *p;
1295 	struct mount *m;
1296 	/*
1297 	 * The warning here probably indicates that somebody messed
1298 	 * up a mnt_want/drop_write() pair.  If this happens, the
1299 	 * filesystem was probably unable to make r/w->r/o transitions.
1300 	 * The locking used to deal with mnt_count decrement provides barriers,
1301 	 * so mnt_get_writers() below is safe.
1302 	 */
1303 	WARN_ON(mnt_get_writers(mnt));
1304 	if (unlikely(mnt->mnt_pins.first))
1305 		mnt_pin_kill(mnt);
1306 	hlist_for_each_entry_safe(m, p, &mnt->mnt_stuck_children, mnt_umount) {
1307 		hlist_del(&m->mnt_umount);
1308 		mntput(&m->mnt);
1309 	}
1310 	fsnotify_vfsmount_delete(&mnt->mnt);
1311 	dput(mnt->mnt.mnt_root);
1312 	deactivate_super(mnt->mnt.mnt_sb);
1313 	mnt_free_id(mnt);
1314 	call_rcu(&mnt->mnt_rcu, delayed_free_vfsmnt);
1315 }
1316 
__cleanup_mnt(struct rcu_head * head)1317 static void __cleanup_mnt(struct rcu_head *head)
1318 {
1319 	cleanup_mnt(container_of(head, struct mount, mnt_rcu));
1320 }
1321 
1322 static LLIST_HEAD(delayed_mntput_list);
delayed_mntput(struct work_struct * unused)1323 static void delayed_mntput(struct work_struct *unused)
1324 {
1325 	struct llist_node *node = llist_del_all(&delayed_mntput_list);
1326 	struct mount *m, *t;
1327 
1328 	llist_for_each_entry_safe(m, t, node, mnt_llist)
1329 		cleanup_mnt(m);
1330 }
1331 static DECLARE_DELAYED_WORK(delayed_mntput_work, delayed_mntput);
1332 
mntput_no_expire_slowpath(struct mount * mnt)1333 static void noinline mntput_no_expire_slowpath(struct mount *mnt)
1334 {
1335 	LIST_HEAD(list);
1336 	int count;
1337 
1338 	VFS_BUG_ON(mnt->mnt_ns);
1339 	lock_mount_hash();
1340 	/*
1341 	 * make sure that if __legitimize_mnt() has not seen us grab
1342 	 * mount_lock, we'll see their refcount increment here.
1343 	 */
1344 	smp_mb();
1345 	mnt_add_count(mnt, -1);
1346 	count = mnt_get_count(mnt);
1347 	if (count != 0) {
1348 		WARN_ON(count < 0);
1349 		rcu_read_unlock();
1350 		unlock_mount_hash();
1351 		return;
1352 	}
1353 	if (unlikely(mnt->mnt.mnt_flags & MNT_DOOMED)) {
1354 		rcu_read_unlock();
1355 		unlock_mount_hash();
1356 		return;
1357 	}
1358 	mnt->mnt.mnt_flags |= MNT_DOOMED;
1359 	rcu_read_unlock();
1360 
1361 	mnt_del_instance(mnt);
1362 	if (unlikely(!list_empty(&mnt->mnt_expire)))
1363 		list_del(&mnt->mnt_expire);
1364 
1365 	if (unlikely(!list_empty(&mnt->mnt_mounts))) {
1366 		struct mount *p, *tmp;
1367 		list_for_each_entry_safe(p, tmp, &mnt->mnt_mounts,  mnt_child) {
1368 			__umount_mnt(p, &list);
1369 			hlist_add_head(&p->mnt_umount, &mnt->mnt_stuck_children);
1370 		}
1371 	}
1372 	unlock_mount_hash();
1373 	shrink_dentry_list(&list);
1374 
1375 	if (likely(!(mnt->mnt.mnt_flags & MNT_INTERNAL))) {
1376 		struct task_struct *task = current;
1377 		if (likely(!(task->flags & PF_KTHREAD))) {
1378 			init_task_work(&mnt->mnt_rcu, __cleanup_mnt);
1379 			if (!task_work_add(task, &mnt->mnt_rcu, TWA_RESUME))
1380 				return;
1381 		}
1382 		if (llist_add(&mnt->mnt_llist, &delayed_mntput_list))
1383 			schedule_delayed_work(&delayed_mntput_work, 1);
1384 		return;
1385 	}
1386 	cleanup_mnt(mnt);
1387 }
1388 
mntput_no_expire(struct mount * mnt)1389 static void mntput_no_expire(struct mount *mnt)
1390 {
1391 	rcu_read_lock();
1392 	if (likely(READ_ONCE(mnt->mnt_ns))) {
1393 		/*
1394 		 * Since we don't do lock_mount_hash() here,
1395 		 * ->mnt_ns can change under us.  However, if it's
1396 		 * non-NULL, then there's a reference that won't
1397 		 * be dropped until after an RCU delay done after
1398 		 * turning ->mnt_ns NULL.  So if we observe it
1399 		 * non-NULL under rcu_read_lock(), the reference
1400 		 * we are dropping is not the final one.
1401 		 */
1402 		mnt_add_count(mnt, -1);
1403 		rcu_read_unlock();
1404 		return;
1405 	}
1406 	mntput_no_expire_slowpath(mnt);
1407 }
1408 
mntput(struct vfsmount * mnt)1409 void mntput(struct vfsmount *mnt)
1410 {
1411 	if (mnt) {
1412 		struct mount *m = real_mount(mnt);
1413 		/* avoid cacheline pingpong */
1414 		if (unlikely(m->mnt_expiry_mark))
1415 			WRITE_ONCE(m->mnt_expiry_mark, 0);
1416 		mntput_no_expire(m);
1417 	}
1418 }
1419 EXPORT_SYMBOL(mntput);
1420 
mntget(struct vfsmount * mnt)1421 struct vfsmount *mntget(struct vfsmount *mnt)
1422 {
1423 	if (mnt)
1424 		mnt_add_count(real_mount(mnt), 1);
1425 	return mnt;
1426 }
1427 EXPORT_SYMBOL(mntget);
1428 
1429 /*
1430  * Make a mount point inaccessible to new lookups.
1431  * Because there may still be current users, the caller MUST WAIT
1432  * for an RCU grace period before destroying the mount point.
1433  */
mnt_make_shortterm(struct vfsmount * mnt)1434 void mnt_make_shortterm(struct vfsmount *mnt)
1435 {
1436 	if (mnt)
1437 		real_mount(mnt)->mnt_ns = NULL;
1438 }
1439 
1440 /**
1441  * path_is_mountpoint() - Check if path is a mount in the current namespace.
1442  * @path: path to check
1443  *
1444  *  d_mountpoint() can only be used reliably to establish if a dentry is
1445  *  not mounted in any namespace and that common case is handled inline.
1446  *  d_mountpoint() isn't aware of the possibility there may be multiple
1447  *  mounts using a given dentry in a different namespace. This function
1448  *  checks if the passed in path is a mountpoint rather than the dentry
1449  *  alone.
1450  */
path_is_mountpoint(const struct path * path)1451 bool path_is_mountpoint(const struct path *path)
1452 {
1453 	unsigned seq;
1454 	bool res;
1455 
1456 	if (!d_mountpoint(path->dentry))
1457 		return false;
1458 
1459 	rcu_read_lock();
1460 	do {
1461 		seq = read_seqbegin(&mount_lock);
1462 		res = __path_is_mountpoint(path);
1463 	} while (read_seqretry(&mount_lock, seq));
1464 	rcu_read_unlock();
1465 
1466 	return res;
1467 }
1468 EXPORT_SYMBOL(path_is_mountpoint);
1469 
mnt_clone_internal(const struct path * path)1470 struct vfsmount *mnt_clone_internal(const struct path *path)
1471 {
1472 	struct mount *p;
1473 	p = clone_mnt(real_mount(path->mnt), path->dentry, CL_PRIVATE);
1474 	if (IS_ERR(p))
1475 		return ERR_CAST(p);
1476 	p->mnt.mnt_flags |= MNT_INTERNAL;
1477 	return &p->mnt;
1478 }
1479 
1480 /*
1481  * Returns the mount which either has the specified mnt_id, or has the next
1482  * smallest id afer the specified one.
1483  */
mnt_find_id_at(struct mnt_namespace * ns,u64 mnt_id)1484 static struct mount *mnt_find_id_at(struct mnt_namespace *ns, u64 mnt_id)
1485 {
1486 	struct rb_node *node = ns->mounts.rb_node;
1487 	struct mount *ret = NULL;
1488 
1489 	while (node) {
1490 		struct mount *m = node_to_mount(node);
1491 
1492 		if (mnt_id <= m->mnt_id_unique) {
1493 			ret = node_to_mount(node);
1494 			if (mnt_id == m->mnt_id_unique)
1495 				break;
1496 			node = node->rb_left;
1497 		} else {
1498 			node = node->rb_right;
1499 		}
1500 	}
1501 	return ret;
1502 }
1503 
1504 /*
1505  * Returns the mount which either has the specified mnt_id, or has the next
1506  * greater id before the specified one.
1507  */
mnt_find_id_at_reverse(struct mnt_namespace * ns,u64 mnt_id)1508 static struct mount *mnt_find_id_at_reverse(struct mnt_namespace *ns, u64 mnt_id)
1509 {
1510 	struct rb_node *node = ns->mounts.rb_node;
1511 	struct mount *ret = NULL;
1512 
1513 	while (node) {
1514 		struct mount *m = node_to_mount(node);
1515 
1516 		if (mnt_id >= m->mnt_id_unique) {
1517 			ret = node_to_mount(node);
1518 			if (mnt_id == m->mnt_id_unique)
1519 				break;
1520 			node = node->rb_right;
1521 		} else {
1522 			node = node->rb_left;
1523 		}
1524 	}
1525 	return ret;
1526 }
1527 
1528 #ifdef CONFIG_PROC_FS
1529 
1530 /* iterator; we want it to have access to namespace_sem, thus here... */
m_start(struct seq_file * m,loff_t * pos)1531 static void *m_start(struct seq_file *m, loff_t *pos)
1532 {
1533 	struct proc_mounts *p = m->private;
1534 	struct mount *mnt;
1535 
1536 	down_read(&namespace_sem);
1537 
1538 	mnt = mnt_find_id_at(p->ns, *pos);
1539 	if (mnt)
1540 		*pos = mnt->mnt_id_unique;
1541 	return mnt;
1542 }
1543 
m_next(struct seq_file * m,void * v,loff_t * pos)1544 static void *m_next(struct seq_file *m, void *v, loff_t *pos)
1545 {
1546 	struct mount *mnt = v;
1547 	struct rb_node *node = rb_next(&mnt->mnt_node);
1548 
1549 	if (node) {
1550 		struct mount *next = node_to_mount(node);
1551 		*pos = next->mnt_id_unique;
1552 		return next;
1553 	}
1554 
1555 	/*
1556 	 * No more mounts. Set pos past current mount's ID so that if
1557 	 * iteration restarts, mnt_find_id_at() returns NULL.
1558 	 */
1559 	*pos = mnt->mnt_id_unique + 1;
1560 	return NULL;
1561 }
1562 
m_stop(struct seq_file * m,void * v)1563 static void m_stop(struct seq_file *m, void *v)
1564 {
1565 	up_read(&namespace_sem);
1566 }
1567 
m_show(struct seq_file * m,void * v)1568 static int m_show(struct seq_file *m, void *v)
1569 {
1570 	struct proc_mounts *p = m->private;
1571 	struct mount *r = v;
1572 	return p->show(m, &r->mnt);
1573 }
1574 
1575 const struct seq_operations mounts_op = {
1576 	.start	= m_start,
1577 	.next	= m_next,
1578 	.stop	= m_stop,
1579 	.show	= m_show,
1580 };
1581 
1582 #endif  /* CONFIG_PROC_FS */
1583 
1584 /**
1585  * may_umount_tree - check if a mount tree is busy
1586  * @m: root of mount tree
1587  *
1588  * This is called to check if a tree of mounts has any
1589  * open files, pwds, chroots or sub mounts that are
1590  * busy.
1591  */
may_umount_tree(struct vfsmount * m)1592 int may_umount_tree(struct vfsmount *m)
1593 {
1594 	struct mount *mnt = real_mount(m);
1595 	bool busy = false;
1596 
1597 	/* write lock needed for mnt_get_count */
1598 	lock_mount_hash();
1599 	for (struct mount *p = mnt; p; p = next_mnt(p, mnt)) {
1600 		if (mnt_get_count(p) > (p == mnt ? 2 : 1)) {
1601 			busy = true;
1602 			break;
1603 		}
1604 	}
1605 	unlock_mount_hash();
1606 
1607 	return !busy;
1608 }
1609 
1610 EXPORT_SYMBOL(may_umount_tree);
1611 
1612 /**
1613  * may_umount - check if a mount point is busy
1614  * @mnt: root of mount
1615  *
1616  * This is called to check if a mount point has any
1617  * open files, pwds, chroots or sub mounts. If the
1618  * mount has sub mounts this will return busy
1619  * regardless of whether the sub mounts are busy.
1620  *
1621  * Doesn't take quota and stuff into account. IOW, in some cases it will
1622  * give false negatives. The main reason why it's here is that we need
1623  * a non-destructive way to look for easily umountable filesystems.
1624  */
may_umount(struct vfsmount * mnt)1625 int may_umount(struct vfsmount *mnt)
1626 {
1627 	int ret = 1;
1628 	down_read(&namespace_sem);
1629 	lock_mount_hash();
1630 	if (propagate_mount_busy(real_mount(mnt), 2))
1631 		ret = 0;
1632 	unlock_mount_hash();
1633 	up_read(&namespace_sem);
1634 	return ret;
1635 }
1636 
1637 EXPORT_SYMBOL(may_umount);
1638 
1639 #ifdef CONFIG_FSNOTIFY
mnt_notify(struct mount * p)1640 static void mnt_notify(struct mount *p)
1641 {
1642 	if (!p->prev_ns && p->mnt_ns) {
1643 		fsnotify_mnt_attach(p->mnt_ns, &p->mnt);
1644 	} else if (p->prev_ns && !p->mnt_ns) {
1645 		fsnotify_mnt_detach(p->prev_ns, &p->mnt);
1646 	} else if (p->prev_ns == p->mnt_ns) {
1647 		fsnotify_mnt_move(p->mnt_ns, &p->mnt);
1648 	} else {
1649 		fsnotify_mnt_detach(p->prev_ns, &p->mnt);
1650 		fsnotify_mnt_attach(p->mnt_ns, &p->mnt);
1651 	}
1652 	p->prev_ns = p->mnt_ns;
1653 }
1654 
notify_mnt_list(void)1655 static void notify_mnt_list(void)
1656 {
1657 	struct mount *m, *tmp;
1658 	/*
1659 	 * Notify about mounts that were added/reparented/detached/remain
1660 	 * connected after unmount.
1661 	 */
1662 	list_for_each_entry_safe(m, tmp, &notify_list, to_notify) {
1663 		mnt_notify(m);
1664 		list_del_init(&m->to_notify);
1665 	}
1666 }
1667 
need_notify_mnt_list(void)1668 static bool need_notify_mnt_list(void)
1669 {
1670 	return !list_empty(&notify_list);
1671 }
1672 #else
notify_mnt_list(void)1673 static void notify_mnt_list(void)
1674 {
1675 }
1676 
need_notify_mnt_list(void)1677 static bool need_notify_mnt_list(void)
1678 {
1679 	return false;
1680 }
1681 #endif
1682 
1683 static void free_mnt_ns(struct mnt_namespace *);
namespace_unlock(void)1684 static void namespace_unlock(void)
1685 {
1686 	struct hlist_head head;
1687 	struct hlist_node *p;
1688 	struct mount *m;
1689 	struct mnt_namespace *ns = emptied_ns;
1690 	LIST_HEAD(list);
1691 
1692 	hlist_move_list(&unmounted, &head);
1693 	list_splice_init(&ex_mountpoints, &list);
1694 	emptied_ns = NULL;
1695 
1696 	if (need_notify_mnt_list()) {
1697 		/*
1698 		 * No point blocking out concurrent readers while notifications
1699 		 * are sent. This will also allow statmount()/listmount() to run
1700 		 * concurrently.
1701 		 */
1702 		downgrade_write(&namespace_sem);
1703 		notify_mnt_list();
1704 		up_read(&namespace_sem);
1705 	} else {
1706 		up_write(&namespace_sem);
1707 	}
1708 	if (unlikely(ns)) {
1709 		/* Make sure we notice when we leak mounts. */
1710 		VFS_WARN_ON_ONCE(!mnt_ns_empty(ns));
1711 		free_mnt_ns(ns);
1712 	}
1713 
1714 	shrink_dentry_list(&list);
1715 
1716 	if (likely(hlist_empty(&head)))
1717 		return;
1718 
1719 	synchronize_rcu_expedited();
1720 
1721 	hlist_for_each_entry_safe(m, p, &head, mnt_umount) {
1722 		hlist_del(&m->mnt_umount);
1723 		mntput(&m->mnt);
1724 	}
1725 }
1726 
namespace_lock(void)1727 static inline void namespace_lock(void)
1728 {
1729 	down_write(&namespace_sem);
1730 }
1731 
1732 enum umount_tree_flags {
1733 	UMOUNT_SYNC = 1,
1734 	UMOUNT_PROPAGATE = 2,
1735 	UMOUNT_CONNECTED = 4,
1736 };
1737 
disconnect_mount(struct mount * mnt,enum umount_tree_flags how)1738 static bool disconnect_mount(struct mount *mnt, enum umount_tree_flags how)
1739 {
1740 	/* Leaving mounts connected is only valid for lazy umounts */
1741 	if (how & UMOUNT_SYNC)
1742 		return true;
1743 
1744 	/* A mount without a parent has nothing to be connected to */
1745 	if (!mnt_has_parent(mnt))
1746 		return true;
1747 
1748 	/* Because the reference counting rules change when mounts are
1749 	 * unmounted and connected, umounted mounts may not be
1750 	 * connected to mounted mounts.
1751 	 */
1752 	if (!(mnt->mnt_parent->mnt.mnt_flags & MNT_UMOUNT))
1753 		return true;
1754 
1755 	/* Has it been requested that the mount remain connected? */
1756 	if (how & UMOUNT_CONNECTED)
1757 		return false;
1758 
1759 	/* Is the mount locked such that it needs to remain connected? */
1760 	if (IS_MNT_LOCKED(mnt))
1761 		return false;
1762 
1763 	/* By default disconnect the mount */
1764 	return true;
1765 }
1766 
1767 /*
1768  * mount_lock must be held
1769  * namespace_sem must be held for write
1770  */
umount_tree(struct mount * mnt,enum umount_tree_flags how)1771 static void umount_tree(struct mount *mnt, enum umount_tree_flags how)
1772 {
1773 	LIST_HEAD(tmp_list);
1774 	struct mount *p;
1775 
1776 	if (how & UMOUNT_PROPAGATE)
1777 		propagate_mount_unlock(mnt);
1778 
1779 	/* Gather the mounts to umount */
1780 	for (p = mnt; p; p = next_mnt(p, mnt)) {
1781 		p->mnt.mnt_flags |= MNT_UMOUNT;
1782 		if (mnt_ns_attached(p))
1783 			move_from_ns(p);
1784 		list_add_tail(&p->mnt_list, &tmp_list);
1785 	}
1786 
1787 	/* Hide the mounts from mnt_mounts */
1788 	list_for_each_entry(p, &tmp_list, mnt_list) {
1789 		list_del_init(&p->mnt_child);
1790 	}
1791 
1792 	/* Add propagated mounts to the tmp_list */
1793 	if (how & UMOUNT_PROPAGATE)
1794 		propagate_umount(&tmp_list);
1795 
1796 	bulk_make_private(&tmp_list);
1797 
1798 	while (!list_empty(&tmp_list)) {
1799 		struct mnt_namespace *ns;
1800 		bool disconnect;
1801 		p = list_first_entry(&tmp_list, struct mount, mnt_list);
1802 		list_del_init(&p->mnt_expire);
1803 		list_del_init(&p->mnt_list);
1804 		ns = p->mnt_ns;
1805 		if (ns) {
1806 			ns->nr_mounts--;
1807 			__touch_mnt_namespace(ns);
1808 		}
1809 		p->mnt_ns = NULL;
1810 		if (how & UMOUNT_SYNC)
1811 			p->mnt.mnt_flags |= MNT_SYNC_UMOUNT;
1812 
1813 		disconnect = disconnect_mount(p, how);
1814 		if (mnt_has_parent(p)) {
1815 			if (!disconnect) {
1816 				/* Don't forget about p */
1817 				list_add_tail(&p->mnt_child, &p->mnt_parent->mnt_mounts);
1818 			} else {
1819 				umount_mnt(p);
1820 			}
1821 		}
1822 		if (disconnect)
1823 			hlist_add_head(&p->mnt_umount, &unmounted);
1824 
1825 		/*
1826 		 * At this point p->mnt_ns is NULL, notification will be queued
1827 		 * only if
1828 		 *
1829 		 *  - p->prev_ns is non-NULL *and*
1830 		 *  - p->prev_ns->n_fsnotify_marks is non-NULL
1831 		 *
1832 		 * This will preclude queuing the mount if this is a cleanup
1833 		 * after a failed copy_tree() or destruction of an anonymous
1834 		 * namespace, etc.
1835 		 */
1836 		mnt_notify_add(p);
1837 	}
1838 }
1839 
1840 static void shrink_submounts(struct mount *mnt);
1841 
do_umount_root(struct super_block * sb)1842 static int do_umount_root(struct super_block *sb)
1843 {
1844 	int ret = 0;
1845 
1846 	down_write(&sb->s_umount);
1847 	if (!sb_rdonly(sb)) {
1848 		struct fs_context *fc;
1849 
1850 		fc = fs_context_for_reconfigure(sb->s_root, SB_RDONLY,
1851 						SB_RDONLY);
1852 		if (IS_ERR(fc)) {
1853 			ret = PTR_ERR(fc);
1854 		} else {
1855 			ret = parse_monolithic_mount_data(fc, NULL);
1856 			if (!ret)
1857 				ret = reconfigure_super(fc);
1858 			put_fs_context(fc);
1859 		}
1860 	}
1861 	up_write(&sb->s_umount);
1862 	return ret;
1863 }
1864 
do_umount(struct mount * mnt,int flags)1865 static int do_umount(struct mount *mnt, int flags)
1866 {
1867 	struct super_block *sb = mnt->mnt.mnt_sb;
1868 	int retval;
1869 
1870 	retval = security_sb_umount(&mnt->mnt, flags);
1871 	if (retval)
1872 		return retval;
1873 
1874 	/*
1875 	 * Allow userspace to request a mountpoint be expired rather than
1876 	 * unmounting unconditionally. Unmount only happens if:
1877 	 *  (1) the mark is already set (the mark is cleared by mntput())
1878 	 *  (2) the usage count == 1 [parent vfsmount] + 1 [sys_umount]
1879 	 */
1880 	if (flags & MNT_EXPIRE) {
1881 		if (&mnt->mnt == current->fs->root.mnt ||
1882 		    flags & (MNT_FORCE | MNT_DETACH))
1883 			return -EINVAL;
1884 
1885 		/*
1886 		 * probably don't strictly need the lock here if we examined
1887 		 * all race cases, but it's a slowpath.
1888 		 */
1889 		lock_mount_hash();
1890 		if (!list_empty(&mnt->mnt_mounts) || mnt_get_count(mnt) != 2) {
1891 			unlock_mount_hash();
1892 			return -EBUSY;
1893 		}
1894 		unlock_mount_hash();
1895 
1896 		if (!xchg(&mnt->mnt_expiry_mark, 1))
1897 			return -EAGAIN;
1898 	}
1899 
1900 	/*
1901 	 * If we may have to abort operations to get out of this
1902 	 * mount, and they will themselves hold resources we must
1903 	 * allow the fs to do things. In the Unix tradition of
1904 	 * 'Gee thats tricky lets do it in userspace' the umount_begin
1905 	 * might fail to complete on the first run through as other tasks
1906 	 * must return, and the like. Thats for the mount program to worry
1907 	 * about for the moment.
1908 	 */
1909 
1910 	if (flags & MNT_FORCE && sb->s_op->umount_begin) {
1911 		sb->s_op->umount_begin(sb);
1912 	}
1913 
1914 	/*
1915 	 * No sense to grab the lock for this test, but test itself looks
1916 	 * somewhat bogus. Suggestions for better replacement?
1917 	 * Ho-hum... In principle, we might treat that as umount + switch
1918 	 * to rootfs. GC would eventually take care of the old vfsmount.
1919 	 * Actually it makes sense, especially if rootfs would contain a
1920 	 * /reboot - static binary that would close all descriptors and
1921 	 * call reboot(9). Then init(8) could umount root and exec /reboot.
1922 	 */
1923 	if (&mnt->mnt == current->fs->root.mnt && !(flags & MNT_DETACH)) {
1924 		/*
1925 		 * Special case for "unmounting" root ...
1926 		 * we just try to remount it readonly.
1927 		 */
1928 		if (!ns_capable(sb->s_user_ns, CAP_SYS_ADMIN))
1929 			return -EPERM;
1930 		return do_umount_root(sb);
1931 	}
1932 
1933 	namespace_lock();
1934 	lock_mount_hash();
1935 
1936 	/* Repeat the earlier racy checks, now that we are holding the locks */
1937 	retval = -EINVAL;
1938 	if (!check_mnt(mnt))
1939 		goto out;
1940 
1941 	if (mnt->mnt.mnt_flags & MNT_LOCKED)
1942 		goto out;
1943 
1944 	if (!mnt_has_parent(mnt)) /* not the absolute root */
1945 		goto out;
1946 
1947 	event++;
1948 	if (flags & MNT_DETACH) {
1949 		umount_tree(mnt, UMOUNT_PROPAGATE);
1950 		retval = 0;
1951 	} else {
1952 		smp_mb(); // paired with __legitimize_mnt()
1953 		shrink_submounts(mnt);
1954 		retval = -EBUSY;
1955 		if (!propagate_mount_busy(mnt, 2)) {
1956 			umount_tree(mnt, UMOUNT_PROPAGATE|UMOUNT_SYNC);
1957 			retval = 0;
1958 		}
1959 	}
1960 out:
1961 	unlock_mount_hash();
1962 	namespace_unlock();
1963 	return retval;
1964 }
1965 
1966 /*
1967  * __detach_mounts - lazily unmount all mounts on the specified dentry
1968  *
1969  * During unlink, rmdir, and d_drop it is possible to loose the path
1970  * to an existing mountpoint, and wind up leaking the mount.
1971  * detach_mounts allows lazily unmounting those mounts instead of
1972  * leaking them.
1973  *
1974  * The caller may hold dentry->d_inode->i_rwsem.
1975  */
__detach_mounts(struct dentry * dentry)1976 void __detach_mounts(struct dentry *dentry)
1977 {
1978 	struct pinned_mountpoint mp = {};
1979 	struct mount *mnt;
1980 
1981 	guard(namespace_excl)();
1982 	guard(mount_writer)();
1983 
1984 	if (!lookup_mountpoint(dentry, &mp))
1985 		return;
1986 
1987 	event++;
1988 	while (mp.node.next) {
1989 		mnt = hlist_entry(mp.node.next, struct mount, mnt_mp_list);
1990 		if (mnt->mnt.mnt_flags & MNT_UMOUNT) {
1991 			umount_mnt(mnt);
1992 			hlist_add_head(&mnt->mnt_umount, &unmounted);
1993 		}
1994 		else umount_tree(mnt, UMOUNT_CONNECTED);
1995 	}
1996 	unpin_mountpoint(&mp);
1997 }
1998 
1999 /*
2000  * Is the caller allowed to modify his namespace?
2001  */
may_mount(void)2002 bool may_mount(void)
2003 {
2004 	return ns_capable(current->nsproxy->mnt_ns->user_ns, CAP_SYS_ADMIN);
2005 }
2006 
warn_mandlock(void)2007 static void warn_mandlock(void)
2008 {
2009 	pr_warn_once("=======================================================\n"
2010 		     "WARNING: The mand mount option has been deprecated and\n"
2011 		     "         and is ignored by this kernel. Remove the mand\n"
2012 		     "         option from the mount to silence this warning.\n"
2013 		     "=======================================================\n");
2014 }
2015 
can_umount(const struct path * path,int flags)2016 static int can_umount(const struct path *path, int flags)
2017 {
2018 	struct mount *mnt = real_mount(path->mnt);
2019 	struct super_block *sb = path->dentry->d_sb;
2020 
2021 	if (!may_mount())
2022 		return -EPERM;
2023 	if (!path_mounted(path))
2024 		return -EINVAL;
2025 	if (!check_mnt(mnt))
2026 		return -EINVAL;
2027 	if (mnt->mnt.mnt_flags & MNT_LOCKED) /* Check optimistically */
2028 		return -EINVAL;
2029 	if (flags & MNT_FORCE && !ns_capable(sb->s_user_ns, CAP_SYS_ADMIN))
2030 		return -EPERM;
2031 	return 0;
2032 }
2033 
2034 // caller is responsible for flags being sane
path_umount(const struct path * path,int flags)2035 int path_umount(const struct path *path, int flags)
2036 {
2037 	struct mount *mnt = real_mount(path->mnt);
2038 	int ret;
2039 
2040 	ret = can_umount(path, flags);
2041 	if (!ret)
2042 		ret = do_umount(mnt, flags);
2043 
2044 	/* we mustn't call path_put() as that would clear mnt_expiry_mark */
2045 	dput(path->dentry);
2046 	mntput_no_expire(mnt);
2047 	return ret;
2048 }
2049 
ksys_umount(char __user * name,int flags)2050 static int ksys_umount(char __user *name, int flags)
2051 {
2052 	int lookup_flags = LOOKUP_MOUNTPOINT;
2053 	struct path path;
2054 	int ret;
2055 
2056 	// basic validity checks done first
2057 	if (flags & ~(MNT_FORCE | MNT_DETACH | MNT_EXPIRE | UMOUNT_NOFOLLOW))
2058 		return -EINVAL;
2059 
2060 	if (!(flags & UMOUNT_NOFOLLOW))
2061 		lookup_flags |= LOOKUP_FOLLOW;
2062 	ret = user_path_at(AT_FDCWD, name, lookup_flags, &path);
2063 	if (ret)
2064 		return ret;
2065 	return path_umount(&path, flags);
2066 }
2067 
SYSCALL_DEFINE2(umount,char __user *,name,int,flags)2068 SYSCALL_DEFINE2(umount, char __user *, name, int, flags)
2069 {
2070 	return ksys_umount(name, flags);
2071 }
2072 
2073 #ifdef __ARCH_WANT_SYS_OLDUMOUNT
2074 
2075 /*
2076  *	The 2.0 compatible umount. No flags.
2077  */
SYSCALL_DEFINE1(oldumount,char __user *,name)2078 SYSCALL_DEFINE1(oldumount, char __user *, name)
2079 {
2080 	return ksys_umount(name, 0);
2081 }
2082 
2083 #endif
2084 
is_mnt_ns_file(struct dentry * dentry)2085 static bool is_mnt_ns_file(struct dentry *dentry)
2086 {
2087 	struct ns_common *ns;
2088 
2089 	/* Is this a proxy for a mount namespace? */
2090 	if (dentry->d_op != &ns_dentry_operations)
2091 		return false;
2092 
2093 	ns = d_inode(dentry)->i_private;
2094 
2095 	return ns->ops == &mntns_operations;
2096 }
2097 
from_mnt_ns(struct mnt_namespace * mnt)2098 struct ns_common *from_mnt_ns(struct mnt_namespace *mnt)
2099 {
2100 	return &mnt->ns;
2101 }
2102 
get_sequential_mnt_ns(struct mnt_namespace * mntns,bool previous)2103 struct mnt_namespace *get_sequential_mnt_ns(struct mnt_namespace *mntns, bool previous)
2104 {
2105 	struct ns_common *ns;
2106 
2107 	guard(rcu)();
2108 
2109 	for (;;) {
2110 		ns = ns_tree_adjoined_rcu(mntns, previous);
2111 		if (IS_ERR(ns))
2112 			return ERR_CAST(ns);
2113 
2114 		mntns = to_mnt_ns(ns);
2115 
2116 		/*
2117 		 * The last passive reference count is put with RCU
2118 		 * delay so accessing the mount namespace is not just
2119 		 * safe but all relevant members are still valid.
2120 		 */
2121 		if (!ns_capable_noaudit(mntns->user_ns, CAP_SYS_ADMIN))
2122 			continue;
2123 
2124 		/*
2125 		 * We need an active reference count as we're persisting
2126 		 * the mount namespace and it might already be on its
2127 		 * deathbed.
2128 		 */
2129 		if (!ns_ref_get(mntns))
2130 			continue;
2131 
2132 		return mntns;
2133 	}
2134 }
2135 
mnt_ns_from_dentry(struct dentry * dentry)2136 struct mnt_namespace *mnt_ns_from_dentry(struct dentry *dentry)
2137 {
2138 	if (!is_mnt_ns_file(dentry))
2139 		return NULL;
2140 
2141 	return to_mnt_ns(get_proc_ns(dentry->d_inode));
2142 }
2143 
mnt_ns_loop(struct dentry * dentry)2144 static bool mnt_ns_loop(struct dentry *dentry)
2145 {
2146 	/* Could bind mounting the mount namespace inode cause a
2147 	 * mount namespace loop?
2148 	 */
2149 	struct mnt_namespace *mnt_ns = mnt_ns_from_dentry(dentry);
2150 
2151 	if (!mnt_ns)
2152 		return false;
2153 
2154 	return current->nsproxy->mnt_ns->ns.ns_id >= mnt_ns->ns.ns_id;
2155 }
2156 
copy_tree(struct mount * src_root,struct dentry * dentry,int flag)2157 struct mount *copy_tree(struct mount *src_root, struct dentry *dentry,
2158 					int flag)
2159 {
2160 	struct mount *res, *src_parent, *src_root_child, *src_mnt,
2161 		*dst_parent, *dst_mnt;
2162 
2163 	if (!(flag & CL_COPY_UNBINDABLE) && IS_MNT_UNBINDABLE(src_root))
2164 		return ERR_PTR(-EINVAL);
2165 
2166 	if (!(flag & CL_COPY_MNT_NS_FILE) && is_mnt_ns_file(dentry))
2167 		return ERR_PTR(-EINVAL);
2168 
2169 	res = dst_mnt = clone_mnt(src_root, dentry, flag);
2170 	if (IS_ERR(dst_mnt))
2171 		return dst_mnt;
2172 
2173 	src_parent = src_root;
2174 
2175 	list_for_each_entry(src_root_child, &src_root->mnt_mounts, mnt_child) {
2176 		if (!is_subdir(src_root_child->mnt_mountpoint, dentry))
2177 			continue;
2178 
2179 		for (src_mnt = src_root_child; src_mnt;
2180 		    src_mnt = next_mnt(src_mnt, src_root_child)) {
2181 			if (!(flag & CL_COPY_UNBINDABLE) &&
2182 			    IS_MNT_UNBINDABLE(src_mnt)) {
2183 				if (src_mnt->mnt.mnt_flags & MNT_LOCKED) {
2184 					/* Both unbindable and locked. */
2185 					dst_mnt = ERR_PTR(-EPERM);
2186 					goto out;
2187 				} else {
2188 					src_mnt = skip_mnt_tree(src_mnt);
2189 					continue;
2190 				}
2191 			}
2192 			if (!(flag & CL_COPY_MNT_NS_FILE) &&
2193 			    is_mnt_ns_file(src_mnt->mnt.mnt_root)) {
2194 				src_mnt = skip_mnt_tree(src_mnt);
2195 				continue;
2196 			}
2197 			while (src_parent != src_mnt->mnt_parent) {
2198 				src_parent = src_parent->mnt_parent;
2199 				dst_mnt = dst_mnt->mnt_parent;
2200 			}
2201 
2202 			src_parent = src_mnt;
2203 			dst_parent = dst_mnt;
2204 			dst_mnt = clone_mnt(src_mnt, src_mnt->mnt.mnt_root, flag);
2205 			if (IS_ERR(dst_mnt))
2206 				goto out;
2207 			lock_mount_hash();
2208 			if (src_mnt->mnt.mnt_flags & MNT_LOCKED)
2209 				dst_mnt->mnt.mnt_flags |= MNT_LOCKED;
2210 			if (unlikely(flag & CL_EXPIRE)) {
2211 				/* stick the duplicate mount on the same expiry
2212 				 * list as the original if that was on one */
2213 				if (!list_empty(&src_mnt->mnt_expire))
2214 					list_add(&dst_mnt->mnt_expire,
2215 						 &src_mnt->mnt_expire);
2216 			}
2217 			attach_mnt(dst_mnt, dst_parent, src_parent->mnt_mp);
2218 			unlock_mount_hash();
2219 		}
2220 	}
2221 	return res;
2222 
2223 out:
2224 	if (res) {
2225 		lock_mount_hash();
2226 		umount_tree(res, UMOUNT_SYNC);
2227 		unlock_mount_hash();
2228 	}
2229 	return dst_mnt;
2230 }
2231 
extend_array(struct path ** res,struct path ** to_free,unsigned n,unsigned * count,unsigned new_count)2232 static inline bool extend_array(struct path **res, struct path **to_free,
2233 				unsigned n, unsigned *count, unsigned new_count)
2234 {
2235 	struct path *p;
2236 
2237 	if (likely(n < *count))
2238 		return true;
2239 	p = kmalloc_objs(struct path, new_count);
2240 	if (p && *count)
2241 		memcpy(p, *res, *count * sizeof(struct path));
2242 	*count = new_count;
2243 	kfree(*to_free);
2244 	*to_free = *res = p;
2245 	return p;
2246 }
2247 
collect_paths(const struct path * path,struct path * prealloc,unsigned count)2248 const struct path *collect_paths(const struct path *path,
2249 			      struct path *prealloc, unsigned count)
2250 {
2251 	struct mount *root = real_mount(path->mnt);
2252 	struct mount *child;
2253 	struct path *res = prealloc, *to_free = NULL;
2254 	unsigned n = 0;
2255 
2256 	guard(namespace_shared)();
2257 
2258 	if (!check_mnt(root))
2259 		return ERR_PTR(-EINVAL);
2260 	if (!extend_array(&res, &to_free, 0, &count, 32))
2261 		return ERR_PTR(-ENOMEM);
2262 	res[n++] = *path;
2263 	list_for_each_entry(child, &root->mnt_mounts, mnt_child) {
2264 		if (!is_subdir(child->mnt_mountpoint, path->dentry))
2265 			continue;
2266 		for (struct mount *m = child; m; m = next_mnt(m, child)) {
2267 			if (!extend_array(&res, &to_free, n, &count, 2 * count))
2268 				return ERR_PTR(-ENOMEM);
2269 			res[n].mnt = &m->mnt;
2270 			res[n].dentry = m->mnt.mnt_root;
2271 			n++;
2272 		}
2273 	}
2274 	if (!extend_array(&res, &to_free, n, &count, count + 1))
2275 		return ERR_PTR(-ENOMEM);
2276 	memset(res + n, 0, (count - n) * sizeof(struct path));
2277 	for (struct path *p = res; p->mnt; p++)
2278 		path_get(p);
2279 	return res;
2280 }
2281 
drop_collected_paths(const struct path * paths,const struct path * prealloc)2282 void drop_collected_paths(const struct path *paths, const struct path *prealloc)
2283 {
2284 	for (const struct path *p = paths; p->mnt; p++)
2285 		path_put(p);
2286 	if (paths != prealloc)
2287 		kfree(paths);
2288 }
2289 
2290 static struct mnt_namespace *alloc_mnt_ns(struct user_namespace *, bool);
2291 
dissolve_on_fput(struct vfsmount * mnt)2292 void dissolve_on_fput(struct vfsmount *mnt)
2293 {
2294 	struct mount *m = real_mount(mnt);
2295 
2296 	/*
2297 	 * m used to be the root of anon namespace; if it still is one,
2298 	 * we need to dissolve the mount tree and free that namespace.
2299 	 * Let's try to avoid taking namespace_sem if we can determine
2300 	 * that there's nothing to do without it - rcu_read_lock() is
2301 	 * enough to make anon_ns_root() memory-safe and once m has
2302 	 * left its namespace, it's no longer our concern, since it will
2303 	 * never become a root of anon ns again.
2304 	 */
2305 
2306 	scoped_guard(rcu) {
2307 		if (!anon_ns_root(m))
2308 			return;
2309 	}
2310 
2311 	scoped_guard(namespace_excl) {
2312 		if (!anon_ns_root(m))
2313 			return;
2314 
2315 		emptied_ns = m->mnt_ns;
2316 		lock_mount_hash();
2317 		umount_tree(m, UMOUNT_CONNECTED);
2318 		unlock_mount_hash();
2319 	}
2320 }
2321 
2322 /* locks: namespace_shared && pinned(mnt) || mount_locked_reader */
__has_locked_children(struct mount * mnt,struct dentry * dentry)2323 static bool __has_locked_children(struct mount *mnt, struct dentry *dentry)
2324 {
2325 	struct mount *child;
2326 
2327 	list_for_each_entry(child, &mnt->mnt_mounts, mnt_child) {
2328 		if (!is_subdir(child->mnt_mountpoint, dentry))
2329 			continue;
2330 
2331 		if (child->mnt.mnt_flags & MNT_LOCKED)
2332 			return true;
2333 	}
2334 	return false;
2335 }
2336 
has_locked_children(struct mount * mnt,struct dentry * dentry)2337 bool has_locked_children(struct mount *mnt, struct dentry *dentry)
2338 {
2339 	guard(mount_locked_reader)();
2340 	return __has_locked_children(mnt, dentry);
2341 }
2342 
2343 /*
2344  * Check that there aren't references to earlier/same mount namespaces in the
2345  * specified subtree.  Such references can act as pins for mount namespaces
2346  * that aren't checked by the mount-cycle checking code, thereby allowing
2347  * cycles to be made.
2348  *
2349  * locks: mount_locked_reader || namespace_shared && pinned(subtree)
2350  */
check_for_nsfs_mounts(struct mount * subtree)2351 static bool check_for_nsfs_mounts(struct mount *subtree)
2352 {
2353 	for (struct mount *p = subtree; p; p = next_mnt(p, subtree))
2354 		if (mnt_ns_loop(p->mnt.mnt_root))
2355 			return false;
2356 	return true;
2357 }
2358 
2359 /**
2360  * clone_private_mount - create a private clone of a path
2361  * @path: path to clone
2362  *
2363  * This creates a new vfsmount, which will be the clone of @path.  The new mount
2364  * will not be attached anywhere in the namespace and will be private (i.e.
2365  * changes to the originating mount won't be propagated into this).
2366  *
2367  * This assumes caller has called or done the equivalent of may_mount().
2368  *
2369  * Release with mntput().
2370  */
clone_private_mount(const struct path * path)2371 struct vfsmount *clone_private_mount(const struct path *path)
2372 {
2373 	struct mount *old_mnt = real_mount(path->mnt);
2374 	struct mount *new_mnt;
2375 
2376 	guard(namespace_shared)();
2377 
2378 	if (IS_MNT_UNBINDABLE(old_mnt))
2379 		return ERR_PTR(-EINVAL);
2380 
2381 	/*
2382 	 * Make sure the source mount is acceptable.
2383 	 * Anything mounted in our mount namespace is allowed.
2384 	 * Otherwise, it must be the root of an anonymous mount
2385 	 * namespace, and we need to make sure no namespace
2386 	 * loops get created.
2387 	 */
2388 	if (!check_mnt(old_mnt)) {
2389 		if (!anon_ns_root(old_mnt))
2390 			return ERR_PTR(-EINVAL);
2391 
2392 		if (!check_for_nsfs_mounts(old_mnt))
2393 			return ERR_PTR(-EINVAL);
2394 	}
2395 
2396 	if (!ns_capable(old_mnt->mnt_ns->user_ns, CAP_SYS_ADMIN))
2397 		return ERR_PTR(-EPERM);
2398 
2399 	if (__has_locked_children(old_mnt, path->dentry))
2400 		return ERR_PTR(-EINVAL);
2401 
2402 	new_mnt = clone_mnt(old_mnt, path->dentry, CL_PRIVATE);
2403 	if (IS_ERR(new_mnt))
2404 		return ERR_PTR(-EINVAL);
2405 
2406 	/* Longterm mount to be removed by kern_unmount*() */
2407 	new_mnt->mnt_ns = MNT_NS_INTERNAL;
2408 	return &new_mnt->mnt;
2409 }
2410 EXPORT_SYMBOL_GPL(clone_private_mount);
2411 
lock_mnt_tree(struct mount * mnt)2412 static void lock_mnt_tree(struct mount *mnt)
2413 {
2414 	struct mount *p;
2415 
2416 	for (p = mnt; p; p = next_mnt(p, mnt)) {
2417 		int flags = p->mnt.mnt_flags;
2418 		/* Don't allow unprivileged users to change mount flags */
2419 		flags |= MNT_LOCK_ATIME;
2420 
2421 		if (flags & MNT_READONLY)
2422 			flags |= MNT_LOCK_READONLY;
2423 
2424 		if (flags & MNT_NODEV)
2425 			flags |= MNT_LOCK_NODEV;
2426 
2427 		if (flags & MNT_NOSUID)
2428 			flags |= MNT_LOCK_NOSUID;
2429 
2430 		if (flags & MNT_NOEXEC)
2431 			flags |= MNT_LOCK_NOEXEC;
2432 		/* Don't allow unprivileged users to reveal what is under a mount */
2433 		if (list_empty(&p->mnt_expire) && p != mnt)
2434 			flags |= MNT_LOCKED;
2435 		p->mnt.mnt_flags = flags;
2436 	}
2437 }
2438 
cleanup_group_ids(struct mount * mnt,struct mount * end)2439 static void cleanup_group_ids(struct mount *mnt, struct mount *end)
2440 {
2441 	struct mount *p;
2442 
2443 	for (p = mnt; p != end; p = next_mnt(p, mnt)) {
2444 		if (p->mnt_group_id && !IS_MNT_SHARED(p))
2445 			mnt_release_group_id(p);
2446 	}
2447 }
2448 
invent_group_ids(struct mount * mnt,bool recurse)2449 static int invent_group_ids(struct mount *mnt, bool recurse)
2450 {
2451 	struct mount *p;
2452 
2453 	for (p = mnt; p; p = recurse ? next_mnt(p, mnt) : NULL) {
2454 		if (!p->mnt_group_id) {
2455 			int err = mnt_alloc_group_id(p);
2456 			if (err) {
2457 				cleanup_group_ids(mnt, p);
2458 				return err;
2459 			}
2460 		}
2461 	}
2462 
2463 	return 0;
2464 }
2465 
count_mounts(struct mnt_namespace * ns,struct mount * mnt)2466 int count_mounts(struct mnt_namespace *ns, struct mount *mnt)
2467 {
2468 	unsigned int max = READ_ONCE(sysctl_mount_max);
2469 	unsigned int mounts = 0;
2470 	struct mount *p;
2471 
2472 	if (ns->nr_mounts >= max)
2473 		return -ENOSPC;
2474 	max -= ns->nr_mounts;
2475 	if (ns->pending_mounts >= max)
2476 		return -ENOSPC;
2477 	max -= ns->pending_mounts;
2478 
2479 	for (p = mnt; p; p = next_mnt(p, mnt))
2480 		mounts++;
2481 
2482 	if (mounts > max)
2483 		return -ENOSPC;
2484 
2485 	ns->pending_mounts += mounts;
2486 	return 0;
2487 }
2488 
2489 enum mnt_tree_flags_t {
2490 	MNT_TREE_BENEATH = BIT(0),
2491 	MNT_TREE_PROPAGATION = BIT(1),
2492 };
2493 
2494 /**
2495  * attach_recursive_mnt - attach a source mount tree
2496  * @source_mnt: mount tree to be attached
2497  * @dest:	the context for mounting at the place where the tree should go
2498  *
2499  *  NOTE: in the table below explains the semantics when a source mount
2500  *  of a given type is attached to a destination mount of a given type.
2501  * ---------------------------------------------------------------------------
2502  * |         BIND MOUNT OPERATION                                            |
2503  * |**************************************************************************
2504  * | source-->| shared        |       private  |       slave    | unbindable |
2505  * | dest     |               |                |                |            |
2506  * |   |      |               |                |                |            |
2507  * |   v      |               |                |                |            |
2508  * |**************************************************************************
2509  * |  shared  | shared (++)   |     shared (+) |     shared(+++)|  invalid   |
2510  * |          |               |                |                |            |
2511  * |non-shared| shared (+)    |      private   |      slave (*) |  invalid   |
2512  * ***************************************************************************
2513  * A bind operation clones the source mount and mounts the clone on the
2514  * destination mount.
2515  *
2516  * (++)  the cloned mount is propagated to all the mounts in the propagation
2517  * 	 tree of the destination mount and the cloned mount is added to
2518  * 	 the peer group of the source mount.
2519  * (+)   the cloned mount is created under the destination mount and is marked
2520  *       as shared. The cloned mount is added to the peer group of the source
2521  *       mount.
2522  * (+++) the mount is propagated to all the mounts in the propagation tree
2523  *       of the destination mount and the cloned mount is made slave
2524  *       of the same master as that of the source mount. The cloned mount
2525  *       is marked as 'shared and slave'.
2526  * (*)   the cloned mount is made a slave of the same master as that of the
2527  * 	 source mount.
2528  *
2529  * ---------------------------------------------------------------------------
2530  * |         		MOVE MOUNT OPERATION                                 |
2531  * |**************************************************************************
2532  * | source-->| shared        |       private  |       slave    | unbindable |
2533  * | dest     |               |                |                |            |
2534  * |   |      |               |                |                |            |
2535  * |   v      |               |                |                |            |
2536  * |**************************************************************************
2537  * |  shared  | shared (+)    |     shared (+) |    shared(+++) |  invalid   |
2538  * |          |               |                |                |            |
2539  * |non-shared| shared (+*)   |      private   |    slave (*)   | unbindable |
2540  * ***************************************************************************
2541  *
2542  * (+)  the mount is moved to the destination. And is then propagated to
2543  * 	all the mounts in the propagation tree of the destination mount.
2544  * (+*)  the mount is moved to the destination.
2545  * (+++)  the mount is moved to the destination and is then propagated to
2546  * 	all the mounts belonging to the destination mount's propagation tree.
2547  * 	the mount is marked as 'shared and slave'.
2548  * (*)	the mount continues to be a slave at the new location.
2549  *
2550  * if the source mount is a tree, the operations explained above is
2551  * applied to each mount in the tree.
2552  * Must be called without spinlocks held, since this function can sleep
2553  * in allocations.
2554  *
2555  * Context: The function expects namespace_lock() to be held.
2556  * Return: If @source_mnt was successfully attached 0 is returned.
2557  *         Otherwise a negative error code is returned.
2558  */
attach_recursive_mnt(struct mount * source_mnt,const struct pinned_mountpoint * dest)2559 static int attach_recursive_mnt(struct mount *source_mnt,
2560 				const struct pinned_mountpoint *dest)
2561 {
2562 	struct user_namespace *user_ns = current->nsproxy->mnt_ns->user_ns;
2563 	struct mount *dest_mnt = dest->parent;
2564 	struct mountpoint *dest_mp = dest->mp;
2565 	HLIST_HEAD(tree_list);
2566 	struct mnt_namespace *ns = dest_mnt->mnt_ns;
2567 	struct pinned_mountpoint root = {};
2568 	struct mountpoint *shorter = NULL;
2569 	struct mount *child, *p;
2570 	struct mount *top;
2571 	struct hlist_node *n;
2572 	int err = 0;
2573 	bool moving = mnt_has_parent(source_mnt);
2574 
2575 	/*
2576 	 * Preallocate a mountpoint in case the new mounts need to be
2577 	 * mounted beneath mounts on the same mountpoint.
2578 	 */
2579 	for (top = source_mnt; unlikely(top->overmount); top = top->overmount) {
2580 		if (!shorter && is_mnt_ns_file(top->mnt.mnt_root))
2581 			shorter = top->mnt_mp;
2582 	}
2583 	err = get_mountpoint(top->mnt.mnt_root, &root);
2584 	if (err)
2585 		return err;
2586 
2587 	/* Is there space to add these mounts to the mount namespace? */
2588 	if (!moving) {
2589 		err = count_mounts(ns, source_mnt);
2590 		if (err)
2591 			goto out;
2592 	}
2593 
2594 	if (IS_MNT_SHARED(dest_mnt)) {
2595 		err = invent_group_ids(source_mnt, true);
2596 		if (err)
2597 			goto out;
2598 		err = propagate_mnt(dest_mnt, dest_mp, source_mnt, &tree_list);
2599 	}
2600 	lock_mount_hash();
2601 	if (err)
2602 		goto out_cleanup_ids;
2603 
2604 	if (IS_MNT_SHARED(dest_mnt)) {
2605 		for (p = source_mnt; p; p = next_mnt(p, source_mnt))
2606 			set_mnt_shared(p);
2607 	}
2608 
2609 	if (moving) {
2610 		umount_mnt(source_mnt);
2611 		mnt_notify_add(source_mnt);
2612 		/* if the mount is moved, it should no longer be expired
2613 		 * automatically */
2614 		list_del_init(&source_mnt->mnt_expire);
2615 	} else {
2616 		if (source_mnt->mnt_ns) {
2617 			/* move from anon - the caller will destroy */
2618 			emptied_ns = source_mnt->mnt_ns;
2619 			for (p = source_mnt; p; p = next_mnt(p, source_mnt))
2620 				move_from_ns(p);
2621 		}
2622 	}
2623 
2624 	mnt_set_mountpoint(dest_mnt, dest_mp, source_mnt);
2625 	/*
2626 	 * Now the original copy is in the same state as the secondaries -
2627 	 * its root attached to mountpoint, but not hashed and all mounts
2628 	 * in it are either in our namespace or in no namespace at all.
2629 	 * Add the original to the list of copies and deal with the
2630 	 * rest of work for all of them uniformly.
2631 	 */
2632 	hlist_add_head(&source_mnt->mnt_hash, &tree_list);
2633 
2634 	hlist_for_each_entry_safe(child, n, &tree_list, mnt_hash) {
2635 		struct mount *q;
2636 		hlist_del_init(&child->mnt_hash);
2637 		/* Notice when we are propagating across user namespaces */
2638 		if (child->mnt_parent->mnt_ns->user_ns != user_ns)
2639 			lock_mnt_tree(child);
2640 		q = __lookup_mnt(&child->mnt_parent->mnt,
2641 				 child->mnt_mountpoint);
2642 		commit_tree(child);
2643 		if (q) {
2644 			struct mount *r = topmost_overmount(child);
2645 			struct mountpoint *mp = root.mp;
2646 
2647 			if (unlikely(shorter) && child != source_mnt)
2648 				mp = shorter;
2649 			/*
2650 			 * If @q was locked it was meant to hide
2651 			 * whatever was under it. Let @child take over
2652 			 * that job and lock it, then we can unlock @q.
2653 			 * That'll allow another namespace to shed @q
2654 			 * and reveal @child. Clearly, that mounter
2655 			 * consented to this by not severing the mount
2656 			 * relationship. Otherwise, what's the point.
2657 			 */
2658 			if (IS_MNT_LOCKED(q)) {
2659 				child->mnt.mnt_flags |= MNT_LOCKED;
2660 				q->mnt.mnt_flags &= ~MNT_LOCKED;
2661 			}
2662 			mnt_change_mountpoint(r, mp, q);
2663 		}
2664 	}
2665 	unpin_mountpoint(&root);
2666 	unlock_mount_hash();
2667 
2668 	return 0;
2669 
2670  out_cleanup_ids:
2671 	while (!hlist_empty(&tree_list)) {
2672 		child = hlist_entry(tree_list.first, struct mount, mnt_hash);
2673 		child->mnt_parent->mnt_ns->pending_mounts = 0;
2674 		umount_tree(child, UMOUNT_SYNC);
2675 	}
2676 	unlock_mount_hash();
2677 	cleanup_group_ids(source_mnt, NULL);
2678  out:
2679 	ns->pending_mounts = 0;
2680 
2681 	read_seqlock_excl(&mount_lock);
2682 	unpin_mountpoint(&root);
2683 	read_sequnlock_excl(&mount_lock);
2684 
2685 	return err;
2686 }
2687 
where_to_mount(const struct path * path,struct dentry ** dentry,bool beneath)2688 static inline struct mount *where_to_mount(const struct path *path,
2689 					   struct dentry **dentry,
2690 					   bool beneath)
2691 {
2692 	struct mount *m;
2693 
2694 	if (unlikely(beneath)) {
2695 		m = topmost_overmount(real_mount(path->mnt));
2696 		*dentry = m->mnt_mountpoint;
2697 		return m->mnt_parent;
2698 	}
2699 	m = __lookup_mnt(path->mnt, path->dentry);
2700 	if (unlikely(m)) {
2701 		m = topmost_overmount(m);
2702 		*dentry = m->mnt.mnt_root;
2703 		return m;
2704 	}
2705 	*dentry = path->dentry;
2706 	return real_mount(path->mnt);
2707 }
2708 
2709 /**
2710  * do_lock_mount - acquire environment for mounting
2711  * @path:	target path
2712  * @res:	context to set up
2713  * @beneath:	whether the intention is to mount beneath @path
2714  *
2715  * To mount something at given location, we need
2716  *	namespace_sem locked exclusive
2717  *	inode of dentry we are mounting on locked exclusive
2718  *	struct mountpoint for that dentry
2719  *	struct mount we are mounting on
2720  *
2721  * Results are stored in caller-supplied context (pinned_mountpoint);
2722  * on success we have res->parent and res->mp pointing to parent and
2723  * mountpoint respectively and res->node inserted into the ->m_list
2724  * of the mountpoint, making sure the mountpoint won't disappear.
2725  * On failure we have res->parent set to ERR_PTR(-E...), res->mp
2726  * left NULL, res->node - empty.
2727  * In case of success do_lock_mount returns with locks acquired (in
2728  * proper order - inode lock nests outside of namespace_sem).
2729  *
2730  * Request to mount on overmounted location is treated as "mount on
2731  * top of whatever's overmounting it"; request to mount beneath
2732  * a location - "mount immediately beneath the topmost mount at that
2733  * place".
2734  *
2735  * In all cases the location must not have been unmounted and the
2736  * chosen mountpoint must be allowed to be mounted on.  For "beneath"
2737  * case we also require the location to be at the root of a mount
2738  * that has something mounted on top of it (i.e. has an overmount).
2739  */
do_lock_mount(const struct path * path,struct pinned_mountpoint * res,bool beneath)2740 static void do_lock_mount(const struct path *path,
2741 			  struct pinned_mountpoint *res,
2742 			  bool beneath)
2743 {
2744 	int err;
2745 
2746 	if (unlikely(beneath) && !path_mounted(path)) {
2747 		res->parent = ERR_PTR(-EINVAL);
2748 		return;
2749 	}
2750 
2751 	do {
2752 		struct dentry *dentry, *d;
2753 		struct mount *m, *n;
2754 
2755 		scoped_guard(mount_locked_reader) {
2756 			m = where_to_mount(path, &dentry, beneath);
2757 			if (&m->mnt != path->mnt) {
2758 				mntget(&m->mnt);
2759 				dget(dentry);
2760 			}
2761 		}
2762 
2763 		inode_lock(dentry->d_inode);
2764 		namespace_lock();
2765 
2766 		// check if the chain of mounts (if any) has changed.
2767 		scoped_guard(mount_locked_reader)
2768 			n = where_to_mount(path, &d, beneath);
2769 
2770 		if (unlikely(n != m || dentry != d))
2771 			err = -EAGAIN;		// something moved, retry
2772 		else if (unlikely(cant_mount(dentry) || !is_mounted(path->mnt)))
2773 			err = -ENOENT;		// not to be mounted on
2774 		else if (beneath && &m->mnt == path->mnt && !m->overmount)
2775 			err = -EINVAL;
2776 		else
2777 			err = get_mountpoint(dentry, res);
2778 
2779 		if (unlikely(err)) {
2780 			res->parent = ERR_PTR(err);
2781 			namespace_unlock();
2782 			inode_unlock(dentry->d_inode);
2783 		} else {
2784 			res->parent = m;
2785 		}
2786 		/*
2787 		 * Drop the temporary references.  This is subtle - on success
2788 		 * we are doing that under namespace_sem, which would normally
2789 		 * be forbidden.  However, in that case we are guaranteed that
2790 		 * refcounts won't reach zero, since we know that path->mnt
2791 		 * is mounted and thus all mounts reachable from it are pinned
2792 		 * and stable, along with their mountpoints and roots.
2793 		 */
2794 		if (&m->mnt != path->mnt) {
2795 			dput(dentry);
2796 			mntput(&m->mnt);
2797 		}
2798 	} while (err == -EAGAIN);
2799 }
2800 
__unlock_mount(struct pinned_mountpoint * m)2801 static void __unlock_mount(struct pinned_mountpoint *m)
2802 {
2803 	inode_unlock(m->mp->m_dentry->d_inode);
2804 	read_seqlock_excl(&mount_lock);
2805 	unpin_mountpoint(m);
2806 	read_sequnlock_excl(&mount_lock);
2807 	namespace_unlock();
2808 }
2809 
unlock_mount(struct pinned_mountpoint * m)2810 static inline void unlock_mount(struct pinned_mountpoint *m)
2811 {
2812 	if (!IS_ERR(m->parent))
2813 		__unlock_mount(m);
2814 }
2815 
2816 static void lock_mount_exact(const struct path *path,
2817 			     struct pinned_mountpoint *mp, bool copy_mount,
2818 			     unsigned int copy_flags);
2819 
2820 #define LOCK_MOUNT_MAYBE_BENEATH(mp, path, beneath) \
2821 	struct pinned_mountpoint mp __cleanup(unlock_mount) = {}; \
2822 	do_lock_mount((path), &mp, (beneath))
2823 #define LOCK_MOUNT(mp, path) LOCK_MOUNT_MAYBE_BENEATH(mp, (path), false)
2824 #define LOCK_MOUNT_EXACT(mp, path) \
2825 	struct pinned_mountpoint mp __cleanup(unlock_mount) = {}; \
2826 	lock_mount_exact((path), &mp, false, 0)
2827 #define LOCK_MOUNT_EXACT_COPY(mp, path, copy_flags) \
2828 	struct pinned_mountpoint mp __cleanup(unlock_mount) = {}; \
2829 	lock_mount_exact((path), &mp, true, (copy_flags))
2830 
graft_tree(struct mount * mnt,const struct pinned_mountpoint * mp)2831 static int graft_tree(struct mount *mnt, const struct pinned_mountpoint *mp)
2832 {
2833 	if (mnt->mnt.mnt_sb->s_flags & SB_NOUSER)
2834 		return -EINVAL;
2835 
2836 	if (d_is_dir(mp->mp->m_dentry) !=
2837 	      d_is_dir(mnt->mnt.mnt_root))
2838 		return -ENOTDIR;
2839 
2840 	return attach_recursive_mnt(mnt, mp);
2841 }
2842 
may_change_propagation(const struct mount * m)2843 static int may_change_propagation(const struct mount *m)
2844 {
2845         struct mnt_namespace *ns = m->mnt_ns;
2846 
2847 	 // it must be mounted in some namespace
2848 	 if (IS_ERR_OR_NULL(ns))         // is_mounted()
2849 		 return -EINVAL;
2850 	 // and the caller must be admin in userns of that namespace
2851 	 if (!ns_capable(ns->user_ns, CAP_SYS_ADMIN))
2852 		 return -EPERM;
2853 	 return 0;
2854 }
2855 
2856 /*
2857  * Sanity check the flags to change_mnt_propagation.
2858  */
2859 
flags_to_propagation_type(int ms_flags)2860 static int flags_to_propagation_type(int ms_flags)
2861 {
2862 	int type = ms_flags & ~(MS_REC | MS_SILENT);
2863 
2864 	/* Fail if any non-propagation flags are set */
2865 	if (type & ~(MS_SHARED | MS_PRIVATE | MS_SLAVE | MS_UNBINDABLE))
2866 		return 0;
2867 	/* Only one propagation flag should be set */
2868 	if (!is_power_of_2(type))
2869 		return 0;
2870 	return type;
2871 }
2872 
2873 /*
2874  * recursively change the type of the mountpoint.
2875  */
do_change_type(const struct path * path,int ms_flags)2876 static int do_change_type(const struct path *path, int ms_flags)
2877 {
2878 	struct mount *m;
2879 	struct mount *mnt = real_mount(path->mnt);
2880 	int recurse = ms_flags & MS_REC;
2881 	int type;
2882 	int err;
2883 
2884 	if (!path_mounted(path))
2885 		return -EINVAL;
2886 
2887 	type = flags_to_propagation_type(ms_flags);
2888 	if (!type)
2889 		return -EINVAL;
2890 
2891 	guard(namespace_excl)();
2892 
2893 	err = may_change_propagation(mnt);
2894 	if (err)
2895 		return err;
2896 
2897 	if (type == MS_SHARED) {
2898 		err = invent_group_ids(mnt, recurse);
2899 		if (err)
2900 			return err;
2901 	}
2902 
2903 	for (m = mnt; m; m = (recurse ? next_mnt(m, mnt) : NULL))
2904 		change_mnt_propagation(m, type);
2905 
2906 	return 0;
2907 }
2908 
2909 /* may_copy_tree() - check if a mount tree can be copied
2910  * @path: path to the mount tree to be copied
2911  *
2912  * This helper checks if the caller may copy the mount tree starting
2913  * from @path->mnt. The caller may copy the mount tree under the
2914  * following circumstances:
2915  *
2916  * (1) The caller is located in the mount namespace of the mount tree.
2917  *     This also implies that the mount does not belong to an anonymous
2918  *     mount namespace.
2919  * (2) The caller tries to copy an nfs mount referring to a mount
2920  *     namespace, i.e., the caller is trying to copy a mount namespace
2921  *     entry from nsfs.
2922  * (3) The caller tries to copy a pidfs mount referring to a pidfd.
2923  * (4) The caller is trying to copy a mount tree that belongs to an
2924  *     anonymous mount namespace.
2925  *
2926  *     For that to be safe, this helper enforces that the origin mount
2927  *     namespace the anonymous mount namespace was created from is the
2928  *     same as the caller's mount namespace by comparing the sequence
2929  *     numbers.
2930  *
2931  *     This is not strictly necessary. The current semantics of the new
2932  *     mount api enforce that the caller must be located in the same
2933  *     mount namespace as the mount tree it interacts with. Using the
2934  *     origin sequence number preserves these semantics even for
2935  *     anonymous mount namespaces. However, one could envision extending
2936  *     the api to directly operate across mount namespace if needed.
2937  *
2938  *     The ownership of a non-anonymous mount namespace such as the
2939  *     caller's cannot change.
2940  *     => We know that the caller's mount namespace is stable.
2941  *
2942  *     If the origin sequence number of the anonymous mount namespace is
2943  *     the same as the sequence number of the caller's mount namespace.
2944  *     => The owning namespaces are the same.
2945  *
2946  *     ==> The earlier capability check on the owning namespace of the
2947  *         caller's mount namespace ensures that the caller has the
2948  *         ability to copy the mount tree.
2949  *
2950  * Returns true if the mount tree can be copied, false otherwise.
2951  */
may_copy_tree(const struct path * path)2952 static inline bool may_copy_tree(const struct path *path)
2953 {
2954 	struct mount *mnt = real_mount(path->mnt);
2955 	const struct dentry_operations *d_op;
2956 
2957 	if (check_mnt(mnt))
2958 		return true;
2959 
2960 	d_op = path->dentry->d_op;
2961 	if (d_op == &ns_dentry_operations)
2962 		return true;
2963 
2964 	if (d_op == &pidfs_dentry_operations)
2965 		return true;
2966 
2967 	if (!is_mounted(path->mnt))
2968 		return false;
2969 
2970 	return check_anonymous_mnt(mnt);
2971 }
2972 
__do_loopback(const struct path * old_path,bool recurse,unsigned int copy_flags)2973 static struct mount *__do_loopback(const struct path *old_path,
2974 				   bool recurse, unsigned int copy_flags)
2975 {
2976 	struct mount *old = real_mount(old_path->mnt);
2977 
2978 	if (IS_MNT_UNBINDABLE(old))
2979 		return ERR_PTR(-EINVAL);
2980 
2981 	if (!may_copy_tree(old_path))
2982 		return ERR_PTR(-EINVAL);
2983 
2984 	if (!recurse && __has_locked_children(old, old_path->dentry))
2985 		return ERR_PTR(-EINVAL);
2986 
2987 	if (recurse)
2988 		return copy_tree(old, old_path->dentry, copy_flags);
2989 
2990 	return clone_mnt(old, old_path->dentry, copy_flags);
2991 }
2992 
2993 /*
2994  * do loopback mount.
2995  */
do_loopback(const struct path * path,const char * old_name,int recurse)2996 static int do_loopback(const struct path *path, const char *old_name,
2997 		       int recurse)
2998 {
2999 	struct path old_path __free(path_put) = {};
3000 	struct mount *mnt = NULL;
3001 	int err;
3002 
3003 	if (!old_name || !*old_name)
3004 		return -EINVAL;
3005 	err = kern_path(old_name, LOOKUP_FOLLOW|LOOKUP_AUTOMOUNT, &old_path);
3006 	if (err)
3007 		return err;
3008 
3009 	if (mnt_ns_loop(old_path.dentry))
3010 		return -EINVAL;
3011 
3012 	LOCK_MOUNT(mp, path);
3013 	if (IS_ERR(mp.parent))
3014 		return PTR_ERR(mp.parent);
3015 
3016 	if (!check_mnt(mp.parent))
3017 		return -EINVAL;
3018 
3019 	mnt = __do_loopback(&old_path, recurse, CL_COPY_MNT_NS_FILE);
3020 	if (IS_ERR(mnt))
3021 		return PTR_ERR(mnt);
3022 
3023 	err = graft_tree(mnt, &mp);
3024 	if (err) {
3025 		lock_mount_hash();
3026 		umount_tree(mnt, UMOUNT_SYNC);
3027 		unlock_mount_hash();
3028 	}
3029 	return err;
3030 }
3031 
get_detached_copy(const struct path * path,unsigned int flags)3032 static struct mnt_namespace *get_detached_copy(const struct path *path, unsigned int flags)
3033 {
3034 	struct mnt_namespace *ns, *mnt_ns = current->nsproxy->mnt_ns, *src_mnt_ns;
3035 	struct user_namespace *user_ns = mnt_ns->user_ns;
3036 	struct mount *mnt, *p;
3037 
3038 	ns = alloc_mnt_ns(user_ns, true);
3039 	if (IS_ERR(ns))
3040 		return ns;
3041 
3042 	guard(namespace_excl)();
3043 
3044 	/*
3045 	 * Record the sequence number of the source mount namespace.
3046 	 * This needs to hold namespace_sem to ensure that the mount
3047 	 * doesn't get attached.
3048 	 */
3049 	if (is_mounted(path->mnt)) {
3050 		src_mnt_ns = real_mount(path->mnt)->mnt_ns;
3051 		if (is_anon_ns(src_mnt_ns))
3052 			ns->seq_origin = src_mnt_ns->seq_origin;
3053 		else
3054 			ns->seq_origin = src_mnt_ns->ns.ns_id;
3055 	}
3056 
3057 	mnt = __do_loopback(path, (flags & AT_RECURSIVE), CL_COPY_MNT_NS_FILE);
3058 	if (IS_ERR(mnt)) {
3059 		emptied_ns = ns;
3060 		return ERR_CAST(mnt);
3061 	}
3062 
3063 	for (p = mnt; p; p = next_mnt(p, mnt)) {
3064 		mnt_add_to_ns(ns, p);
3065 		ns->nr_mounts++;
3066 	}
3067 	ns->root = mnt;
3068 	return ns;
3069 }
3070 
open_detached_copy(struct path * path,unsigned int flags)3071 static struct file *open_detached_copy(struct path *path, unsigned int flags)
3072 {
3073 	struct mnt_namespace *ns = get_detached_copy(path, flags);
3074 	struct file *file;
3075 
3076 	if (IS_ERR(ns))
3077 		return ERR_CAST(ns);
3078 
3079 	mntput(path->mnt);
3080 	path->mnt = mntget(&ns->root->mnt);
3081 	file = dentry_open(path, O_PATH, current_cred());
3082 	if (IS_ERR(file))
3083 		dissolve_on_fput(path->mnt);
3084 	else
3085 		file->f_mode |= FMODE_NEED_UNMOUNT;
3086 	return file;
3087 }
3088 
3089 enum mount_copy_flags_t {
3090 	MOUNT_COPY_RECURSIVE    = (1 << 0),
3091 	MOUNT_COPY_NEW		= (1 << 1),
3092 };
3093 
create_new_namespace(struct path * path,enum mount_copy_flags_t flags)3094 static struct mnt_namespace *create_new_namespace(struct path *path,
3095 						  enum mount_copy_flags_t flags)
3096 {
3097 	struct mnt_namespace *ns = current->nsproxy->mnt_ns;
3098 	struct user_namespace *user_ns = current_user_ns();
3099 	struct mnt_namespace *new_ns;
3100 	struct mount *new_ns_root, *old_ns_root;
3101 	struct path to_path;
3102 	struct mount *mnt;
3103 	unsigned int copy_flags = 0;
3104 	bool locked = false, recurse = flags & MOUNT_COPY_RECURSIVE;
3105 
3106 	if (user_ns != ns->user_ns)
3107 		copy_flags |= CL_SLAVE;
3108 
3109 	new_ns = alloc_mnt_ns(user_ns, false);
3110 	if (IS_ERR(new_ns))
3111 		return ERR_CAST(new_ns);
3112 
3113 	old_ns_root = ns->root;
3114 	to_path.mnt = &old_ns_root->mnt;
3115 	to_path.dentry = old_ns_root->mnt.mnt_root;
3116 
3117 	VFS_WARN_ON_ONCE(old_ns_root->mnt.mnt_sb->s_type != &nullfs_fs_type);
3118 
3119 	LOCK_MOUNT_EXACT_COPY(mp, &to_path, copy_flags);
3120 	if (IS_ERR(mp.parent)) {
3121 		free_mnt_ns(new_ns);
3122 		return ERR_CAST(mp.parent);
3123 	}
3124 	new_ns_root = mp.parent;
3125 
3126 	/*
3127 	 * If the real rootfs had a locked mount on top of it somewhere
3128 	 * in the stack, lock the new mount tree as well so it can't be
3129 	 * exposed.
3130 	 */
3131 	mnt = old_ns_root;
3132 	while (mnt->overmount) {
3133 		mnt = mnt->overmount;
3134 		if (mnt->mnt.mnt_flags & MNT_LOCKED)
3135 			locked = true;
3136 	}
3137 
3138 	/*
3139 	 * We don't emulate unshare()ing a mount namespace. We stick to
3140 	 * the restrictions of creating detached bind-mounts. It has a
3141 	 * lot saner and simpler semantics.
3142 	 */
3143 	if (flags & MOUNT_COPY_NEW)
3144 		mnt = clone_mnt(real_mount(path->mnt), path->dentry, copy_flags);
3145 	else
3146 		mnt = __do_loopback(path, recurse, copy_flags);
3147 	scoped_guard(mount_writer) {
3148 		if (IS_ERR(mnt)) {
3149 			emptied_ns = new_ns;
3150 			umount_tree(new_ns_root, 0);
3151 			return ERR_CAST(mnt);
3152 		}
3153 
3154 		if (locked)
3155 			mnt->mnt.mnt_flags |= MNT_LOCKED;
3156 		/*
3157 		 * now mount the detached tree on top of the copy
3158 		 * of the real rootfs we created.
3159 		 */
3160 		attach_mnt(mnt, new_ns_root, mp.mp);
3161 		if (user_ns != ns->user_ns)
3162 			lock_mnt_tree(new_ns_root);
3163 	}
3164 
3165 	for (mnt = new_ns_root; mnt; mnt = next_mnt(mnt, new_ns_root)) {
3166 		mnt_add_to_ns(new_ns, mnt);
3167 		new_ns->nr_mounts++;
3168 	}
3169 
3170 	new_ns->root = new_ns_root;
3171 	ns_tree_add_raw(new_ns);
3172 	return new_ns;
3173 }
3174 
open_new_namespace(struct path * path,enum mount_copy_flags_t flags)3175 static struct file *open_new_namespace(struct path *path,
3176 				       enum mount_copy_flags_t flags)
3177 {
3178 	struct mnt_namespace *new_ns;
3179 
3180 	new_ns = create_new_namespace(path, flags);
3181 	if (IS_ERR(new_ns))
3182 		return ERR_CAST(new_ns);
3183 	return open_namespace_file(to_ns_common(new_ns));
3184 }
3185 
vfs_open_tree(int dfd,const char __user * filename,unsigned int flags)3186 static struct file *vfs_open_tree(int dfd, const char __user *filename, unsigned int flags)
3187 {
3188 	int ret;
3189 	struct path path __free(path_put) = {};
3190 	int lookup_flags = LOOKUP_AUTOMOUNT | LOOKUP_FOLLOW;
3191 
3192 	BUILD_BUG_ON(OPEN_TREE_CLOEXEC != O_CLOEXEC);
3193 
3194 	if (flags & ~(AT_EMPTY_PATH | AT_NO_AUTOMOUNT | AT_RECURSIVE |
3195 		      AT_SYMLINK_NOFOLLOW | OPEN_TREE_CLONE |
3196 		      OPEN_TREE_CLOEXEC | OPEN_TREE_NAMESPACE))
3197 		return ERR_PTR(-EINVAL);
3198 
3199 	if ((flags & (AT_RECURSIVE | OPEN_TREE_CLONE | OPEN_TREE_NAMESPACE)) ==
3200 	    AT_RECURSIVE)
3201 		return ERR_PTR(-EINVAL);
3202 
3203 	if (hweight32(flags & (OPEN_TREE_CLONE | OPEN_TREE_NAMESPACE)) > 1)
3204 		return ERR_PTR(-EINVAL);
3205 
3206 	if (flags & AT_NO_AUTOMOUNT)
3207 		lookup_flags &= ~LOOKUP_AUTOMOUNT;
3208 	if (flags & AT_SYMLINK_NOFOLLOW)
3209 		lookup_flags &= ~LOOKUP_FOLLOW;
3210 
3211 	/*
3212 	 * If we create a new mount namespace with the cloned mount tree we
3213 	 * just care about being privileged over our current user namespace.
3214 	 * The new mount namespace will be owned by it.
3215 	 */
3216 	if ((flags & OPEN_TREE_NAMESPACE) &&
3217 	    !ns_capable(current_user_ns(), CAP_SYS_ADMIN))
3218 		return ERR_PTR(-EPERM);
3219 
3220 	if ((flags & OPEN_TREE_CLONE) && !may_mount())
3221 		return ERR_PTR(-EPERM);
3222 
3223 	CLASS(filename_uflags, name)(filename, flags);
3224 	ret = filename_lookup(dfd, name, lookup_flags, &path, NULL);
3225 	if (unlikely(ret))
3226 		return ERR_PTR(ret);
3227 
3228 	if (flags & OPEN_TREE_NAMESPACE)
3229 		return open_new_namespace(&path, (flags & AT_RECURSIVE) ? MOUNT_COPY_RECURSIVE : 0);
3230 
3231 	if (flags & OPEN_TREE_CLONE)
3232 		return open_detached_copy(&path, flags);
3233 
3234 	return dentry_open(&path, O_PATH, current_cred());
3235 }
3236 
SYSCALL_DEFINE3(open_tree,int,dfd,const char __user *,filename,unsigned,flags)3237 SYSCALL_DEFINE3(open_tree, int, dfd, const char __user *, filename, unsigned, flags)
3238 {
3239 	return FD_ADD(flags, vfs_open_tree(dfd, filename, flags));
3240 }
3241 
3242 /*
3243  * Don't allow locked mount flags to be cleared.
3244  *
3245  * No locks need to be held here while testing the various MNT_LOCK
3246  * flags because those flags can never be cleared once they are set.
3247  */
can_change_locked_flags(struct mount * mnt,unsigned int mnt_flags)3248 static bool can_change_locked_flags(struct mount *mnt, unsigned int mnt_flags)
3249 {
3250 	unsigned int fl = mnt->mnt.mnt_flags;
3251 
3252 	if ((fl & MNT_LOCK_READONLY) &&
3253 	    !(mnt_flags & MNT_READONLY))
3254 		return false;
3255 
3256 	if ((fl & MNT_LOCK_NODEV) &&
3257 	    !(mnt_flags & MNT_NODEV))
3258 		return false;
3259 
3260 	if ((fl & MNT_LOCK_NOSUID) &&
3261 	    !(mnt_flags & MNT_NOSUID))
3262 		return false;
3263 
3264 	if ((fl & MNT_LOCK_NOEXEC) &&
3265 	    !(mnt_flags & MNT_NOEXEC))
3266 		return false;
3267 
3268 	if ((fl & MNT_LOCK_ATIME) &&
3269 	    ((fl & MNT_ATIME_MASK) != (mnt_flags & MNT_ATIME_MASK)))
3270 		return false;
3271 
3272 	return true;
3273 }
3274 
change_mount_ro_state(struct mount * mnt,unsigned int mnt_flags)3275 static int change_mount_ro_state(struct mount *mnt, unsigned int mnt_flags)
3276 {
3277 	bool readonly_request = (mnt_flags & MNT_READONLY);
3278 
3279 	if (readonly_request == __mnt_is_readonly(&mnt->mnt))
3280 		return 0;
3281 
3282 	if (readonly_request)
3283 		return mnt_make_readonly(mnt);
3284 
3285 	mnt->mnt.mnt_flags &= ~MNT_READONLY;
3286 	return 0;
3287 }
3288 
set_mount_attributes(struct mount * mnt,unsigned int mnt_flags)3289 static void set_mount_attributes(struct mount *mnt, unsigned int mnt_flags)
3290 {
3291 	mnt_flags |= mnt->mnt.mnt_flags & ~MNT_USER_SETTABLE_MASK;
3292 	mnt->mnt.mnt_flags = mnt_flags;
3293 	touch_mnt_namespace(mnt->mnt_ns);
3294 }
3295 
mnt_warn_timestamp_expiry(const struct path * mountpoint,struct vfsmount * mnt)3296 static void mnt_warn_timestamp_expiry(const struct path *mountpoint,
3297 				      struct vfsmount *mnt)
3298 {
3299 	struct super_block *sb = mnt->mnt_sb;
3300 
3301 	if (!__mnt_is_readonly(mnt) &&
3302 	   (!(sb->s_iflags & SB_I_TS_EXPIRY_WARNED)) &&
3303 	   (ktime_get_real_seconds() + TIME_UPTIME_SEC_MAX > sb->s_time_max)) {
3304 		char *buf, *mntpath;
3305 
3306 		buf = (char *)__get_free_page(GFP_KERNEL);
3307 		if (buf)
3308 			mntpath = d_path(mountpoint, buf, PAGE_SIZE);
3309 		else
3310 			mntpath = ERR_PTR(-ENOMEM);
3311 		if (IS_ERR(mntpath))
3312 			mntpath = "(unknown)";
3313 
3314 		pr_warn("%s filesystem being %s at %s supports timestamps until %ptTd (0x%llx)\n",
3315 			sb->s_type->name,
3316 			is_mounted(mnt) ? "remounted" : "mounted",
3317 			mntpath, &sb->s_time_max,
3318 			(unsigned long long)sb->s_time_max);
3319 
3320 		sb->s_iflags |= SB_I_TS_EXPIRY_WARNED;
3321 		if (buf)
3322 			free_page((unsigned long)buf);
3323 	}
3324 }
3325 
3326 /*
3327  * Handle reconfiguration of the mountpoint only without alteration of the
3328  * superblock it refers to.  This is triggered by specifying MS_REMOUNT|MS_BIND
3329  * to mount(2).
3330  */
do_reconfigure_mnt(const struct path * path,unsigned int mnt_flags)3331 static int do_reconfigure_mnt(const struct path *path, unsigned int mnt_flags)
3332 {
3333 	struct super_block *sb = path->mnt->mnt_sb;
3334 	struct mount *mnt = real_mount(path->mnt);
3335 	int ret;
3336 
3337 	if (!check_mnt(mnt))
3338 		return -EINVAL;
3339 
3340 	if (!path_mounted(path))
3341 		return -EINVAL;
3342 
3343 	if (!can_change_locked_flags(mnt, mnt_flags))
3344 		return -EPERM;
3345 
3346 	/*
3347 	 * We're only checking whether the superblock is read-only not
3348 	 * changing it, so only take down_read(&sb->s_umount).
3349 	 */
3350 	down_read(&sb->s_umount);
3351 	lock_mount_hash();
3352 	ret = change_mount_ro_state(mnt, mnt_flags);
3353 	if (ret == 0)
3354 		set_mount_attributes(mnt, mnt_flags);
3355 	unlock_mount_hash();
3356 	up_read(&sb->s_umount);
3357 
3358 	mnt_warn_timestamp_expiry(path, &mnt->mnt);
3359 
3360 	return ret;
3361 }
3362 
3363 /*
3364  * change filesystem flags. dir should be a physical root of filesystem.
3365  * If you've mounted a non-root directory somewhere and want to do remount
3366  * on it - tough luck.
3367  */
do_remount(const struct path * path,int sb_flags,int mnt_flags,void * data)3368 static int do_remount(const struct path *path, int sb_flags,
3369 		      int mnt_flags, void *data)
3370 {
3371 	int err;
3372 	struct super_block *sb = path->mnt->mnt_sb;
3373 	struct mount *mnt = real_mount(path->mnt);
3374 	struct fs_context *fc;
3375 
3376 	if (!check_mnt(mnt))
3377 		return -EINVAL;
3378 
3379 	if (!path_mounted(path))
3380 		return -EINVAL;
3381 
3382 	if (!can_change_locked_flags(mnt, mnt_flags))
3383 		return -EPERM;
3384 
3385 	fc = fs_context_for_reconfigure(path->dentry, sb_flags, MS_RMT_MASK);
3386 	if (IS_ERR(fc))
3387 		return PTR_ERR(fc);
3388 
3389 	/*
3390 	 * Indicate to the filesystem that the remount request is coming
3391 	 * from the legacy mount system call.
3392 	 */
3393 	fc->oldapi = true;
3394 
3395 	err = parse_monolithic_mount_data(fc, data);
3396 	if (!err) {
3397 		down_write(&sb->s_umount);
3398 		err = -EPERM;
3399 		if (ns_capable(sb->s_user_ns, CAP_SYS_ADMIN)) {
3400 			err = reconfigure_super(fc);
3401 			if (!err) {
3402 				lock_mount_hash();
3403 				set_mount_attributes(mnt, mnt_flags);
3404 				unlock_mount_hash();
3405 			}
3406 		}
3407 		up_write(&sb->s_umount);
3408 	}
3409 
3410 	mnt_warn_timestamp_expiry(path, &mnt->mnt);
3411 
3412 	put_fs_context(fc);
3413 	return err;
3414 }
3415 
tree_contains_unbindable(struct mount * mnt)3416 static inline int tree_contains_unbindable(struct mount *mnt)
3417 {
3418 	struct mount *p;
3419 	for (p = mnt; p; p = next_mnt(p, mnt)) {
3420 		if (IS_MNT_UNBINDABLE(p))
3421 			return 1;
3422 	}
3423 	return 0;
3424 }
3425 
do_set_group(const struct path * from_path,const struct path * to_path)3426 static int do_set_group(const struct path *from_path, const struct path *to_path)
3427 {
3428 	struct mount *from = real_mount(from_path->mnt);
3429 	struct mount *to = real_mount(to_path->mnt);
3430 	int err;
3431 
3432 	guard(namespace_excl)();
3433 
3434 	err = may_change_propagation(from);
3435 	if (err)
3436 		return err;
3437 	err = may_change_propagation(to);
3438 	if (err)
3439 		return err;
3440 
3441 	/* To and From paths should be mount roots */
3442 	if (!path_mounted(from_path))
3443 		return -EINVAL;
3444 	if (!path_mounted(to_path))
3445 		return -EINVAL;
3446 
3447 	/* Setting sharing groups is only allowed across same superblock */
3448 	if (from->mnt.mnt_sb != to->mnt.mnt_sb)
3449 		return -EINVAL;
3450 
3451 	/* From mount root should be wider than To mount root */
3452 	if (!is_subdir(to->mnt.mnt_root, from->mnt.mnt_root))
3453 		return -EINVAL;
3454 
3455 	/* From mount should not have locked children in place of To's root */
3456 	if (__has_locked_children(from, to->mnt.mnt_root))
3457 		return -EINVAL;
3458 
3459 	/* Setting sharing groups is only allowed on private mounts */
3460 	if (IS_MNT_SHARED(to) || IS_MNT_SLAVE(to))
3461 		return -EINVAL;
3462 
3463 	/* From should not be private */
3464 	if (!IS_MNT_SHARED(from) && !IS_MNT_SLAVE(from))
3465 		return -EINVAL;
3466 
3467 	if (IS_MNT_SLAVE(from)) {
3468 		hlist_add_behind(&to->mnt_slave, &from->mnt_slave);
3469 		to->mnt_master = from->mnt_master;
3470 	}
3471 
3472 	if (IS_MNT_SHARED(from)) {
3473 		to->mnt_group_id = from->mnt_group_id;
3474 		list_add(&to->mnt_share, &from->mnt_share);
3475 		set_mnt_shared(to);
3476 	}
3477 	return 0;
3478 }
3479 
3480 /**
3481  * path_overmounted - check if path is overmounted
3482  * @path: path to check
3483  *
3484  * Check if path is overmounted, i.e., if there's a mount on top of
3485  * @path->mnt with @path->dentry as mountpoint.
3486  *
3487  * Context: namespace_sem must be held at least shared.
3488  * MUST NOT be called under lock_mount_hash() (there one should just
3489  * call __lookup_mnt() and check if it returns NULL).
3490  * Return: If path is overmounted true is returned, false if not.
3491  */
path_overmounted(const struct path * path)3492 static inline bool path_overmounted(const struct path *path)
3493 {
3494 	unsigned seq = read_seqbegin(&mount_lock);
3495 	bool no_child;
3496 
3497 	rcu_read_lock();
3498 	no_child = !__lookup_mnt(path->mnt, path->dentry);
3499 	rcu_read_unlock();
3500 	if (need_seqretry(&mount_lock, seq)) {
3501 		read_seqlock_excl(&mount_lock);
3502 		no_child = !__lookup_mnt(path->mnt, path->dentry);
3503 		read_sequnlock_excl(&mount_lock);
3504 	}
3505 	return unlikely(!no_child);
3506 }
3507 
3508 /*
3509  * Check if there is a possibly empty chain of descent from p1 to p2.
3510  * Locks: namespace_sem (shared) or mount_lock (read_seqlock_excl).
3511  */
mount_is_ancestor(const struct mount * p1,const struct mount * p2)3512 static bool mount_is_ancestor(const struct mount *p1, const struct mount *p2)
3513 {
3514 	while (p2 != p1 && mnt_has_parent(p2))
3515 		p2 = p2->mnt_parent;
3516 	return p2 == p1;
3517 }
3518 
3519 /**
3520  * can_move_mount_beneath - check that we can mount beneath the top mount
3521  * @mnt_from: mount we are trying to move
3522  * @mnt_to:   mount under which to mount
3523  * @mp:   mountpoint of @mnt_to
3524  *
3525  * - Make sure that the caller can unmount the topmost mount ensuring
3526  *   that the caller could reveal the underlying mountpoint.
3527  * - Ensure that nothing has been mounted on top of @mnt_from before we
3528  *   grabbed @namespace_sem to avoid creating pointless shadow mounts.
3529  * - Prevent mounting beneath a mount if the propagation relationship
3530  *   between the source mount, parent mount, and top mount would lead to
3531  *   nonsensical mount trees.
3532  *
3533  * Context: This function expects namespace_lock() to be held.
3534  * Return: On success 0, and on error a negative error code is returned.
3535  */
can_move_mount_beneath(const struct mount * mnt_from,const struct mount * mnt_to,struct pinned_mountpoint * mp)3536 static int can_move_mount_beneath(const struct mount *mnt_from,
3537 				  const struct mount *mnt_to,
3538 				  struct pinned_mountpoint *mp)
3539 {
3540 	struct mount *parent_mnt_to = mnt_to->mnt_parent;
3541 
3542 	/* Avoid creating shadow mounts during mount propagation. */
3543 	if (mnt_from->overmount)
3544 		return -EINVAL;
3545 
3546 	if (mount_is_ancestor(mnt_to, mnt_from))
3547 		return -EINVAL;
3548 
3549 	/*
3550 	 * If the parent mount propagates to the child mount this would
3551 	 * mean mounting @mnt_from on @mnt_to->mnt_parent and then
3552 	 * propagating a copy @c of @mnt_from on top of @mnt_to. This
3553 	 * defeats the whole purpose of mounting beneath another mount.
3554 	 */
3555 	if (propagation_would_overmount(parent_mnt_to, mnt_to, mp->mp))
3556 		return -EINVAL;
3557 
3558 	/*
3559 	 * If @mnt_to->mnt_parent propagates to @mnt_from this would
3560 	 * mean propagating a copy @c of @mnt_from on top of @mnt_from.
3561 	 * Afterwards @mnt_from would be mounted on top of
3562 	 * @mnt_to->mnt_parent and @mnt_to would be unmounted from
3563 	 * @mnt->mnt_parent and remounted on @mnt_from. But since @c is
3564 	 * already mounted on @mnt_from, @mnt_to would ultimately be
3565 	 * remounted on top of @c. Afterwards, @mnt_from would be
3566 	 * covered by a copy @c of @mnt_from and @c would be covered by
3567 	 * @mnt_from itself. This defeats the whole purpose of mounting
3568 	 * @mnt_from beneath @mnt_to.
3569 	 */
3570 	if (check_mnt(mnt_from) &&
3571 	    propagation_would_overmount(parent_mnt_to, mnt_from, mp->mp))
3572 		return -EINVAL;
3573 
3574 	return 0;
3575 }
3576 
3577 /* may_use_mount() - check if a mount tree can be used
3578  * @mnt: vfsmount to be used
3579  *
3580  * This helper checks if the caller may use the mount tree starting
3581  * from @path->mnt. The caller may use the mount tree under the
3582  * following circumstances:
3583  *
3584  * (1) The caller is located in the mount namespace of the mount tree.
3585  *     This also implies that the mount does not belong to an anonymous
3586  *     mount namespace.
3587  * (2) The caller is trying to use a mount tree that belongs to an
3588  *     anonymous mount namespace.
3589  *
3590  *     For that to be safe, this helper enforces that the origin mount
3591  *     namespace the anonymous mount namespace was created from is the
3592  *     same as the caller's mount namespace by comparing the sequence
3593  *     numbers.
3594  *
3595  *     The ownership of a non-anonymous mount namespace such as the
3596  *     caller's cannot change.
3597  *     => We know that the caller's mount namespace is stable.
3598  *
3599  *     If the origin sequence number of the anonymous mount namespace is
3600  *     the same as the sequence number of the caller's mount namespace.
3601  *     => The owning namespaces are the same.
3602  *
3603  *     ==> The earlier capability check on the owning namespace of the
3604  *         caller's mount namespace ensures that the caller has the
3605  *         ability to use the mount tree.
3606  *
3607  * Returns true if the mount tree can be used, false otherwise.
3608  */
may_use_mount(struct mount * mnt)3609 static inline bool may_use_mount(struct mount *mnt)
3610 {
3611 	if (check_mnt(mnt))
3612 		return true;
3613 
3614 	/*
3615 	 * Make sure that noone unmounted the target path or somehow
3616 	 * managed to get their hands on something purely kernel
3617 	 * internal.
3618 	 */
3619 	if (!is_mounted(&mnt->mnt))
3620 		return false;
3621 
3622 	return check_anonymous_mnt(mnt);
3623 }
3624 
do_move_mount(const struct path * old_path,const struct path * new_path,enum mnt_tree_flags_t flags)3625 static int do_move_mount(const struct path *old_path,
3626 			 const struct path *new_path,
3627 			 enum mnt_tree_flags_t flags)
3628 {
3629 	struct mount *old = real_mount(old_path->mnt);
3630 	int err;
3631 	bool beneath = flags & MNT_TREE_BENEATH;
3632 
3633 	if (!path_mounted(old_path))
3634 		return -EINVAL;
3635 
3636 	if (d_is_dir(new_path->dentry) != d_is_dir(old_path->dentry))
3637 		return -EINVAL;
3638 
3639 	LOCK_MOUNT_MAYBE_BENEATH(mp, new_path, beneath);
3640 	if (IS_ERR(mp.parent))
3641 		return PTR_ERR(mp.parent);
3642 
3643 	if (check_mnt(old)) {
3644 		/* if the source is in our namespace... */
3645 		/* ... it should be detachable from parent */
3646 		if (!mnt_has_parent(old) || IS_MNT_LOCKED(old))
3647 			return -EINVAL;
3648 		/* ... which should not be shared */
3649 		if (IS_MNT_SHARED(old->mnt_parent))
3650 			return -EINVAL;
3651 		/* ... and the target should be in our namespace */
3652 		if (!check_mnt(mp.parent))
3653 			return -EINVAL;
3654 	} else {
3655 		/*
3656 		 * otherwise the source must be the root of some anon namespace.
3657 		 */
3658 		if (!anon_ns_root(old))
3659 			return -EINVAL;
3660 		/*
3661 		 * Bail out early if the target is within the same namespace -
3662 		 * subsequent checks would've rejected that, but they lose
3663 		 * some corner cases if we check it early.
3664 		 */
3665 		if (old->mnt_ns == mp.parent->mnt_ns)
3666 			return -EINVAL;
3667 		/*
3668 		 * Target should be either in our namespace or in an acceptable
3669 		 * anon namespace, sensu check_anonymous_mnt().
3670 		 */
3671 		if (!may_use_mount(mp.parent))
3672 			return -EINVAL;
3673 	}
3674 
3675 	if (beneath) {
3676 		struct mount *over = real_mount(new_path->mnt);
3677 
3678 		if (mp.parent != over->mnt_parent)
3679 			over = mp.parent->overmount;
3680 		err = can_move_mount_beneath(old, over, &mp);
3681 		if (err)
3682 			return err;
3683 	}
3684 
3685 	/*
3686 	 * Don't move a mount tree containing unbindable mounts to a destination
3687 	 * mount which is shared.
3688 	 */
3689 	if (IS_MNT_SHARED(mp.parent) && tree_contains_unbindable(old))
3690 		return -EINVAL;
3691 	if (!check_for_nsfs_mounts(old))
3692 		return -ELOOP;
3693 	if (mount_is_ancestor(old, mp.parent))
3694 		return -ELOOP;
3695 
3696 	return attach_recursive_mnt(old, &mp);
3697 }
3698 
do_move_mount_old(const struct path * path,const char * old_name)3699 static int do_move_mount_old(const struct path *path, const char *old_name)
3700 {
3701 	struct path old_path __free(path_put) = {};
3702 	int err;
3703 
3704 	if (!old_name || !*old_name)
3705 		return -EINVAL;
3706 
3707 	err = kern_path(old_name, LOOKUP_FOLLOW, &old_path);
3708 	if (err)
3709 		return err;
3710 
3711 	return do_move_mount(&old_path, path, 0);
3712 }
3713 
3714 /*
3715  * add a mount into a namespace's mount tree
3716  */
do_add_mount(struct mount * newmnt,const struct pinned_mountpoint * mp,int mnt_flags)3717 static int do_add_mount(struct mount *newmnt, const struct pinned_mountpoint *mp,
3718 			int mnt_flags)
3719 {
3720 	struct mount *parent = mp->parent;
3721 
3722 	if (IS_ERR(parent))
3723 		return PTR_ERR(parent);
3724 
3725 	mnt_flags &= ~MNT_INTERNAL_FLAGS;
3726 
3727 	if (unlikely(!check_mnt(parent))) {
3728 		/* that's acceptable only for automounts done in private ns */
3729 		if (!(mnt_flags & MNT_SHRINKABLE))
3730 			return -EINVAL;
3731 		/* ... and for those we'd better have mountpoint still alive */
3732 		if (!parent->mnt_ns)
3733 			return -EINVAL;
3734 	}
3735 
3736 	/* Refuse the same filesystem on the same mount point */
3737 	if (parent->mnt.mnt_sb == newmnt->mnt.mnt_sb &&
3738 	    parent->mnt.mnt_root == mp->mp->m_dentry)
3739 		return -EBUSY;
3740 
3741 	if (d_is_symlink(newmnt->mnt.mnt_root))
3742 		return -EINVAL;
3743 
3744 	newmnt->mnt.mnt_flags = mnt_flags;
3745 	return graft_tree(newmnt, mp);
3746 }
3747 
3748 static bool mount_too_revealing(const struct super_block *sb, int *new_mnt_flags);
3749 
3750 /*
3751  * Create a new mount using a superblock configuration and request it
3752  * be added to the namespace tree.
3753  */
do_new_mount_fc(struct fs_context * fc,const struct path * mountpoint,unsigned int mnt_flags)3754 static int do_new_mount_fc(struct fs_context *fc, const struct path *mountpoint,
3755 			   unsigned int mnt_flags)
3756 {
3757 	struct super_block *sb;
3758 	struct vfsmount *mnt __free(mntput) = fc_mount(fc);
3759 	int error;
3760 
3761 	if (IS_ERR(mnt))
3762 		return PTR_ERR(mnt);
3763 
3764 	sb = fc->root->d_sb;
3765 	error = security_sb_kern_mount(sb);
3766 	if (unlikely(error))
3767 		return error;
3768 
3769 	if (unlikely(mount_too_revealing(sb, &mnt_flags))) {
3770 		errorfcp(fc, "VFS", "Mount too revealing");
3771 		return -EPERM;
3772 	}
3773 
3774 	mnt_warn_timestamp_expiry(mountpoint, mnt);
3775 
3776 	LOCK_MOUNT(mp, mountpoint);
3777 	error = do_add_mount(real_mount(mnt), &mp, mnt_flags);
3778 	if (!error)
3779 		retain_and_null_ptr(mnt); // consumed on success
3780 	return error;
3781 }
3782 
3783 /*
3784  * create a new mount for userspace and request it to be added into the
3785  * namespace's tree
3786  */
do_new_mount(const struct path * path,const char * fstype,int sb_flags,int mnt_flags,const char * name,void * data)3787 static int do_new_mount(const struct path *path, const char *fstype,
3788 			int sb_flags, int mnt_flags,
3789 			const char *name, void *data)
3790 {
3791 	struct file_system_type *type;
3792 	struct fs_context *fc;
3793 	const char *subtype = NULL;
3794 	int err = 0;
3795 
3796 	if (!fstype)
3797 		return -EINVAL;
3798 
3799 	type = get_fs_type(fstype);
3800 	if (!type)
3801 		return -ENODEV;
3802 
3803 	if (type->fs_flags & FS_HAS_SUBTYPE) {
3804 		subtype = strchr(fstype, '.');
3805 		if (subtype) {
3806 			subtype++;
3807 			if (!*subtype) {
3808 				put_filesystem(type);
3809 				return -EINVAL;
3810 			}
3811 		}
3812 	}
3813 
3814 	fc = fs_context_for_mount(type, sb_flags);
3815 	put_filesystem(type);
3816 	if (IS_ERR(fc))
3817 		return PTR_ERR(fc);
3818 
3819 	/*
3820 	 * Indicate to the filesystem that the mount request is coming
3821 	 * from the legacy mount system call.
3822 	 */
3823 	fc->oldapi = true;
3824 
3825 	if (subtype)
3826 		err = vfs_parse_fs_string(fc, "subtype", subtype);
3827 	if (!err && name)
3828 		err = vfs_parse_fs_string(fc, "source", name);
3829 	if (!err)
3830 		err = parse_monolithic_mount_data(fc, data);
3831 	if (!err && !mount_capable(fc))
3832 		err = -EPERM;
3833 	if (!err)
3834 		err = do_new_mount_fc(fc, path, mnt_flags);
3835 
3836 	put_fs_context(fc);
3837 	return err;
3838 }
3839 
lock_mount_exact(const struct path * path,struct pinned_mountpoint * mp,bool copy_mount,unsigned int copy_flags)3840 static void lock_mount_exact(const struct path *path,
3841 			     struct pinned_mountpoint *mp, bool copy_mount,
3842 			     unsigned int copy_flags)
3843 {
3844 	struct dentry *dentry = path->dentry;
3845 	int err;
3846 
3847 	/* Assert that inode_lock() locked the correct inode. */
3848 	VFS_WARN_ON_ONCE(copy_mount && !path_mounted(path));
3849 
3850 	inode_lock(dentry->d_inode);
3851 	namespace_lock();
3852 	if (unlikely(cant_mount(dentry)))
3853 		err = -ENOENT;
3854 	else if (!copy_mount && path_overmounted(path))
3855 		err = -EBUSY;
3856 	else
3857 		err = get_mountpoint(dentry, mp);
3858 	if (unlikely(err)) {
3859 		namespace_unlock();
3860 		inode_unlock(dentry->d_inode);
3861 		mp->parent = ERR_PTR(err);
3862 		return;
3863 	}
3864 
3865 	if (copy_mount)
3866 		mp->parent = clone_mnt(real_mount(path->mnt), dentry, copy_flags);
3867 	else
3868 		mp->parent = real_mount(path->mnt);
3869 	if (unlikely(IS_ERR(mp->parent)))
3870 		__unlock_mount(mp);
3871 }
3872 
finish_automount(struct vfsmount * __m,const struct path * path)3873 int finish_automount(struct vfsmount *__m, const struct path *path)
3874 {
3875 	struct vfsmount *m __free(mntput) = __m;
3876 	struct mount *mnt;
3877 	int err;
3878 
3879 	if (!m)
3880 		return 0;
3881 	if (IS_ERR(m))
3882 		return PTR_ERR(m);
3883 
3884 	mnt = real_mount(m);
3885 
3886 	if (m->mnt_root == path->dentry)
3887 		return -ELOOP;
3888 
3889 	/*
3890 	 * we don't want to use LOCK_MOUNT() - in this case finding something
3891 	 * that overmounts our mountpoint to be means "quitely drop what we've
3892 	 * got", not "try to mount it on top".
3893 	 */
3894 	LOCK_MOUNT_EXACT(mp, path);
3895 	if (mp.parent == ERR_PTR(-EBUSY))
3896 		return 0;
3897 
3898 	err = do_add_mount(mnt, &mp, path->mnt->mnt_flags | MNT_SHRINKABLE);
3899 	if (likely(!err))
3900 		retain_and_null_ptr(m);
3901 	return err;
3902 }
3903 
3904 /**
3905  * mnt_set_expiry - Put a mount on an expiration list
3906  * @mnt: The mount to list.
3907  * @expiry_list: The list to add the mount to.
3908  */
mnt_set_expiry(struct vfsmount * mnt,struct list_head * expiry_list)3909 void mnt_set_expiry(struct vfsmount *mnt, struct list_head *expiry_list)
3910 {
3911 	guard(mount_locked_reader)();
3912 	list_add_tail(&real_mount(mnt)->mnt_expire, expiry_list);
3913 }
3914 EXPORT_SYMBOL(mnt_set_expiry);
3915 
3916 /*
3917  * process a list of expirable mountpoints with the intent of discarding any
3918  * mountpoints that aren't in use and haven't been touched since last we came
3919  * here
3920  */
mark_mounts_for_expiry(struct list_head * mounts)3921 void mark_mounts_for_expiry(struct list_head *mounts)
3922 {
3923 	struct mount *mnt, *next;
3924 	LIST_HEAD(graveyard);
3925 
3926 	if (list_empty(mounts))
3927 		return;
3928 
3929 	guard(namespace_excl)();
3930 	guard(mount_writer)();
3931 
3932 	/* extract from the expiration list every vfsmount that matches the
3933 	 * following criteria:
3934 	 * - already mounted
3935 	 * - only referenced by its parent vfsmount
3936 	 * - still marked for expiry (marked on the last call here; marks are
3937 	 *   cleared by mntput())
3938 	 */
3939 	list_for_each_entry_safe(mnt, next, mounts, mnt_expire) {
3940 		if (!is_mounted(&mnt->mnt))
3941 			continue;
3942 		if (!xchg(&mnt->mnt_expiry_mark, 1) ||
3943 			propagate_mount_busy(mnt, 1))
3944 			continue;
3945 		list_move(&mnt->mnt_expire, &graveyard);
3946 	}
3947 	while (!list_empty(&graveyard)) {
3948 		mnt = list_first_entry(&graveyard, struct mount, mnt_expire);
3949 		touch_mnt_namespace(mnt->mnt_ns);
3950 		umount_tree(mnt, UMOUNT_PROPAGATE|UMOUNT_SYNC);
3951 	}
3952 }
3953 
3954 EXPORT_SYMBOL_GPL(mark_mounts_for_expiry);
3955 
3956 /*
3957  * Ripoff of 'select_parent()'
3958  *
3959  * search the list of submounts for a given mountpoint, and move any
3960  * shrinkable submounts to the 'graveyard' list.
3961  */
select_submounts(struct mount * parent,struct list_head * graveyard)3962 static int select_submounts(struct mount *parent, struct list_head *graveyard)
3963 {
3964 	struct mount *this_parent = parent;
3965 	struct list_head *next;
3966 	int found = 0;
3967 
3968 repeat:
3969 	next = this_parent->mnt_mounts.next;
3970 resume:
3971 	while (next != &this_parent->mnt_mounts) {
3972 		struct list_head *tmp = next;
3973 		struct mount *mnt = list_entry(tmp, struct mount, mnt_child);
3974 
3975 		next = tmp->next;
3976 		if (!(mnt->mnt.mnt_flags & MNT_SHRINKABLE))
3977 			continue;
3978 		/*
3979 		 * Descend a level if the d_mounts list is non-empty.
3980 		 */
3981 		if (!list_empty(&mnt->mnt_mounts)) {
3982 			this_parent = mnt;
3983 			goto repeat;
3984 		}
3985 
3986 		if (!propagate_mount_busy(mnt, 1)) {
3987 			list_move_tail(&mnt->mnt_expire, graveyard);
3988 			found++;
3989 		}
3990 	}
3991 	/*
3992 	 * All done at this level ... ascend and resume the search
3993 	 */
3994 	if (this_parent != parent) {
3995 		next = this_parent->mnt_child.next;
3996 		this_parent = this_parent->mnt_parent;
3997 		goto resume;
3998 	}
3999 	return found;
4000 }
4001 
4002 /*
4003  * process a list of expirable mountpoints with the intent of discarding any
4004  * submounts of a specific parent mountpoint
4005  *
4006  * mount_lock must be held for write
4007  */
shrink_submounts(struct mount * mnt)4008 static void shrink_submounts(struct mount *mnt)
4009 {
4010 	LIST_HEAD(graveyard);
4011 	struct mount *m;
4012 
4013 	/* extract submounts of 'mountpoint' from the expiration list */
4014 	while (select_submounts(mnt, &graveyard)) {
4015 		while (!list_empty(&graveyard)) {
4016 			m = list_first_entry(&graveyard, struct mount,
4017 						mnt_expire);
4018 			touch_mnt_namespace(m->mnt_ns);
4019 			umount_tree(m, UMOUNT_PROPAGATE|UMOUNT_SYNC);
4020 		}
4021 	}
4022 }
4023 
copy_mount_options(const void __user * data)4024 static void *copy_mount_options(const void __user * data)
4025 {
4026 	char *copy;
4027 	unsigned left, offset;
4028 
4029 	if (!data)
4030 		return NULL;
4031 
4032 	copy = kmalloc(PAGE_SIZE, GFP_KERNEL);
4033 	if (!copy)
4034 		return ERR_PTR(-ENOMEM);
4035 
4036 	left = copy_from_user(copy, data, PAGE_SIZE);
4037 
4038 	/*
4039 	 * Not all architectures have an exact copy_from_user(). Resort to
4040 	 * byte at a time.
4041 	 */
4042 	offset = PAGE_SIZE - left;
4043 	while (left) {
4044 		char c;
4045 		if (get_user(c, (const char __user *)data + offset))
4046 			break;
4047 		copy[offset] = c;
4048 		left--;
4049 		offset++;
4050 	}
4051 
4052 	if (left == PAGE_SIZE) {
4053 		kfree(copy);
4054 		return ERR_PTR(-EFAULT);
4055 	}
4056 
4057 	return copy;
4058 }
4059 
copy_mount_string(const void __user * data)4060 static char *copy_mount_string(const void __user *data)
4061 {
4062 	return data ? strndup_user(data, PATH_MAX) : NULL;
4063 }
4064 
4065 /*
4066  * Flags is a 32-bit value that allows up to 31 non-fs dependent flags to
4067  * be given to the mount() call (ie: read-only, no-dev, no-suid etc).
4068  *
4069  * data is a (void *) that can point to any structure up to
4070  * PAGE_SIZE-1 bytes, which can contain arbitrary fs-dependent
4071  * information (or be NULL).
4072  *
4073  * Pre-0.97 versions of mount() didn't have a flags word.
4074  * When the flags word was introduced its top half was required
4075  * to have the magic value 0xC0ED, and this remained so until 2.4.0-test9.
4076  * Therefore, if this magic number is present, it carries no information
4077  * and must be discarded.
4078  */
path_mount(const char * dev_name,const struct path * path,const char * type_page,unsigned long flags,void * data_page)4079 int path_mount(const char *dev_name, const struct path *path,
4080 		const char *type_page, unsigned long flags, void *data_page)
4081 {
4082 	unsigned int mnt_flags = 0, sb_flags;
4083 	int ret;
4084 
4085 	/* Discard magic */
4086 	if ((flags & MS_MGC_MSK) == MS_MGC_VAL)
4087 		flags &= ~MS_MGC_MSK;
4088 
4089 	/* Basic sanity checks */
4090 	if (data_page)
4091 		((char *)data_page)[PAGE_SIZE - 1] = 0;
4092 
4093 	if (flags & MS_NOUSER)
4094 		return -EINVAL;
4095 
4096 	ret = security_sb_mount(dev_name, path, type_page, flags, data_page);
4097 	if (ret)
4098 		return ret;
4099 	if (!may_mount())
4100 		return -EPERM;
4101 	if (flags & SB_MANDLOCK)
4102 		warn_mandlock();
4103 
4104 	/* Default to relatime unless overriden */
4105 	if (!(flags & MS_NOATIME))
4106 		mnt_flags |= MNT_RELATIME;
4107 
4108 	/* Separate the per-mountpoint flags */
4109 	if (flags & MS_NOSUID)
4110 		mnt_flags |= MNT_NOSUID;
4111 	if (flags & MS_NODEV)
4112 		mnt_flags |= MNT_NODEV;
4113 	if (flags & MS_NOEXEC)
4114 		mnt_flags |= MNT_NOEXEC;
4115 	if (flags & MS_NOATIME)
4116 		mnt_flags |= MNT_NOATIME;
4117 	if (flags & MS_NODIRATIME)
4118 		mnt_flags |= MNT_NODIRATIME;
4119 	if (flags & MS_STRICTATIME)
4120 		mnt_flags &= ~(MNT_RELATIME | MNT_NOATIME);
4121 	if (flags & MS_RDONLY)
4122 		mnt_flags |= MNT_READONLY;
4123 	if (flags & MS_NOSYMFOLLOW)
4124 		mnt_flags |= MNT_NOSYMFOLLOW;
4125 
4126 	/* The default atime for remount is preservation */
4127 	if ((flags & MS_REMOUNT) &&
4128 	    ((flags & (MS_NOATIME | MS_NODIRATIME | MS_RELATIME |
4129 		       MS_STRICTATIME)) == 0)) {
4130 		mnt_flags &= ~MNT_ATIME_MASK;
4131 		mnt_flags |= path->mnt->mnt_flags & MNT_ATIME_MASK;
4132 	}
4133 
4134 	sb_flags = flags & (SB_RDONLY |
4135 			    SB_SYNCHRONOUS |
4136 			    SB_MANDLOCK |
4137 			    SB_DIRSYNC |
4138 			    SB_SILENT |
4139 			    SB_POSIXACL |
4140 			    SB_LAZYTIME |
4141 			    SB_I_VERSION);
4142 
4143 	if ((flags & (MS_REMOUNT | MS_BIND)) == (MS_REMOUNT | MS_BIND))
4144 		return do_reconfigure_mnt(path, mnt_flags);
4145 	if (flags & MS_REMOUNT)
4146 		return do_remount(path, sb_flags, mnt_flags, data_page);
4147 	if (flags & MS_BIND)
4148 		return do_loopback(path, dev_name, flags & MS_REC);
4149 	if (flags & (MS_SHARED | MS_PRIVATE | MS_SLAVE | MS_UNBINDABLE))
4150 		return do_change_type(path, flags);
4151 	if (flags & MS_MOVE)
4152 		return do_move_mount_old(path, dev_name);
4153 
4154 	return do_new_mount(path, type_page, sb_flags, mnt_flags, dev_name,
4155 			    data_page);
4156 }
4157 
do_mount(const char * dev_name,const char __user * dir_name,const char * type_page,unsigned long flags,void * data_page)4158 int do_mount(const char *dev_name, const char __user *dir_name,
4159 		const char *type_page, unsigned long flags, void *data_page)
4160 {
4161 	struct path path __free(path_put) = {};
4162 	int ret;
4163 
4164 	ret = user_path_at(AT_FDCWD, dir_name, LOOKUP_FOLLOW, &path);
4165 	if (ret)
4166 		return ret;
4167 	return path_mount(dev_name, &path, type_page, flags, data_page);
4168 }
4169 
inc_mnt_namespaces(struct user_namespace * ns)4170 static struct ucounts *inc_mnt_namespaces(struct user_namespace *ns)
4171 {
4172 	return inc_ucount(ns, current_euid(), UCOUNT_MNT_NAMESPACES);
4173 }
4174 
dec_mnt_namespaces(struct ucounts * ucounts)4175 static void dec_mnt_namespaces(struct ucounts *ucounts)
4176 {
4177 	dec_ucount(ucounts, UCOUNT_MNT_NAMESPACES);
4178 }
4179 
free_mnt_ns(struct mnt_namespace * ns)4180 static void free_mnt_ns(struct mnt_namespace *ns)
4181 {
4182 	if (!is_anon_ns(ns))
4183 		ns_common_free(ns);
4184 	dec_mnt_namespaces(ns->ucounts);
4185 	mnt_ns_tree_remove(ns);
4186 }
4187 
alloc_mnt_ns(struct user_namespace * user_ns,bool anon)4188 static struct mnt_namespace *alloc_mnt_ns(struct user_namespace *user_ns, bool anon)
4189 {
4190 	struct mnt_namespace *new_ns;
4191 	struct ucounts *ucounts;
4192 	int ret;
4193 
4194 	ucounts = inc_mnt_namespaces(user_ns);
4195 	if (!ucounts)
4196 		return ERR_PTR(-ENOSPC);
4197 
4198 	new_ns = kzalloc_obj(struct mnt_namespace, GFP_KERNEL_ACCOUNT);
4199 	if (!new_ns) {
4200 		dec_mnt_namespaces(ucounts);
4201 		return ERR_PTR(-ENOMEM);
4202 	}
4203 
4204 	if (anon)
4205 		ret = ns_common_init_inum(new_ns, MNT_NS_ANON_INO);
4206 	else
4207 		ret = ns_common_init(new_ns);
4208 	if (ret) {
4209 		kfree(new_ns);
4210 		dec_mnt_namespaces(ucounts);
4211 		return ERR_PTR(ret);
4212 	}
4213 	ns_tree_gen_id(new_ns);
4214 
4215 	new_ns->is_anon = anon;
4216 	refcount_set(&new_ns->passive, 1);
4217 	new_ns->mounts = RB_ROOT;
4218 	init_waitqueue_head(&new_ns->poll);
4219 	new_ns->user_ns = get_user_ns(user_ns);
4220 	new_ns->ucounts = ucounts;
4221 	return new_ns;
4222 }
4223 
4224 __latent_entropy
copy_mnt_ns(u64 flags,struct mnt_namespace * ns,struct user_namespace * user_ns,struct fs_struct * new_fs)4225 struct mnt_namespace *copy_mnt_ns(u64 flags, struct mnt_namespace *ns,
4226 		struct user_namespace *user_ns, struct fs_struct *new_fs)
4227 {
4228 	struct mnt_namespace *new_ns;
4229 	struct path old_root __free(path_put) = {};
4230 	struct path old_pwd __free(path_put) = {};
4231 	struct mount *p, *q;
4232 	struct mount *old;
4233 	struct mount *new;
4234 	int copy_flags;
4235 
4236 	BUG_ON(!ns);
4237 
4238 	if (likely(!(flags & CLONE_NEWNS))) {
4239 		get_mnt_ns(ns);
4240 		return ns;
4241 	}
4242 
4243 	old = ns->root;
4244 
4245 	new_ns = alloc_mnt_ns(user_ns, false);
4246 	if (IS_ERR(new_ns))
4247 		return new_ns;
4248 
4249 	guard(namespace_excl)();
4250 
4251 	if (flags & CLONE_EMPTY_MNTNS)
4252 		copy_flags = 0;
4253 	else
4254 		copy_flags = CL_COPY_UNBINDABLE | CL_EXPIRE;
4255 	if (user_ns != ns->user_ns)
4256 		copy_flags |= CL_SLAVE;
4257 
4258 	if (flags & CLONE_EMPTY_MNTNS)
4259 		new = clone_mnt(old, old->mnt.mnt_root, copy_flags);
4260 	else
4261 		new = copy_tree(old, old->mnt.mnt_root, copy_flags);
4262 	if (IS_ERR(new)) {
4263 		emptied_ns = new_ns;
4264 		return ERR_CAST(new);
4265 	}
4266 	if (user_ns != ns->user_ns) {
4267 		guard(mount_writer)();
4268 		lock_mnt_tree(new);
4269 	}
4270 	new_ns->root = new;
4271 
4272 	if (flags & CLONE_EMPTY_MNTNS) {
4273 		/*
4274 		 * Empty mount namespace: only the root mount exists.
4275 		 * Reset root and pwd to the cloned mount's root dentry.
4276 		 */
4277 		if (new_fs) {
4278 			old_root = new_fs->root;
4279 			old_pwd = new_fs->pwd;
4280 
4281 			new_fs->root.mnt = mntget(&new->mnt);
4282 			new_fs->root.dentry = dget(new->mnt.mnt_root);
4283 
4284 			new_fs->pwd.mnt = mntget(&new->mnt);
4285 			new_fs->pwd.dentry = dget(new->mnt.mnt_root);
4286 		}
4287 		mnt_add_to_ns(new_ns, new);
4288 		new_ns->nr_mounts++;
4289 	} else {
4290 		/*
4291 		 * Full copy: walk old and new trees in parallel, switching
4292 		 * the tsk->fs->* elements and marking new vfsmounts as
4293 		 * belonging to new namespace.  We have already acquired a
4294 		 * private fs_struct, so tsk->fs->lock is not needed.
4295 		 */
4296 		p = old;
4297 		q = new;
4298 		while (p) {
4299 			mnt_add_to_ns(new_ns, q);
4300 			new_ns->nr_mounts++;
4301 			if (new_fs) {
4302 				if (&p->mnt == new_fs->root.mnt) {
4303 					old_root.mnt = new_fs->root.mnt;
4304 					new_fs->root.mnt = mntget(&q->mnt);
4305 				}
4306 				if (&p->mnt == new_fs->pwd.mnt) {
4307 					old_pwd.mnt = new_fs->pwd.mnt;
4308 					new_fs->pwd.mnt = mntget(&q->mnt);
4309 				}
4310 			}
4311 			p = next_mnt(p, old);
4312 			q = next_mnt(q, new);
4313 			if (!q)
4314 				break;
4315 			// an mntns binding we'd skipped?
4316 			while (p->mnt.mnt_root != q->mnt.mnt_root)
4317 				p = next_mnt(skip_mnt_tree(p), old);
4318 		}
4319 	}
4320 	ns_tree_add_raw(new_ns);
4321 	return new_ns;
4322 }
4323 
mount_subtree(struct vfsmount * m,const char * name)4324 struct dentry *mount_subtree(struct vfsmount *m, const char *name)
4325 {
4326 	struct mount *mnt = real_mount(m);
4327 	struct mnt_namespace *ns;
4328 	struct super_block *s;
4329 	struct path path;
4330 	int err;
4331 
4332 	ns = alloc_mnt_ns(&init_user_ns, true);
4333 	if (IS_ERR(ns)) {
4334 		mntput(m);
4335 		return ERR_CAST(ns);
4336 	}
4337 	ns->root = mnt;
4338 	ns->nr_mounts++;
4339 	mnt_add_to_ns(ns, mnt);
4340 
4341 	err = vfs_path_lookup(m->mnt_root, m,
4342 			name, LOOKUP_FOLLOW|LOOKUP_AUTOMOUNT, &path);
4343 
4344 	put_mnt_ns(ns);
4345 
4346 	if (err)
4347 		return ERR_PTR(err);
4348 
4349 	/* trade a vfsmount reference for active sb one */
4350 	s = path.mnt->mnt_sb;
4351 	atomic_inc(&s->s_active);
4352 	mntput(path.mnt);
4353 	/* lock the sucker */
4354 	down_write(&s->s_umount);
4355 	/* ... and return the root of (sub)tree on it */
4356 	return path.dentry;
4357 }
4358 EXPORT_SYMBOL(mount_subtree);
4359 
SYSCALL_DEFINE5(mount,char __user *,dev_name,char __user *,dir_name,char __user *,type,unsigned long,flags,void __user *,data)4360 SYSCALL_DEFINE5(mount, char __user *, dev_name, char __user *, dir_name,
4361 		char __user *, type, unsigned long, flags, void __user *, data)
4362 {
4363 	int ret;
4364 	char *kernel_type;
4365 	char *kernel_dev;
4366 	void *options;
4367 
4368 	kernel_type = copy_mount_string(type);
4369 	ret = PTR_ERR(kernel_type);
4370 	if (IS_ERR(kernel_type))
4371 		goto out_type;
4372 
4373 	kernel_dev = copy_mount_string(dev_name);
4374 	ret = PTR_ERR(kernel_dev);
4375 	if (IS_ERR(kernel_dev))
4376 		goto out_dev;
4377 
4378 	options = copy_mount_options(data);
4379 	ret = PTR_ERR(options);
4380 	if (IS_ERR(options))
4381 		goto out_data;
4382 
4383 	ret = do_mount(kernel_dev, dir_name, kernel_type, flags, options);
4384 
4385 	kfree(options);
4386 out_data:
4387 	kfree(kernel_dev);
4388 out_dev:
4389 	kfree(kernel_type);
4390 out_type:
4391 	return ret;
4392 }
4393 
4394 #define FSMOUNT_VALID_FLAGS                                                    \
4395 	(MOUNT_ATTR_RDONLY | MOUNT_ATTR_NOSUID | MOUNT_ATTR_NODEV |            \
4396 	 MOUNT_ATTR_NOEXEC | MOUNT_ATTR__ATIME | MOUNT_ATTR_NODIRATIME |       \
4397 	 MOUNT_ATTR_NOSYMFOLLOW)
4398 
4399 #define MOUNT_SETATTR_VALID_FLAGS (FSMOUNT_VALID_FLAGS | MOUNT_ATTR_IDMAP)
4400 
4401 #define MOUNT_SETATTR_PROPAGATION_FLAGS \
4402 	(MS_UNBINDABLE | MS_PRIVATE | MS_SLAVE | MS_SHARED)
4403 
attr_flags_to_mnt_flags(u64 attr_flags)4404 static unsigned int attr_flags_to_mnt_flags(u64 attr_flags)
4405 {
4406 	unsigned int mnt_flags = 0;
4407 
4408 	if (attr_flags & MOUNT_ATTR_RDONLY)
4409 		mnt_flags |= MNT_READONLY;
4410 	if (attr_flags & MOUNT_ATTR_NOSUID)
4411 		mnt_flags |= MNT_NOSUID;
4412 	if (attr_flags & MOUNT_ATTR_NODEV)
4413 		mnt_flags |= MNT_NODEV;
4414 	if (attr_flags & MOUNT_ATTR_NOEXEC)
4415 		mnt_flags |= MNT_NOEXEC;
4416 	if (attr_flags & MOUNT_ATTR_NODIRATIME)
4417 		mnt_flags |= MNT_NODIRATIME;
4418 	if (attr_flags & MOUNT_ATTR_NOSYMFOLLOW)
4419 		mnt_flags |= MNT_NOSYMFOLLOW;
4420 
4421 	return mnt_flags;
4422 }
4423 
4424 /*
4425  * Create a kernel mount representation for a new, prepared superblock
4426  * (specified by fs_fd) and attach to an open_tree-like file descriptor.
4427  */
SYSCALL_DEFINE3(fsmount,int,fs_fd,unsigned int,flags,unsigned int,attr_flags)4428 SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,
4429 		unsigned int, attr_flags)
4430 {
4431 	struct path new_path __free(path_put) = {};
4432 	struct mnt_namespace *ns;
4433 	struct fs_context *fc;
4434 	struct vfsmount *new_mnt;
4435 	struct mount *mnt;
4436 	unsigned int mnt_flags = 0;
4437 	long ret;
4438 
4439 	if ((flags & ~(FSMOUNT_CLOEXEC | FSMOUNT_NAMESPACE)) != 0)
4440 		return -EINVAL;
4441 
4442 	if ((flags & FSMOUNT_NAMESPACE) &&
4443 	    !ns_capable(current_user_ns(), CAP_SYS_ADMIN))
4444 		return -EPERM;
4445 
4446 	if (!(flags & FSMOUNT_NAMESPACE) && !may_mount())
4447 		return -EPERM;
4448 
4449 	if (attr_flags & ~FSMOUNT_VALID_FLAGS)
4450 		return -EINVAL;
4451 
4452 	mnt_flags = attr_flags_to_mnt_flags(attr_flags);
4453 
4454 	switch (attr_flags & MOUNT_ATTR__ATIME) {
4455 	case MOUNT_ATTR_STRICTATIME:
4456 		break;
4457 	case MOUNT_ATTR_NOATIME:
4458 		mnt_flags |= MNT_NOATIME;
4459 		break;
4460 	case MOUNT_ATTR_RELATIME:
4461 		mnt_flags |= MNT_RELATIME;
4462 		break;
4463 	default:
4464 		return -EINVAL;
4465 	}
4466 
4467 	CLASS(fd, f)(fs_fd);
4468 	if (fd_empty(f))
4469 		return -EBADF;
4470 
4471 	if (fd_file(f)->f_op != &fscontext_fops)
4472 		return -EINVAL;
4473 
4474 	fc = fd_file(f)->private_data;
4475 
4476 	ACQUIRE(mutex_intr, uapi_mutex)(&fc->uapi_mutex);
4477 	ret = ACQUIRE_ERR(mutex_intr, &uapi_mutex);
4478 	if (ret)
4479 		return ret;
4480 
4481 	/* There must be a valid superblock or we can't mount it */
4482 	ret = -EINVAL;
4483 	if (!fc->root)
4484 		return ret;
4485 
4486 	ret = -EPERM;
4487 	if (mount_too_revealing(fc->root->d_sb, &mnt_flags)) {
4488 		errorfcp(fc, "VFS", "Mount too revealing");
4489 		return ret;
4490 	}
4491 
4492 	ret = -EBUSY;
4493 	if (fc->phase != FS_CONTEXT_AWAITING_MOUNT)
4494 		return ret;
4495 
4496 	if (fc->sb_flags & SB_MANDLOCK)
4497 		warn_mandlock();
4498 
4499 	new_mnt = vfs_create_mount(fc);
4500 	if (IS_ERR(new_mnt))
4501 		return PTR_ERR(new_mnt);
4502 	new_mnt->mnt_flags = mnt_flags;
4503 
4504 	new_path.dentry = dget(fc->root);
4505 	new_path.mnt = new_mnt;
4506 
4507 	/* We've done the mount bit - now move the file context into more or
4508 	 * less the same state as if we'd done an fspick().  We don't want to
4509 	 * do any memory allocation or anything like that at this point as we
4510 	 * don't want to have to handle any errors incurred.
4511 	 */
4512 	vfs_clean_context(fc);
4513 
4514 	if (flags & FSMOUNT_NAMESPACE)
4515 		return FD_ADD((flags & FSMOUNT_CLOEXEC) ? O_CLOEXEC : 0,
4516 			      open_new_namespace(&new_path, MOUNT_COPY_NEW));
4517 
4518 	ns = alloc_mnt_ns(current->nsproxy->mnt_ns->user_ns, true);
4519 	if (IS_ERR(ns))
4520 		return PTR_ERR(ns);
4521 	mnt = real_mount(new_path.mnt);
4522 	ns->root = mnt;
4523 	ns->nr_mounts = 1;
4524 	mnt_add_to_ns(ns, mnt);
4525 	mntget(new_path.mnt);
4526 
4527 	FD_PREPARE(fdf, (flags & FSMOUNT_CLOEXEC) ? O_CLOEXEC : 0,
4528 		   dentry_open(&new_path, O_PATH, fc->cred));
4529 	if (fdf.err) {
4530 		dissolve_on_fput(new_path.mnt);
4531 		return fdf.err;
4532 	}
4533 
4534 	/*
4535 	 * Attach to an apparent O_PATH fd with a note that we
4536 	 * need to unmount it, not just simply put it.
4537 	 */
4538 	fd_prepare_file(fdf)->f_mode |= FMODE_NEED_UNMOUNT;
4539 	return fd_publish(fdf);
4540 }
4541 
vfs_move_mount(const struct path * from_path,const struct path * to_path,enum mnt_tree_flags_t mflags)4542 static inline int vfs_move_mount(const struct path *from_path,
4543 				 const struct path *to_path,
4544 				 enum mnt_tree_flags_t mflags)
4545 {
4546 	int ret;
4547 
4548 	ret = security_move_mount(from_path, to_path);
4549 	if (ret)
4550 		return ret;
4551 
4552 	if (mflags & MNT_TREE_PROPAGATION)
4553 		return do_set_group(from_path, to_path);
4554 
4555 	return do_move_mount(from_path, to_path, mflags);
4556 }
4557 
4558 /*
4559  * Move a mount from one place to another.  In combination with
4560  * fsopen()/fsmount() this is used to install a new mount and in combination
4561  * with open_tree(OPEN_TREE_CLONE [| AT_RECURSIVE]) it can be used to copy
4562  * a mount subtree.
4563  *
4564  * Note the flags value is a combination of MOVE_MOUNT_* flags.
4565  */
SYSCALL_DEFINE5(move_mount,int,from_dfd,const char __user *,from_pathname,int,to_dfd,const char __user *,to_pathname,unsigned int,flags)4566 SYSCALL_DEFINE5(move_mount,
4567 		int, from_dfd, const char __user *, from_pathname,
4568 		int, to_dfd, const char __user *, to_pathname,
4569 		unsigned int, flags)
4570 {
4571 	struct path to_path __free(path_put) = {};
4572 	struct path from_path __free(path_put) = {};
4573 	unsigned int lflags, uflags;
4574 	enum mnt_tree_flags_t mflags = 0;
4575 	int ret = 0;
4576 
4577 	if (!may_mount())
4578 		return -EPERM;
4579 
4580 	if (flags & ~MOVE_MOUNT__MASK)
4581 		return -EINVAL;
4582 
4583 	if ((flags & (MOVE_MOUNT_BENEATH | MOVE_MOUNT_SET_GROUP)) ==
4584 	    (MOVE_MOUNT_BENEATH | MOVE_MOUNT_SET_GROUP))
4585 		return -EINVAL;
4586 
4587 	if (flags & MOVE_MOUNT_SET_GROUP)	mflags |= MNT_TREE_PROPAGATION;
4588 	if (flags & MOVE_MOUNT_BENEATH)		mflags |= MNT_TREE_BENEATH;
4589 
4590 	uflags = 0;
4591 	if (flags & MOVE_MOUNT_T_EMPTY_PATH)
4592 		uflags = AT_EMPTY_PATH;
4593 
4594 	CLASS(filename_maybe_null,to_name)(to_pathname, uflags);
4595 	if (!to_name && to_dfd >= 0) {
4596 		CLASS(fd_raw, f_to)(to_dfd);
4597 		if (fd_empty(f_to))
4598 			return -EBADF;
4599 
4600 		to_path = fd_file(f_to)->f_path;
4601 		path_get(&to_path);
4602 	} else {
4603 		lflags = 0;
4604 		if (flags & MOVE_MOUNT_T_SYMLINKS)
4605 			lflags |= LOOKUP_FOLLOW;
4606 		if (flags & MOVE_MOUNT_T_AUTOMOUNTS)
4607 			lflags |= LOOKUP_AUTOMOUNT;
4608 		ret = filename_lookup(to_dfd, to_name, lflags, &to_path, NULL);
4609 		if (ret)
4610 			return ret;
4611 	}
4612 
4613 	uflags = 0;
4614 	if (flags & MOVE_MOUNT_F_EMPTY_PATH)
4615 		uflags = AT_EMPTY_PATH;
4616 
4617 	CLASS(filename_maybe_null,from_name)(from_pathname, uflags);
4618 	if (!from_name && from_dfd >= 0) {
4619 		CLASS(fd_raw, f_from)(from_dfd);
4620 		if (fd_empty(f_from))
4621 			return -EBADF;
4622 
4623 		return vfs_move_mount(&fd_file(f_from)->f_path, &to_path, mflags);
4624 	}
4625 
4626 	lflags = 0;
4627 	if (flags & MOVE_MOUNT_F_SYMLINKS)
4628 		lflags |= LOOKUP_FOLLOW;
4629 	if (flags & MOVE_MOUNT_F_AUTOMOUNTS)
4630 		lflags |= LOOKUP_AUTOMOUNT;
4631 	ret = filename_lookup(from_dfd, from_name, lflags, &from_path, NULL);
4632 	if (ret)
4633 		return ret;
4634 
4635 	return vfs_move_mount(&from_path, &to_path, mflags);
4636 }
4637 
4638 /*
4639  * Return true if path is reachable from root
4640  *
4641  * locks: mount_locked_reader || namespace_shared && is_mounted(mnt)
4642  */
is_path_reachable(struct mount * mnt,struct dentry * dentry,const struct path * root)4643 bool is_path_reachable(struct mount *mnt, struct dentry *dentry,
4644 			 const struct path *root)
4645 {
4646 	while (&mnt->mnt != root->mnt && mnt_has_parent(mnt)) {
4647 		dentry = mnt->mnt_mountpoint;
4648 		mnt = mnt->mnt_parent;
4649 	}
4650 	return &mnt->mnt == root->mnt && is_subdir(dentry, root->dentry);
4651 }
4652 
path_is_under(const struct path * path1,const struct path * path2)4653 bool path_is_under(const struct path *path1, const struct path *path2)
4654 {
4655 	guard(mount_locked_reader)();
4656 	return is_path_reachable(real_mount(path1->mnt), path1->dentry, path2);
4657 }
4658 EXPORT_SYMBOL(path_is_under);
4659 
path_pivot_root(struct path * new,struct path * old)4660 int path_pivot_root(struct path *new, struct path *old)
4661 {
4662 	struct path root __free(path_put) = {};
4663 	struct mount *new_mnt, *root_mnt, *old_mnt, *root_parent, *ex_parent;
4664 	int error;
4665 
4666 	if (!may_mount())
4667 		return -EPERM;
4668 
4669 	error = security_sb_pivotroot(old, new);
4670 	if (error)
4671 		return error;
4672 
4673 	get_fs_root(current->fs, &root);
4674 
4675 	LOCK_MOUNT(old_mp, old);
4676 	old_mnt = old_mp.parent;
4677 	if (IS_ERR(old_mnt))
4678 		return PTR_ERR(old_mnt);
4679 
4680 	new_mnt = real_mount(new->mnt);
4681 	root_mnt = real_mount(root.mnt);
4682 	ex_parent = new_mnt->mnt_parent;
4683 	root_parent = root_mnt->mnt_parent;
4684 	if (IS_MNT_SHARED(old_mnt) ||
4685 		IS_MNT_SHARED(ex_parent) ||
4686 		IS_MNT_SHARED(root_parent))
4687 		return -EINVAL;
4688 	if (!check_mnt(root_mnt) || !check_mnt(new_mnt))
4689 		return -EINVAL;
4690 	if (new_mnt->mnt.mnt_flags & MNT_LOCKED)
4691 		return -EINVAL;
4692 	if (d_unlinked(new->dentry))
4693 		return -ENOENT;
4694 	if (new_mnt == root_mnt || old_mnt == root_mnt)
4695 		return -EBUSY; /* loop, on the same file system  */
4696 	if (!path_mounted(&root))
4697 		return -EINVAL; /* not a mountpoint */
4698 	if (!mnt_has_parent(root_mnt))
4699 		return -EINVAL; /* absolute root */
4700 	if (!path_mounted(new))
4701 		return -EINVAL; /* not a mountpoint */
4702 	if (!mnt_has_parent(new_mnt))
4703 		return -EINVAL; /* absolute root */
4704 	/* make sure we can reach put_old from new_root */
4705 	if (!is_path_reachable(old_mnt, old_mp.mp->m_dentry, new))
4706 		return -EINVAL;
4707 	/* make certain new is below the root */
4708 	if (!is_path_reachable(new_mnt, new->dentry, &root))
4709 		return -EINVAL;
4710 	lock_mount_hash();
4711 	umount_mnt(new_mnt);
4712 	if (root_mnt->mnt.mnt_flags & MNT_LOCKED) {
4713 		new_mnt->mnt.mnt_flags |= MNT_LOCKED;
4714 		root_mnt->mnt.mnt_flags &= ~MNT_LOCKED;
4715 	}
4716 	/* mount new_root on / */
4717 	attach_mnt(new_mnt, root_parent, root_mnt->mnt_mp);
4718 	umount_mnt(root_mnt);
4719 	/* mount old root on put_old */
4720 	attach_mnt(root_mnt, old_mnt, old_mp.mp);
4721 	touch_mnt_namespace(current->nsproxy->mnt_ns);
4722 	/* A moved mount should not expire automatically */
4723 	list_del_init(&new_mnt->mnt_expire);
4724 	unlock_mount_hash();
4725 	mnt_notify_add(root_mnt);
4726 	mnt_notify_add(new_mnt);
4727 	chroot_fs_refs(&root, new);
4728 	return 0;
4729 }
4730 
4731 /*
4732  * pivot_root Semantics:
4733  * Moves the root file system of the current process to the directory put_old,
4734  * makes new_root as the new root file system of the current process, and sets
4735  * root/cwd of all processes which had them on the current root to new_root.
4736  *
4737  * Restrictions:
4738  * The new_root and put_old must be directories, and  must not be on the
4739  * same file  system as the current process root. The put_old  must  be
4740  * underneath new_root,  i.e. adding a non-zero number of /.. to the string
4741  * pointed to by put_old must yield the same directory as new_root. No other
4742  * file system may be mounted on put_old. After all, new_root is a mountpoint.
4743  *
4744  * The immutable nullfs filesystem is mounted as the true root of the VFS
4745  * hierarchy. The mutable rootfs (tmpfs/ramfs) is layered on top of this,
4746  * allowing pivot_root() to work normally from initramfs.
4747  *
4748  * Notes:
4749  *  - we don't move root/cwd if they are not at the root (reason: if something
4750  *    cared enough to change them, it's probably wrong to force them elsewhere)
4751  *  - it's okay to pick a root that isn't the root of a file system, e.g.
4752  *    /nfs/my_root where /nfs is the mount point. It must be a mountpoint,
4753  *    though, so you may need to say mount --bind /nfs/my_root /nfs/my_root
4754  *    first.
4755  */
SYSCALL_DEFINE2(pivot_root,const char __user *,new_root,const char __user *,put_old)4756 SYSCALL_DEFINE2(pivot_root, const char __user *, new_root,
4757 		const char __user *, put_old)
4758 {
4759 	struct path new __free(path_put) = {};
4760 	struct path old __free(path_put) = {};
4761 	int error;
4762 
4763 	error = user_path_at(AT_FDCWD, new_root,
4764 			     LOOKUP_FOLLOW | LOOKUP_DIRECTORY, &new);
4765 	if (error)
4766 		return error;
4767 
4768 	error = user_path_at(AT_FDCWD, put_old,
4769 			     LOOKUP_FOLLOW | LOOKUP_DIRECTORY, &old);
4770 	if (error)
4771 		return error;
4772 
4773 	return path_pivot_root(&new, &old);
4774 }
4775 
recalc_flags(struct mount_kattr * kattr,struct mount * mnt)4776 static unsigned int recalc_flags(struct mount_kattr *kattr, struct mount *mnt)
4777 {
4778 	unsigned int flags = mnt->mnt.mnt_flags;
4779 
4780 	/*  flags to clear */
4781 	flags &= ~kattr->attr_clr;
4782 	/* flags to raise */
4783 	flags |= kattr->attr_set;
4784 
4785 	return flags;
4786 }
4787 
can_idmap_mount(const struct mount_kattr * kattr,struct mount * mnt)4788 static int can_idmap_mount(const struct mount_kattr *kattr, struct mount *mnt)
4789 {
4790 	struct vfsmount *m = &mnt->mnt;
4791 	struct user_namespace *fs_userns = m->mnt_sb->s_user_ns;
4792 
4793 	if (!kattr->mnt_idmap)
4794 		return 0;
4795 
4796 	/*
4797 	 * Creating an idmapped mount with the filesystem wide idmapping
4798 	 * doesn't make sense so block that. We don't allow mushy semantics.
4799 	 */
4800 	if (kattr->mnt_userns == m->mnt_sb->s_user_ns)
4801 		return -EINVAL;
4802 
4803 	/*
4804 	 * We only allow an mount to change it's idmapping if it has
4805 	 * never been accessible to userspace.
4806 	 */
4807 	if (!(kattr->kflags & MOUNT_KATTR_IDMAP_REPLACE) && is_idmapped_mnt(m))
4808 		return -EPERM;
4809 
4810 	/* The underlying filesystem doesn't support idmapped mounts yet. */
4811 	if (!(m->mnt_sb->s_type->fs_flags & FS_ALLOW_IDMAP))
4812 		return -EINVAL;
4813 
4814 	/* The filesystem has turned off idmapped mounts. */
4815 	if (m->mnt_sb->s_iflags & SB_I_NOIDMAP)
4816 		return -EINVAL;
4817 
4818 	/* We're not controlling the superblock. */
4819 	if (!ns_capable(fs_userns, CAP_SYS_ADMIN))
4820 		return -EPERM;
4821 
4822 	/* Mount has already been visible in the filesystem hierarchy. */
4823 	if (!is_anon_ns(mnt->mnt_ns))
4824 		return -EINVAL;
4825 
4826 	return 0;
4827 }
4828 
4829 /**
4830  * mnt_allow_writers() - check whether the attribute change allows writers
4831  * @kattr: the new mount attributes
4832  * @mnt: the mount to which @kattr will be applied
4833  *
4834  * Check whether thew new mount attributes in @kattr allow concurrent writers.
4835  *
4836  * Return: true if writers need to be held, false if not
4837  */
mnt_allow_writers(const struct mount_kattr * kattr,const struct mount * mnt)4838 static inline bool mnt_allow_writers(const struct mount_kattr *kattr,
4839 				     const struct mount *mnt)
4840 {
4841 	return (!(kattr->attr_set & MNT_READONLY) ||
4842 		(mnt->mnt.mnt_flags & MNT_READONLY)) &&
4843 	       !kattr->mnt_idmap;
4844 }
4845 
mount_setattr_prepare(struct mount_kattr * kattr,struct mount * mnt)4846 static int mount_setattr_prepare(struct mount_kattr *kattr, struct mount *mnt)
4847 {
4848 	struct mount *m;
4849 	int err;
4850 
4851 	for (m = mnt; m; m = next_mnt(m, mnt)) {
4852 		if (!can_change_locked_flags(m, recalc_flags(kattr, m))) {
4853 			err = -EPERM;
4854 			break;
4855 		}
4856 
4857 		err = can_idmap_mount(kattr, m);
4858 		if (err)
4859 			break;
4860 
4861 		if (!mnt_allow_writers(kattr, m)) {
4862 			err = mnt_hold_writers(m);
4863 			if (err) {
4864 				m = next_mnt(m, mnt);
4865 				break;
4866 			}
4867 		}
4868 
4869 		if (!(kattr->kflags & MOUNT_KATTR_RECURSE))
4870 			return 0;
4871 	}
4872 
4873 	if (err) {
4874 		/* undo all mnt_hold_writers() we'd done */
4875 		for (struct mount *p = mnt; p != m; p = next_mnt(p, mnt))
4876 			mnt_unhold_writers(p);
4877 	}
4878 	return err;
4879 }
4880 
do_idmap_mount(const struct mount_kattr * kattr,struct mount * mnt)4881 static void do_idmap_mount(const struct mount_kattr *kattr, struct mount *mnt)
4882 {
4883 	struct mnt_idmap *old_idmap;
4884 
4885 	if (!kattr->mnt_idmap)
4886 		return;
4887 
4888 	old_idmap = mnt_idmap(&mnt->mnt);
4889 
4890 	/* Pairs with smp_load_acquire() in mnt_idmap(). */
4891 	smp_store_release(&mnt->mnt.mnt_idmap, mnt_idmap_get(kattr->mnt_idmap));
4892 	mnt_idmap_put(old_idmap);
4893 }
4894 
mount_setattr_commit(struct mount_kattr * kattr,struct mount * mnt)4895 static void mount_setattr_commit(struct mount_kattr *kattr, struct mount *mnt)
4896 {
4897 	struct mount *m;
4898 
4899 	for (m = mnt; m; m = next_mnt(m, mnt)) {
4900 		unsigned int flags;
4901 
4902 		do_idmap_mount(kattr, m);
4903 		flags = recalc_flags(kattr, m);
4904 		WRITE_ONCE(m->mnt.mnt_flags, flags);
4905 
4906 		/* If we had to hold writers unblock them. */
4907 		mnt_unhold_writers(m);
4908 
4909 		if (kattr->propagation)
4910 			change_mnt_propagation(m, kattr->propagation);
4911 		if (!(kattr->kflags & MOUNT_KATTR_RECURSE))
4912 			break;
4913 	}
4914 	touch_mnt_namespace(mnt->mnt_ns);
4915 }
4916 
do_mount_setattr(const struct path * path,struct mount_kattr * kattr)4917 static int do_mount_setattr(const struct path *path, struct mount_kattr *kattr)
4918 {
4919 	struct mount *mnt = real_mount(path->mnt);
4920 	int err = 0;
4921 
4922 	if (!path_mounted(path))
4923 		return -EINVAL;
4924 
4925 	if (kattr->mnt_userns) {
4926 		struct mnt_idmap *mnt_idmap;
4927 
4928 		mnt_idmap = alloc_mnt_idmap(kattr->mnt_userns);
4929 		if (IS_ERR(mnt_idmap))
4930 			return PTR_ERR(mnt_idmap);
4931 		kattr->mnt_idmap = mnt_idmap;
4932 	}
4933 
4934 	if (kattr->propagation) {
4935 		/*
4936 		 * Only take namespace_lock() if we're actually changing
4937 		 * propagation.
4938 		 */
4939 		namespace_lock();
4940 		if (kattr->propagation == MS_SHARED) {
4941 			err = invent_group_ids(mnt, kattr->kflags & MOUNT_KATTR_RECURSE);
4942 			if (err) {
4943 				namespace_unlock();
4944 				return err;
4945 			}
4946 		}
4947 	}
4948 
4949 	err = -EINVAL;
4950 	lock_mount_hash();
4951 
4952 	if (!anon_ns_root(mnt) && !check_mnt(mnt))
4953 		goto out;
4954 
4955 	/*
4956 	 * First, we get the mount tree in a shape where we can change mount
4957 	 * properties without failure. If we succeeded to do so we commit all
4958 	 * changes and if we failed we clean up.
4959 	 */
4960 	err = mount_setattr_prepare(kattr, mnt);
4961 	if (!err)
4962 		mount_setattr_commit(kattr, mnt);
4963 
4964 out:
4965 	unlock_mount_hash();
4966 
4967 	if (kattr->propagation) {
4968 		if (err)
4969 			cleanup_group_ids(mnt, NULL);
4970 		namespace_unlock();
4971 	}
4972 
4973 	return err;
4974 }
4975 
build_mount_idmapped(const struct mount_attr * attr,size_t usize,struct mount_kattr * kattr)4976 static int build_mount_idmapped(const struct mount_attr *attr, size_t usize,
4977 				struct mount_kattr *kattr)
4978 {
4979 	struct ns_common *ns;
4980 	struct user_namespace *mnt_userns;
4981 
4982 	if (!((attr->attr_set | attr->attr_clr) & MOUNT_ATTR_IDMAP))
4983 		return 0;
4984 
4985 	if (attr->attr_clr & MOUNT_ATTR_IDMAP) {
4986 		/*
4987 		 * We can only remove an idmapping if it's never been
4988 		 * exposed to userspace.
4989 		 */
4990 		if (!(kattr->kflags & MOUNT_KATTR_IDMAP_REPLACE))
4991 			return -EINVAL;
4992 
4993 		/*
4994 		 * Removal of idmappings is equivalent to setting
4995 		 * nop_mnt_idmap.
4996 		 */
4997 		if (!(attr->attr_set & MOUNT_ATTR_IDMAP)) {
4998 			kattr->mnt_idmap = &nop_mnt_idmap;
4999 			return 0;
5000 		}
5001 	}
5002 
5003 	if (attr->userns_fd > INT_MAX)
5004 		return -EINVAL;
5005 
5006 	CLASS(fd, f)(attr->userns_fd);
5007 	if (fd_empty(f))
5008 		return -EBADF;
5009 
5010 	if (!proc_ns_file(fd_file(f)))
5011 		return -EINVAL;
5012 
5013 	ns = get_proc_ns(file_inode(fd_file(f)));
5014 	if (ns->ns_type != CLONE_NEWUSER)
5015 		return -EINVAL;
5016 
5017 	/*
5018 	 * The initial idmapping cannot be used to create an idmapped
5019 	 * mount. We use the initial idmapping as an indicator of a mount
5020 	 * that is not idmapped. It can simply be passed into helpers that
5021 	 * are aware of idmapped mounts as a convenient shortcut. A user
5022 	 * can just create a dedicated identity mapping to achieve the same
5023 	 * result.
5024 	 */
5025 	mnt_userns = container_of(ns, struct user_namespace, ns);
5026 	if (mnt_userns == &init_user_ns)
5027 		return -EPERM;
5028 
5029 	/* We're not controlling the target namespace. */
5030 	if (!ns_capable(mnt_userns, CAP_SYS_ADMIN))
5031 		return -EPERM;
5032 
5033 	kattr->mnt_userns = get_user_ns(mnt_userns);
5034 	return 0;
5035 }
5036 
build_mount_kattr(const struct mount_attr * attr,size_t usize,struct mount_kattr * kattr)5037 static int build_mount_kattr(const struct mount_attr *attr, size_t usize,
5038 			     struct mount_kattr *kattr)
5039 {
5040 	if (attr->propagation & ~MOUNT_SETATTR_PROPAGATION_FLAGS)
5041 		return -EINVAL;
5042 	if (hweight32(attr->propagation & MOUNT_SETATTR_PROPAGATION_FLAGS) > 1)
5043 		return -EINVAL;
5044 	kattr->propagation = attr->propagation;
5045 
5046 	if ((attr->attr_set | attr->attr_clr) & ~MOUNT_SETATTR_VALID_FLAGS)
5047 		return -EINVAL;
5048 
5049 	kattr->attr_set = attr_flags_to_mnt_flags(attr->attr_set);
5050 	kattr->attr_clr = attr_flags_to_mnt_flags(attr->attr_clr);
5051 
5052 	/*
5053 	 * Since the MOUNT_ATTR_<atime> values are an enum, not a bitmap,
5054 	 * users wanting to transition to a different atime setting cannot
5055 	 * simply specify the atime setting in @attr_set, but must also
5056 	 * specify MOUNT_ATTR__ATIME in the @attr_clr field.
5057 	 * So ensure that MOUNT_ATTR__ATIME can't be partially set in
5058 	 * @attr_clr and that @attr_set can't have any atime bits set if
5059 	 * MOUNT_ATTR__ATIME isn't set in @attr_clr.
5060 	 */
5061 	if (attr->attr_clr & MOUNT_ATTR__ATIME) {
5062 		if ((attr->attr_clr & MOUNT_ATTR__ATIME) != MOUNT_ATTR__ATIME)
5063 			return -EINVAL;
5064 
5065 		/*
5066 		 * Clear all previous time settings as they are mutually
5067 		 * exclusive.
5068 		 */
5069 		kattr->attr_clr |= MNT_RELATIME | MNT_NOATIME;
5070 		switch (attr->attr_set & MOUNT_ATTR__ATIME) {
5071 		case MOUNT_ATTR_RELATIME:
5072 			kattr->attr_set |= MNT_RELATIME;
5073 			break;
5074 		case MOUNT_ATTR_NOATIME:
5075 			kattr->attr_set |= MNT_NOATIME;
5076 			break;
5077 		case MOUNT_ATTR_STRICTATIME:
5078 			break;
5079 		default:
5080 			return -EINVAL;
5081 		}
5082 	} else {
5083 		if (attr->attr_set & MOUNT_ATTR__ATIME)
5084 			return -EINVAL;
5085 	}
5086 
5087 	return build_mount_idmapped(attr, usize, kattr);
5088 }
5089 
finish_mount_kattr(struct mount_kattr * kattr)5090 static void finish_mount_kattr(struct mount_kattr *kattr)
5091 {
5092 	if (kattr->mnt_userns) {
5093 		put_user_ns(kattr->mnt_userns);
5094 		kattr->mnt_userns = NULL;
5095 	}
5096 
5097 	if (kattr->mnt_idmap)
5098 		mnt_idmap_put(kattr->mnt_idmap);
5099 }
5100 
wants_mount_setattr(struct mount_attr __user * uattr,size_t usize,struct mount_kattr * kattr)5101 static int wants_mount_setattr(struct mount_attr __user *uattr, size_t usize,
5102 			       struct mount_kattr *kattr)
5103 {
5104 	int ret;
5105 	struct mount_attr attr;
5106 
5107 	BUILD_BUG_ON(sizeof(struct mount_attr) != MOUNT_ATTR_SIZE_VER0);
5108 
5109 	if (unlikely(usize > PAGE_SIZE))
5110 		return -E2BIG;
5111 	if (unlikely(usize < MOUNT_ATTR_SIZE_VER0))
5112 		return -EINVAL;
5113 
5114 	if (!may_mount())
5115 		return -EPERM;
5116 
5117 	ret = copy_struct_from_user(&attr, sizeof(attr), uattr, usize);
5118 	if (ret)
5119 		return ret;
5120 
5121 	/* Don't bother walking through the mounts if this is a nop. */
5122 	if (attr.attr_set == 0 &&
5123 	    attr.attr_clr == 0 &&
5124 	    attr.propagation == 0)
5125 		return 0; /* Tell caller to not bother. */
5126 
5127 	ret = build_mount_kattr(&attr, usize, kattr);
5128 	if (ret < 0)
5129 		return ret;
5130 
5131 	return 1;
5132 }
5133 
SYSCALL_DEFINE5(mount_setattr,int,dfd,const char __user *,path,unsigned int,flags,struct mount_attr __user *,uattr,size_t,usize)5134 SYSCALL_DEFINE5(mount_setattr, int, dfd, const char __user *, path,
5135 		unsigned int, flags, struct mount_attr __user *, uattr,
5136 		size_t, usize)
5137 {
5138 	int err;
5139 	struct path target;
5140 	struct mount_kattr kattr;
5141 	unsigned int lookup_flags = LOOKUP_AUTOMOUNT | LOOKUP_FOLLOW;
5142 
5143 	if (flags & ~(AT_EMPTY_PATH |
5144 		      AT_RECURSIVE |
5145 		      AT_SYMLINK_NOFOLLOW |
5146 		      AT_NO_AUTOMOUNT))
5147 		return -EINVAL;
5148 
5149 	if (flags & AT_NO_AUTOMOUNT)
5150 		lookup_flags &= ~LOOKUP_AUTOMOUNT;
5151 	if (flags & AT_SYMLINK_NOFOLLOW)
5152 		lookup_flags &= ~LOOKUP_FOLLOW;
5153 
5154 	kattr = (struct mount_kattr) {
5155 		.lookup_flags	= lookup_flags,
5156 	};
5157 
5158 	if (flags & AT_RECURSIVE)
5159 		kattr.kflags |= MOUNT_KATTR_RECURSE;
5160 
5161 	err = wants_mount_setattr(uattr, usize, &kattr);
5162 	if (err <= 0)
5163 		return err;
5164 
5165 	CLASS(filename_uflags, name)(path, flags);
5166 	err = filename_lookup(dfd, name, kattr.lookup_flags, &target, NULL);
5167 	if (!err) {
5168 		err = do_mount_setattr(&target, &kattr);
5169 		path_put(&target);
5170 	}
5171 	finish_mount_kattr(&kattr);
5172 	return err;
5173 }
5174 
SYSCALL_DEFINE5(open_tree_attr,int,dfd,const char __user *,filename,unsigned,flags,struct mount_attr __user *,uattr,size_t,usize)5175 SYSCALL_DEFINE5(open_tree_attr, int, dfd, const char __user *, filename,
5176 		unsigned, flags, struct mount_attr __user *, uattr,
5177 		size_t, usize)
5178 {
5179 	if (!uattr && usize)
5180 		return -EINVAL;
5181 
5182 	FD_PREPARE(fdf, flags, vfs_open_tree(dfd, filename, flags));
5183 	if (fdf.err)
5184 		return fdf.err;
5185 
5186 	if (uattr) {
5187 		struct mount_kattr kattr = {};
5188 		struct file *file = fd_prepare_file(fdf);
5189 		int ret;
5190 
5191 		if (flags & OPEN_TREE_CLONE)
5192 			kattr.kflags = MOUNT_KATTR_IDMAP_REPLACE;
5193 		if (flags & AT_RECURSIVE)
5194 			kattr.kflags |= MOUNT_KATTR_RECURSE;
5195 
5196 		ret = wants_mount_setattr(uattr, usize, &kattr);
5197 		if (ret > 0) {
5198 			ret = do_mount_setattr(&file->f_path, &kattr);
5199 			finish_mount_kattr(&kattr);
5200 		}
5201 		if (ret)
5202 			return ret;
5203 	}
5204 
5205 	return fd_publish(fdf);
5206 }
5207 
show_path(struct seq_file * m,struct dentry * root)5208 int show_path(struct seq_file *m, struct dentry *root)
5209 {
5210 	if (root->d_sb->s_op->show_path)
5211 		return root->d_sb->s_op->show_path(m, root);
5212 
5213 	seq_dentry(m, root, " \t\n\\");
5214 	return 0;
5215 }
5216 
lookup_mnt_in_ns(u64 id,struct mnt_namespace * ns)5217 static struct vfsmount *lookup_mnt_in_ns(u64 id, struct mnt_namespace *ns)
5218 {
5219 	struct mount *mnt = mnt_find_id_at(ns, id);
5220 
5221 	if (!mnt || mnt->mnt_id_unique != id)
5222 		return NULL;
5223 
5224 	return &mnt->mnt;
5225 }
5226 
5227 struct kstatmount {
5228 	struct statmount __user *buf;
5229 	size_t bufsize;
5230 	struct vfsmount *mnt;
5231 	struct mnt_idmap *idmap;
5232 	u64 mask;
5233 	struct path root;
5234 	struct seq_file seq;
5235 
5236 	/* Must be last --ends in a flexible-array member. */
5237 	struct statmount sm;
5238 };
5239 
mnt_to_attr_flags(struct vfsmount * mnt)5240 static u64 mnt_to_attr_flags(struct vfsmount *mnt)
5241 {
5242 	unsigned int mnt_flags = READ_ONCE(mnt->mnt_flags);
5243 	u64 attr_flags = 0;
5244 
5245 	if (mnt_flags & MNT_READONLY)
5246 		attr_flags |= MOUNT_ATTR_RDONLY;
5247 	if (mnt_flags & MNT_NOSUID)
5248 		attr_flags |= MOUNT_ATTR_NOSUID;
5249 	if (mnt_flags & MNT_NODEV)
5250 		attr_flags |= MOUNT_ATTR_NODEV;
5251 	if (mnt_flags & MNT_NOEXEC)
5252 		attr_flags |= MOUNT_ATTR_NOEXEC;
5253 	if (mnt_flags & MNT_NODIRATIME)
5254 		attr_flags |= MOUNT_ATTR_NODIRATIME;
5255 	if (mnt_flags & MNT_NOSYMFOLLOW)
5256 		attr_flags |= MOUNT_ATTR_NOSYMFOLLOW;
5257 
5258 	if (mnt_flags & MNT_NOATIME)
5259 		attr_flags |= MOUNT_ATTR_NOATIME;
5260 	else if (mnt_flags & MNT_RELATIME)
5261 		attr_flags |= MOUNT_ATTR_RELATIME;
5262 	else
5263 		attr_flags |= MOUNT_ATTR_STRICTATIME;
5264 
5265 	if (is_idmapped_mnt(mnt))
5266 		attr_flags |= MOUNT_ATTR_IDMAP;
5267 
5268 	return attr_flags;
5269 }
5270 
mnt_to_propagation_flags(struct mount * m)5271 static u64 mnt_to_propagation_flags(struct mount *m)
5272 {
5273 	u64 propagation = 0;
5274 
5275 	if (IS_MNT_SHARED(m))
5276 		propagation |= MS_SHARED;
5277 	if (IS_MNT_SLAVE(m))
5278 		propagation |= MS_SLAVE;
5279 	if (IS_MNT_UNBINDABLE(m))
5280 		propagation |= MS_UNBINDABLE;
5281 	if (!propagation)
5282 		propagation |= MS_PRIVATE;
5283 
5284 	return propagation;
5285 }
5286 
vfsmount_to_propagation_flags(struct vfsmount * mnt)5287 u64 vfsmount_to_propagation_flags(struct vfsmount *mnt)
5288 {
5289 	return mnt_to_propagation_flags(real_mount(mnt));
5290 }
5291 EXPORT_SYMBOL_GPL(vfsmount_to_propagation_flags);
5292 
statmount_sb_basic(struct kstatmount * s)5293 static void statmount_sb_basic(struct kstatmount *s)
5294 {
5295 	struct super_block *sb = s->mnt->mnt_sb;
5296 
5297 	s->sm.mask |= STATMOUNT_SB_BASIC;
5298 	s->sm.sb_dev_major = MAJOR(sb->s_dev);
5299 	s->sm.sb_dev_minor = MINOR(sb->s_dev);
5300 	s->sm.sb_magic = sb->s_magic;
5301 	s->sm.sb_flags = sb->s_flags & (SB_RDONLY|SB_SYNCHRONOUS|SB_DIRSYNC|SB_LAZYTIME);
5302 }
5303 
statmount_mnt_basic(struct kstatmount * s)5304 static void statmount_mnt_basic(struct kstatmount *s)
5305 {
5306 	struct mount *m = real_mount(s->mnt);
5307 
5308 	s->sm.mask |= STATMOUNT_MNT_BASIC;
5309 	s->sm.mnt_id = m->mnt_id_unique;
5310 	s->sm.mnt_parent_id = m->mnt_parent->mnt_id_unique;
5311 	s->sm.mnt_id_old = m->mnt_id;
5312 	s->sm.mnt_parent_id_old = m->mnt_parent->mnt_id;
5313 	s->sm.mnt_attr = mnt_to_attr_flags(&m->mnt);
5314 	s->sm.mnt_propagation = mnt_to_propagation_flags(m);
5315 	s->sm.mnt_peer_group = m->mnt_group_id;
5316 	s->sm.mnt_master = IS_MNT_SLAVE(m) ? m->mnt_master->mnt_group_id : 0;
5317 }
5318 
statmount_propagate_from(struct kstatmount * s)5319 static void statmount_propagate_from(struct kstatmount *s)
5320 {
5321 	struct mount *m = real_mount(s->mnt);
5322 
5323 	s->sm.mask |= STATMOUNT_PROPAGATE_FROM;
5324 	if (IS_MNT_SLAVE(m))
5325 		s->sm.propagate_from = get_dominating_id(m, &current->fs->root);
5326 }
5327 
statmount_mnt_root(struct kstatmount * s,struct seq_file * seq)5328 static int statmount_mnt_root(struct kstatmount *s, struct seq_file *seq)
5329 {
5330 	int ret;
5331 	size_t start = seq->count;
5332 
5333 	ret = show_path(seq, s->mnt->mnt_root);
5334 	if (ret)
5335 		return ret;
5336 
5337 	if (unlikely(seq_has_overflowed(seq)))
5338 		return -EAGAIN;
5339 
5340 	/*
5341          * Unescape the result. It would be better if supplied string was not
5342          * escaped in the first place, but that's a pretty invasive change.
5343          */
5344 	seq->buf[seq->count] = '\0';
5345 	seq->count = start;
5346 	seq_commit(seq, string_unescape_inplace(seq->buf + start, UNESCAPE_OCTAL));
5347 	return 0;
5348 }
5349 
statmount_mnt_point(struct kstatmount * s,struct seq_file * seq)5350 static int statmount_mnt_point(struct kstatmount *s, struct seq_file *seq)
5351 {
5352 	struct vfsmount *mnt = s->mnt;
5353 	struct path mnt_path = { .dentry = mnt->mnt_root, .mnt = mnt };
5354 	int err;
5355 
5356 	err = seq_path_root(seq, &mnt_path, &s->root, "");
5357 	return err == SEQ_SKIP ? 0 : err;
5358 }
5359 
statmount_fs_type(struct kstatmount * s,struct seq_file * seq)5360 static int statmount_fs_type(struct kstatmount *s, struct seq_file *seq)
5361 {
5362 	struct super_block *sb = s->mnt->mnt_sb;
5363 
5364 	seq_puts(seq, sb->s_type->name);
5365 	return 0;
5366 }
5367 
statmount_fs_subtype(struct kstatmount * s,struct seq_file * seq)5368 static void statmount_fs_subtype(struct kstatmount *s, struct seq_file *seq)
5369 {
5370 	struct super_block *sb = s->mnt->mnt_sb;
5371 
5372 	if (sb->s_subtype)
5373 		seq_puts(seq, sb->s_subtype);
5374 }
5375 
statmount_sb_source(struct kstatmount * s,struct seq_file * seq)5376 static int statmount_sb_source(struct kstatmount *s, struct seq_file *seq)
5377 {
5378 	struct super_block *sb = s->mnt->mnt_sb;
5379 	struct mount *r = real_mount(s->mnt);
5380 
5381 	if (sb->s_op->show_devname) {
5382 		size_t start = seq->count;
5383 		int ret;
5384 
5385 		ret = sb->s_op->show_devname(seq, s->mnt->mnt_root);
5386 		if (ret)
5387 			return ret;
5388 
5389 		if (unlikely(seq_has_overflowed(seq)))
5390 			return -EAGAIN;
5391 
5392 		/* Unescape the result */
5393 		seq->buf[seq->count] = '\0';
5394 		seq->count = start;
5395 		seq_commit(seq, string_unescape_inplace(seq->buf + start, UNESCAPE_OCTAL));
5396 	} else {
5397 		seq_puts(seq, r->mnt_devname);
5398 	}
5399 	return 0;
5400 }
5401 
statmount_mnt_ns_id(struct kstatmount * s,struct mnt_namespace * ns)5402 static void statmount_mnt_ns_id(struct kstatmount *s, struct mnt_namespace *ns)
5403 {
5404 	s->sm.mask |= STATMOUNT_MNT_NS_ID;
5405 	s->sm.mnt_ns_id = ns->ns.ns_id;
5406 }
5407 
statmount_mnt_opts(struct kstatmount * s,struct seq_file * seq)5408 static int statmount_mnt_opts(struct kstatmount *s, struct seq_file *seq)
5409 {
5410 	struct vfsmount *mnt = s->mnt;
5411 	struct super_block *sb = mnt->mnt_sb;
5412 	size_t start = seq->count;
5413 	int err;
5414 
5415 	err = security_sb_show_options(seq, sb);
5416 	if (err)
5417 		return err;
5418 
5419 	if (sb->s_op->show_options) {
5420 		err = sb->s_op->show_options(seq, mnt->mnt_root);
5421 		if (err)
5422 			return err;
5423 	}
5424 
5425 	if (unlikely(seq_has_overflowed(seq)))
5426 		return -EAGAIN;
5427 
5428 	if (seq->count == start)
5429 		return 0;
5430 
5431 	/* skip leading comma */
5432 	memmove(seq->buf + start, seq->buf + start + 1,
5433 		seq->count - start - 1);
5434 	seq->count--;
5435 
5436 	return 0;
5437 }
5438 
statmount_opt_process(struct seq_file * seq,size_t start)5439 static inline int statmount_opt_process(struct seq_file *seq, size_t start)
5440 {
5441 	char *buf_end, *opt_end, *src, *dst;
5442 	int count = 0;
5443 
5444 	if (unlikely(seq_has_overflowed(seq)))
5445 		return -EAGAIN;
5446 
5447 	buf_end = seq->buf + seq->count;
5448 	dst = seq->buf + start;
5449 	src = dst + 1;	/* skip initial comma */
5450 
5451 	if (src >= buf_end) {
5452 		seq->count = start;
5453 		return 0;
5454 	}
5455 
5456 	*buf_end = '\0';
5457 	for (; src < buf_end; src = opt_end + 1) {
5458 		opt_end = strchrnul(src, ',');
5459 		*opt_end = '\0';
5460 		dst += string_unescape(src, dst, 0, UNESCAPE_OCTAL) + 1;
5461 		if (WARN_ON_ONCE(++count == INT_MAX))
5462 			return -EOVERFLOW;
5463 	}
5464 	seq->count = dst - 1 - seq->buf;
5465 	return count;
5466 }
5467 
statmount_opt_array(struct kstatmount * s,struct seq_file * seq)5468 static int statmount_opt_array(struct kstatmount *s, struct seq_file *seq)
5469 {
5470 	struct vfsmount *mnt = s->mnt;
5471 	struct super_block *sb = mnt->mnt_sb;
5472 	size_t start = seq->count;
5473 	int err;
5474 
5475 	if (!sb->s_op->show_options)
5476 		return 0;
5477 
5478 	err = sb->s_op->show_options(seq, mnt->mnt_root);
5479 	if (err)
5480 		return err;
5481 
5482 	err = statmount_opt_process(seq, start);
5483 	if (err < 0)
5484 		return err;
5485 
5486 	s->sm.opt_num = err;
5487 	return 0;
5488 }
5489 
statmount_opt_sec_array(struct kstatmount * s,struct seq_file * seq)5490 static int statmount_opt_sec_array(struct kstatmount *s, struct seq_file *seq)
5491 {
5492 	struct vfsmount *mnt = s->mnt;
5493 	struct super_block *sb = mnt->mnt_sb;
5494 	size_t start = seq->count;
5495 	int err;
5496 
5497 	err = security_sb_show_options(seq, sb);
5498 	if (err)
5499 		return err;
5500 
5501 	err = statmount_opt_process(seq, start);
5502 	if (err < 0)
5503 		return err;
5504 
5505 	s->sm.opt_sec_num = err;
5506 	return 0;
5507 }
5508 
statmount_mnt_uidmap(struct kstatmount * s,struct seq_file * seq)5509 static inline int statmount_mnt_uidmap(struct kstatmount *s, struct seq_file *seq)
5510 {
5511 	int ret;
5512 
5513 	ret = statmount_mnt_idmap(s->idmap, seq, true);
5514 	if (ret < 0)
5515 		return ret;
5516 
5517 	s->sm.mnt_uidmap_num = ret;
5518 	/*
5519 	 * Always raise STATMOUNT_MNT_UIDMAP even if there are no valid
5520 	 * mappings. This allows userspace to distinguish between a
5521 	 * non-idmapped mount and an idmapped mount where none of the
5522 	 * individual mappings are valid in the caller's idmapping.
5523 	 */
5524 	if (is_valid_mnt_idmap(s->idmap))
5525 		s->sm.mask |= STATMOUNT_MNT_UIDMAP;
5526 	return 0;
5527 }
5528 
statmount_mnt_gidmap(struct kstatmount * s,struct seq_file * seq)5529 static inline int statmount_mnt_gidmap(struct kstatmount *s, struct seq_file *seq)
5530 {
5531 	int ret;
5532 
5533 	ret = statmount_mnt_idmap(s->idmap, seq, false);
5534 	if (ret < 0)
5535 		return ret;
5536 
5537 	s->sm.mnt_gidmap_num = ret;
5538 	/*
5539 	 * Always raise STATMOUNT_MNT_GIDMAP even if there are no valid
5540 	 * mappings. This allows userspace to distinguish between a
5541 	 * non-idmapped mount and an idmapped mount where none of the
5542 	 * individual mappings are valid in the caller's idmapping.
5543 	 */
5544 	if (is_valid_mnt_idmap(s->idmap))
5545 		s->sm.mask |= STATMOUNT_MNT_GIDMAP;
5546 	return 0;
5547 }
5548 
statmount_string(struct kstatmount * s,u64 flag)5549 static int statmount_string(struct kstatmount *s, u64 flag)
5550 {
5551 	int ret = 0;
5552 	size_t kbufsize;
5553 	struct seq_file *seq = &s->seq;
5554 	struct statmount *sm = &s->sm;
5555 	u32 start, *offp;
5556 
5557 	/* Reserve an empty string at the beginning for any unset offsets */
5558 	if (!seq->count)
5559 		seq_putc(seq, 0);
5560 
5561 	start = seq->count;
5562 
5563 	switch (flag) {
5564 	case STATMOUNT_FS_TYPE:
5565 		offp = &sm->fs_type;
5566 		ret = statmount_fs_type(s, seq);
5567 		break;
5568 	case STATMOUNT_MNT_ROOT:
5569 		offp = &sm->mnt_root;
5570 		ret = statmount_mnt_root(s, seq);
5571 		break;
5572 	case STATMOUNT_MNT_POINT:
5573 		offp = &sm->mnt_point;
5574 		ret = statmount_mnt_point(s, seq);
5575 		break;
5576 	case STATMOUNT_MNT_OPTS:
5577 		offp = &sm->mnt_opts;
5578 		ret = statmount_mnt_opts(s, seq);
5579 		break;
5580 	case STATMOUNT_OPT_ARRAY:
5581 		offp = &sm->opt_array;
5582 		ret = statmount_opt_array(s, seq);
5583 		break;
5584 	case STATMOUNT_OPT_SEC_ARRAY:
5585 		offp = &sm->opt_sec_array;
5586 		ret = statmount_opt_sec_array(s, seq);
5587 		break;
5588 	case STATMOUNT_FS_SUBTYPE:
5589 		offp = &sm->fs_subtype;
5590 		statmount_fs_subtype(s, seq);
5591 		break;
5592 	case STATMOUNT_SB_SOURCE:
5593 		offp = &sm->sb_source;
5594 		ret = statmount_sb_source(s, seq);
5595 		break;
5596 	case STATMOUNT_MNT_UIDMAP:
5597 		offp = &sm->mnt_uidmap;
5598 		ret = statmount_mnt_uidmap(s, seq);
5599 		break;
5600 	case STATMOUNT_MNT_GIDMAP:
5601 		offp = &sm->mnt_gidmap;
5602 		ret = statmount_mnt_gidmap(s, seq);
5603 		break;
5604 	default:
5605 		WARN_ON_ONCE(true);
5606 		return -EINVAL;
5607 	}
5608 
5609 	/*
5610 	 * If nothing was emitted, return to avoid setting the flag
5611 	 * and terminating the buffer.
5612 	 */
5613 	if (seq->count == start)
5614 		return ret;
5615 	if (unlikely(check_add_overflow(sizeof(*sm), seq->count, &kbufsize)))
5616 		return -EOVERFLOW;
5617 	if (kbufsize >= s->bufsize)
5618 		return -EOVERFLOW;
5619 
5620 	/* signal a retry */
5621 	if (unlikely(seq_has_overflowed(seq)))
5622 		return -EAGAIN;
5623 
5624 	if (ret)
5625 		return ret;
5626 
5627 	seq->buf[seq->count++] = '\0';
5628 	sm->mask |= flag;
5629 	*offp = start;
5630 	return 0;
5631 }
5632 
copy_statmount_to_user(struct kstatmount * s)5633 static int copy_statmount_to_user(struct kstatmount *s)
5634 {
5635 	struct statmount *sm = &s->sm;
5636 	struct seq_file *seq = &s->seq;
5637 	char __user *str = ((char __user *)s->buf) + sizeof(*sm);
5638 	size_t copysize = min_t(size_t, s->bufsize, sizeof(*sm));
5639 
5640 	if (seq->count && copy_to_user(str, seq->buf, seq->count))
5641 		return -EFAULT;
5642 
5643 	/* Return the number of bytes copied to the buffer */
5644 	sm->size = copysize + seq->count;
5645 	if (copy_to_user(s->buf, sm, copysize))
5646 		return -EFAULT;
5647 
5648 	return 0;
5649 }
5650 
listmnt_next(struct mount * curr,bool reverse)5651 static struct mount *listmnt_next(struct mount *curr, bool reverse)
5652 {
5653 	struct rb_node *node;
5654 
5655 	if (reverse)
5656 		node = rb_prev(&curr->mnt_node);
5657 	else
5658 		node = rb_next(&curr->mnt_node);
5659 
5660 	return node_to_mount(node);
5661 }
5662 
grab_requested_root(struct mnt_namespace * ns,struct path * root)5663 static int grab_requested_root(struct mnt_namespace *ns, struct path *root)
5664 {
5665 	struct mount *first, *child;
5666 
5667 	rwsem_assert_held(&namespace_sem);
5668 
5669 	/* We're looking at our own ns, just use get_fs_root. */
5670 	if (ns == current->nsproxy->mnt_ns) {
5671 		get_fs_root(current->fs, root);
5672 		return 0;
5673 	}
5674 
5675 	/*
5676 	 * We have to find the first mount in our ns and use that, however it
5677 	 * may not exist, so handle that properly.
5678 	 */
5679 	if (mnt_ns_empty(ns))
5680 		return -ENOENT;
5681 
5682 	first = ns->root;
5683 	for (child = node_to_mount(ns->mnt_first_node); child;
5684 	     child = listmnt_next(child, false)) {
5685 		if (child != first && child->mnt_parent == first)
5686 			break;
5687 	}
5688 	if (!child)
5689 		return -ENOENT;
5690 
5691 	root->mnt = mntget(&child->mnt);
5692 	root->dentry = dget(root->mnt->mnt_root);
5693 	return 0;
5694 }
5695 
5696 /* This must be updated whenever a new flag is added */
5697 #define STATMOUNT_SUPPORTED (STATMOUNT_SB_BASIC | \
5698 			     STATMOUNT_MNT_BASIC | \
5699 			     STATMOUNT_PROPAGATE_FROM | \
5700 			     STATMOUNT_MNT_ROOT | \
5701 			     STATMOUNT_MNT_POINT | \
5702 			     STATMOUNT_FS_TYPE | \
5703 			     STATMOUNT_MNT_NS_ID | \
5704 			     STATMOUNT_MNT_OPTS | \
5705 			     STATMOUNT_FS_SUBTYPE | \
5706 			     STATMOUNT_SB_SOURCE | \
5707 			     STATMOUNT_OPT_ARRAY | \
5708 			     STATMOUNT_OPT_SEC_ARRAY | \
5709 			     STATMOUNT_SUPPORTED_MASK | \
5710 			     STATMOUNT_MNT_UIDMAP | \
5711 			     STATMOUNT_MNT_GIDMAP)
5712 
5713 /* locks: namespace_shared */
do_statmount(struct kstatmount * s,u64 mnt_id,u64 mnt_ns_id,struct file * mnt_file,struct mnt_namespace * ns)5714 static int do_statmount(struct kstatmount *s, u64 mnt_id, u64 mnt_ns_id,
5715                         struct file *mnt_file, struct mnt_namespace *ns)
5716 {
5717 	int err;
5718 
5719 	if (mnt_file) {
5720 		WARN_ON_ONCE(ns != NULL);
5721 
5722 		s->mnt = mnt_file->f_path.mnt;
5723 		ns = real_mount(s->mnt)->mnt_ns;
5724 		if (IS_ERR(ns))
5725 			return PTR_ERR(ns);
5726 		if (!ns)
5727 			/*
5728 			 * We can't set mount point and mnt_ns_id since we don't have a
5729 			 * ns for the mount. This can happen if the mount is unmounted
5730 			 * with MNT_DETACH.
5731 			 */
5732 			s->mask &= ~(STATMOUNT_MNT_POINT | STATMOUNT_MNT_NS_ID);
5733 	} else {
5734 		/* Has the namespace already been emptied? */
5735 		if (mnt_ns_id && mnt_ns_empty(ns))
5736 			return -ENOENT;
5737 
5738 		s->mnt = lookup_mnt_in_ns(mnt_id, ns);
5739 		if (!s->mnt)
5740 			return -ENOENT;
5741 	}
5742 
5743 	if (ns) {
5744 		err = grab_requested_root(ns, &s->root);
5745 		if (err)
5746 			return err;
5747 
5748 		if (!mnt_file) {
5749 			struct mount *m;
5750 			/*
5751 			 * Don't trigger audit denials. We just want to determine what
5752 			 * mounts to show users.
5753 			 */
5754 			m = real_mount(s->mnt);
5755 			if (!is_path_reachable(m, m->mnt.mnt_root, &s->root) &&
5756 			    !ns_capable_noaudit(ns->user_ns, CAP_SYS_ADMIN))
5757 				return -EPERM;
5758 		}
5759 	}
5760 
5761 	err = security_sb_statfs(s->mnt->mnt_root);
5762 	if (err)
5763 		return err;
5764 
5765 	/*
5766 	 * Note that mount properties in mnt->mnt_flags, mnt->mnt_idmap
5767 	 * can change concurrently as we only hold the read-side of the
5768 	 * namespace semaphore and mount properties may change with only
5769 	 * the mount lock held.
5770 	 *
5771 	 * We could sample the mount lock sequence counter to detect
5772 	 * those changes and retry. But it's not worth it. Worst that
5773 	 * happens is that the mnt->mnt_idmap pointer is already changed
5774 	 * while mnt->mnt_flags isn't or vica versa. So what.
5775 	 *
5776 	 * Both mnt->mnt_flags and mnt->mnt_idmap are set and retrieved
5777 	 * via READ_ONCE()/WRITE_ONCE() and guard against theoretical
5778 	 * torn read/write. That's all we care about right now.
5779 	 */
5780 	s->idmap = mnt_idmap(s->mnt);
5781 	if (s->mask & STATMOUNT_MNT_BASIC)
5782 		statmount_mnt_basic(s);
5783 
5784 	if (s->mask & STATMOUNT_SB_BASIC)
5785 		statmount_sb_basic(s);
5786 
5787 	if (s->mask & STATMOUNT_PROPAGATE_FROM)
5788 		statmount_propagate_from(s);
5789 
5790 	if (s->mask & STATMOUNT_FS_TYPE)
5791 		err = statmount_string(s, STATMOUNT_FS_TYPE);
5792 
5793 	if (!err && s->mask & STATMOUNT_MNT_ROOT)
5794 		err = statmount_string(s, STATMOUNT_MNT_ROOT);
5795 
5796 	if (!err && s->mask & STATMOUNT_MNT_POINT)
5797 		err = statmount_string(s, STATMOUNT_MNT_POINT);
5798 
5799 	if (!err && s->mask & STATMOUNT_MNT_OPTS)
5800 		err = statmount_string(s, STATMOUNT_MNT_OPTS);
5801 
5802 	if (!err && s->mask & STATMOUNT_OPT_ARRAY)
5803 		err = statmount_string(s, STATMOUNT_OPT_ARRAY);
5804 
5805 	if (!err && s->mask & STATMOUNT_OPT_SEC_ARRAY)
5806 		err = statmount_string(s, STATMOUNT_OPT_SEC_ARRAY);
5807 
5808 	if (!err && s->mask & STATMOUNT_FS_SUBTYPE)
5809 		err = statmount_string(s, STATMOUNT_FS_SUBTYPE);
5810 
5811 	if (!err && s->mask & STATMOUNT_SB_SOURCE)
5812 		err = statmount_string(s, STATMOUNT_SB_SOURCE);
5813 
5814 	if (!err && s->mask & STATMOUNT_MNT_UIDMAP)
5815 		err = statmount_string(s, STATMOUNT_MNT_UIDMAP);
5816 
5817 	if (!err && s->mask & STATMOUNT_MNT_GIDMAP)
5818 		err = statmount_string(s, STATMOUNT_MNT_GIDMAP);
5819 
5820 	if (!err && s->mask & STATMOUNT_MNT_NS_ID)
5821 		statmount_mnt_ns_id(s, ns);
5822 
5823 	if (!err && s->mask & STATMOUNT_SUPPORTED_MASK) {
5824 		s->sm.mask |= STATMOUNT_SUPPORTED_MASK;
5825 		s->sm.supported_mask = STATMOUNT_SUPPORTED;
5826 	}
5827 
5828 	if (err)
5829 		return err;
5830 
5831 	/* Are there bits in the return mask not present in STATMOUNT_SUPPORTED? */
5832 	WARN_ON_ONCE(~STATMOUNT_SUPPORTED & s->sm.mask);
5833 
5834 	return 0;
5835 }
5836 
retry_statmount(const long ret,size_t * seq_size)5837 static inline bool retry_statmount(const long ret, size_t *seq_size)
5838 {
5839 	if (likely(ret != -EAGAIN))
5840 		return false;
5841 	if (unlikely(check_mul_overflow(*seq_size, 2, seq_size)))
5842 		return false;
5843 	if (unlikely(*seq_size > MAX_RW_COUNT))
5844 		return false;
5845 	return true;
5846 }
5847 
5848 #define STATMOUNT_STRING_REQ (STATMOUNT_MNT_ROOT | STATMOUNT_MNT_POINT | \
5849 			      STATMOUNT_FS_TYPE | STATMOUNT_MNT_OPTS | \
5850 			      STATMOUNT_FS_SUBTYPE | STATMOUNT_SB_SOURCE | \
5851 			      STATMOUNT_OPT_ARRAY | STATMOUNT_OPT_SEC_ARRAY | \
5852 			      STATMOUNT_MNT_UIDMAP | STATMOUNT_MNT_GIDMAP)
5853 
prepare_kstatmount(struct kstatmount * ks,struct mnt_id_req * kreq,struct statmount __user * buf,size_t bufsize,size_t seq_size)5854 static int prepare_kstatmount(struct kstatmount *ks, struct mnt_id_req *kreq,
5855 			      struct statmount __user *buf, size_t bufsize,
5856 			      size_t seq_size)
5857 {
5858 	if (!access_ok(buf, bufsize))
5859 		return -EFAULT;
5860 
5861 	memset(ks, 0, sizeof(*ks));
5862 	ks->mask = kreq->param;
5863 	ks->buf = buf;
5864 	ks->bufsize = bufsize;
5865 
5866 	if (ks->mask & STATMOUNT_STRING_REQ) {
5867 		if (bufsize == sizeof(ks->sm))
5868 			return -EOVERFLOW;
5869 
5870 		ks->seq.buf = kvmalloc(seq_size, GFP_KERNEL_ACCOUNT);
5871 		if (!ks->seq.buf)
5872 			return -ENOMEM;
5873 
5874 		ks->seq.size = seq_size;
5875 	}
5876 
5877 	return 0;
5878 }
5879 
copy_mnt_id_req(const struct mnt_id_req __user * req,struct mnt_id_req * kreq,unsigned int flags)5880 static int copy_mnt_id_req(const struct mnt_id_req __user *req,
5881 			   struct mnt_id_req *kreq, unsigned int flags)
5882 {
5883 	int ret;
5884 	size_t usize;
5885 
5886 	BUILD_BUG_ON(sizeof(struct mnt_id_req) != MNT_ID_REQ_SIZE_VER1);
5887 
5888 	ret = get_user(usize, &req->size);
5889 	if (ret)
5890 		return -EFAULT;
5891 	if (unlikely(usize > PAGE_SIZE))
5892 		return -E2BIG;
5893 	if (unlikely(usize < MNT_ID_REQ_SIZE_VER0))
5894 		return -EINVAL;
5895 	memset(kreq, 0, sizeof(*kreq));
5896 	ret = copy_struct_from_user(kreq, sizeof(*kreq), req, usize);
5897 	if (ret)
5898 		return ret;
5899 
5900 	if (flags & STATMOUNT_BY_FD) {
5901 		if (kreq->mnt_id || kreq->mnt_ns_id)
5902 			return -EINVAL;
5903 	} else {
5904 		if (kreq->mnt_ns_fd != 0 && kreq->mnt_ns_id)
5905 			return -EINVAL;
5906 		/* The first valid unique mount id is MNT_UNIQUE_ID_OFFSET + 1. */
5907 		if (kreq->mnt_id <= MNT_UNIQUE_ID_OFFSET)
5908 			return -EINVAL;
5909 	}
5910 	return 0;
5911 }
5912 
5913 /*
5914  * If the user requested a specific mount namespace id, look that up and return
5915  * that, or if not simply grab a passive reference on our mount namespace and
5916  * return that.
5917  */
grab_requested_mnt_ns(const struct mnt_id_req * kreq)5918 static struct mnt_namespace *grab_requested_mnt_ns(const struct mnt_id_req *kreq)
5919 {
5920 	struct mnt_namespace *mnt_ns;
5921 
5922 	if (kreq->mnt_ns_id) {
5923 		mnt_ns = lookup_mnt_ns(kreq->mnt_ns_id);
5924 		if (!mnt_ns)
5925 			return ERR_PTR(-ENOENT);
5926 	} else if (kreq->mnt_ns_fd) {
5927 		struct ns_common *ns;
5928 
5929 		CLASS(fd, f)(kreq->mnt_ns_fd);
5930 		if (fd_empty(f))
5931 			return ERR_PTR(-EBADF);
5932 
5933 		if (!proc_ns_file(fd_file(f)))
5934 			return ERR_PTR(-EINVAL);
5935 
5936 		ns = get_proc_ns(file_inode(fd_file(f)));
5937 		if (ns->ns_type != CLONE_NEWNS)
5938 			return ERR_PTR(-EINVAL);
5939 
5940 		mnt_ns = to_mnt_ns(ns);
5941 		refcount_inc(&mnt_ns->passive);
5942 	} else {
5943 		mnt_ns = current->nsproxy->mnt_ns;
5944 		refcount_inc(&mnt_ns->passive);
5945 	}
5946 
5947 	return mnt_ns;
5948 }
5949 
SYSCALL_DEFINE4(statmount,const struct mnt_id_req __user *,req,struct statmount __user *,buf,size_t,bufsize,unsigned int,flags)5950 SYSCALL_DEFINE4(statmount, const struct mnt_id_req __user *, req,
5951 		struct statmount __user *, buf, size_t, bufsize,
5952 		unsigned int, flags)
5953 {
5954 	struct mnt_namespace *ns __free(mnt_ns_release) = NULL;
5955 	struct kstatmount *ks __free(kfree) = NULL;
5956 	struct file *mnt_file __free(fput) = NULL;
5957 	struct mnt_id_req kreq;
5958 	/* We currently support retrieval of 3 strings. */
5959 	size_t seq_size = 3 * PATH_MAX;
5960 	int ret;
5961 
5962 	if (flags & ~STATMOUNT_BY_FD)
5963 		return -EINVAL;
5964 
5965 	ret = copy_mnt_id_req(req, &kreq, flags);
5966 	if (ret)
5967 		return ret;
5968 
5969 	if (flags & STATMOUNT_BY_FD) {
5970 		mnt_file = fget_raw(kreq.mnt_fd);
5971 		if (!mnt_file)
5972 			return -EBADF;
5973 		/* do_statmount sets ns in case of STATMOUNT_BY_FD */
5974 	} else {
5975 		ns = grab_requested_mnt_ns(&kreq);
5976 		if (IS_ERR(ns))
5977 			return PTR_ERR(ns);
5978 
5979 		if (kreq.mnt_ns_id && (ns != current->nsproxy->mnt_ns) &&
5980 		    !ns_capable_noaudit(ns->user_ns, CAP_SYS_ADMIN))
5981 			return -EPERM;
5982 	}
5983 
5984 	ks = kmalloc(sizeof(*ks), GFP_KERNEL_ACCOUNT);
5985 	if (!ks)
5986 		return -ENOMEM;
5987 
5988 retry:
5989 	ret = prepare_kstatmount(ks, &kreq, buf, bufsize, seq_size);
5990 	if (ret)
5991 		return ret;
5992 
5993 	scoped_guard(namespace_shared)
5994 		ret = do_statmount(ks, kreq.mnt_id, kreq.mnt_ns_id, mnt_file, ns);
5995 
5996 	if (!ret)
5997 		ret = copy_statmount_to_user(ks);
5998 	kvfree(ks->seq.buf);
5999 	path_put(&ks->root);
6000 	if (retry_statmount(ret, &seq_size))
6001 		goto retry;
6002 	return ret;
6003 }
6004 
6005 struct klistmount {
6006 	u64 last_mnt_id;
6007 	u64 mnt_parent_id;
6008 	u64 *kmnt_ids;
6009 	u32 nr_mnt_ids;
6010 	struct mnt_namespace *ns;
6011 	struct path root;
6012 };
6013 
6014 /* locks: namespace_shared */
do_listmount(struct klistmount * kls,bool reverse)6015 static ssize_t do_listmount(struct klistmount *kls, bool reverse)
6016 {
6017 	struct mnt_namespace *ns = kls->ns;
6018 	u64 mnt_parent_id = kls->mnt_parent_id;
6019 	u64 last_mnt_id = kls->last_mnt_id;
6020 	u64 *mnt_ids = kls->kmnt_ids;
6021 	size_t nr_mnt_ids = kls->nr_mnt_ids;
6022 	struct path orig;
6023 	struct mount *r, *first;
6024 	ssize_t ret;
6025 
6026 	rwsem_assert_held(&namespace_sem);
6027 
6028 	ret = grab_requested_root(ns, &kls->root);
6029 	if (ret)
6030 		return ret;
6031 
6032 	if (mnt_parent_id == LSMT_ROOT) {
6033 		orig = kls->root;
6034 	} else {
6035 		orig.mnt = lookup_mnt_in_ns(mnt_parent_id, ns);
6036 		if (!orig.mnt)
6037 			return -ENOENT;
6038 		orig.dentry = orig.mnt->mnt_root;
6039 	}
6040 
6041 	/*
6042 	 * Don't trigger audit denials. We just want to determine what
6043 	 * mounts to show users.
6044 	 */
6045 	if (!is_path_reachable(real_mount(orig.mnt), orig.dentry, &kls->root) &&
6046 	    !ns_capable_noaudit(ns->user_ns, CAP_SYS_ADMIN))
6047 		return -EPERM;
6048 
6049 	ret = security_sb_statfs(orig.dentry);
6050 	if (ret)
6051 		return ret;
6052 
6053 	if (!last_mnt_id) {
6054 		if (reverse)
6055 			first = node_to_mount(ns->mnt_last_node);
6056 		else
6057 			first = node_to_mount(ns->mnt_first_node);
6058 	} else {
6059 		if (reverse)
6060 			first = mnt_find_id_at_reverse(ns, last_mnt_id - 1);
6061 		else
6062 			first = mnt_find_id_at(ns, last_mnt_id + 1);
6063 	}
6064 
6065 	for (ret = 0, r = first; r && nr_mnt_ids; r = listmnt_next(r, reverse)) {
6066 		if (r->mnt_id_unique == mnt_parent_id)
6067 			continue;
6068 		if (!is_path_reachable(r, r->mnt.mnt_root, &orig))
6069 			continue;
6070 		*mnt_ids = r->mnt_id_unique;
6071 		mnt_ids++;
6072 		nr_mnt_ids--;
6073 		ret++;
6074 	}
6075 	return ret;
6076 }
6077 
__free_klistmount_free(const struct klistmount * kls)6078 static void __free_klistmount_free(const struct klistmount *kls)
6079 {
6080 	path_put(&kls->root);
6081 	kvfree(kls->kmnt_ids);
6082 	mnt_ns_release(kls->ns);
6083 }
6084 
prepare_klistmount(struct klistmount * kls,struct mnt_id_req * kreq,size_t nr_mnt_ids)6085 static inline int prepare_klistmount(struct klistmount *kls, struct mnt_id_req *kreq,
6086 				     size_t nr_mnt_ids)
6087 {
6088 	u64 last_mnt_id = kreq->param;
6089 	struct mnt_namespace *ns;
6090 
6091 	/* The first valid unique mount id is MNT_UNIQUE_ID_OFFSET + 1. */
6092 	if (last_mnt_id != 0 && last_mnt_id <= MNT_UNIQUE_ID_OFFSET)
6093 		return -EINVAL;
6094 
6095 	kls->last_mnt_id = last_mnt_id;
6096 
6097 	kls->nr_mnt_ids = nr_mnt_ids;
6098 	kls->kmnt_ids = kvmalloc_array(nr_mnt_ids, sizeof(*kls->kmnt_ids),
6099 				       GFP_KERNEL_ACCOUNT);
6100 	if (!kls->kmnt_ids)
6101 		return -ENOMEM;
6102 
6103 	ns = grab_requested_mnt_ns(kreq);
6104 	if (IS_ERR(ns))
6105 		return PTR_ERR(ns);
6106 	kls->ns = ns;
6107 
6108 	kls->mnt_parent_id = kreq->mnt_id;
6109 	return 0;
6110 }
6111 
SYSCALL_DEFINE4(listmount,const struct mnt_id_req __user *,req,u64 __user *,mnt_ids,size_t,nr_mnt_ids,unsigned int,flags)6112 SYSCALL_DEFINE4(listmount, const struct mnt_id_req __user *, req,
6113 		u64 __user *, mnt_ids, size_t, nr_mnt_ids, unsigned int, flags)
6114 {
6115 	struct klistmount kls __free(klistmount_free) = {};
6116 	const size_t maxcount = 1000000;
6117 	struct mnt_id_req kreq;
6118 	ssize_t ret;
6119 
6120 	if (flags & ~LISTMOUNT_REVERSE)
6121 		return -EINVAL;
6122 
6123 	/*
6124 	 * If the mount namespace really has more than 1 million mounts the
6125 	 * caller must iterate over the mount namespace (and reconsider their
6126 	 * system design...).
6127 	 */
6128 	if (unlikely(nr_mnt_ids > maxcount))
6129 		return -EOVERFLOW;
6130 
6131 	if (!access_ok(mnt_ids, nr_mnt_ids * sizeof(*mnt_ids)))
6132 		return -EFAULT;
6133 
6134 	ret = copy_mnt_id_req(req, &kreq, 0);
6135 	if (ret)
6136 		return ret;
6137 
6138 	ret = prepare_klistmount(&kls, &kreq, nr_mnt_ids);
6139 	if (ret)
6140 		return ret;
6141 
6142 	if (kreq.mnt_ns_id && (kls.ns != current->nsproxy->mnt_ns) &&
6143 	    !ns_capable_noaudit(kls.ns->user_ns, CAP_SYS_ADMIN))
6144 		return -ENOENT;
6145 
6146 	/*
6147 	 * We only need to guard against mount topology changes as
6148 	 * listmount() doesn't care about any mount properties.
6149 	 */
6150 	scoped_guard(namespace_shared)
6151 		ret = do_listmount(&kls, (flags & LISTMOUNT_REVERSE));
6152 	if (ret <= 0)
6153 		return ret;
6154 
6155 	if (copy_to_user(mnt_ids, kls.kmnt_ids, ret * sizeof(*mnt_ids)))
6156 		return -EFAULT;
6157 
6158 	return ret;
6159 }
6160 
6161 struct mnt_namespace init_mnt_ns = {
6162 	.ns		= NS_COMMON_INIT(init_mnt_ns),
6163 	.user_ns	= &init_user_ns,
6164 	.passive	= REFCOUNT_INIT(1),
6165 	.mounts		= RB_ROOT,
6166 	.poll		= __WAIT_QUEUE_HEAD_INITIALIZER(init_mnt_ns.poll),
6167 };
6168 
init_mount_tree(void)6169 static void __init init_mount_tree(void)
6170 {
6171 	struct vfsmount *mnt, *nullfs_mnt;
6172 	struct mount *mnt_root;
6173 	struct path root;
6174 
6175 	/*
6176 	 * We create two mounts:
6177 	 *
6178 	 * (1) nullfs with mount id 1
6179 	 * (2) mutable rootfs with mount id 2
6180 	 *
6181 	 * with (2) mounted on top of (1).
6182 	 */
6183 	nullfs_mnt = vfs_kern_mount(&nullfs_fs_type, 0, "nullfs", NULL);
6184 	if (IS_ERR(nullfs_mnt))
6185 		panic("VFS: Failed to create nullfs");
6186 
6187 	mnt = vfs_kern_mount(&rootfs_fs_type, 0, "rootfs", initramfs_options);
6188 	if (IS_ERR(mnt))
6189 		panic("Can't create rootfs");
6190 
6191 	VFS_WARN_ON_ONCE(real_mount(nullfs_mnt)->mnt_id != 1);
6192 	VFS_WARN_ON_ONCE(real_mount(mnt)->mnt_id != 2);
6193 
6194 	/* The namespace root is the nullfs mnt. */
6195 	mnt_root		= real_mount(nullfs_mnt);
6196 	init_mnt_ns.root	= mnt_root;
6197 
6198 	/* Mount mutable rootfs on top of nullfs. */
6199 	root.mnt		= nullfs_mnt;
6200 	root.dentry		= nullfs_mnt->mnt_root;
6201 
6202 	LOCK_MOUNT_EXACT(mp, &root);
6203 	if (unlikely(IS_ERR(mp.parent)))
6204 		panic("VFS: Failed to mount rootfs on nullfs");
6205 	scoped_guard(mount_writer)
6206 		attach_mnt(real_mount(mnt), mp.parent, mp.mp);
6207 
6208 	pr_info("VFS: Finished mounting rootfs on nullfs\n");
6209 
6210 	/*
6211 	 * We've dropped all locks here but that's fine. Not just are we
6212 	 * the only task that's running, there's no other mount
6213 	 * namespace in existence and the initial mount namespace is
6214 	 * completely empty until we add the mounts we just created.
6215 	 */
6216 	for (struct mount *p = mnt_root; p; p = next_mnt(p, mnt_root)) {
6217 		mnt_add_to_ns(&init_mnt_ns, p);
6218 		init_mnt_ns.nr_mounts++;
6219 	}
6220 
6221 	init_task.nsproxy->mnt_ns = &init_mnt_ns;
6222 	get_mnt_ns(&init_mnt_ns);
6223 
6224 	/* The root and pwd always point to the mutable rootfs. */
6225 	root.mnt	= mnt;
6226 	root.dentry	= mnt->mnt_root;
6227 	set_fs_pwd(current->fs, &root);
6228 	set_fs_root(current->fs, &root);
6229 
6230 	ns_tree_add(&init_mnt_ns);
6231 }
6232 
mnt_init(void)6233 void __init mnt_init(void)
6234 {
6235 	int err;
6236 
6237 	mnt_cache = kmem_cache_create("mnt_cache", sizeof(struct mount),
6238 			0, SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT, NULL);
6239 
6240 	mount_hashtable = alloc_large_system_hash("Mount-cache",
6241 				sizeof(struct hlist_head),
6242 				mhash_entries, 19,
6243 				HASH_ZERO,
6244 				&m_hash_shift, &m_hash_mask, 0, 0);
6245 	mountpoint_hashtable = alloc_large_system_hash("Mountpoint-cache",
6246 				sizeof(struct hlist_head),
6247 				mphash_entries, 19,
6248 				HASH_ZERO,
6249 				&mp_hash_shift, &mp_hash_mask, 0, 0);
6250 
6251 	if (!mount_hashtable || !mountpoint_hashtable)
6252 		panic("Failed to allocate mount hash table\n");
6253 
6254 	kernfs_init();
6255 
6256 	err = sysfs_init();
6257 	if (err)
6258 		printk(KERN_WARNING "%s: sysfs_init error: %d\n",
6259 			__func__, err);
6260 	fs_kobj = kobject_create_and_add("fs", NULL);
6261 	if (!fs_kobj)
6262 		printk(KERN_WARNING "%s: kobj create error\n", __func__);
6263 	shmem_init();
6264 	init_rootfs();
6265 	init_mount_tree();
6266 }
6267 
put_mnt_ns(struct mnt_namespace * ns)6268 void put_mnt_ns(struct mnt_namespace *ns)
6269 {
6270 	if (!ns_ref_put(ns))
6271 		return;
6272 	guard(namespace_excl)();
6273 	emptied_ns = ns;
6274 	guard(mount_writer)();
6275 	umount_tree(ns->root, 0);
6276 }
6277 
kern_mount(struct file_system_type * type)6278 struct vfsmount *kern_mount(struct file_system_type *type)
6279 {
6280 	struct vfsmount *mnt;
6281 	mnt = vfs_kern_mount(type, SB_KERNMOUNT, type->name, NULL);
6282 	if (!IS_ERR(mnt)) {
6283 		/*
6284 		 * it is a longterm mount, don't release mnt until
6285 		 * we unmount before file sys is unregistered
6286 		*/
6287 		real_mount(mnt)->mnt_ns = MNT_NS_INTERNAL;
6288 	}
6289 	return mnt;
6290 }
6291 EXPORT_SYMBOL_GPL(kern_mount);
6292 
kern_unmount(struct vfsmount * mnt)6293 void kern_unmount(struct vfsmount *mnt)
6294 {
6295 	/* release long term mount so mount point can be released */
6296 	if (!IS_ERR(mnt)) {
6297 		mnt_make_shortterm(mnt);
6298 		synchronize_rcu();	/* yecchhh... */
6299 		mntput(mnt);
6300 	}
6301 }
6302 EXPORT_SYMBOL(kern_unmount);
6303 
kern_unmount_array(struct vfsmount * mnt[],unsigned int num)6304 void kern_unmount_array(struct vfsmount *mnt[], unsigned int num)
6305 {
6306 	unsigned int i;
6307 
6308 	for (i = 0; i < num; i++)
6309 		mnt_make_shortterm(mnt[i]);
6310 	synchronize_rcu_expedited();
6311 	for (i = 0; i < num; i++)
6312 		mntput(mnt[i]);
6313 }
6314 EXPORT_SYMBOL(kern_unmount_array);
6315 
our_mnt(struct vfsmount * mnt)6316 bool our_mnt(struct vfsmount *mnt)
6317 {
6318 	return check_mnt(real_mount(mnt));
6319 }
6320 
current_chrooted(void)6321 bool current_chrooted(void)
6322 {
6323 	/* Does the current process have a non-standard root */
6324 	struct path fs_root __free(path_put) = {};
6325 	struct mount *root;
6326 
6327 	get_fs_root(current->fs, &fs_root);
6328 
6329 	/* Find the namespace root */
6330 
6331 	guard(mount_locked_reader)();
6332 
6333 	root = topmost_overmount(current->nsproxy->mnt_ns->root);
6334 
6335 	return fs_root.mnt != &root->mnt || !path_mounted(&fs_root);
6336 }
6337 
mnt_already_visible(struct mnt_namespace * ns,const struct super_block * sb,int * new_mnt_flags)6338 static bool mnt_already_visible(struct mnt_namespace *ns,
6339 				const struct super_block *sb,
6340 				int *new_mnt_flags)
6341 {
6342 	int new_flags = *new_mnt_flags;
6343 	struct mount *mnt, *n;
6344 
6345 	guard(namespace_shared)();
6346 	rbtree_postorder_for_each_entry_safe(mnt, n, &ns->mounts, mnt_node) {
6347 		struct mount *child;
6348 		int mnt_flags;
6349 
6350 		if (mnt->mnt.mnt_sb->s_type != sb->s_type)
6351 			continue;
6352 
6353 		/* This mount is not fully visible if it's root directory
6354 		 * is not the root directory of the filesystem.
6355 		 */
6356 		if (mnt->mnt.mnt_root != mnt->mnt.mnt_sb->s_root)
6357 			continue;
6358 
6359 		/* A local view of the mount flags */
6360 		mnt_flags = mnt->mnt.mnt_flags;
6361 
6362 		/* Don't miss readonly hidden in the superblock flags */
6363 		if (sb_rdonly(mnt->mnt.mnt_sb))
6364 			mnt_flags |= MNT_LOCK_READONLY;
6365 
6366 		/* Verify the mount flags are equal to or more permissive
6367 		 * than the proposed new mount.
6368 		 */
6369 		if ((mnt_flags & MNT_LOCK_READONLY) &&
6370 		    !(new_flags & MNT_READONLY))
6371 			continue;
6372 		if ((mnt_flags & MNT_LOCK_ATIME) &&
6373 		    ((mnt_flags & MNT_ATIME_MASK) != (new_flags & MNT_ATIME_MASK)))
6374 			continue;
6375 
6376 		/* This mount is not fully visible if there are any
6377 		 * locked child mounts that cover anything except for
6378 		 * empty directories.
6379 		 */
6380 		list_for_each_entry(child, &mnt->mnt_mounts, mnt_child) {
6381 			struct inode *inode = child->mnt_mountpoint->d_inode;
6382 			/* Only worry about locked mounts */
6383 			if (!(child->mnt.mnt_flags & MNT_LOCKED))
6384 				continue;
6385 			/* Is the directory permanently empty? */
6386 			if (!is_empty_dir_inode(inode))
6387 				goto next;
6388 		}
6389 		/* Preserve the locked attributes */
6390 		*new_mnt_flags |= mnt_flags & (MNT_LOCK_READONLY | \
6391 					       MNT_LOCK_ATIME);
6392 		return true;
6393 	next:	;
6394 	}
6395 	return false;
6396 }
6397 
mount_too_revealing(const struct super_block * sb,int * new_mnt_flags)6398 static bool mount_too_revealing(const struct super_block *sb, int *new_mnt_flags)
6399 {
6400 	const unsigned long required_iflags = SB_I_NOEXEC | SB_I_NODEV;
6401 	struct mnt_namespace *ns = current->nsproxy->mnt_ns;
6402 	unsigned long s_iflags;
6403 
6404 	if (ns->user_ns == &init_user_ns)
6405 		return false;
6406 
6407 	/* Can this filesystem be too revealing? */
6408 	s_iflags = sb->s_iflags;
6409 	if (!(s_iflags & SB_I_USERNS_VISIBLE))
6410 		return false;
6411 
6412 	if ((s_iflags & required_iflags) != required_iflags) {
6413 		WARN_ONCE(1, "Expected s_iflags to contain 0x%lx\n",
6414 			  required_iflags);
6415 		return true;
6416 	}
6417 
6418 	return !mnt_already_visible(ns, sb, new_mnt_flags);
6419 }
6420 
mnt_may_suid(struct vfsmount * mnt)6421 bool mnt_may_suid(struct vfsmount *mnt)
6422 {
6423 	/*
6424 	 * Foreign mounts (accessed via fchdir or through /proc
6425 	 * symlinks) are always treated as if they are nosuid.  This
6426 	 * prevents namespaces from trusting potentially unsafe
6427 	 * suid/sgid bits, file caps, or security labels that originate
6428 	 * in other namespaces.
6429 	 */
6430 	return !(mnt->mnt_flags & MNT_NOSUID) && check_mnt(real_mount(mnt)) &&
6431 	       current_in_userns(mnt->mnt_sb->s_user_ns);
6432 }
6433 
mntns_get(struct task_struct * task)6434 static struct ns_common *mntns_get(struct task_struct *task)
6435 {
6436 	struct ns_common *ns = NULL;
6437 	struct nsproxy *nsproxy;
6438 
6439 	task_lock(task);
6440 	nsproxy = task->nsproxy;
6441 	if (nsproxy) {
6442 		ns = &nsproxy->mnt_ns->ns;
6443 		get_mnt_ns(to_mnt_ns(ns));
6444 	}
6445 	task_unlock(task);
6446 
6447 	return ns;
6448 }
6449 
mntns_put(struct ns_common * ns)6450 static void mntns_put(struct ns_common *ns)
6451 {
6452 	put_mnt_ns(to_mnt_ns(ns));
6453 }
6454 
mntns_install(struct nsset * nsset,struct ns_common * ns)6455 static int mntns_install(struct nsset *nsset, struct ns_common *ns)
6456 {
6457 	struct nsproxy *nsproxy = nsset->nsproxy;
6458 	struct fs_struct *fs = nsset->fs;
6459 	struct mnt_namespace *mnt_ns = to_mnt_ns(ns), *old_mnt_ns;
6460 	struct user_namespace *user_ns = nsset->cred->user_ns;
6461 	struct path root;
6462 	int err;
6463 
6464 	if (!ns_capable(mnt_ns->user_ns, CAP_SYS_ADMIN) ||
6465 	    !ns_capable(user_ns, CAP_SYS_CHROOT) ||
6466 	    !ns_capable(user_ns, CAP_SYS_ADMIN))
6467 		return -EPERM;
6468 
6469 	if (is_anon_ns(mnt_ns))
6470 		return -EINVAL;
6471 
6472 	if (fs->users != 1)
6473 		return -EINVAL;
6474 
6475 	get_mnt_ns(mnt_ns);
6476 	old_mnt_ns = nsproxy->mnt_ns;
6477 	nsproxy->mnt_ns = mnt_ns;
6478 
6479 	/* Find the root */
6480 	err = vfs_path_lookup(mnt_ns->root->mnt.mnt_root, &mnt_ns->root->mnt,
6481 				"/", LOOKUP_DOWN, &root);
6482 	if (err) {
6483 		/* revert to old namespace */
6484 		nsproxy->mnt_ns = old_mnt_ns;
6485 		put_mnt_ns(mnt_ns);
6486 		return err;
6487 	}
6488 
6489 	put_mnt_ns(old_mnt_ns);
6490 
6491 	/* Update the pwd and root */
6492 	set_fs_pwd(fs, &root);
6493 	set_fs_root(fs, &root);
6494 
6495 	path_put(&root);
6496 	return 0;
6497 }
6498 
mntns_owner(struct ns_common * ns)6499 static struct user_namespace *mntns_owner(struct ns_common *ns)
6500 {
6501 	return to_mnt_ns(ns)->user_ns;
6502 }
6503 
6504 const struct proc_ns_operations mntns_operations = {
6505 	.name		= "mnt",
6506 	.get		= mntns_get,
6507 	.put		= mntns_put,
6508 	.install	= mntns_install,
6509 	.owner		= mntns_owner,
6510 };
6511 
6512 #ifdef CONFIG_SYSCTL
6513 static const struct ctl_table fs_namespace_sysctls[] = {
6514 	{
6515 		.procname	= "mount-max",
6516 		.data		= &sysctl_mount_max,
6517 		.maxlen		= sizeof(unsigned int),
6518 		.mode		= 0644,
6519 		.proc_handler	= proc_dointvec_minmax,
6520 		.extra1		= SYSCTL_ONE,
6521 	},
6522 };
6523 
init_fs_namespace_sysctls(void)6524 static int __init init_fs_namespace_sysctls(void)
6525 {
6526 	register_sysctl_init("fs", fs_namespace_sysctls);
6527 	return 0;
6528 }
6529 fs_initcall(init_fs_namespace_sysctls);
6530 
6531 #endif /* CONFIG_SYSCTL */
6532