1 // SPDX-License-Identifier: GPL-2.0
13 #include <linux/sched.h>
22 #include <sys/syscall.h>
23 #include <sys/types.h>
30 /* A few helpful macros. */
31 #define STRLITERALLEN(x) (sizeof(""x"") - 1)
33 #define INTTYPE_TO_STRLEN(type) \
34 (2 + (sizeof(type) <= 1 \
40 : sizeof(type) <= 8 ? 20 : sizeof(int[-2 * (sizeof(type) > 8)])))
42 #define syserror(format, ...) \
44 fprintf(stderr, format, ##__VA_ARGS__); \
48 #define syserror_set(__ret__, format, ...) \
50 typeof(__ret__) __internal_ret__ = (__ret__); \
51 errno = labs(__ret__); \
52 fprintf(stderr, format, ##__VA_ARGS__); \
62 #define list_for_each(__iterator, __list) \
63 for (__iterator = (__list)->next; __iterator != __list; __iterator = __iterator->next)
65 static inline void list_init(struct list *list)
68 list->next = list->prev = list;
71 static inline int list_empty(const struct list *list)
73 return list == list->next;
76 static inline void __list_add(struct list *new, struct list *prev, struct list *next)
84 static inline void list_add_tail(struct list *head, struct list *list)
86 __list_add(list, head->prev, head);
89 typedef enum idmap_type_t {
95 idmap_type_t map_type;
101 static struct list active_map;
103 static int add_map_entry(__u32 id_host,
106 idmap_type_t map_type)
108 struct list *new_list = NULL;
109 struct id_map *newmap = NULL;
111 newmap = malloc(sizeof(*newmap));
115 new_list = malloc(sizeof(struct list));
121 *newmap = (struct id_map){
125 .map_type = map_type,
128 new_list->elem = newmap;
129 list_add_tail(&active_map, new_list);
133 static int parse_map(char *map)
135 char types[2] = {'u', 'g'};
137 __u32 id_host, id_ns, range;
143 ret = sscanf(map, "%c:%u:%u:%u", &which, &id_ns, &id_host, &range);
147 if (which != 'b' && which != 'u' && which != 'g')
150 for (i = 0; i < 2; i++) {
151 idmap_type_t map_type;
153 if (which != types[i] && which != 'b')
157 map_type = ID_TYPE_UID;
159 map_type = ID_TYPE_GID;
161 ret = add_map_entry(id_host, id_ns, range, map_type);
169 static int write_id_mapping(idmap_type_t map_type, pid_t pid, const char *buf, size_t buf_size)
171 int fd = -EBADF, setgroups_fd = -EBADF;
174 char path[STRLITERALLEN("/proc/") + INTTYPE_TO_STRLEN(pid_t) +
175 STRLITERALLEN("/setgroups") + 1];
177 if (geteuid() != 0 && map_type == ID_TYPE_GID) {
178 ret = snprintf(path, sizeof(path), "/proc/%d/setgroups", pid);
179 if (ret < 0 || ret >= sizeof(path))
182 setgroups_fd = open(path, O_WRONLY | O_CLOEXEC);
183 if (setgroups_fd < 0 && errno != ENOENT) {
184 syserror("Failed to open \"%s\"", path);
188 if (setgroups_fd >= 0) {
189 ret = write_nointr(setgroups_fd, "deny\n", STRLITERALLEN("deny\n"));
190 if (ret != STRLITERALLEN("deny\n")) {
191 syserror("Failed to write \"deny\" to \"/proc/%d/setgroups\"", pid);
197 ret = snprintf(path, sizeof(path), "/proc/%d/%cid_map", pid, map_type == ID_TYPE_UID ? 'u' : 'g');
198 if (ret < 0 || ret >= sizeof(path))
201 fd = open(path, O_WRONLY | O_CLOEXEC);
203 syserror("Failed to open \"%s\"", path);
207 ret = write_nointr(fd, buf, buf_size);
208 if (ret != buf_size) {
209 syserror("Failed to write %cid mapping to \"%s\"",
210 map_type == ID_TYPE_UID ? 'u' : 'g', path);
218 if (setgroups_fd >= 0)
224 static int map_ids_from_idmap(struct list *idmap, pid_t pid)
227 char mapbuf[4096] = {};
228 bool had_entry = false;
229 idmap_type_t map_type, u_or_g;
231 for (map_type = ID_TYPE_UID, u_or_g = 'u';
232 map_type <= ID_TYPE_GID; map_type++, u_or_g = 'g') {
235 struct list *iterator;
238 list_for_each(iterator, idmap) {
239 struct id_map *map = iterator->elem;
240 if (map->map_type != map_type)
245 left = 4096 - (pos - mapbuf);
246 fill = snprintf(pos, left, "%u %u %u\n", map->nsid, map->hostid, map->range);
248 * The kernel only takes <= 4k for writes to
249 * /proc/<pid>/{g,u}id_map
251 if (fill <= 0 || fill >= left)
252 return syserror_set(-E2BIG, "Too many %cid mappings defined", u_or_g);
259 ret = write_id_mapping(map_type, pid, mapbuf, pos - mapbuf);
261 return syserror("Failed to write mapping: %s", mapbuf);
263 memset(mapbuf, 0, sizeof(mapbuf));
269 static int get_userns_fd_from_idmap(struct list *idmap)
273 char path_ns[STRLITERALLEN("/proc/") + INTTYPE_TO_STRLEN(pid_t) +
274 STRLITERALLEN("/ns/user") + 1];
276 pid = do_clone(get_userns_fd_cb, NULL, CLONE_NEWUSER | CLONE_NEWNS);
280 ret = map_ids_from_idmap(idmap, pid);
284 ret = snprintf(path_ns, sizeof(path_ns), "/proc/%d/ns/user", pid);
285 if (ret < 0 || (size_t)ret >= sizeof(path_ns))
288 ret = open(path_ns, O_RDONLY | O_CLOEXEC | O_NOCTTY);
290 (void)kill(pid, SIGKILL);
291 (void)wait_for_pid(pid);
295 static inline bool strnequal(const char *str, const char *eq, size_t len)
297 return strncmp(str, eq, len) == 0;
300 static void usage(void)
302 const char *text = "\
303 mount-idmapped --map-mount=<idmap> <source> <target>\n\
305 Create an idmapped mount of <source> at <target>\n\
307 --map-mount=<idmap>\n\
308 Specify an idmap for the <target> mount in the format\n\
309 <idmap-type>:<id-from>:<id-to>:<id-range>\n\
310 The <idmap-type> can be:\n\
311 \"b\" or \"both\" -> map both uids and gids\n\
312 \"u\" or \"uid\" -> map uids\n\
313 \"g\" or \"gid\" -> map gids\n\
314 For example, specifying:\n\
315 both:1000:1001:1 -> map uid and gid 1000 to uid and gid 1001 in <target> and no other ids\n\
316 uid:20000:100000:1000 -> map uid 20000 to uid 100000, uid 20001 to uid 100001 [...] in <target>\n\
317 Currently up to 340 separate idmappings may be specified.\n\n\
318 --map-mount=/proc/<pid>/ns/user\n\
319 Specify a path to a user namespace whose idmap is to be used.\n\n\
321 Copy the whole mount tree from <source> and apply the idmap to everyone at <target>.\n\n\
323 - Create an idmapped mount of /source on /target with both ('b') uids and gids mapped:\n\
324 mount-idmapped --map-mount b:0:10000:10000 /source /target\n\n\
325 - Create an idmapped mount of /source on /target with uids ('u') and gids ('g') mapped separately:\n\
326 mount-idmapped --map-mount u:0:10000:10000 g:0:20000:20000 /source /target\n\n\
328 fprintf(stderr, "%s", text);
332 #define exit_usage(format, ...) \
334 fprintf(stderr, format, ##__VA_ARGS__); \
338 #define exit_log(format, ...) \
340 fprintf(stderr, format, ##__VA_ARGS__); \
341 exit(EXIT_FAILURE); \
344 static const struct option longopts[] = {
345 {"map-mount", required_argument, 0, 'a'},
346 {"help", no_argument, 0, 'c'},
347 {"recursive", no_argument, 0, 'd'},
351 int main(int argc, char *argv[])
353 int fd_userns = -EBADF;
355 const char *source = NULL, *target = NULL;
356 bool recursive = false;
357 int fd_tree, new_argc, ret;
358 char *const *new_argv;
360 list_init(&active_map);
361 while ((ret = getopt_long_only(argc, argv, "", longopts, &index)) != -1) {
364 if (strnequal(optarg, "/proc/", STRLITERALLEN("/proc/"))) {
365 fd_userns = open(optarg, O_RDONLY | O_CLOEXEC);
367 exit_log("%m - Failed top open user namespace path %s\n", optarg);
371 ret = parse_map(optarg);
373 exit_log("Failed to parse idmaps for mount\n");
385 new_argv = &argv[optind];
386 new_argc = argc - optind;
388 exit_usage("Missing source or target mountpoint\n\n");
389 source = new_argv[0];
390 target = new_argv[1];
392 fd_tree = sys_open_tree(-EBADF, source,
396 (recursive ? AT_RECURSIVE : 0));
398 exit_log("%m - Failed to open %s\n", source);
402 if (!list_empty(&active_map) || fd_userns >= 0) {
403 struct mount_attr attr = {
404 .attr_set = MOUNT_ATTR_IDMAP,
408 attr.userns_fd = fd_userns;
410 attr.userns_fd = get_userns_fd_from_idmap(&active_map);
411 if (attr.userns_fd < 0)
412 exit_log("%m - Failed to create user namespace\n");
414 ret = sys_mount_setattr(fd_tree, "", AT_EMPTY_PATH | AT_RECURSIVE,
415 &attr, sizeof(attr));
417 exit_log("%m - Failed to change mount attributes\n");
418 close(attr.userns_fd);
421 ret = sys_move_mount(fd_tree, "", -EBADF, target,
422 MOVE_MOUNT_F_EMPTY_PATH);
424 exit_log("%m - Failed to attach mount to %s\n", target);