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