xref: /linux/kernel/user_namespace.c (revision bf5ba73c9bdd5e872eb35e801e429a3b526f8f04)
1 // SPDX-License-Identifier: GPL-2.0-only
2 
3 #include <kunit/visibility.h>
4 #include <linux/export.h>
5 #include <linux/nsproxy.h>
6 #include <linux/slab.h>
7 #include <linux/sched/signal.h>
8 #include <linux/user_namespace.h>
9 #include <linux/proc_ns.h>
10 #include <linux/highuid.h>
11 #include <linux/cred.h>
12 #include <linux/securebits.h>
13 #include <linux/security.h>
14 #include <linux/keyctl.h>
15 #include <linux/key-type.h>
16 #include <keys/user-type.h>
17 #include <linux/seq_file.h>
18 #include <linux/fs.h>
19 #include <linux/uaccess.h>
20 #include <linux/ctype.h>
21 #include <linux/projid.h>
22 #include <linux/fs_struct.h>
23 #include <linux/bsearch.h>
24 #include <linux/sort.h>
25 #include <linux/nstree.h>
26 
27 static struct kmem_cache *user_ns_cachep __ro_after_init;
28 static DEFINE_MUTEX(userns_state_mutex);
29 
30 static bool new_idmap_permitted(const struct file *file,
31 				struct user_namespace *ns, int cap_setid,
32 				struct uid_gid_map *map);
33 static void free_user_ns(struct work_struct *work);
34 
35 static struct ucounts *inc_user_namespaces(struct user_namespace *ns, kuid_t uid)
36 {
37 	return inc_ucount(ns, uid, UCOUNT_USER_NAMESPACES);
38 }
39 
40 static void dec_user_namespaces(struct ucounts *ucounts)
41 {
42 	return dec_ucount(ucounts, UCOUNT_USER_NAMESPACES);
43 }
44 
45 static void set_cred_user_ns(struct cred *cred, struct user_namespace *user_ns)
46 {
47 	/* Start with the same capabilities as init but useless for doing
48 	 * anything as the capabilities are bound to the new user namespace.
49 	 * The exec securebits grant nothing, they are restrictions the task
50 	 * placed on itself. Keep them and their locks.
51 	 */
52 	cred->securebits = SECUREBITS_DEFAULT |
53 		(cred->securebits & (SECURE_ALL_UNPRIVILEGED | SECURE_ALL_UNPRIVILEGED << 1));
54 	cred->cap_inheritable = CAP_EMPTY_SET;
55 	cred->cap_permitted = CAP_FULL_SET;
56 	cred->cap_effective = CAP_FULL_SET;
57 	cred->cap_ambient = CAP_EMPTY_SET;
58 	cred->cap_bset = CAP_FULL_SET;
59 #ifdef CONFIG_KEYS
60 	key_put(cred->request_key_auth);
61 	cred->request_key_auth = NULL;
62 #endif
63 	/* tgcred will be cleared in our caller bc CLONE_THREAD won't be set */
64 	cred->user_ns = user_ns;
65 }
66 
67 static unsigned long enforced_nproc_rlimit(void)
68 {
69 	unsigned long limit = RLIM_INFINITY;
70 
71 	/* Is RLIMIT_NPROC currently enforced? */
72 	if (!uid_eq(current_uid(), GLOBAL_ROOT_UID) ||
73 	    (current_user_ns() != &init_user_ns))
74 		limit = rlimit(RLIMIT_NPROC);
75 
76 	return limit;
77 }
78 
79 /*
80  * Create a new user namespace, deriving the creator from the user in the
81  * passed credentials, and replacing that user with the new root user for the
82  * new namespace.
83  *
84  * This is called by copy_creds(), which will finish setting the target task's
85  * credentials.
86  */
87 int create_user_ns(struct cred *new)
88 {
89 	struct user_namespace *ns, *parent_ns = new->user_ns;
90 	kuid_t owner = new->euid;
91 	kgid_t group = new->egid;
92 	struct ucounts *ucounts;
93 	int ret, i;
94 
95 	ret = -ENOSPC;
96 	if (parent_ns->level > 32)
97 		goto fail;
98 
99 	ucounts = inc_user_namespaces(parent_ns, owner);
100 	if (!ucounts)
101 		goto fail;
102 
103 	/*
104 	 * Verify that we can not violate the policy of which files
105 	 * may be accessed that is specified by the root directory,
106 	 * by verifying that the root directory is at the root of the
107 	 * mount namespace which allows all files to be accessed.
108 	 */
109 	ret = -EPERM;
110 	if (current_chrooted())
111 		goto fail_dec;
112 
113 	/* The creator needs a mapping in the parent user namespace
114 	 * or else we won't be able to reasonably tell userspace who
115 	 * created a user_namespace.
116 	 */
117 	ret = -EPERM;
118 	if (!kuid_has_mapping(parent_ns, owner) ||
119 	    !kgid_has_mapping(parent_ns, group))
120 		goto fail_dec;
121 
122 	ret = security_create_user_ns(new);
123 	if (ret < 0)
124 		goto fail_dec;
125 
126 	ret = -ENOMEM;
127 	ns = kmem_cache_zalloc(user_ns_cachep, GFP_KERNEL);
128 	if (!ns)
129 		goto fail_dec;
130 
131 	ns->parent_could_setfcap = cap_raised(new->cap_effective, CAP_SETFCAP);
132 
133 	ret = ns_common_init(ns);
134 	if (ret)
135 		goto fail_free;
136 
137 	/* Leave the new->user_ns reference with the new user namespace. */
138 	ns->parent = parent_ns;
139 	ns->level = parent_ns->level + 1;
140 	ns->owner = owner;
141 	ns->group = group;
142 	INIT_WORK(&ns->work, free_user_ns);
143 	for (i = 0; i < UCOUNT_COUNTS; i++) {
144 		ns->ucount_max[i] = INT_MAX;
145 	}
146 	set_userns_rlimit_max(ns, UCOUNT_RLIMIT_NPROC, enforced_nproc_rlimit());
147 	set_userns_rlimit_max(ns, UCOUNT_RLIMIT_MSGQUEUE, rlimit(RLIMIT_MSGQUEUE));
148 	set_userns_rlimit_max(ns, UCOUNT_RLIMIT_SIGPENDING, rlimit(RLIMIT_SIGPENDING));
149 	set_userns_rlimit_max(ns, UCOUNT_RLIMIT_MEMLOCK, rlimit(RLIMIT_MEMLOCK));
150 	ns->ucounts = ucounts;
151 
152 	/* Inherit USERNS_SETGROUPS_ALLOWED from our parent */
153 	mutex_lock(&userns_state_mutex);
154 	ns->flags = parent_ns->flags;
155 	mutex_unlock(&userns_state_mutex);
156 
157 #ifdef CONFIG_KEYS
158 	INIT_LIST_HEAD(&ns->keyring_name_list);
159 	init_rwsem(&ns->keyring_sem);
160 #endif
161 	ret = -ENOMEM;
162 	if (!setup_userns_sysctls(ns))
163 		goto fail_keyring;
164 
165 	set_cred_user_ns(new, ns);
166 	ns_tree_add(ns);
167 	return 0;
168 fail_keyring:
169 	ns_common_free(ns);
170 fail_free:
171 	kmem_cache_free(user_ns_cachep, ns);
172 fail_dec:
173 	dec_user_namespaces(ucounts);
174 fail:
175 	return ret;
176 }
177 
178 int unshare_userns(unsigned long unshare_flags, struct cred **new_cred)
179 {
180 	struct cred *cred;
181 	int err = -ENOMEM;
182 
183 	if (!(unshare_flags & CLONE_NEWUSER))
184 		return 0;
185 
186 	cred = prepare_creds();
187 	if (cred) {
188 		err = create_user_ns(cred);
189 		if (err)
190 			put_cred(cred);
191 		else
192 			*new_cred = cred;
193 	}
194 
195 	return err;
196 }
197 
198 static void free_user_ns(struct work_struct *work)
199 {
200 	struct user_namespace *parent, *ns =
201 		container_of(work, struct user_namespace, work);
202 
203 	do {
204 		struct ucounts *ucounts = ns->ucounts;
205 		parent = ns->parent;
206 		ns_tree_remove(ns);
207 		if (ns->gid_map.nr_extents > UID_GID_MAP_MAX_BASE_EXTENTS) {
208 			kfree(ns->gid_map.forward);
209 			kfree(ns->gid_map.reverse);
210 		}
211 		if (ns->uid_map.nr_extents > UID_GID_MAP_MAX_BASE_EXTENTS) {
212 			kfree(ns->uid_map.forward);
213 			kfree(ns->uid_map.reverse);
214 		}
215 		if (ns->projid_map.nr_extents > UID_GID_MAP_MAX_BASE_EXTENTS) {
216 			kfree(ns->projid_map.forward);
217 			kfree(ns->projid_map.reverse);
218 		}
219 #if IS_ENABLED(CONFIG_BINFMT_MISC)
220 		kfree(ns->binfmt_misc);
221 #endif
222 		retire_userns_sysctls(ns);
223 		key_free_user_ns(ns);
224 		ns_common_free(ns);
225 		/* Concurrent nstree traversal depends on a grace period. */
226 		kfree_rcu(ns, ns.ns_rcu);
227 		dec_user_namespaces(ucounts);
228 		ns = parent;
229 	} while (ns_ref_put(parent));
230 }
231 
232 void __put_user_ns(struct user_namespace *ns)
233 {
234 	schedule_work(&ns->work);
235 }
236 EXPORT_SYMBOL(__put_user_ns);
237 
238 /*
239  * struct idmap_key - holds the information necessary to find an idmapping in a
240  * sorted idmap array. It is passed to cmp_map_id() as first argument.
241  */
242 struct idmap_key {
243 	bool map_up; /* true  -> id from kid; false -> kid from id */
244 	u32 id; /* id to find */
245 	u32 count;
246 };
247 
248 /*
249  * cmp_map_id - Function to be passed to bsearch() to find the requested
250  * idmapping. Expects struct idmap_key to be passed via @k.
251  */
252 static int cmp_map_id(const void *k, const void *e)
253 {
254 	u32 first, last, id2;
255 	const struct idmap_key *key = k;
256 	const struct uid_gid_extent *el = e;
257 
258 	id2 = key->id + key->count - 1;
259 
260 	/* handle map_id_{down,up}() */
261 	if (key->map_up)
262 		first = el->lower_first;
263 	else
264 		first = el->first;
265 
266 	last = first + el->count - 1;
267 
268 	if (key->id >= first && key->id <= last &&
269 	    (id2 >= first && id2 <= last))
270 		return 0;
271 
272 	if (key->id < first || id2 < first)
273 		return -1;
274 
275 	return 1;
276 }
277 
278 /*
279  * map_id_range_down_max - Find idmap via binary search in ordered idmap array.
280  * Can only be called if number of mappings exceeds UID_GID_MAP_MAX_BASE_EXTENTS.
281  */
282 static const struct uid_gid_extent *
283 map_id_range_down_max(unsigned extents, const struct uid_gid_map *map, u32 id, u32 count)
284 {
285 	struct idmap_key key;
286 
287 	key.map_up = false;
288 	key.count = count;
289 	key.id = id;
290 
291 	return bsearch(&key, map->forward, extents,
292 		       sizeof(struct uid_gid_extent), cmp_map_id);
293 }
294 
295 /*
296  * map_id_range_down_base - Find idmap via binary search in static extent array.
297  * Can only be called if number of mappings is equal or less than
298  * UID_GID_MAP_MAX_BASE_EXTENTS.
299  */
300 static const struct uid_gid_extent *
301 map_id_range_down_base(unsigned extents, const struct uid_gid_map *map, u32 id, u32 count)
302 {
303 	unsigned idx;
304 	u32 first, last, id2;
305 
306 	id2 = id + count - 1;
307 
308 	/* Find the matching extent */
309 	for (idx = 0; idx < extents; idx++) {
310 		first = map->extent[idx].first;
311 		last = first + map->extent[idx].count - 1;
312 		if (id >= first && id <= last &&
313 		    (id2 >= first && id2 <= last))
314 			return &map->extent[idx];
315 	}
316 	return NULL;
317 }
318 
319 static u32 map_id_range_down(const struct uid_gid_map *map, u32 id, u32 count)
320 {
321 	const struct uid_gid_extent *extent;
322 	unsigned extents = map->nr_extents;
323 	smp_rmb();
324 
325 	if (extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
326 		extent = map_id_range_down_base(extents, map, id, count);
327 	else
328 		extent = map_id_range_down_max(extents, map, id, count);
329 
330 	/* Map the id or note failure */
331 	if (extent)
332 		id = (id - extent->first) + extent->lower_first;
333 	else
334 		id = (u32) -1;
335 
336 	return id;
337 }
338 
339 u32 map_id_down(const struct uid_gid_map *map, u32 id)
340 {
341 	return map_id_range_down(map, id, 1);
342 }
343 
344 /*
345  * map_id_up_base - Find idmap via binary search in static extent array.
346  * Can only be called if number of mappings is equal or less than
347  * UID_GID_MAP_MAX_BASE_EXTENTS.
348  */
349 static const struct uid_gid_extent *
350 map_id_range_up_base(unsigned extents, const struct uid_gid_map *map, u32 id, u32 count)
351 {
352 	unsigned idx;
353 	u32 first, last, id2;
354 
355 	id2 = id + count - 1;
356 
357 	/* Find the matching extent */
358 	for (idx = 0; idx < extents; idx++) {
359 		first = map->extent[idx].lower_first;
360 		last = first + map->extent[idx].count - 1;
361 		if (id >= first && id <= last &&
362 		    (id2 >= first && id2 <= last))
363 			return &map->extent[idx];
364 	}
365 	return NULL;
366 }
367 
368 /*
369  * map_id_up_max - Find idmap via binary search in ordered idmap array.
370  * Can only be called if number of mappings exceeds UID_GID_MAP_MAX_BASE_EXTENTS.
371  */
372 static const struct uid_gid_extent *
373 map_id_range_up_max(unsigned extents, const struct uid_gid_map *map, u32 id, u32 count)
374 {
375 	struct idmap_key key;
376 
377 	key.map_up = true;
378 	key.count = count;
379 	key.id = id;
380 
381 	return bsearch(&key, map->reverse, extents,
382 		       sizeof(struct uid_gid_extent), cmp_map_id);
383 }
384 
385 u32 map_id_range_up(const struct uid_gid_map *map, u32 id, u32 count)
386 {
387 	const struct uid_gid_extent *extent;
388 	unsigned extents = map->nr_extents;
389 	smp_rmb();
390 
391 	if (extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
392 		extent = map_id_range_up_base(extents, map, id, count);
393 	else
394 		extent = map_id_range_up_max(extents, map, id, count);
395 
396 	/* Map the id or note failure */
397 	if (extent)
398 		id = (id - extent->lower_first) + extent->first;
399 	else
400 		id = (u32) -1;
401 
402 	return id;
403 }
404 
405 u32 map_id_up(const struct uid_gid_map *map, u32 id)
406 {
407 	return map_id_range_up(map, id, 1);
408 }
409 
410 /**
411  *	make_kuid - Map a user-namespace uid pair into a kuid.
412  *	@ns:  User namespace that the uid is in
413  *	@uid: User identifier
414  *
415  *	Maps a user-namespace uid pair into a kernel internal kuid,
416  *	and returns that kuid.
417  *
418  *	When there is no mapping defined for the user-namespace uid
419  *	pair INVALID_UID is returned.  Callers are expected to test
420  *	for and handle INVALID_UID being returned.  INVALID_UID
421  *	may be tested for using uid_valid().
422  */
423 kuid_t make_kuid(struct user_namespace *ns, uid_t uid)
424 {
425 	/* Map the uid to a global kernel uid */
426 	return KUIDT_INIT(map_id_down(&ns->uid_map, uid));
427 }
428 EXPORT_SYMBOL(make_kuid);
429 
430 /**
431  *	from_kuid - Create a uid from a kuid user-namespace pair.
432  *	@targ: The user namespace we want a uid in.
433  *	@kuid: The kernel internal uid to start with.
434  *
435  *	Map @kuid into the user-namespace specified by @targ and
436  *	return the resulting uid.
437  *
438  *	There is always a mapping into the initial user_namespace.
439  *
440  *	If @kuid has no mapping in @targ (uid_t)-1 is returned.
441  */
442 uid_t from_kuid(struct user_namespace *targ, kuid_t kuid)
443 {
444 	/* Map the uid from a global kernel uid */
445 	return map_id_up(&targ->uid_map, __kuid_val(kuid));
446 }
447 EXPORT_SYMBOL(from_kuid);
448 
449 /**
450  *	from_kuid_munged - Create a uid from a kuid user-namespace pair.
451  *	@targ: The user namespace we want a uid in.
452  *	@kuid: The kernel internal uid to start with.
453  *
454  *	Map @kuid into the user-namespace specified by @targ and
455  *	return the resulting uid.
456  *
457  *	There is always a mapping into the initial user_namespace.
458  *
459  *	Unlike from_kuid from_kuid_munged never fails and always
460  *	returns a valid uid.  This makes from_kuid_munged appropriate
461  *	for use in syscalls like stat and getuid where failing the
462  *	system call and failing to provide a valid uid are not an
463  *	options.
464  *
465  *	If @kuid has no mapping in @targ overflowuid is returned.
466  */
467 uid_t from_kuid_munged(struct user_namespace *targ, kuid_t kuid)
468 {
469 	uid_t uid;
470 	uid = from_kuid(targ, kuid);
471 
472 	if (uid == (uid_t) -1)
473 		uid = overflowuid;
474 	return uid;
475 }
476 EXPORT_SYMBOL(from_kuid_munged);
477 
478 /**
479  *	make_kgid - Map a user-namespace gid pair into a kgid.
480  *	@ns:  User namespace that the gid is in
481  *	@gid: group identifier
482  *
483  *	Maps a user-namespace gid pair into a kernel internal kgid,
484  *	and returns that kgid.
485  *
486  *	When there is no mapping defined for the user-namespace gid
487  *	pair INVALID_GID is returned.  Callers are expected to test
488  *	for and handle INVALID_GID being returned.  INVALID_GID may be
489  *	tested for using gid_valid().
490  */
491 kgid_t make_kgid(struct user_namespace *ns, gid_t gid)
492 {
493 	/* Map the gid to a global kernel gid */
494 	return KGIDT_INIT(map_id_down(&ns->gid_map, gid));
495 }
496 EXPORT_SYMBOL(make_kgid);
497 
498 /**
499  *	from_kgid - Create a gid from a kgid user-namespace pair.
500  *	@targ: The user namespace we want a gid in.
501  *	@kgid: The kernel internal gid to start with.
502  *
503  *	Map @kgid into the user-namespace specified by @targ and
504  *	return the resulting gid.
505  *
506  *	There is always a mapping into the initial user_namespace.
507  *
508  *	If @kgid has no mapping in @targ (gid_t)-1 is returned.
509  */
510 gid_t from_kgid(struct user_namespace *targ, kgid_t kgid)
511 {
512 	/* Map the gid from a global kernel gid */
513 	return map_id_up(&targ->gid_map, __kgid_val(kgid));
514 }
515 EXPORT_SYMBOL(from_kgid);
516 
517 /**
518  *	from_kgid_munged - Create a gid from a kgid user-namespace pair.
519  *	@targ: The user namespace we want a gid in.
520  *	@kgid: The kernel internal gid to start with.
521  *
522  *	Map @kgid into the user-namespace specified by @targ and
523  *	return the resulting gid.
524  *
525  *	There is always a mapping into the initial user_namespace.
526  *
527  *	Unlike from_kgid from_kgid_munged never fails and always
528  *	returns a valid gid.  This makes from_kgid_munged appropriate
529  *	for use in syscalls like stat and getgid where failing the
530  *	system call and failing to provide a valid gid are not options.
531  *
532  *	If @kgid has no mapping in @targ overflowgid is returned.
533  */
534 gid_t from_kgid_munged(struct user_namespace *targ, kgid_t kgid)
535 {
536 	gid_t gid;
537 	gid = from_kgid(targ, kgid);
538 
539 	if (gid == (gid_t) -1)
540 		gid = overflowgid;
541 	return gid;
542 }
543 EXPORT_SYMBOL(from_kgid_munged);
544 
545 /**
546  *	make_kprojid - Map a user-namespace projid pair into a kprojid.
547  *	@ns:  User namespace that the projid is in
548  *	@projid: Project identifier
549  *
550  *	Maps a user-namespace uid pair into a kernel internal kuid,
551  *	and returns that kuid.
552  *
553  *	When there is no mapping defined for the user-namespace projid
554  *	pair INVALID_PROJID is returned.  Callers are expected to test
555  *	for and handle INVALID_PROJID being returned.  INVALID_PROJID
556  *	may be tested for using projid_valid().
557  */
558 kprojid_t make_kprojid(struct user_namespace *ns, projid_t projid)
559 {
560 	/* Map the uid to a global kernel uid */
561 	return KPROJIDT_INIT(map_id_down(&ns->projid_map, projid));
562 }
563 EXPORT_SYMBOL(make_kprojid);
564 
565 /**
566  *	from_kprojid - Create a projid from a kprojid user-namespace pair.
567  *	@targ: The user namespace we want a projid in.
568  *	@kprojid: The kernel internal project identifier to start with.
569  *
570  *	Map @kprojid into the user-namespace specified by @targ and
571  *	return the resulting projid.
572  *
573  *	There is always a mapping into the initial user_namespace.
574  *
575  *	If @kprojid has no mapping in @targ (projid_t)-1 is returned.
576  */
577 projid_t from_kprojid(struct user_namespace *targ, kprojid_t kprojid)
578 {
579 	/* Map the uid from a global kernel uid */
580 	return map_id_up(&targ->projid_map, __kprojid_val(kprojid));
581 }
582 EXPORT_SYMBOL(from_kprojid);
583 
584 /**
585  *	from_kprojid_munged - Create a projiid from a kprojid user-namespace pair.
586  *	@targ: The user namespace we want a projid in.
587  *	@kprojid: The kernel internal projid to start with.
588  *
589  *	Map @kprojid into the user-namespace specified by @targ and
590  *	return the resulting projid.
591  *
592  *	There is always a mapping into the initial user_namespace.
593  *
594  *	Unlike from_kprojid from_kprojid_munged never fails and always
595  *	returns a valid projid.  This makes from_kprojid_munged
596  *	appropriate for use in syscalls like stat and where
597  *	failing the system call and failing to provide a valid projid are
598  *	not an options.
599  *
600  *	If @kprojid has no mapping in @targ OVERFLOW_PROJID is returned.
601  */
602 projid_t from_kprojid_munged(struct user_namespace *targ, kprojid_t kprojid)
603 {
604 	projid_t projid;
605 	projid = from_kprojid(targ, kprojid);
606 
607 	if (projid == (projid_t) -1)
608 		projid = OVERFLOW_PROJID;
609 	return projid;
610 }
611 EXPORT_SYMBOL(from_kprojid_munged);
612 
613 
614 static int uid_m_show(struct seq_file *seq, void *v)
615 {
616 	struct user_namespace *ns = seq->private;
617 	struct uid_gid_extent *extent = v;
618 	struct user_namespace *lower_ns;
619 	uid_t lower;
620 
621 	lower_ns = seq_user_ns(seq);
622 	if ((lower_ns == ns) && lower_ns->parent)
623 		lower_ns = lower_ns->parent;
624 
625 	lower = from_kuid(lower_ns, KUIDT_INIT(extent->lower_first));
626 
627 	seq_printf(seq, "%10u %10u %10u\n",
628 		extent->first,
629 		lower,
630 		extent->count);
631 
632 	return 0;
633 }
634 
635 static int gid_m_show(struct seq_file *seq, void *v)
636 {
637 	struct user_namespace *ns = seq->private;
638 	struct uid_gid_extent *extent = v;
639 	struct user_namespace *lower_ns;
640 	gid_t lower;
641 
642 	lower_ns = seq_user_ns(seq);
643 	if ((lower_ns == ns) && lower_ns->parent)
644 		lower_ns = lower_ns->parent;
645 
646 	lower = from_kgid(lower_ns, KGIDT_INIT(extent->lower_first));
647 
648 	seq_printf(seq, "%10u %10u %10u\n",
649 		extent->first,
650 		lower,
651 		extent->count);
652 
653 	return 0;
654 }
655 
656 static int projid_m_show(struct seq_file *seq, void *v)
657 {
658 	struct user_namespace *ns = seq->private;
659 	struct uid_gid_extent *extent = v;
660 	struct user_namespace *lower_ns;
661 	projid_t lower;
662 
663 	lower_ns = seq_user_ns(seq);
664 	if ((lower_ns == ns) && lower_ns->parent)
665 		lower_ns = lower_ns->parent;
666 
667 	lower = from_kprojid(lower_ns, KPROJIDT_INIT(extent->lower_first));
668 
669 	seq_printf(seq, "%10u %10u %10u\n",
670 		extent->first,
671 		lower,
672 		extent->count);
673 
674 	return 0;
675 }
676 
677 static void *m_start(struct seq_file *seq, loff_t *ppos,
678 		     struct uid_gid_map *map)
679 {
680 	loff_t pos = *ppos;
681 	unsigned extents = map->nr_extents;
682 	smp_rmb();
683 
684 	if (pos >= extents)
685 		return NULL;
686 
687 	if (extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
688 		return &map->extent[pos];
689 
690 	return &map->forward[pos];
691 }
692 
693 static void *uid_m_start(struct seq_file *seq, loff_t *ppos)
694 {
695 	struct user_namespace *ns = seq->private;
696 
697 	return m_start(seq, ppos, &ns->uid_map);
698 }
699 
700 static void *gid_m_start(struct seq_file *seq, loff_t *ppos)
701 {
702 	struct user_namespace *ns = seq->private;
703 
704 	return m_start(seq, ppos, &ns->gid_map);
705 }
706 
707 static void *projid_m_start(struct seq_file *seq, loff_t *ppos)
708 {
709 	struct user_namespace *ns = seq->private;
710 
711 	return m_start(seq, ppos, &ns->projid_map);
712 }
713 
714 static void *m_next(struct seq_file *seq, void *v, loff_t *pos)
715 {
716 	(*pos)++;
717 	return seq->op->start(seq, pos);
718 }
719 
720 static void m_stop(struct seq_file *seq, void *v)
721 {
722 	return;
723 }
724 
725 const struct seq_operations proc_uid_seq_operations = {
726 	.start = uid_m_start,
727 	.stop = m_stop,
728 	.next = m_next,
729 	.show = uid_m_show,
730 };
731 
732 const struct seq_operations proc_gid_seq_operations = {
733 	.start = gid_m_start,
734 	.stop = m_stop,
735 	.next = m_next,
736 	.show = gid_m_show,
737 };
738 
739 const struct seq_operations proc_projid_seq_operations = {
740 	.start = projid_m_start,
741 	.stop = m_stop,
742 	.next = m_next,
743 	.show = projid_m_show,
744 };
745 
746 static bool mappings_overlap(struct uid_gid_map *new_map,
747 			     struct uid_gid_extent *extent)
748 {
749 	u32 upper_first, lower_first, upper_last, lower_last;
750 	unsigned idx;
751 
752 	upper_first = extent->first;
753 	lower_first = extent->lower_first;
754 	upper_last = upper_first + extent->count - 1;
755 	lower_last = lower_first + extent->count - 1;
756 
757 	for (idx = 0; idx < new_map->nr_extents; idx++) {
758 		u32 prev_upper_first, prev_lower_first;
759 		u32 prev_upper_last, prev_lower_last;
760 		struct uid_gid_extent *prev;
761 
762 		if (new_map->nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
763 			prev = &new_map->extent[idx];
764 		else
765 			prev = &new_map->forward[idx];
766 
767 		prev_upper_first = prev->first;
768 		prev_lower_first = prev->lower_first;
769 		prev_upper_last = prev_upper_first + prev->count - 1;
770 		prev_lower_last = prev_lower_first + prev->count - 1;
771 
772 		/* Does the upper range intersect a previous extent? */
773 		if ((prev_upper_first <= upper_last) &&
774 		    (prev_upper_last >= upper_first))
775 			return true;
776 
777 		/* Does the lower range intersect a previous extent? */
778 		if ((prev_lower_first <= lower_last) &&
779 		    (prev_lower_last >= lower_first))
780 			return true;
781 	}
782 	return false;
783 }
784 
785 /*
786  * uid_gid_map_insert_extent - Safely insert a new idmap extent into
787  * struct uid_gid_map.
788  * Takes care to allocate a 4K block of memory if the number of mappings exceeds
789  * UID_GID_MAP_MAX_BASE_EXTENTS.
790  */
791 VISIBLE_IF_KUNIT int uid_gid_map_insert_extent(struct uid_gid_map *map,
792 					       struct uid_gid_extent *extent)
793 {
794 	struct uid_gid_extent *dest;
795 
796 	if (map->nr_extents == UID_GID_MAP_MAX_BASE_EXTENTS) {
797 		struct uid_gid_extent *forward;
798 
799 		/* Allocate memory for 340 mappings. */
800 		forward = kmalloc_objs(struct uid_gid_extent,
801 				       UID_GID_MAP_MAX_EXTENTS);
802 		if (!forward)
803 			return -ENOMEM;
804 
805 		/* Copy over memory. Only set up memory for the forward pointer.
806 		 * Defer the memory setup for the reverse pointer.
807 		 */
808 		memcpy(forward, map->extent,
809 		       map->nr_extents * sizeof(map->extent[0]));
810 
811 		map->forward = forward;
812 		map->reverse = NULL;
813 	}
814 
815 	/*
816 	 * nr_extents must be updated before the extent and forward arrays are
817 	 * accessed, otherwise KSAN will assert an out-of-bounds error.
818 	 */
819 	map->nr_extents++;
820 	if (map->nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
821 		dest = &map->extent[map->nr_extents - 1];
822 	else
823 		dest = &map->forward[map->nr_extents - 1];
824 
825 	*dest = *extent;
826 	return 0;
827 }
828 EXPORT_SYMBOL_IF_KUNIT(uid_gid_map_insert_extent);
829 
830 /* cmp function to sort() forward mappings */
831 static int cmp_extents_forward(const void *a, const void *b)
832 {
833 	const struct uid_gid_extent *e1 = a;
834 	const struct uid_gid_extent *e2 = b;
835 
836 	if (e1->first < e2->first)
837 		return -1;
838 
839 	if (e1->first > e2->first)
840 		return 1;
841 
842 	return 0;
843 }
844 
845 /* cmp function to sort() reverse mappings */
846 static int cmp_extents_reverse(const void *a, const void *b)
847 {
848 	const struct uid_gid_extent *e1 = a;
849 	const struct uid_gid_extent *e2 = b;
850 
851 	if (e1->lower_first < e2->lower_first)
852 		return -1;
853 
854 	if (e1->lower_first > e2->lower_first)
855 		return 1;
856 
857 	return 0;
858 }
859 
860 /*
861  * uid_gid_map_sort - Sorts an array of idmap entries.
862  * Can only be called if number of mappings exceeds UID_GID_MAP_MAX_BASE_EXTENTS.
863  */
864 VISIBLE_IF_KUNIT int uid_gid_map_sort(struct uid_gid_map *map)
865 {
866 	if (map->nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
867 		return 0;
868 
869 	/* Sort forward array. */
870 	sort(map->forward, map->nr_extents, sizeof(struct uid_gid_extent),
871 	     cmp_extents_forward, NULL);
872 
873 	/* Only copy the memory from forward we actually need. */
874 	map->reverse = kmemdup_array(map->forward, map->nr_extents,
875 				     sizeof(struct uid_gid_extent), GFP_KERNEL);
876 	if (!map->reverse)
877 		return -ENOMEM;
878 
879 	/* Sort reverse array. */
880 	sort(map->reverse, map->nr_extents, sizeof(struct uid_gid_extent),
881 	     cmp_extents_reverse, NULL);
882 
883 	return 0;
884 }
885 EXPORT_SYMBOL_IF_KUNIT(uid_gid_map_sort);
886 
887 /**
888  * verify_root_map() - check the uid 0 mapping
889  * @file: idmapping file
890  * @map_ns: user namespace of the target process
891  * @new_map: requested idmap
892  *
893  * If a process requests mapping parent uid 0 into the new ns, verify that the
894  * process writing the map had the CAP_SETFCAP capability as the target process
895  * will be able to write fscaps that are valid in ancestor user namespaces.
896  *
897  * Return: true if the mapping is allowed, false if not.
898  */
899 static bool verify_root_map(const struct file *file,
900 			    struct user_namespace *map_ns,
901 			    struct uid_gid_map *new_map)
902 {
903 	int idx;
904 	const struct user_namespace *file_ns = file->f_cred->user_ns;
905 	struct uid_gid_extent *extent0 = NULL;
906 
907 	for (idx = 0; idx < new_map->nr_extents; idx++) {
908 		if (new_map->nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
909 			extent0 = &new_map->extent[idx];
910 		else
911 			extent0 = &new_map->forward[idx];
912 		if (extent0->lower_first == 0)
913 			break;
914 
915 		extent0 = NULL;
916 	}
917 
918 	if (!extent0)
919 		return true;
920 
921 	if (map_ns == file_ns) {
922 		/* The process unshared its ns and is writing to its own
923 		 * /proc/self/uid_map.  User already has full capabilites in
924 		 * the new namespace.  Verify that the parent had CAP_SETFCAP
925 		 * when it unshared.
926 		 * */
927 		if (!file_ns->parent_could_setfcap)
928 			return false;
929 	} else {
930 		/* Process p1 is writing to uid_map of p2, who is in a child
931 		 * user namespace to p1's.  Verify that the opener of the map
932 		 * file has CAP_SETFCAP against the parent of the new map
933 		 * namespace */
934 		if (!file_ns_capable(file, map_ns->parent, CAP_SETFCAP))
935 			return false;
936 	}
937 
938 	return true;
939 }
940 
941 /*
942  * Parse the decimal u32 at *pos, up to the next whitespace or NUL, and
943  * leave *pos pointing at that character.
944  */
945 static int map_parse_u32(char **pos, u32 *res)
946 {
947 	char *end = *pos;
948 	char c;
949 	int ret;
950 
951 	while (*end && !isspace(*end))
952 		end++;
953 	c = *end;
954 	*end = '\0';
955 	ret = kstrtou32(*pos, 10, res);
956 	*end = c;
957 	*pos = end;
958 	return ret;
959 }
960 
961 static ssize_t map_write(struct file *file, const char __user *buf,
962 			 size_t count, loff_t *ppos,
963 			 int cap_setid,
964 			 struct uid_gid_map *map,
965 			 struct uid_gid_map *parent_map)
966 {
967 	struct seq_file *seq = file->private_data;
968 	struct user_namespace *map_ns = seq->private;
969 	struct uid_gid_map new_map;
970 	unsigned idx;
971 	struct uid_gid_extent extent;
972 	char *kbuf, *pos, *next_line;
973 	ssize_t ret;
974 
975 	/* Only allow < page size writes at the beginning of the file */
976 	if ((*ppos != 0) || (count >= PAGE_SIZE))
977 		return -EINVAL;
978 
979 	/* Slurp in the user data */
980 	kbuf = memdup_user_nul(buf, count);
981 	if (IS_ERR(kbuf))
982 		return PTR_ERR(kbuf);
983 
984 	/*
985 	 * The userns_state_mutex serializes all writes to any given map.
986 	 *
987 	 * Any map is only ever written once.
988 	 *
989 	 * An id map fits within 1 cache line on most architectures.
990 	 *
991 	 * On read nothing needs to be done unless you are on an
992 	 * architecture with a crazy cache coherency model like alpha.
993 	 *
994 	 * There is a one time data dependency between reading the
995 	 * count of the extents and the values of the extents.  The
996 	 * desired behavior is to see the values of the extents that
997 	 * were written before the count of the extents.
998 	 *
999 	 * To achieve this smp_wmb() is used on guarantee the write
1000 	 * order and smp_rmb() is guaranteed that we don't have crazy
1001 	 * architectures returning stale data.
1002 	 */
1003 	mutex_lock(&userns_state_mutex);
1004 
1005 	memset(&new_map, 0, sizeof(struct uid_gid_map));
1006 
1007 	ret = -EPERM;
1008 	/* Only allow one successful write to the map */
1009 	if (map->nr_extents != 0)
1010 		goto out;
1011 
1012 	/*
1013 	 * Adjusting namespace settings requires capabilities on the target.
1014 	 */
1015 	if (cap_valid(cap_setid) && !file_ns_capable(file, map_ns, CAP_SYS_ADMIN))
1016 		goto out;
1017 
1018 	/* Parse the user data */
1019 	ret = -EINVAL;
1020 	pos = kbuf;
1021 	for (; pos; pos = next_line) {
1022 
1023 		/* Find the end of line and ensure I don't look past it */
1024 		next_line = strchr(pos, '\n');
1025 		if (next_line) {
1026 			*next_line = '\0';
1027 			next_line++;
1028 			if (*next_line == '\0')
1029 				next_line = NULL;
1030 		}
1031 
1032 		pos = skip_spaces(pos);
1033 		if (map_parse_u32(&pos, &extent.first))
1034 			goto out;
1035 		if (!isspace(*pos))
1036 			goto out;
1037 
1038 		pos = skip_spaces(pos);
1039 		if (map_parse_u32(&pos, &extent.lower_first))
1040 			goto out;
1041 		if (!isspace(*pos))
1042 			goto out;
1043 
1044 		pos = skip_spaces(pos);
1045 		if (map_parse_u32(&pos, &extent.count))
1046 			goto out;
1047 		if (*pos && !isspace(*pos))
1048 			goto out;
1049 
1050 		/* Verify there is not trailing junk on the line */
1051 		pos = skip_spaces(pos);
1052 		if (*pos != '\0')
1053 			goto out;
1054 
1055 		/* Verify we have been given valid starting values */
1056 		if ((extent.first == (u32) -1) ||
1057 		    (extent.lower_first == (u32) -1))
1058 			goto out;
1059 
1060 		/* Verify count is not zero and does not cause the
1061 		 * extent to wrap
1062 		 */
1063 		if ((extent.first + extent.count) <= extent.first)
1064 			goto out;
1065 		if ((extent.lower_first + extent.count) <=
1066 		     extent.lower_first)
1067 			goto out;
1068 
1069 		/* Do the ranges in extent overlap any previous extents? */
1070 		if (mappings_overlap(&new_map, &extent))
1071 			goto out;
1072 
1073 		if ((new_map.nr_extents + 1) == UID_GID_MAP_MAX_EXTENTS &&
1074 		    (next_line != NULL))
1075 			goto out;
1076 
1077 		ret = uid_gid_map_insert_extent(&new_map, &extent);
1078 		if (ret < 0)
1079 			goto out;
1080 		ret = -EINVAL;
1081 	}
1082 	/* Be very certain the new map actually exists */
1083 	if (new_map.nr_extents == 0)
1084 		goto out;
1085 
1086 	ret = -EPERM;
1087 	/* Validate the user is allowed to use user id's mapped to. */
1088 	if (!new_idmap_permitted(file, map_ns, cap_setid, &new_map))
1089 		goto out;
1090 
1091 	ret = -EPERM;
1092 	/* Map the lower ids from the parent user namespace to the
1093 	 * kernel global id space.
1094 	 */
1095 	for (idx = 0; idx < new_map.nr_extents; idx++) {
1096 		struct uid_gid_extent *e;
1097 		u32 lower_first;
1098 
1099 		if (new_map.nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
1100 			e = &new_map.extent[idx];
1101 		else
1102 			e = &new_map.forward[idx];
1103 
1104 		lower_first = map_id_range_down(parent_map,
1105 						e->lower_first,
1106 						e->count);
1107 
1108 		/* Fail if we can not map the specified extent to
1109 		 * the kernel global id space.
1110 		 */
1111 		if (lower_first == (u32) -1)
1112 			goto out;
1113 
1114 		e->lower_first = lower_first;
1115 	}
1116 
1117 	/*
1118 	 * If we want to use binary search for lookup, this clones the extent
1119 	 * array and sorts both copies.
1120 	 */
1121 	ret = uid_gid_map_sort(&new_map);
1122 	if (ret < 0)
1123 		goto out;
1124 
1125 	/* Install the map */
1126 	if (new_map.nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS) {
1127 		memcpy(map->extent, new_map.extent,
1128 		       new_map.nr_extents * sizeof(new_map.extent[0]));
1129 	} else {
1130 		map->forward = new_map.forward;
1131 		map->reverse = new_map.reverse;
1132 	}
1133 	smp_wmb();
1134 	map->nr_extents = new_map.nr_extents;
1135 
1136 	*ppos = count;
1137 	ret = count;
1138 out:
1139 	if (ret < 0 && new_map.nr_extents > UID_GID_MAP_MAX_BASE_EXTENTS) {
1140 		kfree(new_map.forward);
1141 		kfree(new_map.reverse);
1142 		map->forward = NULL;
1143 		map->reverse = NULL;
1144 		map->nr_extents = 0;
1145 	}
1146 
1147 	mutex_unlock(&userns_state_mutex);
1148 	kfree(kbuf);
1149 	return ret;
1150 }
1151 
1152 ssize_t proc_uid_map_write(struct file *file, const char __user *buf,
1153 			   size_t size, loff_t *ppos)
1154 {
1155 	struct seq_file *seq = file->private_data;
1156 	struct user_namespace *ns = seq->private;
1157 	struct user_namespace *seq_ns = seq_user_ns(seq);
1158 
1159 	if (!ns->parent)
1160 		return -EPERM;
1161 
1162 	if ((seq_ns != ns) && (seq_ns != ns->parent))
1163 		return -EPERM;
1164 
1165 	return map_write(file, buf, size, ppos, CAP_SETUID,
1166 			 &ns->uid_map, &ns->parent->uid_map);
1167 }
1168 
1169 ssize_t proc_gid_map_write(struct file *file, const char __user *buf,
1170 			   size_t size, loff_t *ppos)
1171 {
1172 	struct seq_file *seq = file->private_data;
1173 	struct user_namespace *ns = seq->private;
1174 	struct user_namespace *seq_ns = seq_user_ns(seq);
1175 
1176 	if (!ns->parent)
1177 		return -EPERM;
1178 
1179 	if ((seq_ns != ns) && (seq_ns != ns->parent))
1180 		return -EPERM;
1181 
1182 	return map_write(file, buf, size, ppos, CAP_SETGID,
1183 			 &ns->gid_map, &ns->parent->gid_map);
1184 }
1185 
1186 ssize_t proc_projid_map_write(struct file *file, const char __user *buf,
1187 			      size_t size, loff_t *ppos)
1188 {
1189 	struct seq_file *seq = file->private_data;
1190 	struct user_namespace *ns = seq->private;
1191 	struct user_namespace *seq_ns = seq_user_ns(seq);
1192 
1193 	if (!ns->parent)
1194 		return -EPERM;
1195 
1196 	if ((seq_ns != ns) && (seq_ns != ns->parent))
1197 		return -EPERM;
1198 
1199 	/* Anyone can set any valid project id no capability needed */
1200 	return map_write(file, buf, size, ppos, -1,
1201 			 &ns->projid_map, &ns->parent->projid_map);
1202 }
1203 
1204 static bool new_idmap_permitted(const struct file *file,
1205 				struct user_namespace *ns, int cap_setid,
1206 				struct uid_gid_map *new_map)
1207 {
1208 	const struct cred *cred = file->f_cred;
1209 
1210 	if (cap_setid == CAP_SETUID && !verify_root_map(file, ns, new_map))
1211 		return false;
1212 
1213 	/* Don't allow mappings that would allow anything that wouldn't
1214 	 * be allowed without the establishment of unprivileged mappings.
1215 	 */
1216 	if ((new_map->nr_extents == 1) && (new_map->extent[0].count == 1) &&
1217 	    uid_eq(ns->owner, cred->euid)) {
1218 		u32 id = new_map->extent[0].lower_first;
1219 		if (cap_setid == CAP_SETUID) {
1220 			kuid_t uid = make_kuid(ns->parent, id);
1221 			if (uid_eq(uid, cred->euid))
1222 				return true;
1223 		} else if (cap_setid == CAP_SETGID) {
1224 			kgid_t gid = make_kgid(ns->parent, id);
1225 			if (!(ns->flags & USERNS_SETGROUPS_ALLOWED) &&
1226 			    gid_eq(gid, cred->egid))
1227 				return true;
1228 		}
1229 	}
1230 
1231 	/* Allow anyone to set a mapping that doesn't require privilege */
1232 	if (!cap_valid(cap_setid))
1233 		return true;
1234 
1235 	/* Allow the specified ids if we have the appropriate capability
1236 	 * (CAP_SETUID or CAP_SETGID) over the parent user namespace.
1237 	 * And the opener of the id file also has the appropriate capability.
1238 	 */
1239 	if (ns_capable(ns->parent, cap_setid) &&
1240 	    file_ns_capable(file, ns->parent, cap_setid))
1241 		return true;
1242 
1243 	return false;
1244 }
1245 
1246 int proc_setgroups_show(struct seq_file *seq, void *v)
1247 {
1248 	struct user_namespace *ns = seq->private;
1249 	unsigned long userns_flags = READ_ONCE(ns->flags);
1250 
1251 	seq_printf(seq, "%s\n",
1252 		   (userns_flags & USERNS_SETGROUPS_ALLOWED) ?
1253 		   "allow" : "deny");
1254 	return 0;
1255 }
1256 
1257 ssize_t proc_setgroups_write(struct file *file, const char __user *buf,
1258 			     size_t count, loff_t *ppos)
1259 {
1260 	struct seq_file *seq = file->private_data;
1261 	struct user_namespace *ns = seq->private;
1262 	char kbuf[8], *pos;
1263 	bool setgroups_allowed;
1264 	ssize_t ret;
1265 
1266 	/* Only allow a very narrow range of strings to be written */
1267 	ret = -EINVAL;
1268 	if ((*ppos != 0) || (count >= sizeof(kbuf)))
1269 		goto out;
1270 
1271 	/* What was written? */
1272 	ret = -EFAULT;
1273 	if (copy_from_user(kbuf, buf, count))
1274 		goto out;
1275 	kbuf[count] = '\0';
1276 	pos = kbuf;
1277 
1278 	/* What is being requested? */
1279 	ret = -EINVAL;
1280 	if (strncmp(pos, "allow", 5) == 0) {
1281 		pos += 5;
1282 		setgroups_allowed = true;
1283 	}
1284 	else if (strncmp(pos, "deny", 4) == 0) {
1285 		pos += 4;
1286 		setgroups_allowed = false;
1287 	}
1288 	else
1289 		goto out;
1290 
1291 	/* Verify there is not trailing junk on the line */
1292 	pos = skip_spaces(pos);
1293 	if (*pos != '\0')
1294 		goto out;
1295 
1296 	ret = -EPERM;
1297 	mutex_lock(&userns_state_mutex);
1298 	if (setgroups_allowed) {
1299 		/* Enabling setgroups after setgroups has been disabled
1300 		 * is not allowed.
1301 		 */
1302 		if (!(ns->flags & USERNS_SETGROUPS_ALLOWED))
1303 			goto out_unlock;
1304 	} else {
1305 		/* Permanently disabling setgroups after setgroups has
1306 		 * been enabled by writing the gid_map is not allowed.
1307 		 */
1308 		if (ns->gid_map.nr_extents != 0)
1309 			goto out_unlock;
1310 		ns->flags &= ~USERNS_SETGROUPS_ALLOWED;
1311 	}
1312 	mutex_unlock(&userns_state_mutex);
1313 
1314 	/* Report a successful write */
1315 	*ppos = count;
1316 	ret = count;
1317 out:
1318 	return ret;
1319 out_unlock:
1320 	mutex_unlock(&userns_state_mutex);
1321 	goto out;
1322 }
1323 
1324 bool userns_may_setgroups(const struct user_namespace *ns)
1325 {
1326 	bool allowed;
1327 
1328 	mutex_lock(&userns_state_mutex);
1329 	/* It is not safe to use setgroups until a gid mapping in
1330 	 * the user namespace has been established.
1331 	 */
1332 	allowed = ns->gid_map.nr_extents != 0;
1333 	/* Is setgroups allowed? */
1334 	allowed = allowed && (ns->flags & USERNS_SETGROUPS_ALLOWED);
1335 	mutex_unlock(&userns_state_mutex);
1336 
1337 	return allowed;
1338 }
1339 
1340 /*
1341  * Returns true if @child is the same namespace or a descendant of
1342  * @ancestor.
1343  */
1344 bool in_userns(const struct user_namespace *ancestor,
1345 	       const struct user_namespace *child)
1346 {
1347 	const struct user_namespace *ns;
1348 	for (ns = child; ns->level > ancestor->level; ns = ns->parent)
1349 		;
1350 	return (ns == ancestor);
1351 }
1352 
1353 bool current_in_userns(const struct user_namespace *target_ns)
1354 {
1355 	return in_userns(target_ns, current_user_ns());
1356 }
1357 EXPORT_SYMBOL(current_in_userns);
1358 
1359 static struct ns_common *userns_get(struct task_struct *task)
1360 {
1361 	struct user_namespace *user_ns;
1362 
1363 	rcu_read_lock();
1364 	user_ns = get_user_ns(__task_cred(task)->user_ns);
1365 	rcu_read_unlock();
1366 
1367 	return user_ns ? &user_ns->ns : NULL;
1368 }
1369 
1370 static void userns_put(struct ns_common *ns)
1371 {
1372 	put_user_ns(to_user_ns(ns));
1373 }
1374 
1375 static int userns_install(struct nsset *nsset, struct ns_common *ns)
1376 {
1377 	struct user_namespace *user_ns = to_user_ns(ns);
1378 	struct cred *cred;
1379 
1380 	/* Don't allow gaining capabilities by reentering
1381 	 * the same user namespace.
1382 	 */
1383 	if (user_ns == current_user_ns())
1384 		return -EINVAL;
1385 
1386 	/* Tasks that share a thread group must share a user namespace */
1387 	if (!thread_group_empty(current))
1388 		return -EINVAL;
1389 
1390 	if (current->fs->users != 1)
1391 		return -EINVAL;
1392 
1393 	if (!ns_capable(user_ns, CAP_SYS_ADMIN))
1394 		return -EPERM;
1395 
1396 	cred = nsset_cred(nsset);
1397 	if (!cred)
1398 		return -EINVAL;
1399 
1400 	put_user_ns(cred->user_ns);
1401 	set_cred_user_ns(cred, get_user_ns(user_ns));
1402 
1403 	if (set_cred_ucounts(cred) < 0)
1404 		return -EINVAL;
1405 
1406 	return 0;
1407 }
1408 
1409 struct ns_common *ns_get_owner(struct ns_common *ns)
1410 {
1411 	struct user_namespace *my_user_ns = current_user_ns();
1412 	struct user_namespace *owner, *p;
1413 
1414 	/* See if the owner is in the current user namespace */
1415 	owner = p = ns->ops->owner(ns);
1416 	for (;;) {
1417 		if (!p)
1418 			return ERR_PTR(-EPERM);
1419 		if (p == my_user_ns)
1420 			break;
1421 		p = p->parent;
1422 	}
1423 
1424 	return &get_user_ns(owner)->ns;
1425 }
1426 
1427 static struct user_namespace *userns_owner(struct ns_common *ns)
1428 {
1429 	return to_user_ns(ns)->parent;
1430 }
1431 
1432 const struct proc_ns_operations userns_operations = {
1433 	.name		= "user",
1434 	.get		= userns_get,
1435 	.put		= userns_put,
1436 	.install	= userns_install,
1437 	.owner		= userns_owner,
1438 	.get_parent	= ns_get_owner,
1439 };
1440 
1441 static __init int user_namespaces_init(void)
1442 {
1443 	user_ns_cachep = KMEM_CACHE(user_namespace, SLAB_PANIC | SLAB_ACCOUNT);
1444 	ns_tree_add(&init_user_ns);
1445 	return 0;
1446 }
1447 subsys_initcall(user_namespaces_init);
1448