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