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