1
2
3
4
5
6
7
8#include <linux/module.h>
9#include <linux/nsproxy.h>
10#include <linux/slab.h>
11#include <linux/user_namespace.h>
12#include <linux/highuid.h>
13#include <linux/cred.h>
14
15
16
17
18
19
20
21
22
23int create_user_ns(struct cred *new)
24{
25 struct user_namespace *ns;
26 struct user_struct *root_user;
27 int n;
28
29 ns = kmalloc(sizeof(struct user_namespace), GFP_KERNEL);
30 if (!ns)
31 return -ENOMEM;
32
33 kref_init(&ns->kref);
34
35 for (n = 0; n < UIDHASH_SZ; ++n)
36 INIT_HLIST_HEAD(ns->uidhash_table + n);
37
38
39 root_user = alloc_uid(ns, 0);
40 if (!root_user) {
41 kfree(ns);
42 return -ENOMEM;
43 }
44
45
46 ns->creator = new->user;
47 new->user = root_user;
48 new->uid = new->euid = new->suid = new->fsuid = 0;
49 new->gid = new->egid = new->sgid = new->fsgid = 0;
50 put_group_info(new->group_info);
51 new->group_info = get_group_info(&init_groups);
52#ifdef CONFIG_KEYS
53 key_put(new->request_key_auth);
54 new->request_key_auth = NULL;
55#endif
56
57
58
59 put_user_ns(ns);
60
61 return 0;
62}
63
64
65
66
67
68
69static void free_user_ns_work(struct work_struct *work)
70{
71 struct user_namespace *ns =
72 container_of(work, struct user_namespace, destroyer);
73 free_uid(ns->creator);
74 kfree(ns);
75}
76
77void free_user_ns(struct kref *kref)
78{
79 struct user_namespace *ns =
80 container_of(kref, struct user_namespace, kref);
81
82 INIT_WORK(&ns->destroyer, free_user_ns_work);
83 schedule_work(&ns->destroyer);
84}
85EXPORT_SYMBOL(free_user_ns);
86
87uid_t user_ns_map_uid(struct user_namespace *to, const struct cred *cred, uid_t uid)
88{
89 struct user_namespace *tmp;
90
91 if (likely(to == cred->user->user_ns))
92 return uid;
93
94
95
96
97
98 for ( tmp = to; tmp != &init_user_ns;
99 tmp = tmp->creator->user_ns ) {
100 if (cred->user == tmp->creator) {
101 return (uid_t)0;
102 }
103 }
104
105
106 return overflowuid;
107}
108
109gid_t user_ns_map_gid(struct user_namespace *to, const struct cred *cred, gid_t gid)
110{
111 struct user_namespace *tmp;
112
113 if (likely(to == cred->user->user_ns))
114 return gid;
115
116
117
118
119 for ( tmp = to; tmp != &init_user_ns;
120 tmp = tmp->creator->user_ns ) {
121 if (cred->user == tmp->creator) {
122 return (gid_t)0;
123 }
124 }
125
126
127 return overflowgid;
128}
129