1 // SPDX-License-Identifier: GPL-2.0-only
3 #include <linux/export.h>
4 #include <linux/nsproxy.h>
5 #include <linux/slab.h>
6 #include <linux/sched/signal.h>
7 #include <linux/user_namespace.h>
8 #include <linux/proc_ns.h>
9 #include <linux/highuid.h>
10 #include <linux/cred.h>
11 #include <linux/securebits.h>
12 #include <linux/security.h>
13 #include <linux/keyctl.h>
14 #include <linux/key-type.h>
15 #include <keys/user-type.h>
16 #include <linux/seq_file.h>
18 #include <linux/uaccess.h>
19 #include <linux/ctype.h>
20 #include <linux/projid.h>
21 #include <linux/fs_struct.h>
22 #include <linux/bsearch.h>
23 #include <linux/sort.h>
25 static struct kmem_cache *user_ns_cachep __read_mostly;
26 static DEFINE_MUTEX(userns_state_mutex);
28 static bool new_idmap_permitted(const struct file *file,
29 struct user_namespace *ns, int cap_setid,
30 struct uid_gid_map *map);
31 static void free_user_ns(struct work_struct *work);
33 static struct ucounts *inc_user_namespaces(struct user_namespace *ns, kuid_t uid)
35 return inc_ucount(ns, uid, UCOUNT_USER_NAMESPACES);
38 static void dec_user_namespaces(struct ucounts *ucounts)
40 return dec_ucount(ucounts, UCOUNT_USER_NAMESPACES);
43 static void set_cred_user_ns(struct cred *cred, struct user_namespace *user_ns)
45 /* Start with the same capabilities as init but useless for doing
46 * anything as the capabilities are bound to the new user namespace.
48 cred->securebits = SECUREBITS_DEFAULT;
49 cred->cap_inheritable = CAP_EMPTY_SET;
50 cred->cap_permitted = CAP_FULL_SET;
51 cred->cap_effective = CAP_FULL_SET;
52 cred->cap_ambient = CAP_EMPTY_SET;
53 cred->cap_bset = CAP_FULL_SET;
55 key_put(cred->request_key_auth);
56 cred->request_key_auth = NULL;
58 /* tgcred will be cleared in our caller bc CLONE_THREAD won't be set */
59 cred->user_ns = user_ns;
62 static unsigned long enforced_nproc_rlimit(void)
64 unsigned long limit = RLIM_INFINITY;
66 /* Is RLIMIT_NPROC currently enforced? */
67 if (!uid_eq(current_uid(), GLOBAL_ROOT_UID) ||
68 (current_user_ns() != &init_user_ns))
69 limit = rlimit(RLIMIT_NPROC);
75 * Create a new user namespace, deriving the creator from the user in the
76 * passed credentials, and replacing that user with the new root user for the
79 * This is called by copy_creds(), which will finish setting the target task's
82 int create_user_ns(struct cred *new)
84 struct user_namespace *ns, *parent_ns = new->user_ns;
85 kuid_t owner = new->euid;
86 kgid_t group = new->egid;
87 struct ucounts *ucounts;
91 if (parent_ns->level > 32)
94 ucounts = inc_user_namespaces(parent_ns, owner);
99 * Verify that we can not violate the policy of which files
100 * may be accessed that is specified by the root directory,
101 * by verifying that the root directory is at the root of the
102 * mount namespace which allows all files to be accessed.
105 if (current_chrooted())
108 /* The creator needs a mapping in the parent user namespace
109 * or else we won't be able to reasonably tell userspace who
110 * created a user_namespace.
113 if (!kuid_has_mapping(parent_ns, owner) ||
114 !kgid_has_mapping(parent_ns, group))
117 ret = security_create_user_ns(new);
122 ns = kmem_cache_zalloc(user_ns_cachep, GFP_KERNEL);
126 ns->parent_could_setfcap = cap_raised(new->cap_effective, CAP_SETFCAP);
127 ret = ns_alloc_inum(&ns->ns);
130 ns->ns.ops = &userns_operations;
132 refcount_set(&ns->ns.count, 1);
133 /* Leave the new->user_ns reference with the new user namespace. */
134 ns->parent = parent_ns;
135 ns->level = parent_ns->level + 1;
138 INIT_WORK(&ns->work, free_user_ns);
139 for (i = 0; i < UCOUNT_COUNTS; i++) {
140 ns->ucount_max[i] = INT_MAX;
142 set_userns_rlimit_max(ns, UCOUNT_RLIMIT_NPROC, enforced_nproc_rlimit());
143 set_userns_rlimit_max(ns, UCOUNT_RLIMIT_MSGQUEUE, rlimit(RLIMIT_MSGQUEUE));
144 set_userns_rlimit_max(ns, UCOUNT_RLIMIT_SIGPENDING, rlimit(RLIMIT_SIGPENDING));
145 set_userns_rlimit_max(ns, UCOUNT_RLIMIT_MEMLOCK, rlimit(RLIMIT_MEMLOCK));
146 ns->ucounts = ucounts;
148 /* Inherit USERNS_SETGROUPS_ALLOWED from our parent */
149 mutex_lock(&userns_state_mutex);
150 ns->flags = parent_ns->flags;
151 mutex_unlock(&userns_state_mutex);
154 INIT_LIST_HEAD(&ns->keyring_name_list);
155 init_rwsem(&ns->keyring_sem);
158 if (!setup_userns_sysctls(ns))
161 set_cred_user_ns(new, ns);
164 #ifdef CONFIG_PERSISTENT_KEYRINGS
165 key_put(ns->persistent_keyring_register);
167 ns_free_inum(&ns->ns);
169 kmem_cache_free(user_ns_cachep, ns);
171 dec_user_namespaces(ucounts);
176 int unshare_userns(unsigned long unshare_flags, struct cred **new_cred)
181 if (!(unshare_flags & CLONE_NEWUSER))
184 cred = prepare_creds();
186 err = create_user_ns(cred);
196 static void free_user_ns(struct work_struct *work)
198 struct user_namespace *parent, *ns =
199 container_of(work, struct user_namespace, work);
202 struct ucounts *ucounts = ns->ucounts;
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);
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);
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);
216 retire_userns_sysctls(ns);
217 key_free_user_ns(ns);
218 ns_free_inum(&ns->ns);
219 kmem_cache_free(user_ns_cachep, ns);
220 dec_user_namespaces(ucounts);
222 } while (refcount_dec_and_test(&parent->ns.count));
225 void __put_user_ns(struct user_namespace *ns)
227 schedule_work(&ns->work);
229 EXPORT_SYMBOL(__put_user_ns);
232 * idmap_key struct holds the information necessary to find an idmapping in a
233 * sorted idmap array. It is passed to cmp_map_id() as first argument.
236 bool map_up; /* true -> id from kid; false -> kid from id */
237 u32 id; /* id to find */
238 u32 count; /* == 0 unless used with map_id_range_down() */
242 * cmp_map_id - Function to be passed to bsearch() to find the requested
243 * idmapping. Expects struct idmap_key to be passed via @k.
245 static int cmp_map_id(const void *k, const void *e)
247 u32 first, last, id2;
248 const struct idmap_key *key = k;
249 const struct uid_gid_extent *el = e;
251 id2 = key->id + key->count - 1;
253 /* handle map_id_{down,up}() */
255 first = el->lower_first;
259 last = first + el->count - 1;
261 if (key->id >= first && key->id <= last &&
262 (id2 >= first && id2 <= last))
265 if (key->id < first || id2 < first)
272 * map_id_range_down_max - Find idmap via binary search in ordered idmap array.
273 * Can only be called if number of mappings exceeds UID_GID_MAP_MAX_BASE_EXTENTS.
275 static struct uid_gid_extent *
276 map_id_range_down_max(unsigned extents, struct uid_gid_map *map, u32 id, u32 count)
278 struct idmap_key key;
284 return bsearch(&key, map->forward, extents,
285 sizeof(struct uid_gid_extent), cmp_map_id);
289 * map_id_range_down_base - Find idmap via binary search in static extent array.
290 * Can only be called if number of mappings is equal or less than
291 * UID_GID_MAP_MAX_BASE_EXTENTS.
293 static struct uid_gid_extent *
294 map_id_range_down_base(unsigned extents, struct uid_gid_map *map, u32 id, u32 count)
297 u32 first, last, id2;
299 id2 = id + count - 1;
301 /* Find the matching extent */
302 for (idx = 0; idx < extents; idx++) {
303 first = map->extent[idx].first;
304 last = first + map->extent[idx].count - 1;
305 if (id >= first && id <= last &&
306 (id2 >= first && id2 <= last))
307 return &map->extent[idx];
312 static u32 map_id_range_down(struct uid_gid_map *map, u32 id, u32 count)
314 struct uid_gid_extent *extent;
315 unsigned extents = map->nr_extents;
318 if (extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
319 extent = map_id_range_down_base(extents, map, id, count);
321 extent = map_id_range_down_max(extents, map, id, count);
323 /* Map the id or note failure */
325 id = (id - extent->first) + extent->lower_first;
332 static u32 map_id_down(struct uid_gid_map *map, u32 id)
334 return map_id_range_down(map, id, 1);
338 * map_id_up_base - Find idmap via binary search in static extent array.
339 * Can only be called if number of mappings is equal or less than
340 * UID_GID_MAP_MAX_BASE_EXTENTS.
342 static struct uid_gid_extent *
343 map_id_up_base(unsigned extents, struct uid_gid_map *map, u32 id)
348 /* Find the matching extent */
349 for (idx = 0; idx < extents; idx++) {
350 first = map->extent[idx].lower_first;
351 last = first + map->extent[idx].count - 1;
352 if (id >= first && id <= last)
353 return &map->extent[idx];
359 * map_id_up_max - Find idmap via binary search in ordered idmap array.
360 * Can only be called if number of mappings exceeds UID_GID_MAP_MAX_BASE_EXTENTS.
362 static struct uid_gid_extent *
363 map_id_up_max(unsigned extents, struct uid_gid_map *map, u32 id)
365 struct idmap_key key;
371 return bsearch(&key, map->reverse, extents,
372 sizeof(struct uid_gid_extent), cmp_map_id);
375 static u32 map_id_up(struct uid_gid_map *map, u32 id)
377 struct uid_gid_extent *extent;
378 unsigned extents = map->nr_extents;
381 if (extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
382 extent = map_id_up_base(extents, map, id);
384 extent = map_id_up_max(extents, map, id);
386 /* Map the id or note failure */
388 id = (id - extent->lower_first) + extent->first;
396 * make_kuid - Map a user-namespace uid pair into a kuid.
397 * @ns: User namespace that the uid is in
398 * @uid: User identifier
400 * Maps a user-namespace uid pair into a kernel internal kuid,
401 * and returns that kuid.
403 * When there is no mapping defined for the user-namespace uid
404 * pair INVALID_UID is returned. Callers are expected to test
405 * for and handle INVALID_UID being returned. INVALID_UID
406 * may be tested for using uid_valid().
408 kuid_t make_kuid(struct user_namespace *ns, uid_t uid)
410 /* Map the uid to a global kernel uid */
411 return KUIDT_INIT(map_id_down(&ns->uid_map, uid));
413 EXPORT_SYMBOL(make_kuid);
416 * from_kuid - Create a uid from a kuid user-namespace pair.
417 * @targ: The user namespace we want a uid in.
418 * @kuid: The kernel internal uid to start with.
420 * Map @kuid into the user-namespace specified by @targ and
421 * return the resulting uid.
423 * There is always a mapping into the initial user_namespace.
425 * If @kuid has no mapping in @targ (uid_t)-1 is returned.
427 uid_t from_kuid(struct user_namespace *targ, kuid_t kuid)
429 /* Map the uid from a global kernel uid */
430 return map_id_up(&targ->uid_map, __kuid_val(kuid));
432 EXPORT_SYMBOL(from_kuid);
435 * from_kuid_munged - Create a uid from a kuid user-namespace pair.
436 * @targ: The user namespace we want a uid in.
437 * @kuid: The kernel internal uid to start with.
439 * Map @kuid into the user-namespace specified by @targ and
440 * return the resulting uid.
442 * There is always a mapping into the initial user_namespace.
444 * Unlike from_kuid from_kuid_munged never fails and always
445 * returns a valid uid. This makes from_kuid_munged appropriate
446 * for use in syscalls like stat and getuid where failing the
447 * system call and failing to provide a valid uid are not an
450 * If @kuid has no mapping in @targ overflowuid is returned.
452 uid_t from_kuid_munged(struct user_namespace *targ, kuid_t kuid)
455 uid = from_kuid(targ, kuid);
457 if (uid == (uid_t) -1)
461 EXPORT_SYMBOL(from_kuid_munged);
464 * make_kgid - Map a user-namespace gid pair into a kgid.
465 * @ns: User namespace that the gid is in
466 * @gid: group identifier
468 * Maps a user-namespace gid pair into a kernel internal kgid,
469 * and returns that kgid.
471 * When there is no mapping defined for the user-namespace gid
472 * pair INVALID_GID is returned. Callers are expected to test
473 * for and handle INVALID_GID being returned. INVALID_GID may be
474 * tested for using gid_valid().
476 kgid_t make_kgid(struct user_namespace *ns, gid_t gid)
478 /* Map the gid to a global kernel gid */
479 return KGIDT_INIT(map_id_down(&ns->gid_map, gid));
481 EXPORT_SYMBOL(make_kgid);
484 * from_kgid - Create a gid from a kgid user-namespace pair.
485 * @targ: The user namespace we want a gid in.
486 * @kgid: The kernel internal gid to start with.
488 * Map @kgid into the user-namespace specified by @targ and
489 * return the resulting gid.
491 * There is always a mapping into the initial user_namespace.
493 * If @kgid has no mapping in @targ (gid_t)-1 is returned.
495 gid_t from_kgid(struct user_namespace *targ, kgid_t kgid)
497 /* Map the gid from a global kernel gid */
498 return map_id_up(&targ->gid_map, __kgid_val(kgid));
500 EXPORT_SYMBOL(from_kgid);
503 * from_kgid_munged - Create a gid from a kgid user-namespace pair.
504 * @targ: The user namespace we want a gid in.
505 * @kgid: The kernel internal gid to start with.
507 * Map @kgid into the user-namespace specified by @targ and
508 * return the resulting gid.
510 * There is always a mapping into the initial user_namespace.
512 * Unlike from_kgid from_kgid_munged never fails and always
513 * returns a valid gid. This makes from_kgid_munged appropriate
514 * for use in syscalls like stat and getgid where failing the
515 * system call and failing to provide a valid gid are not options.
517 * If @kgid has no mapping in @targ overflowgid is returned.
519 gid_t from_kgid_munged(struct user_namespace *targ, kgid_t kgid)
522 gid = from_kgid(targ, kgid);
524 if (gid == (gid_t) -1)
528 EXPORT_SYMBOL(from_kgid_munged);
531 * make_kprojid - Map a user-namespace projid pair into a kprojid.
532 * @ns: User namespace that the projid is in
533 * @projid: Project identifier
535 * Maps a user-namespace uid pair into a kernel internal kuid,
536 * and returns that kuid.
538 * When there is no mapping defined for the user-namespace projid
539 * pair INVALID_PROJID is returned. Callers are expected to test
540 * for and handle INVALID_PROJID being returned. INVALID_PROJID
541 * may be tested for using projid_valid().
543 kprojid_t make_kprojid(struct user_namespace *ns, projid_t projid)
545 /* Map the uid to a global kernel uid */
546 return KPROJIDT_INIT(map_id_down(&ns->projid_map, projid));
548 EXPORT_SYMBOL(make_kprojid);
551 * from_kprojid - Create a projid from a kprojid user-namespace pair.
552 * @targ: The user namespace we want a projid in.
553 * @kprojid: The kernel internal project identifier to start with.
555 * Map @kprojid into the user-namespace specified by @targ and
556 * return the resulting projid.
558 * There is always a mapping into the initial user_namespace.
560 * If @kprojid has no mapping in @targ (projid_t)-1 is returned.
562 projid_t from_kprojid(struct user_namespace *targ, kprojid_t kprojid)
564 /* Map the uid from a global kernel uid */
565 return map_id_up(&targ->projid_map, __kprojid_val(kprojid));
567 EXPORT_SYMBOL(from_kprojid);
570 * from_kprojid_munged - Create a projiid from a kprojid user-namespace pair.
571 * @targ: The user namespace we want a projid in.
572 * @kprojid: The kernel internal projid to start with.
574 * Map @kprojid into the user-namespace specified by @targ and
575 * return the resulting projid.
577 * There is always a mapping into the initial user_namespace.
579 * Unlike from_kprojid from_kprojid_munged never fails and always
580 * returns a valid projid. This makes from_kprojid_munged
581 * appropriate for use in syscalls like stat and where
582 * failing the system call and failing to provide a valid projid are
585 * If @kprojid has no mapping in @targ OVERFLOW_PROJID is returned.
587 projid_t from_kprojid_munged(struct user_namespace *targ, kprojid_t kprojid)
590 projid = from_kprojid(targ, kprojid);
592 if (projid == (projid_t) -1)
593 projid = OVERFLOW_PROJID;
596 EXPORT_SYMBOL(from_kprojid_munged);
599 static int uid_m_show(struct seq_file *seq, void *v)
601 struct user_namespace *ns = seq->private;
602 struct uid_gid_extent *extent = v;
603 struct user_namespace *lower_ns;
606 lower_ns = seq_user_ns(seq);
607 if ((lower_ns == ns) && lower_ns->parent)
608 lower_ns = lower_ns->parent;
610 lower = from_kuid(lower_ns, KUIDT_INIT(extent->lower_first));
612 seq_printf(seq, "%10u %10u %10u\n",
620 static int gid_m_show(struct seq_file *seq, void *v)
622 struct user_namespace *ns = seq->private;
623 struct uid_gid_extent *extent = v;
624 struct user_namespace *lower_ns;
627 lower_ns = seq_user_ns(seq);
628 if ((lower_ns == ns) && lower_ns->parent)
629 lower_ns = lower_ns->parent;
631 lower = from_kgid(lower_ns, KGIDT_INIT(extent->lower_first));
633 seq_printf(seq, "%10u %10u %10u\n",
641 static int projid_m_show(struct seq_file *seq, void *v)
643 struct user_namespace *ns = seq->private;
644 struct uid_gid_extent *extent = v;
645 struct user_namespace *lower_ns;
648 lower_ns = seq_user_ns(seq);
649 if ((lower_ns == ns) && lower_ns->parent)
650 lower_ns = lower_ns->parent;
652 lower = from_kprojid(lower_ns, KPROJIDT_INIT(extent->lower_first));
654 seq_printf(seq, "%10u %10u %10u\n",
662 static void *m_start(struct seq_file *seq, loff_t *ppos,
663 struct uid_gid_map *map)
666 unsigned extents = map->nr_extents;
672 if (extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
673 return &map->extent[pos];
675 return &map->forward[pos];
678 static void *uid_m_start(struct seq_file *seq, loff_t *ppos)
680 struct user_namespace *ns = seq->private;
682 return m_start(seq, ppos, &ns->uid_map);
685 static void *gid_m_start(struct seq_file *seq, loff_t *ppos)
687 struct user_namespace *ns = seq->private;
689 return m_start(seq, ppos, &ns->gid_map);
692 static void *projid_m_start(struct seq_file *seq, loff_t *ppos)
694 struct user_namespace *ns = seq->private;
696 return m_start(seq, ppos, &ns->projid_map);
699 static void *m_next(struct seq_file *seq, void *v, loff_t *pos)
702 return seq->op->start(seq, pos);
705 static void m_stop(struct seq_file *seq, void *v)
710 const struct seq_operations proc_uid_seq_operations = {
711 .start = uid_m_start,
717 const struct seq_operations proc_gid_seq_operations = {
718 .start = gid_m_start,
724 const struct seq_operations proc_projid_seq_operations = {
725 .start = projid_m_start,
728 .show = projid_m_show,
731 static bool mappings_overlap(struct uid_gid_map *new_map,
732 struct uid_gid_extent *extent)
734 u32 upper_first, lower_first, upper_last, lower_last;
737 upper_first = extent->first;
738 lower_first = extent->lower_first;
739 upper_last = upper_first + extent->count - 1;
740 lower_last = lower_first + extent->count - 1;
742 for (idx = 0; idx < new_map->nr_extents; idx++) {
743 u32 prev_upper_first, prev_lower_first;
744 u32 prev_upper_last, prev_lower_last;
745 struct uid_gid_extent *prev;
747 if (new_map->nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
748 prev = &new_map->extent[idx];
750 prev = &new_map->forward[idx];
752 prev_upper_first = prev->first;
753 prev_lower_first = prev->lower_first;
754 prev_upper_last = prev_upper_first + prev->count - 1;
755 prev_lower_last = prev_lower_first + prev->count - 1;
757 /* Does the upper range intersect a previous extent? */
758 if ((prev_upper_first <= upper_last) &&
759 (prev_upper_last >= upper_first))
762 /* Does the lower range intersect a previous extent? */
763 if ((prev_lower_first <= lower_last) &&
764 (prev_lower_last >= lower_first))
771 * insert_extent - Safely insert a new idmap extent into struct uid_gid_map.
772 * Takes care to allocate a 4K block of memory if the number of mappings exceeds
773 * UID_GID_MAP_MAX_BASE_EXTENTS.
775 static int insert_extent(struct uid_gid_map *map, struct uid_gid_extent *extent)
777 struct uid_gid_extent *dest;
779 if (map->nr_extents == UID_GID_MAP_MAX_BASE_EXTENTS) {
780 struct uid_gid_extent *forward;
782 /* Allocate memory for 340 mappings. */
783 forward = kmalloc_array(UID_GID_MAP_MAX_EXTENTS,
784 sizeof(struct uid_gid_extent),
789 /* Copy over memory. Only set up memory for the forward pointer.
790 * Defer the memory setup for the reverse pointer.
792 memcpy(forward, map->extent,
793 map->nr_extents * sizeof(map->extent[0]));
795 map->forward = forward;
799 if (map->nr_extents < UID_GID_MAP_MAX_BASE_EXTENTS)
800 dest = &map->extent[map->nr_extents];
802 dest = &map->forward[map->nr_extents];
809 /* cmp function to sort() forward mappings */
810 static int cmp_extents_forward(const void *a, const void *b)
812 const struct uid_gid_extent *e1 = a;
813 const struct uid_gid_extent *e2 = b;
815 if (e1->first < e2->first)
818 if (e1->first > e2->first)
824 /* cmp function to sort() reverse mappings */
825 static int cmp_extents_reverse(const void *a, const void *b)
827 const struct uid_gid_extent *e1 = a;
828 const struct uid_gid_extent *e2 = b;
830 if (e1->lower_first < e2->lower_first)
833 if (e1->lower_first > e2->lower_first)
840 * sort_idmaps - Sorts an array of idmap entries.
841 * Can only be called if number of mappings exceeds UID_GID_MAP_MAX_BASE_EXTENTS.
843 static int sort_idmaps(struct uid_gid_map *map)
845 if (map->nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
848 /* Sort forward array. */
849 sort(map->forward, map->nr_extents, sizeof(struct uid_gid_extent),
850 cmp_extents_forward, NULL);
852 /* Only copy the memory from forward we actually need. */
853 map->reverse = kmemdup(map->forward,
854 map->nr_extents * sizeof(struct uid_gid_extent),
859 /* Sort reverse array. */
860 sort(map->reverse, map->nr_extents, sizeof(struct uid_gid_extent),
861 cmp_extents_reverse, NULL);
867 * verify_root_map() - check the uid 0 mapping
868 * @file: idmapping file
869 * @map_ns: user namespace of the target process
870 * @new_map: requested idmap
872 * If a process requests mapping parent uid 0 into the new ns, verify that the
873 * process writing the map had the CAP_SETFCAP capability as the target process
874 * will be able to write fscaps that are valid in ancestor user namespaces.
876 * Return: true if the mapping is allowed, false if not.
878 static bool verify_root_map(const struct file *file,
879 struct user_namespace *map_ns,
880 struct uid_gid_map *new_map)
883 const struct user_namespace *file_ns = file->f_cred->user_ns;
884 struct uid_gid_extent *extent0 = NULL;
886 for (idx = 0; idx < new_map->nr_extents; idx++) {
887 if (new_map->nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
888 extent0 = &new_map->extent[idx];
890 extent0 = &new_map->forward[idx];
891 if (extent0->lower_first == 0)
900 if (map_ns == file_ns) {
901 /* The process unshared its ns and is writing to its own
902 * /proc/self/uid_map. User already has full capabilites in
903 * the new namespace. Verify that the parent had CAP_SETFCAP
906 if (!file_ns->parent_could_setfcap)
909 /* Process p1 is writing to uid_map of p2, who is in a child
910 * user namespace to p1's. Verify that the opener of the map
911 * file has CAP_SETFCAP against the parent of the new map
913 if (!file_ns_capable(file, map_ns->parent, CAP_SETFCAP))
920 static ssize_t map_write(struct file *file, const char __user *buf,
921 size_t count, loff_t *ppos,
923 struct uid_gid_map *map,
924 struct uid_gid_map *parent_map)
926 struct seq_file *seq = file->private_data;
927 struct user_namespace *map_ns = seq->private;
928 struct uid_gid_map new_map;
930 struct uid_gid_extent extent;
931 char *kbuf = NULL, *pos, *next_line;
934 /* Only allow < page size writes at the beginning of the file */
935 if ((*ppos != 0) || (count >= PAGE_SIZE))
938 /* Slurp in the user data */
939 kbuf = memdup_user_nul(buf, count);
941 return PTR_ERR(kbuf);
944 * The userns_state_mutex serializes all writes to any given map.
946 * Any map is only ever written once.
948 * An id map fits within 1 cache line on most architectures.
950 * On read nothing needs to be done unless you are on an
951 * architecture with a crazy cache coherency model like alpha.
953 * There is a one time data dependency between reading the
954 * count of the extents and the values of the extents. The
955 * desired behavior is to see the values of the extents that
956 * were written before the count of the extents.
958 * To achieve this smp_wmb() is used on guarantee the write
959 * order and smp_rmb() is guaranteed that we don't have crazy
960 * architectures returning stale data.
962 mutex_lock(&userns_state_mutex);
964 memset(&new_map, 0, sizeof(struct uid_gid_map));
967 /* Only allow one successful write to the map */
968 if (map->nr_extents != 0)
972 * Adjusting namespace settings requires capabilities on the target.
974 if (cap_valid(cap_setid) && !file_ns_capable(file, map_ns, CAP_SYS_ADMIN))
977 /* Parse the user data */
980 for (; pos; pos = next_line) {
982 /* Find the end of line and ensure I don't look past it */
983 next_line = strchr(pos, '\n');
987 if (*next_line == '\0')
991 pos = skip_spaces(pos);
992 extent.first = simple_strtoul(pos, &pos, 10);
996 pos = skip_spaces(pos);
997 extent.lower_first = simple_strtoul(pos, &pos, 10);
1001 pos = skip_spaces(pos);
1002 extent.count = simple_strtoul(pos, &pos, 10);
1003 if (*pos && !isspace(*pos))
1006 /* Verify there is not trailing junk on the line */
1007 pos = skip_spaces(pos);
1011 /* Verify we have been given valid starting values */
1012 if ((extent.first == (u32) -1) ||
1013 (extent.lower_first == (u32) -1))
1016 /* Verify count is not zero and does not cause the
1019 if ((extent.first + extent.count) <= extent.first)
1021 if ((extent.lower_first + extent.count) <=
1025 /* Do the ranges in extent overlap any previous extents? */
1026 if (mappings_overlap(&new_map, &extent))
1029 if ((new_map.nr_extents + 1) == UID_GID_MAP_MAX_EXTENTS &&
1030 (next_line != NULL))
1033 ret = insert_extent(&new_map, &extent);
1038 /* Be very certain the new map actually exists */
1039 if (new_map.nr_extents == 0)
1043 /* Validate the user is allowed to use user id's mapped to. */
1044 if (!new_idmap_permitted(file, map_ns, cap_setid, &new_map))
1048 /* Map the lower ids from the parent user namespace to the
1049 * kernel global id space.
1051 for (idx = 0; idx < new_map.nr_extents; idx++) {
1052 struct uid_gid_extent *e;
1055 if (new_map.nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
1056 e = &new_map.extent[idx];
1058 e = &new_map.forward[idx];
1060 lower_first = map_id_range_down(parent_map,
1064 /* Fail if we can not map the specified extent to
1065 * the kernel global id space.
1067 if (lower_first == (u32) -1)
1070 e->lower_first = lower_first;
1074 * If we want to use binary search for lookup, this clones the extent
1075 * array and sorts both copies.
1077 ret = sort_idmaps(&new_map);
1081 /* Install the map */
1082 if (new_map.nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS) {
1083 memcpy(map->extent, new_map.extent,
1084 new_map.nr_extents * sizeof(new_map.extent[0]));
1086 map->forward = new_map.forward;
1087 map->reverse = new_map.reverse;
1090 map->nr_extents = new_map.nr_extents;
1095 if (ret < 0 && new_map.nr_extents > UID_GID_MAP_MAX_BASE_EXTENTS) {
1096 kfree(new_map.forward);
1097 kfree(new_map.reverse);
1098 map->forward = NULL;
1099 map->reverse = NULL;
1100 map->nr_extents = 0;
1103 mutex_unlock(&userns_state_mutex);
1108 ssize_t proc_uid_map_write(struct file *file, const char __user *buf,
1109 size_t size, loff_t *ppos)
1111 struct seq_file *seq = file->private_data;
1112 struct user_namespace *ns = seq->private;
1113 struct user_namespace *seq_ns = seq_user_ns(seq);
1118 if ((seq_ns != ns) && (seq_ns != ns->parent))
1121 return map_write(file, buf, size, ppos, CAP_SETUID,
1122 &ns->uid_map, &ns->parent->uid_map);
1125 ssize_t proc_gid_map_write(struct file *file, const char __user *buf,
1126 size_t size, loff_t *ppos)
1128 struct seq_file *seq = file->private_data;
1129 struct user_namespace *ns = seq->private;
1130 struct user_namespace *seq_ns = seq_user_ns(seq);
1135 if ((seq_ns != ns) && (seq_ns != ns->parent))
1138 return map_write(file, buf, size, ppos, CAP_SETGID,
1139 &ns->gid_map, &ns->parent->gid_map);
1142 ssize_t proc_projid_map_write(struct file *file, const char __user *buf,
1143 size_t size, loff_t *ppos)
1145 struct seq_file *seq = file->private_data;
1146 struct user_namespace *ns = seq->private;
1147 struct user_namespace *seq_ns = seq_user_ns(seq);
1152 if ((seq_ns != ns) && (seq_ns != ns->parent))
1155 /* Anyone can set any valid project id no capability needed */
1156 return map_write(file, buf, size, ppos, -1,
1157 &ns->projid_map, &ns->parent->projid_map);
1160 static bool new_idmap_permitted(const struct file *file,
1161 struct user_namespace *ns, int cap_setid,
1162 struct uid_gid_map *new_map)
1164 const struct cred *cred = file->f_cred;
1166 if (cap_setid == CAP_SETUID && !verify_root_map(file, ns, new_map))
1169 /* Don't allow mappings that would allow anything that wouldn't
1170 * be allowed without the establishment of unprivileged mappings.
1172 if ((new_map->nr_extents == 1) && (new_map->extent[0].count == 1) &&
1173 uid_eq(ns->owner, cred->euid)) {
1174 u32 id = new_map->extent[0].lower_first;
1175 if (cap_setid == CAP_SETUID) {
1176 kuid_t uid = make_kuid(ns->parent, id);
1177 if (uid_eq(uid, cred->euid))
1179 } else if (cap_setid == CAP_SETGID) {
1180 kgid_t gid = make_kgid(ns->parent, id);
1181 if (!(ns->flags & USERNS_SETGROUPS_ALLOWED) &&
1182 gid_eq(gid, cred->egid))
1187 /* Allow anyone to set a mapping that doesn't require privilege */
1188 if (!cap_valid(cap_setid))
1191 /* Allow the specified ids if we have the appropriate capability
1192 * (CAP_SETUID or CAP_SETGID) over the parent user namespace.
1193 * And the opener of the id file also has the appropriate capability.
1195 if (ns_capable(ns->parent, cap_setid) &&
1196 file_ns_capable(file, ns->parent, cap_setid))
1202 int proc_setgroups_show(struct seq_file *seq, void *v)
1204 struct user_namespace *ns = seq->private;
1205 unsigned long userns_flags = READ_ONCE(ns->flags);
1207 seq_printf(seq, "%s\n",
1208 (userns_flags & USERNS_SETGROUPS_ALLOWED) ?
1213 ssize_t proc_setgroups_write(struct file *file, const char __user *buf,
1214 size_t count, loff_t *ppos)
1216 struct seq_file *seq = file->private_data;
1217 struct user_namespace *ns = seq->private;
1219 bool setgroups_allowed;
1222 /* Only allow a very narrow range of strings to be written */
1224 if ((*ppos != 0) || (count >= sizeof(kbuf)))
1227 /* What was written? */
1229 if (copy_from_user(kbuf, buf, count))
1234 /* What is being requested? */
1236 if (strncmp(pos, "allow", 5) == 0) {
1238 setgroups_allowed = true;
1240 else if (strncmp(pos, "deny", 4) == 0) {
1242 setgroups_allowed = false;
1247 /* Verify there is not trailing junk on the line */
1248 pos = skip_spaces(pos);
1253 mutex_lock(&userns_state_mutex);
1254 if (setgroups_allowed) {
1255 /* Enabling setgroups after setgroups has been disabled
1258 if (!(ns->flags & USERNS_SETGROUPS_ALLOWED))
1261 /* Permanently disabling setgroups after setgroups has
1262 * been enabled by writing the gid_map is not allowed.
1264 if (ns->gid_map.nr_extents != 0)
1266 ns->flags &= ~USERNS_SETGROUPS_ALLOWED;
1268 mutex_unlock(&userns_state_mutex);
1270 /* Report a successful write */
1276 mutex_unlock(&userns_state_mutex);
1280 bool userns_may_setgroups(const struct user_namespace *ns)
1284 mutex_lock(&userns_state_mutex);
1285 /* It is not safe to use setgroups until a gid mapping in
1286 * the user namespace has been established.
1288 allowed = ns->gid_map.nr_extents != 0;
1289 /* Is setgroups allowed? */
1290 allowed = allowed && (ns->flags & USERNS_SETGROUPS_ALLOWED);
1291 mutex_unlock(&userns_state_mutex);
1297 * Returns true if @child is the same namespace or a descendant of
1300 bool in_userns(const struct user_namespace *ancestor,
1301 const struct user_namespace *child)
1303 const struct user_namespace *ns;
1304 for (ns = child; ns->level > ancestor->level; ns = ns->parent)
1306 return (ns == ancestor);
1309 bool current_in_userns(const struct user_namespace *target_ns)
1311 return in_userns(target_ns, current_user_ns());
1313 EXPORT_SYMBOL(current_in_userns);
1315 static inline struct user_namespace *to_user_ns(struct ns_common *ns)
1317 return container_of(ns, struct user_namespace, ns);
1320 static struct ns_common *userns_get(struct task_struct *task)
1322 struct user_namespace *user_ns;
1325 user_ns = get_user_ns(__task_cred(task)->user_ns);
1328 return user_ns ? &user_ns->ns : NULL;
1331 static void userns_put(struct ns_common *ns)
1333 put_user_ns(to_user_ns(ns));
1336 static int userns_install(struct nsset *nsset, struct ns_common *ns)
1338 struct user_namespace *user_ns = to_user_ns(ns);
1341 /* Don't allow gaining capabilities by reentering
1342 * the same user namespace.
1344 if (user_ns == current_user_ns())
1347 /* Tasks that share a thread group must share a user namespace */
1348 if (!thread_group_empty(current))
1351 if (current->fs->users != 1)
1354 if (!ns_capable(user_ns, CAP_SYS_ADMIN))
1357 cred = nsset_cred(nsset);
1361 put_user_ns(cred->user_ns);
1362 set_cred_user_ns(cred, get_user_ns(user_ns));
1364 if (set_cred_ucounts(cred) < 0)
1370 struct ns_common *ns_get_owner(struct ns_common *ns)
1372 struct user_namespace *my_user_ns = current_user_ns();
1373 struct user_namespace *owner, *p;
1375 /* See if the owner is in the current user namespace */
1376 owner = p = ns->ops->owner(ns);
1379 return ERR_PTR(-EPERM);
1380 if (p == my_user_ns)
1385 return &get_user_ns(owner)->ns;
1388 static struct user_namespace *userns_owner(struct ns_common *ns)
1390 return to_user_ns(ns)->parent;
1393 const struct proc_ns_operations userns_operations = {
1395 .type = CLONE_NEWUSER,
1398 .install = userns_install,
1399 .owner = userns_owner,
1400 .get_parent = ns_get_owner,
1403 static __init int user_namespaces_init(void)
1405 user_ns_cachep = KMEM_CACHE(user_namespace, SLAB_PANIC | SLAB_ACCOUNT);
1408 subsys_initcall(user_namespaces_init);