userns: Simplify the user and group mapping functions
[cris-mirror.git] / kernel / user_namespace.c
blob563a2981d7c79e894d772ac2657d1f7262c74c5b
1 /*
2 * This program is free software; you can redistribute it and/or
3 * modify it under the terms of the GNU General Public License as
4 * published by the Free Software Foundation, version 2 of the
5 * License.
6 */
8 #include <linux/export.h>
9 #include <linux/nsproxy.h>
10 #include <linux/slab.h>
11 #include <linux/sched/signal.h>
12 #include <linux/user_namespace.h>
13 #include <linux/proc_ns.h>
14 #include <linux/highuid.h>
15 #include <linux/cred.h>
16 #include <linux/securebits.h>
17 #include <linux/keyctl.h>
18 #include <linux/key-type.h>
19 #include <keys/user-type.h>
20 #include <linux/seq_file.h>
21 #include <linux/fs.h>
22 #include <linux/uaccess.h>
23 #include <linux/ctype.h>
24 #include <linux/projid.h>
25 #include <linux/fs_struct.h>
26 #include <linux/bsearch.h>
27 #include <linux/sort.h>
29 static struct kmem_cache *user_ns_cachep __read_mostly;
30 static DEFINE_MUTEX(userns_state_mutex);
32 static bool new_idmap_permitted(const struct file *file,
33 struct user_namespace *ns, int cap_setid,
34 struct uid_gid_map *map);
35 static void free_user_ns(struct work_struct *work);
37 static struct ucounts *inc_user_namespaces(struct user_namespace *ns, kuid_t uid)
39 return inc_ucount(ns, uid, UCOUNT_USER_NAMESPACES);
42 static void dec_user_namespaces(struct ucounts *ucounts)
44 return dec_ucount(ucounts, UCOUNT_USER_NAMESPACES);
47 static void set_cred_user_ns(struct cred *cred, struct user_namespace *user_ns)
49 /* Start with the same capabilities as init but useless for doing
50 * anything as the capabilities are bound to the new user namespace.
52 cred->securebits = SECUREBITS_DEFAULT;
53 cred->cap_inheritable = CAP_EMPTY_SET;
54 cred->cap_permitted = CAP_FULL_SET;
55 cred->cap_effective = CAP_FULL_SET;
56 cred->cap_ambient = CAP_EMPTY_SET;
57 cred->cap_bset = CAP_FULL_SET;
58 #ifdef CONFIG_KEYS
59 key_put(cred->request_key_auth);
60 cred->request_key_auth = NULL;
61 #endif
62 /* tgcred will be cleared in our caller bc CLONE_THREAD won't be set */
63 cred->user_ns = user_ns;
67 * Create a new user namespace, deriving the creator from the user in the
68 * passed credentials, and replacing that user with the new root user for the
69 * new namespace.
71 * This is called by copy_creds(), which will finish setting the target task's
72 * credentials.
74 int create_user_ns(struct cred *new)
76 struct user_namespace *ns, *parent_ns = new->user_ns;
77 kuid_t owner = new->euid;
78 kgid_t group = new->egid;
79 struct ucounts *ucounts;
80 int ret, i;
82 ret = -ENOSPC;
83 if (parent_ns->level > 32)
84 goto fail;
86 ucounts = inc_user_namespaces(parent_ns, owner);
87 if (!ucounts)
88 goto fail;
91 * Verify that we can not violate the policy of which files
92 * may be accessed that is specified by the root directory,
93 * by verifing that the root directory is at the root of the
94 * mount namespace which allows all files to be accessed.
96 ret = -EPERM;
97 if (current_chrooted())
98 goto fail_dec;
100 /* The creator needs a mapping in the parent user namespace
101 * or else we won't be able to reasonably tell userspace who
102 * created a user_namespace.
104 ret = -EPERM;
105 if (!kuid_has_mapping(parent_ns, owner) ||
106 !kgid_has_mapping(parent_ns, group))
107 goto fail_dec;
109 ret = -ENOMEM;
110 ns = kmem_cache_zalloc(user_ns_cachep, GFP_KERNEL);
111 if (!ns)
112 goto fail_dec;
114 ret = ns_alloc_inum(&ns->ns);
115 if (ret)
116 goto fail_free;
117 ns->ns.ops = &userns_operations;
119 atomic_set(&ns->count, 1);
120 /* Leave the new->user_ns reference with the new user namespace. */
121 ns->parent = parent_ns;
122 ns->level = parent_ns->level + 1;
123 ns->owner = owner;
124 ns->group = group;
125 INIT_WORK(&ns->work, free_user_ns);
126 for (i = 0; i < UCOUNT_COUNTS; i++) {
127 ns->ucount_max[i] = INT_MAX;
129 ns->ucounts = ucounts;
131 /* Inherit USERNS_SETGROUPS_ALLOWED from our parent */
132 mutex_lock(&userns_state_mutex);
133 ns->flags = parent_ns->flags;
134 mutex_unlock(&userns_state_mutex);
136 #ifdef CONFIG_PERSISTENT_KEYRINGS
137 init_rwsem(&ns->persistent_keyring_register_sem);
138 #endif
139 ret = -ENOMEM;
140 if (!setup_userns_sysctls(ns))
141 goto fail_keyring;
143 set_cred_user_ns(new, ns);
144 return 0;
145 fail_keyring:
146 #ifdef CONFIG_PERSISTENT_KEYRINGS
147 key_put(ns->persistent_keyring_register);
148 #endif
149 ns_free_inum(&ns->ns);
150 fail_free:
151 kmem_cache_free(user_ns_cachep, ns);
152 fail_dec:
153 dec_user_namespaces(ucounts);
154 fail:
155 return ret;
158 int unshare_userns(unsigned long unshare_flags, struct cred **new_cred)
160 struct cred *cred;
161 int err = -ENOMEM;
163 if (!(unshare_flags & CLONE_NEWUSER))
164 return 0;
166 cred = prepare_creds();
167 if (cred) {
168 err = create_user_ns(cred);
169 if (err)
170 put_cred(cred);
171 else
172 *new_cred = cred;
175 return err;
178 static void free_user_ns(struct work_struct *work)
180 struct user_namespace *parent, *ns =
181 container_of(work, struct user_namespace, work);
183 do {
184 struct ucounts *ucounts = ns->ucounts;
185 parent = ns->parent;
186 if (ns->gid_map.nr_extents > UID_GID_MAP_MAX_BASE_EXTENTS) {
187 kfree(ns->gid_map.forward);
188 kfree(ns->gid_map.reverse);
190 if (ns->uid_map.nr_extents > UID_GID_MAP_MAX_BASE_EXTENTS) {
191 kfree(ns->uid_map.forward);
192 kfree(ns->uid_map.reverse);
194 if (ns->projid_map.nr_extents > UID_GID_MAP_MAX_BASE_EXTENTS) {
195 kfree(ns->projid_map.forward);
196 kfree(ns->projid_map.reverse);
198 retire_userns_sysctls(ns);
199 #ifdef CONFIG_PERSISTENT_KEYRINGS
200 key_put(ns->persistent_keyring_register);
201 #endif
202 ns_free_inum(&ns->ns);
203 kmem_cache_free(user_ns_cachep, ns);
204 dec_user_namespaces(ucounts);
205 ns = parent;
206 } while (atomic_dec_and_test(&parent->count));
209 void __put_user_ns(struct user_namespace *ns)
211 schedule_work(&ns->work);
213 EXPORT_SYMBOL(__put_user_ns);
216 * idmap_key struct holds the information necessary to find an idmapping in a
217 * sorted idmap array. It is passed to cmp_map_id() as first argument.
219 struct idmap_key {
220 bool map_up; /* true -> id from kid; false -> kid from id */
221 u32 id; /* id to find */
222 u32 count; /* == 0 unless used with map_id_range_down() */
226 * cmp_map_id - Function to be passed to bsearch() to find the requested
227 * idmapping. Expects struct idmap_key to be passed via @k.
229 static int cmp_map_id(const void *k, const void *e)
231 u32 first, last, id2;
232 const struct idmap_key *key = k;
233 const struct uid_gid_extent *el = e;
235 id2 = key->id + key->count - 1;
237 /* handle map_id_{down,up}() */
238 if (key->map_up)
239 first = el->lower_first;
240 else
241 first = el->first;
243 last = first + el->count - 1;
245 if (key->id >= first && key->id <= last &&
246 (id2 >= first && id2 <= last))
247 return 0;
249 if (key->id < first || id2 < first)
250 return -1;
252 return 1;
256 * map_id_range_down_max - Find idmap via binary search in ordered idmap array.
257 * Can only be called if number of mappings exceeds UID_GID_MAP_MAX_BASE_EXTENTS.
259 static struct uid_gid_extent *
260 map_id_range_down_max(unsigned extents, struct uid_gid_map *map, u32 id, u32 count)
262 struct idmap_key key;
264 key.map_up = false;
265 key.count = count;
266 key.id = id;
268 return bsearch(&key, map->forward, extents,
269 sizeof(struct uid_gid_extent), cmp_map_id);
273 * map_id_range_down_base - Find idmap via binary search in static extent array.
274 * Can only be called if number of mappings is equal or less than
275 * UID_GID_MAP_MAX_BASE_EXTENTS.
277 static struct uid_gid_extent *
278 map_id_range_down_base(unsigned extents, struct uid_gid_map *map, u32 id, u32 count)
280 unsigned idx;
281 u32 first, last, id2;
283 id2 = id + count - 1;
285 /* Find the matching extent */
286 for (idx = 0; idx < extents; idx++) {
287 first = map->extent[idx].first;
288 last = first + map->extent[idx].count - 1;
289 if (id >= first && id <= last &&
290 (id2 >= first && id2 <= last))
291 return &map->extent[idx];
293 return NULL;
296 static u32 map_id_range_down(struct uid_gid_map *map, u32 id, u32 count)
298 struct uid_gid_extent *extent;
299 unsigned extents = map->nr_extents;
300 smp_rmb();
302 if (extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
303 extent = map_id_range_down_base(extents, map, id, count);
304 else
305 extent = map_id_range_down_max(extents, map, id, count);
307 /* Map the id or note failure */
308 if (extent)
309 id = (id - extent->first) + extent->lower_first;
310 else
311 id = (u32) -1;
313 return id;
317 * map_id_down_base - Find idmap via binary search in static extent array.
318 * Can only be called if number of mappings is equal or less than
319 * UID_GID_MAP_MAX_BASE_EXTENTS.
321 static struct uid_gid_extent *
322 map_id_down_base(unsigned extents, struct uid_gid_map *map, u32 id)
324 unsigned idx;
325 u32 first, last;
327 /* Find the matching extent */
328 for (idx = 0; idx < extents; idx++) {
329 first = map->extent[idx].first;
330 last = first + map->extent[idx].count - 1;
331 if (id >= first && id <= last)
332 return &map->extent[idx];
334 return NULL;
337 static u32 map_id_down(struct uid_gid_map *map, u32 id)
339 struct uid_gid_extent *extent;
340 unsigned extents = map->nr_extents;
341 smp_rmb();
343 if (extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
344 extent = map_id_down_base(extents, map, id);
345 else
346 extent = map_id_range_down_max(extents, map, id, 1);
348 /* Map the id or note failure */
349 if (extent)
350 id = (id - extent->first) + extent->lower_first;
351 else
352 id = (u32) -1;
354 return id;
358 * map_id_up_base - Find idmap via binary search in static extent array.
359 * Can only be called if number of mappings is equal or less than
360 * UID_GID_MAP_MAX_BASE_EXTENTS.
362 static struct uid_gid_extent *
363 map_id_up_base(unsigned extents, struct uid_gid_map *map, u32 id)
365 unsigned idx;
366 u32 first, last;
368 /* Find the matching extent */
369 for (idx = 0; idx < extents; idx++) {
370 first = map->extent[idx].lower_first;
371 last = first + map->extent[idx].count - 1;
372 if (id >= first && id <= last)
373 return &map->extent[idx];
375 return NULL;
379 * map_id_up_max - Find idmap via binary search in ordered idmap array.
380 * Can only be called if number of mappings exceeds UID_GID_MAP_MAX_BASE_EXTENTS.
382 static struct uid_gid_extent *
383 map_id_up_max(unsigned extents, struct uid_gid_map *map, u32 id)
385 struct idmap_key key;
387 key.map_up = true;
388 key.count = 1;
389 key.id = id;
391 return bsearch(&key, map->reverse, extents,
392 sizeof(struct uid_gid_extent), cmp_map_id);
395 static u32 map_id_up(struct uid_gid_map *map, u32 id)
397 struct uid_gid_extent *extent;
398 unsigned extents = map->nr_extents;
399 smp_rmb();
401 if (extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
402 extent = map_id_up_base(extents, map, id);
403 else
404 extent = map_id_up_max(extents, map, id);
406 /* Map the id or note failure */
407 if (extent)
408 id = (id - extent->lower_first) + extent->first;
409 else
410 id = (u32) -1;
412 return id;
416 * make_kuid - Map a user-namespace uid pair into a kuid.
417 * @ns: User namespace that the uid is in
418 * @uid: User identifier
420 * Maps a user-namespace uid pair into a kernel internal kuid,
421 * and returns that kuid.
423 * When there is no mapping defined for the user-namespace uid
424 * pair INVALID_UID is returned. Callers are expected to test
425 * for and handle INVALID_UID being returned. INVALID_UID
426 * may be tested for using uid_valid().
428 kuid_t make_kuid(struct user_namespace *ns, uid_t uid)
430 /* Map the uid to a global kernel uid */
431 return KUIDT_INIT(map_id_down(&ns->uid_map, uid));
433 EXPORT_SYMBOL(make_kuid);
436 * from_kuid - Create a uid from a kuid user-namespace pair.
437 * @targ: The user namespace we want a uid in.
438 * @kuid: The kernel internal uid to start with.
440 * Map @kuid into the user-namespace specified by @targ and
441 * return the resulting uid.
443 * There is always a mapping into the initial user_namespace.
445 * If @kuid has no mapping in @targ (uid_t)-1 is returned.
447 uid_t from_kuid(struct user_namespace *targ, kuid_t kuid)
449 /* Map the uid from a global kernel uid */
450 return map_id_up(&targ->uid_map, __kuid_val(kuid));
452 EXPORT_SYMBOL(from_kuid);
455 * from_kuid_munged - Create a uid from a kuid user-namespace pair.
456 * @targ: The user namespace we want a uid in.
457 * @kuid: The kernel internal uid to start with.
459 * Map @kuid into the user-namespace specified by @targ and
460 * return the resulting uid.
462 * There is always a mapping into the initial user_namespace.
464 * Unlike from_kuid from_kuid_munged never fails and always
465 * returns a valid uid. This makes from_kuid_munged appropriate
466 * for use in syscalls like stat and getuid where failing the
467 * system call and failing to provide a valid uid are not an
468 * options.
470 * If @kuid has no mapping in @targ overflowuid is returned.
472 uid_t from_kuid_munged(struct user_namespace *targ, kuid_t kuid)
474 uid_t uid;
475 uid = from_kuid(targ, kuid);
477 if (uid == (uid_t) -1)
478 uid = overflowuid;
479 return uid;
481 EXPORT_SYMBOL(from_kuid_munged);
484 * make_kgid - Map a user-namespace gid pair into a kgid.
485 * @ns: User namespace that the gid is in
486 * @gid: group identifier
488 * Maps a user-namespace gid pair into a kernel internal kgid,
489 * and returns that kgid.
491 * When there is no mapping defined for the user-namespace gid
492 * pair INVALID_GID is returned. Callers are expected to test
493 * for and handle INVALID_GID being returned. INVALID_GID may be
494 * tested for using gid_valid().
496 kgid_t make_kgid(struct user_namespace *ns, gid_t gid)
498 /* Map the gid to a global kernel gid */
499 return KGIDT_INIT(map_id_down(&ns->gid_map, gid));
501 EXPORT_SYMBOL(make_kgid);
504 * from_kgid - Create a gid from a kgid user-namespace pair.
505 * @targ: The user namespace we want a gid in.
506 * @kgid: The kernel internal gid to start with.
508 * Map @kgid into the user-namespace specified by @targ and
509 * return the resulting gid.
511 * There is always a mapping into the initial user_namespace.
513 * If @kgid has no mapping in @targ (gid_t)-1 is returned.
515 gid_t from_kgid(struct user_namespace *targ, kgid_t kgid)
517 /* Map the gid from a global kernel gid */
518 return map_id_up(&targ->gid_map, __kgid_val(kgid));
520 EXPORT_SYMBOL(from_kgid);
523 * from_kgid_munged - Create a gid from a kgid user-namespace pair.
524 * @targ: The user namespace we want a gid in.
525 * @kgid: The kernel internal gid to start with.
527 * Map @kgid into the user-namespace specified by @targ and
528 * return the resulting gid.
530 * There is always a mapping into the initial user_namespace.
532 * Unlike from_kgid from_kgid_munged never fails and always
533 * returns a valid gid. This makes from_kgid_munged appropriate
534 * for use in syscalls like stat and getgid where failing the
535 * system call and failing to provide a valid gid are not options.
537 * If @kgid has no mapping in @targ overflowgid is returned.
539 gid_t from_kgid_munged(struct user_namespace *targ, kgid_t kgid)
541 gid_t gid;
542 gid = from_kgid(targ, kgid);
544 if (gid == (gid_t) -1)
545 gid = overflowgid;
546 return gid;
548 EXPORT_SYMBOL(from_kgid_munged);
551 * make_kprojid - Map a user-namespace projid pair into a kprojid.
552 * @ns: User namespace that the projid is in
553 * @projid: Project identifier
555 * Maps a user-namespace uid pair into a kernel internal kuid,
556 * and returns that kuid.
558 * When there is no mapping defined for the user-namespace projid
559 * pair INVALID_PROJID is returned. Callers are expected to test
560 * for and handle handle INVALID_PROJID being returned. INVALID_PROJID
561 * may be tested for using projid_valid().
563 kprojid_t make_kprojid(struct user_namespace *ns, projid_t projid)
565 /* Map the uid to a global kernel uid */
566 return KPROJIDT_INIT(map_id_down(&ns->projid_map, projid));
568 EXPORT_SYMBOL(make_kprojid);
571 * from_kprojid - Create a projid from a kprojid user-namespace pair.
572 * @targ: The user namespace we want a projid in.
573 * @kprojid: The kernel internal project identifier to start with.
575 * Map @kprojid into the user-namespace specified by @targ and
576 * return the resulting projid.
578 * There is always a mapping into the initial user_namespace.
580 * If @kprojid has no mapping in @targ (projid_t)-1 is returned.
582 projid_t from_kprojid(struct user_namespace *targ, kprojid_t kprojid)
584 /* Map the uid from a global kernel uid */
585 return map_id_up(&targ->projid_map, __kprojid_val(kprojid));
587 EXPORT_SYMBOL(from_kprojid);
590 * from_kprojid_munged - Create a projiid from a kprojid user-namespace pair.
591 * @targ: The user namespace we want a projid in.
592 * @kprojid: The kernel internal projid to start with.
594 * Map @kprojid into the user-namespace specified by @targ and
595 * return the resulting projid.
597 * There is always a mapping into the initial user_namespace.
599 * Unlike from_kprojid from_kprojid_munged never fails and always
600 * returns a valid projid. This makes from_kprojid_munged
601 * appropriate for use in syscalls like stat and where
602 * failing the system call and failing to provide a valid projid are
603 * not an options.
605 * If @kprojid has no mapping in @targ OVERFLOW_PROJID is returned.
607 projid_t from_kprojid_munged(struct user_namespace *targ, kprojid_t kprojid)
609 projid_t projid;
610 projid = from_kprojid(targ, kprojid);
612 if (projid == (projid_t) -1)
613 projid = OVERFLOW_PROJID;
614 return projid;
616 EXPORT_SYMBOL(from_kprojid_munged);
619 static int uid_m_show(struct seq_file *seq, void *v)
621 struct user_namespace *ns = seq->private;
622 struct uid_gid_extent *extent = v;
623 struct user_namespace *lower_ns;
624 uid_t lower;
626 lower_ns = seq_user_ns(seq);
627 if ((lower_ns == ns) && lower_ns->parent)
628 lower_ns = lower_ns->parent;
630 lower = from_kuid(lower_ns, KUIDT_INIT(extent->lower_first));
632 seq_printf(seq, "%10u %10u %10u\n",
633 extent->first,
634 lower,
635 extent->count);
637 return 0;
640 static int gid_m_show(struct seq_file *seq, void *v)
642 struct user_namespace *ns = seq->private;
643 struct uid_gid_extent *extent = v;
644 struct user_namespace *lower_ns;
645 gid_t lower;
647 lower_ns = seq_user_ns(seq);
648 if ((lower_ns == ns) && lower_ns->parent)
649 lower_ns = lower_ns->parent;
651 lower = from_kgid(lower_ns, KGIDT_INIT(extent->lower_first));
653 seq_printf(seq, "%10u %10u %10u\n",
654 extent->first,
655 lower,
656 extent->count);
658 return 0;
661 static int projid_m_show(struct seq_file *seq, void *v)
663 struct user_namespace *ns = seq->private;
664 struct uid_gid_extent *extent = v;
665 struct user_namespace *lower_ns;
666 projid_t lower;
668 lower_ns = seq_user_ns(seq);
669 if ((lower_ns == ns) && lower_ns->parent)
670 lower_ns = lower_ns->parent;
672 lower = from_kprojid(lower_ns, KPROJIDT_INIT(extent->lower_first));
674 seq_printf(seq, "%10u %10u %10u\n",
675 extent->first,
676 lower,
677 extent->count);
679 return 0;
682 static void *m_start(struct seq_file *seq, loff_t *ppos,
683 struct uid_gid_map *map)
685 loff_t pos = *ppos;
687 if (pos >= map->nr_extents)
688 return NULL;
690 if (map->nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
691 return &map->extent[pos];
693 return &map->forward[pos];
696 static void *uid_m_start(struct seq_file *seq, loff_t *ppos)
698 struct user_namespace *ns = seq->private;
700 return m_start(seq, ppos, &ns->uid_map);
703 static void *gid_m_start(struct seq_file *seq, loff_t *ppos)
705 struct user_namespace *ns = seq->private;
707 return m_start(seq, ppos, &ns->gid_map);
710 static void *projid_m_start(struct seq_file *seq, loff_t *ppos)
712 struct user_namespace *ns = seq->private;
714 return m_start(seq, ppos, &ns->projid_map);
717 static void *m_next(struct seq_file *seq, void *v, loff_t *pos)
719 (*pos)++;
720 return seq->op->start(seq, pos);
723 static void m_stop(struct seq_file *seq, void *v)
725 return;
728 const struct seq_operations proc_uid_seq_operations = {
729 .start = uid_m_start,
730 .stop = m_stop,
731 .next = m_next,
732 .show = uid_m_show,
735 const struct seq_operations proc_gid_seq_operations = {
736 .start = gid_m_start,
737 .stop = m_stop,
738 .next = m_next,
739 .show = gid_m_show,
742 const struct seq_operations proc_projid_seq_operations = {
743 .start = projid_m_start,
744 .stop = m_stop,
745 .next = m_next,
746 .show = projid_m_show,
749 static bool mappings_overlap(struct uid_gid_map *new_map,
750 struct uid_gid_extent *extent)
752 u32 upper_first, lower_first, upper_last, lower_last;
753 unsigned idx;
755 upper_first = extent->first;
756 lower_first = extent->lower_first;
757 upper_last = upper_first + extent->count - 1;
758 lower_last = lower_first + extent->count - 1;
760 for (idx = 0; idx < new_map->nr_extents; idx++) {
761 u32 prev_upper_first, prev_lower_first;
762 u32 prev_upper_last, prev_lower_last;
763 struct uid_gid_extent *prev;
765 if (new_map->nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
766 prev = &new_map->extent[idx];
767 else
768 prev = &new_map->forward[idx];
770 prev_upper_first = prev->first;
771 prev_lower_first = prev->lower_first;
772 prev_upper_last = prev_upper_first + prev->count - 1;
773 prev_lower_last = prev_lower_first + prev->count - 1;
775 /* Does the upper range intersect a previous extent? */
776 if ((prev_upper_first <= upper_last) &&
777 (prev_upper_last >= upper_first))
778 return true;
780 /* Does the lower range intersect a previous extent? */
781 if ((prev_lower_first <= lower_last) &&
782 (prev_lower_last >= lower_first))
783 return true;
785 return false;
789 * insert_extent - Safely insert a new idmap extent into struct uid_gid_map.
790 * Takes care to allocate a 4K block of memory if the number of mappings exceeds
791 * UID_GID_MAP_MAX_BASE_EXTENTS.
793 static int insert_extent(struct uid_gid_map *map, struct uid_gid_extent *extent)
795 if (map->nr_extents < UID_GID_MAP_MAX_BASE_EXTENTS) {
796 map->extent[map->nr_extents].first = extent->first;
797 map->extent[map->nr_extents].lower_first = extent->lower_first;
798 map->extent[map->nr_extents].count = extent->count;
799 return 0;
802 if (map->nr_extents == UID_GID_MAP_MAX_BASE_EXTENTS) {
803 struct uid_gid_extent *forward;
805 /* Allocate memory for 340 mappings. */
806 forward = kmalloc(sizeof(struct uid_gid_extent) *
807 UID_GID_MAP_MAX_EXTENTS, GFP_KERNEL);
808 if (!forward)
809 return -ENOMEM;
811 /* Copy over memory. Only set up memory for the forward pointer.
812 * Defer the memory setup for the reverse pointer.
814 memcpy(forward, map->extent,
815 map->nr_extents * sizeof(map->extent[0]));
817 map->forward = forward;
818 map->reverse = NULL;
821 map->forward[map->nr_extents].first = extent->first;
822 map->forward[map->nr_extents].lower_first = extent->lower_first;
823 map->forward[map->nr_extents].count = extent->count;
824 return 0;
827 /* cmp function to sort() forward mappings */
828 static int cmp_extents_forward(const void *a, const void *b)
830 const struct uid_gid_extent *e1 = a;
831 const struct uid_gid_extent *e2 = b;
833 if (e1->first < e2->first)
834 return -1;
836 if (e1->first > e2->first)
837 return 1;
839 return 0;
842 /* cmp function to sort() reverse mappings */
843 static int cmp_extents_reverse(const void *a, const void *b)
845 const struct uid_gid_extent *e1 = a;
846 const struct uid_gid_extent *e2 = b;
848 if (e1->lower_first < e2->lower_first)
849 return -1;
851 if (e1->lower_first > e2->lower_first)
852 return 1;
854 return 0;
858 * sort_idmaps - Sorts an array of idmap entries.
859 * Can only be called if number of mappings exceeds UID_GID_MAP_MAX_BASE_EXTENTS.
861 static int sort_idmaps(struct uid_gid_map *map)
863 if (map->nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
864 return 0;
866 /* Sort forward array. */
867 sort(map->forward, map->nr_extents, sizeof(struct uid_gid_extent),
868 cmp_extents_forward, NULL);
870 /* Only copy the memory from forward we actually need. */
871 map->reverse = kmemdup(map->forward,
872 map->nr_extents * sizeof(struct uid_gid_extent),
873 GFP_KERNEL);
874 if (!map->reverse)
875 return -ENOMEM;
877 /* Sort reverse array. */
878 sort(map->reverse, map->nr_extents, sizeof(struct uid_gid_extent),
879 cmp_extents_reverse, NULL);
881 return 0;
884 static ssize_t map_write(struct file *file, const char __user *buf,
885 size_t count, loff_t *ppos,
886 int cap_setid,
887 struct uid_gid_map *map,
888 struct uid_gid_map *parent_map)
890 struct seq_file *seq = file->private_data;
891 struct user_namespace *ns = seq->private;
892 struct uid_gid_map new_map;
893 unsigned idx;
894 struct uid_gid_extent extent;
895 char *kbuf = NULL, *pos, *next_line;
896 ssize_t ret = -EINVAL;
899 * The userns_state_mutex serializes all writes to any given map.
901 * Any map is only ever written once.
903 * An id map fits within 1 cache line on most architectures.
905 * On read nothing needs to be done unless you are on an
906 * architecture with a crazy cache coherency model like alpha.
908 * There is a one time data dependency between reading the
909 * count of the extents and the values of the extents. The
910 * desired behavior is to see the values of the extents that
911 * were written before the count of the extents.
913 * To achieve this smp_wmb() is used on guarantee the write
914 * order and smp_rmb() is guaranteed that we don't have crazy
915 * architectures returning stale data.
917 mutex_lock(&userns_state_mutex);
919 memset(&new_map, 0, sizeof(struct uid_gid_map));
921 ret = -EPERM;
922 /* Only allow one successful write to the map */
923 if (map->nr_extents != 0)
924 goto out;
927 * Adjusting namespace settings requires capabilities on the target.
929 if (cap_valid(cap_setid) && !file_ns_capable(file, ns, CAP_SYS_ADMIN))
930 goto out;
932 /* Only allow < page size writes at the beginning of the file */
933 ret = -EINVAL;
934 if ((*ppos != 0) || (count >= PAGE_SIZE))
935 goto out;
937 /* Slurp in the user data */
938 kbuf = memdup_user_nul(buf, count);
939 if (IS_ERR(kbuf)) {
940 ret = PTR_ERR(kbuf);
941 kbuf = NULL;
942 goto out;
945 /* Parse the user data */
946 ret = -EINVAL;
947 pos = kbuf;
948 for (; pos; pos = next_line) {
950 /* Find the end of line and ensure I don't look past it */
951 next_line = strchr(pos, '\n');
952 if (next_line) {
953 *next_line = '\0';
954 next_line++;
955 if (*next_line == '\0')
956 next_line = NULL;
959 pos = skip_spaces(pos);
960 extent.first = simple_strtoul(pos, &pos, 10);
961 if (!isspace(*pos))
962 goto out;
964 pos = skip_spaces(pos);
965 extent.lower_first = simple_strtoul(pos, &pos, 10);
966 if (!isspace(*pos))
967 goto out;
969 pos = skip_spaces(pos);
970 extent.count = simple_strtoul(pos, &pos, 10);
971 if (*pos && !isspace(*pos))
972 goto out;
974 /* Verify there is not trailing junk on the line */
975 pos = skip_spaces(pos);
976 if (*pos != '\0')
977 goto out;
979 /* Verify we have been given valid starting values */
980 if ((extent.first == (u32) -1) ||
981 (extent.lower_first == (u32) -1))
982 goto out;
984 /* Verify count is not zero and does not cause the
985 * extent to wrap
987 if ((extent.first + extent.count) <= extent.first)
988 goto out;
989 if ((extent.lower_first + extent.count) <=
990 extent.lower_first)
991 goto out;
993 /* Do the ranges in extent overlap any previous extents? */
994 if (mappings_overlap(&new_map, &extent))
995 goto out;
997 if ((new_map.nr_extents + 1) == UID_GID_MAP_MAX_EXTENTS &&
998 (next_line != NULL))
999 goto out;
1001 ret = insert_extent(&new_map, &extent);
1002 if (ret < 0)
1003 goto out;
1004 ret = -EINVAL;
1006 new_map.nr_extents++;
1008 /* Be very certaint the new map actually exists */
1009 if (new_map.nr_extents == 0)
1010 goto out;
1012 ret = -EPERM;
1013 /* Validate the user is allowed to use user id's mapped to. */
1014 if (!new_idmap_permitted(file, ns, cap_setid, &new_map))
1015 goto out;
1017 ret = sort_idmaps(&new_map);
1018 if (ret < 0)
1019 goto out;
1021 ret = -EPERM;
1022 /* Map the lower ids from the parent user namespace to the
1023 * kernel global id space.
1025 for (idx = 0; idx < new_map.nr_extents; idx++) {
1026 struct uid_gid_extent *e;
1027 u32 lower_first;
1029 if (new_map.nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
1030 e = &new_map.extent[idx];
1031 else
1032 e = &new_map.forward[idx];
1034 lower_first = map_id_range_down(parent_map,
1035 e->lower_first,
1036 e->count);
1038 /* Fail if we can not map the specified extent to
1039 * the kernel global id space.
1041 if (lower_first == (u32) -1)
1042 goto out;
1044 e->lower_first = lower_first;
1047 /* Install the map */
1048 if (new_map.nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS) {
1049 memcpy(map->extent, new_map.extent,
1050 new_map.nr_extents * sizeof(new_map.extent[0]));
1051 } else {
1052 map->forward = new_map.forward;
1053 map->reverse = new_map.reverse;
1055 smp_wmb();
1056 map->nr_extents = new_map.nr_extents;
1058 *ppos = count;
1059 ret = count;
1060 out:
1061 if (ret < 0 && new_map.nr_extents > UID_GID_MAP_MAX_BASE_EXTENTS) {
1062 kfree(new_map.forward);
1063 kfree(new_map.reverse);
1064 map->forward = NULL;
1065 map->reverse = NULL;
1066 map->nr_extents = 0;
1069 mutex_unlock(&userns_state_mutex);
1070 kfree(kbuf);
1071 return ret;
1074 ssize_t proc_uid_map_write(struct file *file, const char __user *buf,
1075 size_t size, loff_t *ppos)
1077 struct seq_file *seq = file->private_data;
1078 struct user_namespace *ns = seq->private;
1079 struct user_namespace *seq_ns = seq_user_ns(seq);
1081 if (!ns->parent)
1082 return -EPERM;
1084 if ((seq_ns != ns) && (seq_ns != ns->parent))
1085 return -EPERM;
1087 return map_write(file, buf, size, ppos, CAP_SETUID,
1088 &ns->uid_map, &ns->parent->uid_map);
1091 ssize_t proc_gid_map_write(struct file *file, const char __user *buf,
1092 size_t size, loff_t *ppos)
1094 struct seq_file *seq = file->private_data;
1095 struct user_namespace *ns = seq->private;
1096 struct user_namespace *seq_ns = seq_user_ns(seq);
1098 if (!ns->parent)
1099 return -EPERM;
1101 if ((seq_ns != ns) && (seq_ns != ns->parent))
1102 return -EPERM;
1104 return map_write(file, buf, size, ppos, CAP_SETGID,
1105 &ns->gid_map, &ns->parent->gid_map);
1108 ssize_t proc_projid_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);
1115 if (!ns->parent)
1116 return -EPERM;
1118 if ((seq_ns != ns) && (seq_ns != ns->parent))
1119 return -EPERM;
1121 /* Anyone can set any valid project id no capability needed */
1122 return map_write(file, buf, size, ppos, -1,
1123 &ns->projid_map, &ns->parent->projid_map);
1126 static bool new_idmap_permitted(const struct file *file,
1127 struct user_namespace *ns, int cap_setid,
1128 struct uid_gid_map *new_map)
1130 const struct cred *cred = file->f_cred;
1131 /* Don't allow mappings that would allow anything that wouldn't
1132 * be allowed without the establishment of unprivileged mappings.
1134 if ((new_map->nr_extents == 1) && (new_map->extent[0].count == 1) &&
1135 uid_eq(ns->owner, cred->euid)) {
1136 u32 id = new_map->extent[0].lower_first;
1137 if (cap_setid == CAP_SETUID) {
1138 kuid_t uid = make_kuid(ns->parent, id);
1139 if (uid_eq(uid, cred->euid))
1140 return true;
1141 } else if (cap_setid == CAP_SETGID) {
1142 kgid_t gid = make_kgid(ns->parent, id);
1143 if (!(ns->flags & USERNS_SETGROUPS_ALLOWED) &&
1144 gid_eq(gid, cred->egid))
1145 return true;
1149 /* Allow anyone to set a mapping that doesn't require privilege */
1150 if (!cap_valid(cap_setid))
1151 return true;
1153 /* Allow the specified ids if we have the appropriate capability
1154 * (CAP_SETUID or CAP_SETGID) over the parent user namespace.
1155 * And the opener of the id file also had the approprpiate capability.
1157 if (ns_capable(ns->parent, cap_setid) &&
1158 file_ns_capable(file, ns->parent, cap_setid))
1159 return true;
1161 return false;
1164 int proc_setgroups_show(struct seq_file *seq, void *v)
1166 struct user_namespace *ns = seq->private;
1167 unsigned long userns_flags = ACCESS_ONCE(ns->flags);
1169 seq_printf(seq, "%s\n",
1170 (userns_flags & USERNS_SETGROUPS_ALLOWED) ?
1171 "allow" : "deny");
1172 return 0;
1175 ssize_t proc_setgroups_write(struct file *file, const char __user *buf,
1176 size_t count, loff_t *ppos)
1178 struct seq_file *seq = file->private_data;
1179 struct user_namespace *ns = seq->private;
1180 char kbuf[8], *pos;
1181 bool setgroups_allowed;
1182 ssize_t ret;
1184 /* Only allow a very narrow range of strings to be written */
1185 ret = -EINVAL;
1186 if ((*ppos != 0) || (count >= sizeof(kbuf)))
1187 goto out;
1189 /* What was written? */
1190 ret = -EFAULT;
1191 if (copy_from_user(kbuf, buf, count))
1192 goto out;
1193 kbuf[count] = '\0';
1194 pos = kbuf;
1196 /* What is being requested? */
1197 ret = -EINVAL;
1198 if (strncmp(pos, "allow", 5) == 0) {
1199 pos += 5;
1200 setgroups_allowed = true;
1202 else if (strncmp(pos, "deny", 4) == 0) {
1203 pos += 4;
1204 setgroups_allowed = false;
1206 else
1207 goto out;
1209 /* Verify there is not trailing junk on the line */
1210 pos = skip_spaces(pos);
1211 if (*pos != '\0')
1212 goto out;
1214 ret = -EPERM;
1215 mutex_lock(&userns_state_mutex);
1216 if (setgroups_allowed) {
1217 /* Enabling setgroups after setgroups has been disabled
1218 * is not allowed.
1220 if (!(ns->flags & USERNS_SETGROUPS_ALLOWED))
1221 goto out_unlock;
1222 } else {
1223 /* Permanently disabling setgroups after setgroups has
1224 * been enabled by writing the gid_map is not allowed.
1226 if (ns->gid_map.nr_extents != 0)
1227 goto out_unlock;
1228 ns->flags &= ~USERNS_SETGROUPS_ALLOWED;
1230 mutex_unlock(&userns_state_mutex);
1232 /* Report a successful write */
1233 *ppos = count;
1234 ret = count;
1235 out:
1236 return ret;
1237 out_unlock:
1238 mutex_unlock(&userns_state_mutex);
1239 goto out;
1242 bool userns_may_setgroups(const struct user_namespace *ns)
1244 bool allowed;
1246 mutex_lock(&userns_state_mutex);
1247 /* It is not safe to use setgroups until a gid mapping in
1248 * the user namespace has been established.
1250 allowed = ns->gid_map.nr_extents != 0;
1251 /* Is setgroups allowed? */
1252 allowed = allowed && (ns->flags & USERNS_SETGROUPS_ALLOWED);
1253 mutex_unlock(&userns_state_mutex);
1255 return allowed;
1259 * Returns true if @child is the same namespace or a descendant of
1260 * @ancestor.
1262 bool in_userns(const struct user_namespace *ancestor,
1263 const struct user_namespace *child)
1265 const struct user_namespace *ns;
1266 for (ns = child; ns->level > ancestor->level; ns = ns->parent)
1268 return (ns == ancestor);
1271 bool current_in_userns(const struct user_namespace *target_ns)
1273 return in_userns(target_ns, current_user_ns());
1276 static inline struct user_namespace *to_user_ns(struct ns_common *ns)
1278 return container_of(ns, struct user_namespace, ns);
1281 static struct ns_common *userns_get(struct task_struct *task)
1283 struct user_namespace *user_ns;
1285 rcu_read_lock();
1286 user_ns = get_user_ns(__task_cred(task)->user_ns);
1287 rcu_read_unlock();
1289 return user_ns ? &user_ns->ns : NULL;
1292 static void userns_put(struct ns_common *ns)
1294 put_user_ns(to_user_ns(ns));
1297 static int userns_install(struct nsproxy *nsproxy, struct ns_common *ns)
1299 struct user_namespace *user_ns = to_user_ns(ns);
1300 struct cred *cred;
1302 /* Don't allow gaining capabilities by reentering
1303 * the same user namespace.
1305 if (user_ns == current_user_ns())
1306 return -EINVAL;
1308 /* Tasks that share a thread group must share a user namespace */
1309 if (!thread_group_empty(current))
1310 return -EINVAL;
1312 if (current->fs->users != 1)
1313 return -EINVAL;
1315 if (!ns_capable(user_ns, CAP_SYS_ADMIN))
1316 return -EPERM;
1318 cred = prepare_creds();
1319 if (!cred)
1320 return -ENOMEM;
1322 put_user_ns(cred->user_ns);
1323 set_cred_user_ns(cred, get_user_ns(user_ns));
1325 return commit_creds(cred);
1328 struct ns_common *ns_get_owner(struct ns_common *ns)
1330 struct user_namespace *my_user_ns = current_user_ns();
1331 struct user_namespace *owner, *p;
1333 /* See if the owner is in the current user namespace */
1334 owner = p = ns->ops->owner(ns);
1335 for (;;) {
1336 if (!p)
1337 return ERR_PTR(-EPERM);
1338 if (p == my_user_ns)
1339 break;
1340 p = p->parent;
1343 return &get_user_ns(owner)->ns;
1346 static struct user_namespace *userns_owner(struct ns_common *ns)
1348 return to_user_ns(ns)->parent;
1351 const struct proc_ns_operations userns_operations = {
1352 .name = "user",
1353 .type = CLONE_NEWUSER,
1354 .get = userns_get,
1355 .put = userns_put,
1356 .install = userns_install,
1357 .owner = userns_owner,
1358 .get_parent = ns_get_owner,
1361 static __init int user_namespaces_init(void)
1363 user_ns_cachep = KMEM_CACHE(user_namespace, SLAB_PANIC);
1364 return 0;
1366 subsys_initcall(user_namespaces_init);