2 * lxc: linux Container library
4 * (C) Copyright IBM Corp. 2007, 2008
7 * Daniel Lezcano <daniel.lezcano at free.fr>
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
28 #include <arpa/inet.h>
35 #include <linux/loop.h>
37 #include <netinet/in.h>
44 #include <sys/mount.h>
45 #include <sys/param.h>
46 #include <sys/prctl.h>
47 #include <sys/sendfile.h>
48 #include <sys/socket.h>
50 #include <sys/syscall.h>
51 #include <sys/sysmacros.h>
52 #include <sys/types.h>
53 #include <sys/utsname.h>
59 #include <sys/mkdev.h>
63 #include <sys/statvfs.h>
69 #include <../include/openpty.h>
73 #include <sys/capability.h>
76 #if HAVE_SYS_PERSONALITY_H
77 #include <sys/personality.h>
81 #include "include/strlcat.h"
85 #include <../include/lxcmntent.h>
90 #if !defined(HAVE_PRLIMIT) && defined(HAVE_PRLIMIT64)
91 #include <../include/prlimit.h>
98 #include "confile_utils.h"
103 #include "lxcseccomp.h"
105 #include "namespace.h"
111 #include "storage/overlay.h"
112 #include "terminal.h"
115 lxc_log_define(conf
, lxc
);
117 /* The lxc_conf of the container currently being worked on in an API call.
118 * This is used in the error calls.
121 thread_local
struct lxc_conf
*current_config
;
123 struct lxc_conf
*current_config
;
126 /* Define pivot_root() if missing from the C library */
127 #ifndef HAVE_PIVOT_ROOT
128 static int pivot_root(const char *new_root
, const char *put_old
)
130 #ifdef __NR_pivot_root
131 return syscall(__NR_pivot_root
, new_root
, put_old
);
138 extern int pivot_root(const char *new_root
, const char *put_old
);
141 char *lxchook_names
[NUM_LXC_HOOKS
] = {
170 static struct mount_opt mount_opt
[] = {
171 { "async", 1, MS_SYNCHRONOUS
},
172 { "atime", 1, MS_NOATIME
},
173 { "bind", 0, MS_BIND
},
174 { "defaults", 0, 0 },
175 { "dev", 1, MS_NODEV
},
176 { "diratime", 1, MS_NODIRATIME
},
177 { "dirsync", 0, MS_DIRSYNC
},
178 { "exec", 1, MS_NOEXEC
},
179 { "lazytime", 0, MS_LAZYTIME
},
180 { "mand", 0, MS_MANDLOCK
},
181 { "noatime", 0, MS_NOATIME
},
182 { "nodev", 0, MS_NODEV
},
183 { "nodiratime", 0, MS_NODIRATIME
},
184 { "noexec", 0, MS_NOEXEC
},
185 { "nomand", 1, MS_MANDLOCK
},
186 { "norelatime", 1, MS_RELATIME
},
187 { "nostrictatime", 1, MS_STRICTATIME
},
188 { "nosuid", 0, MS_NOSUID
},
189 { "rbind", 0, MS_BIND
|MS_REC
},
190 { "relatime", 0, MS_RELATIME
},
191 { "remount", 0, MS_REMOUNT
},
192 { "ro", 0, MS_RDONLY
},
193 { "rw", 1, MS_RDONLY
},
194 { "strictatime", 0, MS_STRICTATIME
},
195 { "suid", 1, MS_NOSUID
},
196 { "sync", 0, MS_SYNCHRONOUS
},
200 static struct mount_opt propagation_opt
[] = {
201 { "private", 0, MS_PRIVATE
},
202 { "shared", 0, MS_SHARED
},
203 { "slave", 0, MS_SLAVE
},
204 { "unbindable", 0, MS_UNBINDABLE
},
205 { "rprivate", 0, MS_PRIVATE
|MS_REC
},
206 { "rshared", 0, MS_SHARED
|MS_REC
},
207 { "rslave", 0, MS_SLAVE
|MS_REC
},
208 { "runbindable", 0, MS_UNBINDABLE
|MS_REC
},
212 static struct caps_opt caps_opt
[] = {
214 { "chown", CAP_CHOWN
},
215 { "dac_override", CAP_DAC_OVERRIDE
},
216 { "dac_read_search", CAP_DAC_READ_SEARCH
},
217 { "fowner", CAP_FOWNER
},
218 { "fsetid", CAP_FSETID
},
219 { "kill", CAP_KILL
},
220 { "setgid", CAP_SETGID
},
221 { "setuid", CAP_SETUID
},
222 { "setpcap", CAP_SETPCAP
},
223 { "linux_immutable", CAP_LINUX_IMMUTABLE
},
224 { "net_bind_service", CAP_NET_BIND_SERVICE
},
225 { "net_broadcast", CAP_NET_BROADCAST
},
226 { "net_admin", CAP_NET_ADMIN
},
227 { "net_raw", CAP_NET_RAW
},
228 { "ipc_lock", CAP_IPC_LOCK
},
229 { "ipc_owner", CAP_IPC_OWNER
},
230 { "sys_module", CAP_SYS_MODULE
},
231 { "sys_rawio", CAP_SYS_RAWIO
},
232 { "sys_chroot", CAP_SYS_CHROOT
},
233 { "sys_ptrace", CAP_SYS_PTRACE
},
234 { "sys_pacct", CAP_SYS_PACCT
},
235 { "sys_admin", CAP_SYS_ADMIN
},
236 { "sys_boot", CAP_SYS_BOOT
},
237 { "sys_nice", CAP_SYS_NICE
},
238 { "sys_resource", CAP_SYS_RESOURCE
},
239 { "sys_time", CAP_SYS_TIME
},
240 { "sys_tty_config", CAP_SYS_TTY_CONFIG
},
241 { "mknod", CAP_MKNOD
},
242 { "lease", CAP_LEASE
},
243 #ifdef CAP_AUDIT_READ
244 { "audit_read", CAP_AUDIT_READ
},
246 #ifdef CAP_AUDIT_WRITE
247 { "audit_write", CAP_AUDIT_WRITE
},
249 #ifdef CAP_AUDIT_CONTROL
250 { "audit_control", CAP_AUDIT_CONTROL
},
252 { "setfcap", CAP_SETFCAP
},
253 { "mac_override", CAP_MAC_OVERRIDE
},
254 { "mac_admin", CAP_MAC_ADMIN
},
256 { "syslog", CAP_SYSLOG
},
258 #ifdef CAP_WAKE_ALARM
259 { "wake_alarm", CAP_WAKE_ALARM
},
261 #ifdef CAP_BLOCK_SUSPEND
262 { "block_suspend", CAP_BLOCK_SUSPEND
},
267 static struct limit_opt limit_opt
[] = {
272 { "core", RLIMIT_CORE
},
275 { "cpu", RLIMIT_CPU
},
278 { "data", RLIMIT_DATA
},
281 { "fsize", RLIMIT_FSIZE
},
284 { "locks", RLIMIT_LOCKS
},
286 #ifdef RLIMIT_MEMLOCK
287 { "memlock", RLIMIT_MEMLOCK
},
289 #ifdef RLIMIT_MSGQUEUE
290 { "msgqueue", RLIMIT_MSGQUEUE
},
293 { "nice", RLIMIT_NICE
},
296 { "nofile", RLIMIT_NOFILE
},
299 { "nproc", RLIMIT_NPROC
},
302 { "rss", RLIMIT_RSS
},
305 { "rtprio", RLIMIT_RTPRIO
},
308 { "rttime", RLIMIT_RTTIME
},
310 #ifdef RLIMIT_SIGPENDING
311 { "sigpending", RLIMIT_SIGPENDING
},
314 { "stack", RLIMIT_STACK
},
318 static int run_buffer(char *buffer
)
322 struct lxc_popen_FILE
*f
;
324 f
= lxc_popen(buffer
);
326 SYSERROR("Failed to popen() %s", buffer
);
330 output
= malloc(LXC_LOG_BUFFER_SIZE
);
332 ERROR("Failed to allocate memory for %s", buffer
);
337 while (fgets(output
, LXC_LOG_BUFFER_SIZE
, f
->f
))
338 DEBUG("Script %s with output: %s", buffer
, output
);
344 SYSERROR("Script exited with error");
346 } else if (WIFEXITED(ret
) && WEXITSTATUS(ret
) != 0) {
347 ERROR("Script exited with status %d", WEXITSTATUS(ret
));
349 } else if (WIFSIGNALED(ret
)) {
350 ERROR("Script terminated by signal %d", WTERMSIG(ret
));
357 int run_script_argv(const char *name
, unsigned int hook_version
,
358 const char *section
, const char *script
,
359 const char *hookname
, char **argv
)
366 if (hook_version
== 0)
367 INFO("Executing script \"%s\" for container \"%s\", config "
368 "section \"%s\"", script
, name
, section
);
370 INFO("Executing script \"%s\" for container \"%s\"", script
, name
);
372 for (i
= 0; argv
&& argv
[i
]; i
++)
373 size
+= strlen(argv
[i
]) + 1;
375 size
+= sizeof("exec");
376 size
+= strlen(script
);
382 if (hook_version
== 0) {
383 size
+= strlen(hookname
);
386 size
+= strlen(name
);
389 size
+= strlen(section
);
396 buffer
= malloc(size
);
400 if (hook_version
== 0)
401 buf_pos
= snprintf(buffer
, size
, "exec %s %s %s %s", script
, name
, section
, hookname
);
403 buf_pos
= snprintf(buffer
, size
, "exec %s", script
);
404 if (buf_pos
< 0 || (size_t)buf_pos
>= size
) {
405 ERROR("Failed to create command line for script \"%s\"", script
);
409 if (hook_version
== 1) {
410 ret
= setenv("LXC_HOOK_TYPE", hookname
, 1);
412 SYSERROR("Failed to set environment variable: "
413 "LXC_HOOK_TYPE=%s", hookname
);
416 TRACE("Set environment variable: LXC_HOOK_TYPE=%s", hookname
);
418 ret
= setenv("LXC_HOOK_SECTION", section
, 1);
420 SYSERROR("Failed to set environment variable: "
421 "LXC_HOOK_SECTION=%s", section
);
424 TRACE("Set environment variable: LXC_HOOK_SECTION=%s", section
);
426 if (strcmp(section
, "net") == 0) {
429 if (!argv
|| !argv
[0])
432 ret
= setenv("LXC_NET_TYPE", argv
[0], 1);
434 SYSERROR("Failed to set environment variable: "
435 "LXC_NET_TYPE=%s", argv
[0]);
438 TRACE("Set environment variable: LXC_NET_TYPE=%s", argv
[0]);
440 parent
= argv
[1] ? argv
[1] : "";
442 if (strcmp(argv
[0], "macvlan") == 0) {
443 ret
= setenv("LXC_NET_PARENT", parent
, 1);
445 SYSERROR("Failed to set environment "
446 "variable: LXC_NET_PARENT=%s", parent
);
449 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
450 } else if (strcmp(argv
[0], "phys") == 0) {
451 ret
= setenv("LXC_NET_PARENT", parent
, 1);
453 SYSERROR("Failed to set environment "
454 "variable: LXC_NET_PARENT=%s", parent
);
457 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
458 } else if (strcmp(argv
[0], "veth") == 0) {
459 char *peer
= argv
[2] ? argv
[2] : "";
461 ret
= setenv("LXC_NET_PEER", peer
, 1);
463 SYSERROR("Failed to set environment "
464 "variable: LXC_NET_PEER=%s", peer
);
467 TRACE("Set environment variable: LXC_NET_PEER=%s", peer
);
469 ret
= setenv("LXC_NET_PARENT", parent
, 1);
471 SYSERROR("Failed to set environment "
472 "variable: LXC_NET_PARENT=%s", parent
);
475 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
480 for (i
= 0; argv
&& argv
[i
]; i
++) {
481 size_t len
= size
- buf_pos
;
483 ret
= snprintf(buffer
+ buf_pos
, len
, " %s", argv
[i
]);
484 if (ret
< 0 || (size_t)ret
>= len
) {
485 ERROR("Failed to create command line for script \"%s\"", script
);
491 fret
= run_buffer(buffer
);
498 int run_script(const char *name
, const char *section
, const char *script
, ...)
505 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\"",
506 script
, name
, section
);
508 va_start(ap
, script
);
509 while ((p
= va_arg(ap
, char *)))
510 size
+= strlen(p
) + 1;
513 size
+= strlen("exec");
514 size
+= strlen(script
);
515 size
+= strlen(name
);
516 size
+= strlen(section
);
522 buffer
= alloca(size
);
523 ret
= snprintf(buffer
, size
, "exec %s %s %s", script
, name
, section
);
524 if (ret
< 0 || ret
>= size
)
527 va_start(ap
, script
);
528 while ((p
= va_arg(ap
, char *))) {
529 int len
= size
- ret
;
531 rc
= snprintf(buffer
+ ret
, len
, " %s", p
);
532 if (rc
< 0 || rc
>= len
) {
540 return run_buffer(buffer
);
544 * if rootfs is a directory, then open ${rootfs}/.lxc-keep for writing for
545 * the duration of the container run, to prevent the container from marking
546 * the underlying fs readonly on shutdown. unlink the file immediately so
547 * no name pollution is happens.
548 * don't unlink on NFS to avoid random named stale handles.
549 * return -1 on error.
550 * return -2 if nothing needed to be pinned.
551 * return an open fd (>=0) if we pinned it.
553 int pin_rootfs(const char *rootfs
)
556 char absrootfs
[MAXPATHLEN
], absrootfspin
[MAXPATHLEN
];
560 if (rootfs
== NULL
|| strlen(rootfs
) == 0)
563 if (!realpath(rootfs
, absrootfs
))
566 ret
= stat(absrootfs
, &s
);
570 if (!S_ISDIR(s
.st_mode
))
573 ret
= snprintf(absrootfspin
, MAXPATHLEN
, "%s/.lxc-keep", absrootfs
);
574 if (ret
>= MAXPATHLEN
)
577 fd
= open(absrootfspin
, O_CREAT
| O_RDWR
, S_IWUSR
| S_IRUSR
);
581 ret
= fstatfs (fd
, &sfs
);
585 if (sfs
.f_type
== NFS_SUPER_MAGIC
) {
586 DEBUG("Rootfs on NFS, not unlinking pin file \"%s\"", absrootfspin
);
590 (void)unlink(absrootfspin
);
595 /* If we are asking to remount something, make sure that any NOEXEC etc are
598 unsigned long add_required_remount_flags(const char *s
, const char *d
,
604 unsigned long required_flags
= 0;
612 ret
= statvfs(s
, &sb
);
616 if (flags
& MS_REMOUNT
) {
617 if (sb
.f_flag
& MS_NOSUID
)
618 required_flags
|= MS_NOSUID
;
619 if (sb
.f_flag
& MS_NODEV
)
620 required_flags
|= MS_NODEV
;
621 if (sb
.f_flag
& MS_RDONLY
)
622 required_flags
|= MS_RDONLY
;
623 if (sb
.f_flag
& MS_NOEXEC
)
624 required_flags
|= MS_NOEXEC
;
627 if (sb
.f_flag
& MS_NOATIME
)
628 required_flags
|= MS_NOATIME
;
629 if (sb
.f_flag
& MS_NODIRATIME
)
630 required_flags
|= MS_NODIRATIME
;
631 if (sb
.f_flag
& MS_LAZYTIME
)
632 required_flags
|= MS_LAZYTIME
;
633 if (sb
.f_flag
& MS_RELATIME
)
634 required_flags
|= MS_RELATIME
;
635 if (sb
.f_flag
& MS_STRICTATIME
)
636 required_flags
|= MS_STRICTATIME
;
638 return flags
| required_flags
;
644 static int add_shmount_to_list(struct lxc_conf
*conf
)
646 char new_mount
[MAXPATHLEN
];
647 /* Offset for the leading '/' since the path_cont
648 * is absolute inside the container.
650 int offset
= 1, ret
= -1;
652 ret
= snprintf(new_mount
, sizeof(new_mount
),
653 "%s %s none bind,create=dir 0 0", conf
->shmount
.path_host
,
654 conf
->shmount
.path_cont
+ offset
);
655 if (ret
< 0 || (size_t)ret
>= sizeof(new_mount
))
658 return add_elem_to_mount_list(new_mount
, conf
);
661 static int lxc_mount_auto_mounts(struct lxc_conf
*conf
, int flags
, struct lxc_handler
*handler
)
668 const char *destination
;
672 } default_mounts
[] = {
673 /* Read-only bind-mounting... In older kernels, doing that
674 * required to do one MS_BIND mount and then
675 * MS_REMOUNT|MS_RDONLY the same one. According to mount(2)
676 * manpage, MS_BIND honors MS_RDONLY from kernel 2.6.26
677 * onwards. However, this apparently does not work on kernel
678 * 3.8. Unfortunately, on that very same kernel, doing the same
679 * trick as above doesn't seem to work either, there one needs
680 * to ALSO specify MS_BIND for the remount, otherwise the
681 * entire fs is remounted read-only or the mount fails because
682 * it's busy... MS_REMOUNT|MS_BIND|MS_RDONLY seems to work for
683 * kernels as low as 2.6.32...
685 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "proc", "%r/proc", "proc", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
686 /* proc/tty is used as a temporary placeholder for proc/sys/net which we'll move back in a few steps */
687 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sys/net", "%r/proc/tty", NULL
, MS_BIND
, NULL
},
688 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sys", "%r/proc/sys", NULL
, MS_BIND
, NULL
},
689 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, NULL
, "%r/proc/sys", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
690 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/tty", "%r/proc/sys/net", NULL
, MS_MOVE
, NULL
},
691 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sysrq-trigger", "%r/proc/sysrq-trigger", NULL
, MS_BIND
, NULL
},
692 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, NULL
, "%r/proc/sysrq-trigger", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
693 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_RW
, "proc", "%r/proc", "proc", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
694 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_RW
, "sysfs", "%r/sys", "sysfs", 0, NULL
},
695 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_RO
, "sysfs", "%r/sys", "sysfs", MS_RDONLY
, NULL
},
696 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "sysfs", "%r/sys", "sysfs", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
697 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "%r/sys", "%r/sys", NULL
, MS_BIND
, NULL
},
698 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, NULL
, "%r/sys", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
699 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "sysfs", "%r/sys/devices/virtual/net", "sysfs", 0, NULL
},
700 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "%r/sys/devices/virtual/net/devices/virtual/net", "%r/sys/devices/virtual/net", NULL
, MS_BIND
, NULL
},
701 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, NULL
, "%r/sys/devices/virtual/net", NULL
, MS_REMOUNT
|MS_BIND
|MS_NOSUID
|MS_NODEV
|MS_NOEXEC
, NULL
},
702 { 0, 0, NULL
, NULL
, NULL
, 0, NULL
}
705 for (i
= 0; default_mounts
[i
].match_mask
; i
++) {
707 unsigned long mflags
;
708 char *destination
= NULL
;
710 if ((flags
& default_mounts
[i
].match_mask
) != default_mounts
[i
].match_flag
)
713 if (default_mounts
[i
].source
) {
714 /* will act like strdup if %r is not present */
715 source
= lxc_string_replace("%r", conf
->rootfs
.path
? conf
->rootfs
.mount
: "", default_mounts
[i
].source
);
720 if (!default_mounts
[i
].destination
) {
721 ERROR("BUG: auto mounts destination %d was NULL", i
);
726 /* will act like strdup if %r is not present */
727 destination
= lxc_string_replace("%r", conf
->rootfs
.path
? conf
->rootfs
.mount
: "", default_mounts
[i
].destination
);
735 mflags
= add_required_remount_flags(source
, destination
,
736 default_mounts
[i
].flags
);
737 r
= safe_mount(source
, destination
, default_mounts
[i
].fstype
,
738 mflags
, default_mounts
[i
].options
,
739 conf
->rootfs
.path
? conf
->rootfs
.mount
: NULL
);
741 if (r
< 0 && errno
== ENOENT
) {
742 INFO("Mount source or target for \"%s\" on \"%s\" does "
743 "not exist. Skipping", source
, destination
);
746 SYSERROR("Failed to mount \"%s\" on \"%s\" with flags %lu", source
, destination
, mflags
);
757 if (flags
& LXC_AUTO_CGROUP_MASK
) {
760 cg_flags
= flags
& (LXC_AUTO_CGROUP_MASK
& ~LXC_AUTO_CGROUP_FORCE
);
761 /* If the type of cgroup mount was not specified, it depends on
762 * the container's capabilities as to what makes sense: if we
763 * have CAP_SYS_ADMIN, the read-only part can be remounted
764 * read-write anyway, so we may as well default to read-write;
765 * then the admin will not be given a false sense of security.
766 * (And if they really want mixed r/o r/w, then they can
767 * explicitly specify :mixed.) OTOH, if the container lacks
768 * CAP_SYS_ADMIN, do only default to :mixed, because then the
769 * container can't remount it read-write.
771 if (cg_flags
== LXC_AUTO_CGROUP_NOSPEC
|| cg_flags
== LXC_AUTO_CGROUP_FULL_NOSPEC
) {
772 int has_sys_admin
= 0;
774 if (!lxc_list_empty(&conf
->keepcaps
))
775 has_sys_admin
= in_caplist(CAP_SYS_ADMIN
, &conf
->keepcaps
);
777 has_sys_admin
= !in_caplist(CAP_SYS_ADMIN
, &conf
->caps
);
779 if (cg_flags
== LXC_AUTO_CGROUP_NOSPEC
)
780 cg_flags
= has_sys_admin
? LXC_AUTO_CGROUP_RW
: LXC_AUTO_CGROUP_MIXED
;
782 cg_flags
= has_sys_admin
? LXC_AUTO_CGROUP_FULL_RW
: LXC_AUTO_CGROUP_FULL_MIXED
;
785 if (flags
& LXC_AUTO_CGROUP_FORCE
)
786 cg_flags
|= LXC_AUTO_CGROUP_FORCE
;
788 if (!handler
->cgroup_ops
->mount(handler
->cgroup_ops
,
790 conf
->rootfs
.path
? conf
->rootfs
.mount
: "",
792 SYSERROR("Failed to mount \"/sys/fs/cgroup\"");
797 if (flags
& LXC_AUTO_SHMOUNTS_MASK
) {
798 int ret
= add_shmount_to_list(conf
);
800 ERROR("Failed to add shmount entry to container config");
808 static int setup_utsname(struct utsname
*utsname
)
815 ret
= sethostname(utsname
->nodename
, strlen(utsname
->nodename
));
817 SYSERROR("Failed to set the hostname to \"%s\"", utsname
->nodename
);
821 INFO("Set hostname to \"%s\"", utsname
->nodename
);
826 struct dev_symlinks
{
831 static const struct dev_symlinks dev_symlinks
[] = {
832 { "/proc/self/fd", "fd" },
833 { "/proc/self/fd/0", "stdin" },
834 { "/proc/self/fd/1", "stdout" },
835 { "/proc/self/fd/2", "stderr" },
838 static int lxc_setup_dev_symlinks(const struct lxc_rootfs
*rootfs
)
841 char path
[MAXPATHLEN
];
844 for (i
= 0; i
< sizeof(dev_symlinks
) / sizeof(dev_symlinks
[0]); i
++) {
845 const struct dev_symlinks
*d
= &dev_symlinks
[i
];
847 ret
= snprintf(path
, sizeof(path
), "%s/dev/%s",
848 rootfs
->path
? rootfs
->mount
: "", d
->name
);
849 if (ret
< 0 || ret
>= MAXPATHLEN
)
852 /* Stat the path first. If we don't get an error accept it as
853 * is and don't try to create it
855 ret
= stat(path
, &s
);
859 ret
= symlink(d
->oldpath
, path
);
860 if (ret
&& errno
!= EEXIST
) {
861 if (errno
== EROFS
) {
862 WARN("Failed to create \"%s\". Read-only filesystem", path
);
864 SYSERROR("Failed to create \"%s\"", path
);
873 /* Build a space-separate list of ptys to pass to systemd. */
874 static bool append_ttyname(char **pp
, char *name
)
880 *pp
= malloc(strlen(name
) + strlen("container_ttys=") + 1);
884 sprintf(*pp
, "container_ttys=%s", name
);
888 size
= strlen(*pp
) + strlen(name
) + 2;
889 p
= realloc(*pp
, size
);
894 (void)strlcat(p
, " ", size
);
895 (void)strlcat(p
, name
, size
);
900 static int lxc_setup_ttys(struct lxc_conf
*conf
)
903 const struct lxc_tty_info
*ttys
= &conf
->ttys
;
904 char *ttydir
= ttys
->dir
;
905 char path
[MAXPATHLEN
], lxcpath
[MAXPATHLEN
];
907 if (!conf
->rootfs
.path
)
910 for (i
= 0; i
< ttys
->max
; i
++) {
911 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
913 ret
= snprintf(path
, sizeof(path
), "/dev/tty%d", i
+ 1);
914 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
918 /* create dev/lxc/tty%d" */
919 ret
= snprintf(lxcpath
, sizeof(lxcpath
),
920 "/dev/%s/tty%d", ttydir
, i
+ 1);
921 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
924 ret
= mknod(lxcpath
, S_IFREG
| 0000, 0);
925 if (ret
< 0 && errno
!= EEXIST
) {
926 SYSERROR("Failed to create \"%s\"", lxcpath
);
931 if (ret
< 0 && errno
!= ENOENT
) {
932 SYSERROR("Failed to unlink \"%s\"", path
);
936 ret
= mount(tty
->name
, lxcpath
, "none", MS_BIND
, 0);
938 SYSWARN("Failed to bind mount \"%s\" onto \"%s\"",
942 DEBUG("Bind mounted \"%s\" onto \"%s\"", tty
->name
,
945 ret
= snprintf(lxcpath
, sizeof(lxcpath
), "%s/tty%d",
947 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
950 ret
= symlink(lxcpath
, path
);
952 SYSERROR("Failed to create symlink \"%s\" -> \"%s\"",
957 /* If we populated /dev, then we need to create
960 ret
= mknod(path
, S_IFREG
| 0000, 0);
961 if (ret
< 0) /* this isn't fatal, continue */
962 SYSERROR("Failed to create \"%s\"", path
);
964 ret
= mount(tty
->name
, path
, "none", MS_BIND
, 0);
966 SYSERROR("Failed to mount '%s'->'%s'", tty
->name
, path
);
970 DEBUG("Bind mounted \"%s\" onto \"%s\"", tty
->name
, path
);
973 if (!append_ttyname(&conf
->ttys
.tty_names
, tty
->name
)) {
974 ERROR("Error setting up container_ttys string");
979 INFO("Finished setting up %zu /dev/tty<N> device(s)", ttys
->max
);
983 int lxc_allocate_ttys(struct lxc_conf
*conf
)
987 struct lxc_tty_info
*ttys
= &conf
->ttys
;
989 /* no tty in the configuration */
993 ttys
->tty
= malloc(sizeof(*ttys
->tty
) * ttys
->max
);
997 for (i
= 0; i
< ttys
->max
; i
++) {
998 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
1000 tty
->master
= -EBADF
;
1001 tty
->slave
= -EBADF
;
1002 ret
= openpty(&tty
->master
, &tty
->slave
, NULL
, NULL
, NULL
);
1004 SYSERROR("Failed to create tty %zu", i
);
1006 lxc_delete_tty(ttys
);
1010 ret
= ttyname_r(tty
->slave
, tty
->name
, sizeof(tty
->name
));
1012 SYSERROR("Failed to retrieve name of tty %zu slave", i
);
1014 lxc_delete_tty(ttys
);
1018 DEBUG("Created tty \"%s\" with master fd %d and slave fd %d",
1019 tty
->name
, tty
->master
, tty
->slave
);
1021 /* Prevent leaking the file descriptors to the container */
1022 ret
= fd_cloexec(tty
->master
, true);
1024 SYSWARN("Failed to set FD_CLOEXEC flag on master fd %d of "
1025 "tty device \"%s\"", tty
->master
, tty
->name
);
1027 ret
= fd_cloexec(tty
->slave
, true);
1029 SYSWARN("Failed to set FD_CLOEXEC flag on slave fd %d of "
1030 "tty device \"%s\"", tty
->slave
, tty
->name
);
1035 INFO("Finished creating %zu tty devices", ttys
->max
);
1039 void lxc_delete_tty(struct lxc_tty_info
*ttys
)
1046 for (i
= 0; i
< ttys
->max
; i
++) {
1047 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
1049 if (tty
->master
>= 0) {
1051 tty
->master
= -EBADF
;
1054 if (tty
->slave
>= 0) {
1056 tty
->slave
= -EBADF
;
1064 static int lxc_send_ttys_to_parent(struct lxc_handler
*handler
)
1068 struct lxc_conf
*conf
= handler
->conf
;
1069 struct lxc_tty_info
*ttys
= &conf
->ttys
;
1070 int sock
= handler
->data_sock
[0];
1075 for (i
= 0; i
< ttys
->max
; i
++) {
1077 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
1079 ttyfds
[0] = tty
->master
;
1080 ttyfds
[1] = tty
->slave
;
1082 ret
= lxc_abstract_unix_send_fds(sock
, ttyfds
, 2, NULL
, 0);
1086 TRACE("Sent ty \"%s\" with master fd %d and slave fd %d to "
1087 "parent", tty
->name
, tty
->master
, tty
->slave
);
1091 SYSERROR("Failed to send %zu ttys to parent", ttys
->max
);
1093 TRACE("Sent %zu ttys to parent", ttys
->max
);
1098 static int lxc_create_ttys(struct lxc_handler
*handler
)
1101 struct lxc_conf
*conf
= handler
->conf
;
1103 ret
= lxc_allocate_ttys(conf
);
1105 ERROR("Failed to allocate ttys");
1109 ret
= lxc_send_ttys_to_parent(handler
);
1111 ERROR("Failed to send ttys to parent");
1115 if (!conf
->is_execute
) {
1116 ret
= lxc_setup_ttys(conf
);
1118 ERROR("Failed to setup ttys");
1123 if (conf
->ttys
.tty_names
) {
1124 ret
= setenv("container_ttys", conf
->ttys
.tty_names
, 1);
1126 SYSERROR("Failed to set \"container_ttys=%s\"", conf
->ttys
.tty_names
);
1132 lxc_delete_tty(&conf
->ttys
);
1137 /* Just create a path for /dev under $lxcpath/$name and in rootfs If we hit an
1138 * error, log it but don't fail yet.
1140 static int mount_autodev(const char *name
, const struct lxc_rootfs
*rootfs
,
1141 const char *lxcpath
)
1148 INFO("Preparing \"/dev\"");
1150 /* $(rootfs->mount) + "/dev/pts" + '\0' */
1151 clen
= (rootfs
->path
? strlen(rootfs
->mount
) : 0) + 9;
1152 path
= alloca(clen
);
1154 ret
= snprintf(path
, clen
, "%s/dev", rootfs
->path
? rootfs
->mount
: "");
1155 if (ret
< 0 || (size_t)ret
>= clen
)
1158 cur_mask
= umask(S_IXUSR
| S_IXGRP
| S_IXOTH
);
1159 ret
= mkdir(path
, S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
1160 if (ret
< 0 && errno
!= EEXIST
) {
1161 SYSERROR("Failed to create \"/dev\" directory");
1166 ret
= safe_mount("none", path
, "tmpfs", 0, "size=500000,mode=755",
1167 rootfs
->path
? rootfs
->mount
: NULL
);
1169 SYSERROR("Failed to mount tmpfs on \"%s\"", path
);
1172 TRACE("Mounted tmpfs on \"%s\"", path
);
1174 ret
= snprintf(path
, clen
, "%s/dev/pts", rootfs
->path
? rootfs
->mount
: "");
1175 if (ret
< 0 || (size_t)ret
>= clen
) {
1180 /* If we are running on a devtmpfs mapping, dev/pts may already exist.
1181 * If not, then create it and exit if that fails...
1183 ret
= mkdir(path
, S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
1184 if (ret
< 0 && errno
!= EEXIST
) {
1185 SYSERROR("Failed to create directory \"%s\"", path
);
1193 (void)umask(cur_mask
);
1195 INFO("Prepared \"/dev\"");
1199 struct lxc_device_node
{
1206 static const struct lxc_device_node lxc_devices
[] = {
1207 { "full", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 7 },
1208 { "null", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 3 },
1209 { "random", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 8 },
1210 { "tty", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 5, 0 },
1211 { "urandom", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 9 },
1212 { "zero", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 5 },
1219 LXC_DEVNODE_PARTIAL
,
1223 static int lxc_fill_autodev(const struct lxc_rootfs
*rootfs
)
1226 char path
[MAXPATHLEN
];
1228 int use_mknod
= LXC_DEVNODE_MKNOD
;
1230 ret
= snprintf(path
, MAXPATHLEN
, "%s/dev",
1231 rootfs
->path
? rootfs
->mount
: "");
1232 if (ret
< 0 || ret
>= MAXPATHLEN
)
1235 /* ignore, just don't try to fill in */
1236 if (!dir_exists(path
))
1239 INFO("Populating \"/dev\"");
1241 cmask
= umask(S_IXUSR
| S_IXGRP
| S_IXOTH
);
1242 for (i
= 0; i
< sizeof(lxc_devices
) / sizeof(lxc_devices
[0]); i
++) {
1243 char hostpath
[MAXPATHLEN
];
1244 const struct lxc_device_node
*device
= &lxc_devices
[i
];
1246 ret
= snprintf(path
, MAXPATHLEN
, "%s/dev/%s",
1247 rootfs
->path
? rootfs
->mount
: "", device
->name
);
1248 if (ret
< 0 || ret
>= MAXPATHLEN
)
1251 if (use_mknod
>= LXC_DEVNODE_MKNOD
) {
1252 ret
= mknod(path
, device
->mode
, makedev(device
->maj
, device
->min
));
1253 if (ret
== 0 || (ret
< 0 && errno
== EEXIST
)) {
1254 DEBUG("Created device node \"%s\"", path
);
1255 } else if (ret
< 0) {
1256 if (errno
!= EPERM
) {
1257 SYSERROR("Failed to create device node \"%s\"", path
);
1261 use_mknod
= LXC_DEVNODE_BIND
;
1264 /* Device nodes are fully useable. */
1265 if (use_mknod
== LXC_DEVNODE_OPEN
)
1268 if (use_mknod
== LXC_DEVNODE_MKNOD
) {
1270 * - https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=55956b59df336f6738da916dbb520b6e37df9fbd
1271 * - https://lists.linuxfoundation.org/pipermail/containers/2018-June/039176.html
1273 ret
= open(path
, O_RDONLY
| O_CLOEXEC
);
1276 /* Device nodes are fully useable. */
1277 use_mknod
= LXC_DEVNODE_OPEN
;
1281 SYSTRACE("Failed to open \"%s\" device", path
);
1282 /* Device nodes are only partially useable. */
1283 use_mknod
= LXC_DEVNODE_PARTIAL
;
1287 if (use_mknod
!= LXC_DEVNODE_PARTIAL
) {
1288 /* If we are dealing with partially functional device
1289 * nodes the prio mknod() call will have created the
1290 * device node so we can use it as a bind-mount target.
1292 ret
= mknod(path
, S_IFREG
| 0000, 0);
1293 if (ret
< 0 && errno
!= EEXIST
) {
1294 SYSERROR("Failed to create file \"%s\"", path
);
1299 /* Fallback to bind-mounting the device from the host. */
1300 ret
= snprintf(hostpath
, MAXPATHLEN
, "/dev/%s", device
->name
);
1301 if (ret
< 0 || ret
>= MAXPATHLEN
)
1304 ret
= safe_mount(hostpath
, path
, 0, MS_BIND
, NULL
,
1305 rootfs
->path
? rootfs
->mount
: NULL
);
1307 SYSERROR("Failed to bind mount host device node \"%s\" "
1308 "onto \"%s\"", hostpath
, path
);
1311 DEBUG("Bind mounted host device node \"%s\" onto \"%s\"",
1316 INFO("Populated \"/dev\"");
1320 static int lxc_mount_rootfs(struct lxc_conf
*conf
)
1323 struct lxc_storage
*bdev
;
1324 const struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
1326 if (!rootfs
->path
) {
1327 ret
= mount("", "/", NULL
, MS_SLAVE
| MS_REC
, 0);
1329 SYSERROR("Failed to remount \"/\" MS_REC | MS_SLAVE");
1336 ret
= access(rootfs
->mount
, F_OK
);
1338 SYSERROR("Failed to access to \"%s\". Check it is present",
1343 bdev
= storage_init(conf
);
1345 ERROR("Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\"",
1346 rootfs
->path
, rootfs
->mount
,
1347 rootfs
->options
? rootfs
->options
: "(null)");
1351 ret
= bdev
->ops
->mount(bdev
);
1354 ERROR("Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\"",
1355 rootfs
->path
, rootfs
->mount
,
1356 rootfs
->options
? rootfs
->options
: "(null)");
1360 DEBUG("Mounted rootfs \"%s\" onto \"%s\" with options \"%s\"",
1361 rootfs
->path
, rootfs
->mount
,
1362 rootfs
->options
? rootfs
->options
: "(null)");
1367 int lxc_chroot(const struct lxc_rootfs
*rootfs
)
1371 char buf
[LXC_LINELEN
], nroot
[PATH_MAX
];
1373 char *root
= rootfs
->mount
;
1375 if (!realpath(root
, nroot
)) {
1376 SYSERROR("Failed to resolve \"%s\"", root
);
1384 /* We could use here MS_MOVE, but in userns this mount is locked and
1387 ret
= mount(nroot
, "/", NULL
, MS_REC
| MS_BIND
, NULL
);
1389 SYSERROR("Failed to mount \"%s\" onto \"/\" as MS_REC | MS_BIND", nroot
);
1393 ret
= mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, NULL
);
1395 SYSERROR("Failed to remount \"/\"");
1399 /* The following code cleans up inhereted mounts which are not required
1402 * The mountinfo file shows not all mounts, if a few points have been
1403 * unmounted between read operations from the mountinfo. So we need to
1404 * read mountinfo a few times.
1406 * This loop can be skipped if a container uses unserns, because all
1407 * inherited mounts are locked and we should live with all this trash.
1412 f
= fopen("./proc/self/mountinfo", "r");
1414 SYSERROR("Failed to open \"/proc/self/mountinfo\"");
1418 while (fgets(buf
, LXC_LINELEN
, f
)) {
1419 for (p
= buf
, i
=0; p
&& i
< 4; i
++)
1420 p
= strchr(p
+1, ' ');
1425 p2
= strchr(p
+1, ' ');
1432 if (strcmp(p
+ 1, "/") == 0)
1435 if (strcmp(p
+ 1, "/proc") == 0)
1438 ret
= umount2(p
, MNT_DETACH
);
1449 /* This also can be skipped if a container uses unserns. */
1450 (void)umount2("./proc", MNT_DETACH
);
1452 /* It is weird, but chdir("..") moves us in a new root */
1455 SYSERROR("Failed to chdir(\"..\")");
1461 SYSERROR("Failed to chroot(\".\")");
1468 /* (The following explanation is copied verbatim from the kernel.)
1470 * pivot_root Semantics:
1471 * Moves the root file system of the current process to the directory put_old,
1472 * makes new_root as the new root file system of the current process, and sets
1473 * root/cwd of all processes which had them on the current root to new_root.
1476 * The new_root and put_old must be directories, and must not be on the
1477 * same file system as the current process root. The put_old must be
1478 * underneath new_root, i.e. adding a non-zero number of /.. to the string
1479 * pointed to by put_old must yield the same directory as new_root. No other
1480 * file system may be mounted on put_old. After all, new_root is a mountpoint.
1482 * Also, the current root cannot be on the 'rootfs' (initial ramfs) filesystem.
1483 * See Documentation/filesystems/ramfs-rootfs-initramfs.txt for alternatives
1484 * in this situation.
1487 * - we don't move root/cwd if they are not at the root (reason: if something
1488 * cared enough to change them, it's probably wrong to force them elsewhere)
1489 * - it's okay to pick a root that isn't the root of a file system, e.g.
1490 * /nfs/my_root where /nfs is the mount point. It must be a mountpoint,
1491 * though, so you may need to say mount --bind /nfs/my_root /nfs/my_root
1494 static int lxc_pivot_root(const char *rootfs
)
1496 int newroot
= -1, oldroot
= -1, ret
= -1;
1498 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
);
1500 SYSERROR("Failed to open old root directory");
1504 newroot
= open(rootfs
, O_DIRECTORY
| O_RDONLY
);
1506 SYSERROR("Failed to open new root directory");
1510 /* change into new root fs */
1511 ret
= fchdir(newroot
);
1514 SYSERROR("Failed to change to new rootfs \"%s\"", rootfs
);
1518 /* pivot_root into our new root fs */
1519 ret
= pivot_root(".", ".");
1522 SYSERROR("Failed to pivot_root()");
1526 /* At this point the old-root is mounted on top of our new-root. To
1527 * unmounted it we must not be chdir'd into it, so escape back to
1530 ret
= fchdir(oldroot
);
1533 SYSERROR("Failed to enter old root directory");
1537 /* Make oldroot rslave to make sure our umounts don't propagate to the
1540 ret
= mount("", ".", "", MS_SLAVE
| MS_REC
, NULL
);
1543 SYSERROR("Failed to make oldroot rslave");
1547 ret
= umount2(".", MNT_DETACH
);
1550 SYSERROR("Failed to detach old root directory");
1554 ret
= fchdir(newroot
);
1557 SYSERROR("Failed to re-enter new root directory");
1563 TRACE("pivot_root(\"%s\") successful", rootfs
);
1574 static int lxc_setup_rootfs_switch_root(const struct lxc_rootfs
*rootfs
)
1576 if (!rootfs
->path
) {
1577 DEBUG("Container does not have a rootfs");
1581 if (detect_ramfs_rootfs())
1582 return lxc_chroot(rootfs
);
1584 return lxc_pivot_root(rootfs
->mount
);
1587 static const struct id_map
*find_mapped_nsid_entry(struct lxc_conf
*conf
,
1591 struct lxc_list
*it
;
1593 struct id_map
*retmap
= NULL
;
1595 /* Shortcut for container's root mappings. */
1597 if (idtype
== ID_TYPE_UID
)
1598 return conf
->root_nsuid_map
;
1600 if (idtype
== ID_TYPE_GID
)
1601 return conf
->root_nsgid_map
;
1604 lxc_list_for_each(it
, &conf
->id_map
) {
1606 if (map
->idtype
!= idtype
)
1609 if (id
>= map
->nsid
&& id
< map
->nsid
+ map
->range
) {
1618 static int lxc_setup_devpts(struct lxc_conf
*conf
)
1622 char devpts_mntopts
[256];
1623 char *mntopt_sets
[5];
1624 char default_devpts_mntopts
[256] = "gid=5,newinstance,ptmxmode=0666,mode=0620";
1626 if (conf
->pty_max
<= 0) {
1627 DEBUG("No new devpts instance will be mounted since no pts "
1628 "devices are requested");
1632 ret
= snprintf(devpts_mntopts
, sizeof(devpts_mntopts
), "%s,max=%zu",
1633 default_devpts_mntopts
, conf
->pty_max
);
1634 if (ret
< 0 || (size_t)ret
>= sizeof(devpts_mntopts
))
1637 ret
= umount2("/dev/pts", MNT_DETACH
);
1639 SYSWARN("Failed to unmount old devpts instance");
1641 DEBUG("Unmounted old devpts instance");
1643 /* Create mountpoint for devpts instance. */
1644 ret
= mkdir("/dev/pts", 0755);
1645 if (ret
< 0 && errno
!= EEXIST
) {
1646 SYSERROR("Failed to create \"/dev/pts\" directory");
1651 mntopt_sets
[0] = devpts_mntopts
;
1653 /* !gid=5 && max= */
1654 mntopt_sets
[1] = devpts_mntopts
+ sizeof("gid=5");
1656 /* gid=5 && !max= */
1657 mntopt_sets
[2] = default_devpts_mntopts
;
1659 /* !gid=5 && !max= */
1660 mntopt_sets
[3] = default_devpts_mntopts
+ sizeof("gid=5");
1663 mntopt_sets
[4] = NULL
;
1665 for (ret
= -1, opts
= mntopt_sets
; opts
&& *opts
; opts
++) {
1666 /* mount new devpts instance */
1667 ret
= mount("devpts", "/dev/pts", "devpts", MS_NOSUID
| MS_NOEXEC
, *opts
);
1673 SYSERROR("Failed to mount new devpts instance");
1676 DEBUG("Mount new devpts instance with options \"%s\"", *opts
);
1678 /* Remove any pre-existing /dev/ptmx file. */
1679 ret
= remove("/dev/ptmx");
1681 if (errno
!= ENOENT
) {
1682 SYSERROR("Failed to remove existing \"/dev/ptmx\" file");
1686 DEBUG("Removed existing \"/dev/ptmx\" file");
1689 /* Create dummy /dev/ptmx file as bind mountpoint for /dev/pts/ptmx. */
1690 ret
= mknod("/dev/ptmx", S_IFREG
| 0000, 0);
1691 if (ret
< 0 && errno
!= EEXIST
) {
1692 SYSERROR("Failed to create dummy \"/dev/ptmx\" file as bind mount target");
1695 DEBUG("Created dummy \"/dev/ptmx\" file as bind mount target");
1697 /* Fallback option: create symlink /dev/ptmx -> /dev/pts/ptmx */
1698 ret
= mount("/dev/pts/ptmx", "/dev/ptmx", NULL
, MS_BIND
, NULL
);
1700 DEBUG("Bind mounted \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1703 /* Fallthrough and try to create a symlink. */
1704 ERROR("Failed to bind mount \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1707 /* Remove the dummy /dev/ptmx file we created above. */
1708 ret
= remove("/dev/ptmx");
1710 SYSERROR("Failed to remove existing \"/dev/ptmx\"");
1714 /* Fallback option: Create symlink /dev/ptmx -> /dev/pts/ptmx. */
1715 ret
= symlink("/dev/pts/ptmx", "/dev/ptmx");
1717 SYSERROR("Failed to create symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
1720 DEBUG("Created symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
1725 static int setup_personality(int persona
)
1729 #if HAVE_SYS_PERSONALITY_H
1733 ret
= personality(persona
);
1735 SYSERROR("Failed to set personality to \"0x%x\"", persona
);
1739 INFO("Set personality to \"0x%x\"", persona
);
1745 static int lxc_setup_dev_console(const struct lxc_rootfs
*rootfs
,
1746 const struct lxc_terminal
*console
)
1749 char path
[MAXPATHLEN
];
1750 char *rootfs_path
= rootfs
->path
? rootfs
->mount
: "";
1752 if (console
->path
&& !strcmp(console
->path
, "none"))
1755 ret
= snprintf(path
, sizeof(path
), "%s/dev/console", rootfs_path
);
1756 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1759 /* When we are asked to setup a console we remove any previous
1760 * /dev/console bind-mounts.
1762 if (file_exists(path
)) {
1763 ret
= lxc_unstack_mountpoint(path
, false);
1765 SYSERROR("Failed to unmount \"%s\"", path
);
1768 DEBUG("Cleared all (%d) mounts from \"%s\"", ret
, path
);
1772 /* For unprivileged containers autodev or automounts will already have
1773 * taken care of creating /dev/console.
1775 ret
= mknod(path
, S_IFREG
| 0000, 0);
1776 if (ret
< 0 && errno
!= EEXIST
) {
1777 SYSERROR("Failed to create console");
1781 ret
= fchmod(console
->slave
, S_IXUSR
| S_IXGRP
| S_IXOTH
);
1783 SYSERROR("Failed to set mode \"0%o\" to \"%s\"",
1784 S_IXUSR
| S_IXGRP
| S_IXOTH
, console
->name
);
1788 ret
= safe_mount(console
->name
, path
, "none", MS_BIND
, 0, rootfs_path
);
1790 ERROR("Failed to mount \"%s\" on \"%s\"", console
->name
, path
);
1794 DEBUG("Mounted pts device \"%s\" onto \"%s\"", console
->name
, path
);
1798 static int lxc_setup_ttydir_console(const struct lxc_rootfs
*rootfs
,
1799 const struct lxc_terminal
*console
,
1803 char path
[MAXPATHLEN
], lxcpath
[MAXPATHLEN
];
1804 char *rootfs_path
= rootfs
->path
? rootfs
->mount
: "";
1806 if (console
->path
&& !strcmp(console
->path
, "none"))
1809 /* create rootfs/dev/<ttydir> directory */
1810 ret
= snprintf(path
, sizeof(path
), "%s/dev/%s", rootfs_path
, ttydir
);
1811 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1814 ret
= mkdir(path
, 0755);
1815 if (ret
&& errno
!= EEXIST
) {
1816 SYSERROR("Failed to create \"%s\"", path
);
1819 DEBUG("Created directory for console and tty devices at \"%s\"", path
);
1821 ret
= snprintf(lxcpath
, sizeof(lxcpath
), "%s/dev/%s/console", rootfs_path
, ttydir
);
1822 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
1825 ret
= mknod(lxcpath
, S_IFREG
| 0000, 0);
1826 if (ret
< 0 && errno
!= EEXIST
) {
1827 SYSERROR("Failed to create \"%s\"", lxcpath
);
1831 ret
= snprintf(path
, sizeof(path
), "%s/dev/console", rootfs_path
);
1832 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1835 if (file_exists(path
)) {
1836 ret
= lxc_unstack_mountpoint(path
, false);
1838 SYSERROR("Failed to unmount \"%s\"", path
);
1841 DEBUG("Cleared all (%d) mounts from \"%s\"", ret
, path
);
1845 ret
= mknod(path
, S_IFREG
| 0000, 0);
1846 if (ret
< 0 && errno
!= EEXIST
) {
1847 SYSERROR("Failed to create console");
1851 ret
= fchmod(console
->slave
, S_IXUSR
| S_IXGRP
| S_IXOTH
);
1853 SYSERROR("Failed to set mode \"0%o\" to \"%s\"",
1854 S_IXUSR
| S_IXGRP
| S_IXOTH
, console
->name
);
1858 /* bind mount console->name to '/dev/<ttydir>/console' */
1859 ret
= safe_mount(console
->name
, lxcpath
, "none", MS_BIND
, 0, rootfs_path
);
1861 ERROR("Failed to mount \"%s\" on \"%s\"", console
->name
, lxcpath
);
1864 DEBUG("Mounted \"%s\" onto \"%s\"", console
->name
, lxcpath
);
1866 /* bind mount '/dev/<ttydir>/console' to '/dev/console' */
1867 ret
= safe_mount(lxcpath
, path
, "none", MS_BIND
, 0, rootfs_path
);
1869 ERROR("Failed to mount \"%s\" on \"%s\"", console
->name
, lxcpath
);
1872 DEBUG("Mounted \"%s\" onto \"%s\"", console
->name
, lxcpath
);
1874 DEBUG("Console has been setup under \"%s\" and mounted to \"%s\"", lxcpath
, path
);
1878 static int lxc_setup_console(const struct lxc_rootfs
*rootfs
,
1879 const struct lxc_terminal
*console
, char *ttydir
)
1883 return lxc_setup_dev_console(rootfs
, console
);
1885 return lxc_setup_ttydir_console(rootfs
, console
, ttydir
);
1888 static void parse_mntopt(char *opt
, unsigned long *flags
, char **data
, size_t size
)
1890 struct mount_opt
*mo
;
1892 /* If opt is found in mount_opt, set or clear flags.
1893 * Otherwise append it to data. */
1895 for (mo
= &mount_opt
[0]; mo
->name
!= NULL
; mo
++) {
1896 if (strncmp(opt
, mo
->name
, strlen(mo
->name
)) == 0) {
1898 *flags
&= ~mo
->flag
;
1906 (void)strlcat(*data
, ",", size
);
1908 (void)strlcat(*data
, opt
, size
);
1911 int parse_mntopts(const char *mntopts
, unsigned long *mntflags
, char **mntdata
)
1922 s
= strdup(mntopts
);
1926 size
= strlen(s
) + 1;
1927 data
= malloc(size
);
1934 lxc_iterate_parts(p
, s
, ",")
1935 parse_mntopt(p
, mntflags
, &data
, size
);
1946 static void parse_propagationopt(char *opt
, unsigned long *flags
)
1948 struct mount_opt
*mo
;
1950 /* If opt is found in propagation_opt, set or clear flags. */
1951 for (mo
= &propagation_opt
[0]; mo
->name
!= NULL
; mo
++) {
1952 if (strncmp(opt
, mo
->name
, strlen(mo
->name
)) != 0)
1956 *flags
&= ~mo
->flag
;
1964 int parse_propagationopts(const char *mntopts
, unsigned long *pflags
)
1971 s
= strdup(mntopts
);
1973 SYSERROR("Failed to allocate memory");
1978 lxc_iterate_parts(p
, s
, ",")
1979 parse_propagationopt(p
, pflags
);
1985 static void null_endofword(char *word
)
1987 while (*word
&& *word
!= ' ' && *word
!= '\t')
1992 /* skip @nfields spaces in @src */
1993 static char *get_field(char *src
, int nfields
)
1998 for (i
= 0; i
< nfields
; i
++) {
1999 while (*p
&& *p
!= ' ' && *p
!= '\t')
2011 static int mount_entry(const char *fsname
, const char *target
,
2012 const char *fstype
, unsigned long mountflags
,
2013 unsigned long pflags
, const char *data
, bool optional
,
2014 bool dev
, bool relative
, const char *rootfs
)
2017 char srcbuf
[MAXPATHLEN
];
2018 const char *srcpath
= fsname
;
2024 ret
= snprintf(srcbuf
, MAXPATHLEN
, "%s/%s", rootfs
? rootfs
: "/", fsname
? fsname
: "");
2025 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2026 ERROR("source path is too long");
2032 ret
= safe_mount(srcpath
, target
, fstype
, mountflags
& ~MS_REMOUNT
, data
,
2036 SYSINFO("Failed to mount \"%s\" on \"%s\" (optional)",
2037 srcpath
? srcpath
: "(null)", target
);
2041 SYSERROR("Failed to mount \"%s\" on \"%s\"",
2042 srcpath
? srcpath
: "(null)", target
);
2046 if ((mountflags
& MS_REMOUNT
) || (mountflags
& MS_BIND
)) {
2047 unsigned long rqd_flags
= 0;
2049 DEBUG("Remounting \"%s\" on \"%s\" to respect bind or remount "
2050 "options", srcpath
? srcpath
: "(none)", target
? target
: "(none)");
2052 if (mountflags
& MS_RDONLY
)
2053 rqd_flags
|= MS_RDONLY
;
2055 if (srcpath
&& statvfs(srcpath
, &sb
) == 0) {
2056 unsigned long required_flags
= rqd_flags
;
2058 if (sb
.f_flag
& MS_NOSUID
)
2059 required_flags
|= MS_NOSUID
;
2061 if (sb
.f_flag
& MS_NODEV
&& !dev
)
2062 required_flags
|= MS_NODEV
;
2064 if (sb
.f_flag
& MS_RDONLY
)
2065 required_flags
|= MS_RDONLY
;
2067 if (sb
.f_flag
& MS_NOEXEC
)
2068 required_flags
|= MS_NOEXEC
;
2070 DEBUG("Flags for \"%s\" were %lu, required extra flags "
2071 "are %lu", srcpath
, sb
.f_flag
, required_flags
);
2073 /* If this was a bind mount request, and required_flags
2074 * does not have any flags which are not already in
2075 * mountflags, then skip the remount.
2077 if (!(mountflags
& MS_REMOUNT
)) {
2078 if (!(required_flags
& ~mountflags
) &&
2080 DEBUG("Mountflags already were %lu, "
2081 "skipping remount", mountflags
);
2086 mountflags
|= required_flags
;
2090 ret
= mount(srcpath
, target
, fstype
, mountflags
| MS_REMOUNT
, data
);
2093 SYSINFO("Failed to mount \"%s\" on \"%s\" (optional)",
2094 srcpath
? srcpath
: "(null)", target
);
2098 SYSERROR("Failed to mount \"%s\" on \"%s\"",
2099 srcpath
? srcpath
: "(null)", target
);
2105 ret
= mount(NULL
, target
, NULL
, pflags
, NULL
);
2108 SYSINFO("Failed to change mount propagation "
2109 "for \"%s\" (optional)", target
);
2112 SYSERROR("Failed to change mount propagation "
2113 "for \"%s\" (optional)", target
);
2117 DEBUG("Changed mount propagation for \"%s\"", target
);
2124 DEBUG("Mounted \"%s\" on \"%s\" with filesystem type \"%s\"",
2125 srcpath
? srcpath
: "(null)", target
, fstype
);
2130 /* Remove "optional", "create=dir", and "create=file" from mntopt */
2131 static void cull_mntent_opt(struct mntent
*mntent
)
2142 for (i
= 0; list
[i
]; i
++) {
2145 p
= strstr(mntent
->mnt_opts
, list
[i
]);
2149 p2
= strchr(p
, ',');
2151 /* no more mntopts, so just chop it here */
2156 memmove(p
, p2
+ 1, strlen(p2
+ 1) + 1);
2160 static int mount_entry_create_dir_file(const struct mntent
*mntent
,
2162 const struct lxc_rootfs
*rootfs
,
2163 const char *lxc_name
, const char *lxc_path
)
2168 if (strncmp(mntent
->mnt_type
, "overlay", 7) == 0) {
2169 ret
= ovl_mkdir(mntent
, rootfs
, lxc_name
, lxc_path
);
2174 if (hasmntopt(mntent
, "create=dir")) {
2175 ret
= mkdir_p(path
, 0755);
2176 if (ret
< 0 && errno
!= EEXIST
) {
2177 SYSERROR("Failed to create directory \"%s\"", path
);
2182 if (!hasmntopt(mntent
, "create=file"))
2185 ret
= access(path
, F_OK
);
2195 ret
= mkdir_p(p2
, 0755);
2197 if (ret
< 0 && errno
!= EEXIST
) {
2198 SYSERROR("Failed to create directory \"%s\"", path
);
2202 ret
= mknod(path
, S_IFREG
| 0000, 0);
2203 if (ret
< 0 && errno
!= EEXIST
)
2209 /* rootfs, lxc_name, and lxc_path can be NULL when the container is created
2210 * without a rootfs. */
2211 static inline int mount_entry_on_generic(struct mntent
*mntent
,
2213 const struct lxc_rootfs
*rootfs
,
2214 const char *lxc_name
,
2215 const char *lxc_path
)
2218 unsigned long mntflags
;
2220 bool dev
, optional
, relative
;
2221 unsigned long pflags
= 0;
2222 char *rootfs_path
= NULL
;
2224 optional
= hasmntopt(mntent
, "optional") != NULL
;
2225 dev
= hasmntopt(mntent
, "dev") != NULL
;
2226 relative
= hasmntopt(mntent
, "relative") != NULL
;
2228 if (rootfs
&& rootfs
->path
)
2229 rootfs_path
= rootfs
->mount
;
2231 ret
= mount_entry_create_dir_file(mntent
, path
, rootfs
, lxc_name
,
2239 cull_mntent_opt(mntent
);
2241 ret
= parse_propagationopts(mntent
->mnt_opts
, &pflags
);
2245 ret
= parse_mntopts(mntent
->mnt_opts
, &mntflags
, &mntdata
);
2249 ret
= mount_entry(mntent
->mnt_fsname
, path
, mntent
->mnt_type
, mntflags
,
2250 pflags
, mntdata
, optional
, dev
, relative
, rootfs_path
);
2256 static inline int mount_entry_on_systemfs(struct mntent
*mntent
)
2259 char path
[MAXPATHLEN
];
2261 /* For containers created without a rootfs all mounts are treated as
2262 * absolute paths starting at / on the host.
2264 if (mntent
->mnt_dir
[0] != '/')
2265 ret
= snprintf(path
, sizeof(path
), "/%s", mntent
->mnt_dir
);
2267 ret
= snprintf(path
, sizeof(path
), "%s", mntent
->mnt_dir
);
2268 if (ret
< 0 || ret
>= sizeof(path
))
2271 return mount_entry_on_generic(mntent
, path
, NULL
, NULL
, NULL
);
2274 static int mount_entry_on_absolute_rootfs(struct mntent
*mntent
,
2275 const struct lxc_rootfs
*rootfs
,
2276 const char *lxc_name
,
2277 const char *lxc_path
)
2281 const char *lxcpath
;
2282 char path
[MAXPATHLEN
];
2285 lxcpath
= lxc_global_config_value("lxc.lxcpath");
2289 /* If rootfs->path is a blockdev path, allow container fstab to use
2290 * <lxcpath>/<name>/rootfs" as the target prefix.
2292 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/rootfs", lxcpath
, lxc_name
);
2293 if (ret
< 0 || ret
>= MAXPATHLEN
)
2296 aux
= strstr(mntent
->mnt_dir
, path
);
2298 offset
= strlen(path
);
2303 aux
= strstr(mntent
->mnt_dir
, rootfs
->path
);
2305 WARN("Ignoring mount point \"%s\"", mntent
->mnt_dir
);
2308 offset
= strlen(rootfs
->path
);
2311 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s", rootfs
->mount
, aux
+ offset
);
2312 if (ret
< 0 || ret
>= MAXPATHLEN
)
2315 return mount_entry_on_generic(mntent
, path
, rootfs
, lxc_name
, lxc_path
);
2318 static int mount_entry_on_relative_rootfs(struct mntent
*mntent
,
2319 const struct lxc_rootfs
*rootfs
,
2320 const char *lxc_name
,
2321 const char *lxc_path
)
2324 char path
[MAXPATHLEN
];
2326 /* relative to root mount point */
2327 ret
= snprintf(path
, sizeof(path
), "%s/%s", rootfs
->mount
, mntent
->mnt_dir
);
2328 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
2331 return mount_entry_on_generic(mntent
, path
, rootfs
, lxc_name
, lxc_path
);
2334 static int mount_file_entries(const struct lxc_conf
*conf
,
2335 const struct lxc_rootfs
*rootfs
, FILE *file
,
2336 const char *lxc_name
, const char *lxc_path
)
2339 struct mntent mntent
;
2342 while (getmntent_r(file
, &mntent
, buf
, sizeof(buf
))) {
2344 ret
= mount_entry_on_systemfs(&mntent
);
2345 else if (mntent
.mnt_dir
[0] != '/')
2346 ret
= mount_entry_on_relative_rootfs(&mntent
, rootfs
,
2347 lxc_name
, lxc_path
);
2349 ret
= mount_entry_on_absolute_rootfs(&mntent
, rootfs
,
2350 lxc_name
, lxc_path
);
2356 INFO("Finished setting up mounts");
2360 static int setup_mount(const struct lxc_conf
*conf
,
2361 const struct lxc_rootfs
*rootfs
, const char *fstab
,
2362 const char *lxc_name
, const char *lxc_path
)
2370 f
= setmntent(fstab
, "r");
2372 SYSERROR("Failed to open \"%s\"", fstab
);
2376 ret
= mount_file_entries(conf
, rootfs
, f
, lxc_name
, lxc_path
);
2378 ERROR("Failed to set up mount entries");
2385 * In order for nested containers to be able to mount /proc and /sys they need
2386 * to see a "pure" proc and sysfs mount points with nothing mounted on top
2388 * For this we provide proc and sysfs in /dev/.lxc/{proc,sys} while using an
2389 * apparmor rule to deny access to them. This is mostly for convenience: The
2390 * container's root user can mount them anyway and thus has access to the two
2391 * file systems. But a non-root user in the container should not be allowed to
2392 * access them as a side effect without explicitly allowing it.
2394 static const char nesting_helpers
[] =
2395 "proc dev/.lxc/proc proc create=dir,optional\n"
2396 "sys dev/.lxc/sys sysfs create=dir,optional\n"
2399 FILE *make_anonymous_mount_file(struct lxc_list
*mount
,
2400 bool include_nesting_helpers
)
2404 struct lxc_list
*iterator
;
2407 fd
= memfd_create(".lxc_mount_file", MFD_CLOEXEC
);
2409 char template[] = P_tmpdir
"/.lxc_mount_file_XXXXXX";
2411 if (errno
!= ENOSYS
)
2414 fd
= lxc_make_tmpfile(template, true);
2416 SYSERROR("Could not create temporary mount file");
2420 TRACE("Created temporary mount file");
2423 SYSERROR("Could not create temporary mount file");
2427 lxc_list_for_each (iterator
, mount
) {
2430 mount_entry
= iterator
->elem
;
2431 len
= strlen(mount_entry
);
2433 ret
= lxc_write_nointr(fd
, mount_entry
, len
);
2437 ret
= lxc_write_nointr(fd
, "\n", 1);
2442 if (include_nesting_helpers
) {
2443 ret
= lxc_write_nointr(fd
, nesting_helpers
,
2444 sizeof(nesting_helpers
) - 1);
2445 if (ret
!= sizeof(nesting_helpers
) - 1)
2449 ret
= lseek(fd
, 0, SEEK_SET
);
2453 return fdopen(fd
, "r+");
2456 SYSERROR("Failed to write mount entry to temporary mount file");
2461 static int setup_mount_entries(const struct lxc_conf
*conf
,
2462 const struct lxc_rootfs
*rootfs
,
2463 struct lxc_list
*mount
, const char *lxc_name
,
2464 const char *lxc_path
)
2469 f
= make_anonymous_mount_file(mount
, conf
->lsm_aa_allow_nesting
);
2473 ret
= mount_file_entries(conf
, rootfs
, f
, lxc_name
, lxc_path
);
2479 static int parse_cap(const char *cap
)
2483 size_t end
= sizeof(caps_opt
) / sizeof(caps_opt
[0]);
2486 if (strcmp(cap
, "none") == 0)
2489 for (i
= 0; i
< end
; i
++) {
2490 if (strcmp(cap
, caps_opt
[i
].name
))
2493 capid
= caps_opt
[i
].value
;
2498 /* Try to see if it's numeric, so the user may specify
2499 * capabilities that the running kernel knows about but we
2503 capid
= strtol(cap
, &ptr
, 10);
2504 if (!ptr
|| *ptr
!= '\0' || errno
!= 0)
2505 /* not a valid number */
2507 else if (capid
> lxc_caps_last_cap())
2508 /* we have a number but it's not a valid
2516 int in_caplist(int cap
, struct lxc_list
*caps
)
2519 struct lxc_list
*iterator
;
2521 lxc_list_for_each (iterator
, caps
) {
2522 capid
= parse_cap(iterator
->elem
);
2530 static int setup_caps(struct lxc_list
*caps
)
2534 struct lxc_list
*iterator
;
2536 lxc_list_for_each (iterator
, caps
) {
2539 drop_entry
= iterator
->elem
;
2541 capid
= parse_cap(drop_entry
);
2543 ERROR("unknown capability %s", drop_entry
);
2547 ret
= prctl(PR_CAPBSET_DROP
, prctl_arg(capid
), prctl_arg(0),
2548 prctl_arg(0), prctl_arg(0));
2550 SYSERROR("Failed to remove %s capability", drop_entry
);
2553 DEBUG("Dropped %s (%d) capability", drop_entry
, capid
);
2556 DEBUG("Capabilities have been setup");
2560 static int dropcaps_except(struct lxc_list
*caps
)
2562 int i
, capid
, numcaps
;
2564 struct lxc_list
*iterator
;
2566 numcaps
= lxc_caps_last_cap() + 1;
2567 if (numcaps
<= 0 || numcaps
> 200)
2569 TRACE("Found %d capabilities", numcaps
);
2571 /* caplist[i] is 1 if we keep capability i */
2572 int *caplist
= alloca(numcaps
* sizeof(int));
2573 memset(caplist
, 0, numcaps
* sizeof(int));
2575 lxc_list_for_each (iterator
, caps
) {
2576 keep_entry
= iterator
->elem
;
2578 capid
= parse_cap(keep_entry
);
2583 ERROR("Unknown capability %s", keep_entry
);
2587 DEBUG("Keep capability %s (%d)", keep_entry
, capid
);
2591 for (i
= 0; i
< numcaps
; i
++) {
2597 ret
= prctl(PR_CAPBSET_DROP
, prctl_arg(i
), prctl_arg(0),
2598 prctl_arg(0), prctl_arg(0));
2600 SYSERROR("Failed to remove capability %d", i
);
2605 DEBUG("Capabilities have been setup");
2609 static int parse_resource(const char *res
)
2615 for (i
= 0; i
< sizeof(limit_opt
) / sizeof(limit_opt
[0]); ++i
)
2616 if (strcmp(res
, limit_opt
[i
].name
) == 0)
2617 return limit_opt
[i
].value
;
2619 /* Try to see if it's numeric, so the user may specify
2620 * resources that the running kernel knows about but
2623 ret
= lxc_safe_int(res
, &resid
);
2630 int setup_resource_limits(struct lxc_list
*limits
, pid_t pid
)
2633 struct lxc_list
*it
;
2634 struct lxc_limit
*lim
;
2636 lxc_list_for_each (it
, limits
) {
2639 resid
= parse_resource(lim
->resource
);
2641 ERROR("Unknown resource %s", lim
->resource
);
2645 #if HAVE_PRLIMIT || HAVE_PRLIMIT64
2646 if (prlimit(pid
, resid
, &lim
->limit
, NULL
) != 0) {
2647 SYSERROR("Failed to set limit %s", lim
->resource
);
2651 ERROR("Cannot set limit %s as prlimit is missing", lim
->resource
);
2659 int setup_sysctl_parameters(struct lxc_list
*sysctls
)
2661 struct lxc_list
*it
;
2662 struct lxc_sysctl
*elem
;
2665 char filename
[MAXPATHLEN
] = {0};
2667 lxc_list_for_each (it
, sysctls
) {
2669 tmp
= lxc_string_replace(".", "/", elem
->key
);
2671 ERROR("Failed to replace key %s", elem
->key
);
2675 ret
= snprintf(filename
, sizeof(filename
), "/proc/sys/%s", tmp
);
2677 if (ret
< 0 || (size_t)ret
>= sizeof(filename
)) {
2678 ERROR("Error setting up sysctl parameters path");
2682 ret
= lxc_write_to_file(filename
, elem
->value
,
2683 strlen(elem
->value
), false, 0666);
2685 ERROR("Failed to setup sysctl parameters %s to %s",
2686 elem
->key
, elem
->value
);
2694 int setup_proc_filesystem(struct lxc_list
*procs
, pid_t pid
)
2696 struct lxc_list
*it
;
2697 struct lxc_proc
*elem
;
2700 char filename
[MAXPATHLEN
] = {0};
2702 lxc_list_for_each (it
, procs
) {
2704 tmp
= lxc_string_replace(".", "/", elem
->filename
);
2706 ERROR("Failed to replace key %s", elem
->filename
);
2710 ret
= snprintf(filename
, sizeof(filename
), "/proc/%d/%s", pid
, tmp
);
2712 if (ret
< 0 || (size_t)ret
>= sizeof(filename
)) {
2713 ERROR("Error setting up proc filesystem path");
2717 ret
= lxc_write_to_file(filename
, elem
->value
,
2718 strlen(elem
->value
), false, 0666);
2720 ERROR("Failed to setup proc filesystem %s to %s",
2721 elem
->filename
, elem
->value
);
2729 static char *default_rootfs_mount
= LXCROOTFSMOUNT
;
2731 struct lxc_conf
*lxc_conf_init(void)
2734 struct lxc_conf
*new;
2736 new = malloc(sizeof(*new));
2739 memset(new, 0, sizeof(*new));
2741 new->loglevel
= LXC_LOG_LEVEL_NOTSET
;
2742 new->personality
= -1;
2744 new->console
.buffer_size
= 0;
2745 new->console
.log_path
= NULL
;
2746 new->console
.log_fd
= -1;
2747 new->console
.log_size
= 0;
2748 new->console
.path
= NULL
;
2749 new->console
.peer
= -1;
2750 new->console
.proxy
.busy
= -1;
2751 new->console
.proxy
.master
= -1;
2752 new->console
.proxy
.slave
= -1;
2753 new->console
.master
= -1;
2754 new->console
.slave
= -1;
2755 new->console
.name
[0] = '\0';
2756 memset(&new->console
.ringbuf
, 0, sizeof(struct lxc_ringbuf
));
2757 new->maincmd_fd
= -1;
2758 new->monitor_signal_pdeath
= SIGKILL
;
2760 new->rootfs
.mount
= strdup(default_rootfs_mount
);
2761 if (!new->rootfs
.mount
) {
2765 new->rootfs
.managed
= true;
2767 lxc_list_init(&new->cgroup
);
2768 lxc_list_init(&new->cgroup2
);
2769 lxc_list_init(&new->network
);
2770 lxc_list_init(&new->mount_list
);
2771 lxc_list_init(&new->caps
);
2772 lxc_list_init(&new->keepcaps
);
2773 lxc_list_init(&new->id_map
);
2774 new->root_nsuid_map
= NULL
;
2775 new->root_nsgid_map
= NULL
;
2776 lxc_list_init(&new->includes
);
2777 lxc_list_init(&new->aliens
);
2778 lxc_list_init(&new->environment
);
2779 lxc_list_init(&new->limits
);
2780 lxc_list_init(&new->sysctls
);
2781 lxc_list_init(&new->procs
);
2782 new->hooks_version
= 0;
2783 for (i
= 0; i
< NUM_LXC_HOOKS
; i
++)
2784 lxc_list_init(&new->hooks
[i
]);
2785 lxc_list_init(&new->groups
);
2786 lxc_list_init(&new->state_clients
);
2787 new->lsm_aa_profile
= NULL
;
2788 lxc_list_init(&new->lsm_aa_raw
);
2789 new->lsm_se_context
= NULL
;
2790 new->tmp_umount_proc
= false;
2791 new->tmp_umount_proc
= 0;
2792 new->shmount
.path_host
= NULL
;
2793 new->shmount
.path_cont
= NULL
;
2795 /* if running in a new user namespace, init and COMMAND
2796 * default to running as UID/GID 0 when using lxc-execute */
2799 memset(&new->cgroup_meta
, 0, sizeof(struct lxc_cgroup
));
2800 memset(&new->ns_share
, 0, sizeof(char *) * LXC_NS_MAX
);
2805 int write_id_mapping(enum idtype idtype
, pid_t pid
, const char *buf
,
2809 char path
[MAXPATHLEN
];
2811 if (geteuid() != 0 && idtype
== ID_TYPE_GID
) {
2814 ret
= snprintf(path
, MAXPATHLEN
, "/proc/%d/setgroups", pid
);
2815 if (ret
< 0 || ret
>= MAXPATHLEN
)
2818 fd
= open(path
, O_WRONLY
);
2819 if (fd
< 0 && errno
!= ENOENT
) {
2820 SYSERROR("Failed to open \"%s\"", path
);
2825 buflen
= sizeof("deny\n") - 1;
2827 ret
= lxc_write_nointr(fd
, "deny\n", buflen
);
2829 if (ret
!= buflen
) {
2830 SYSERROR("Failed to write \"deny\" to "
2831 "\"/proc/%d/setgroups\"", pid
);
2834 TRACE("Wrote \"deny\" to \"/proc/%d/setgroups\"", pid
);
2838 ret
= snprintf(path
, MAXPATHLEN
, "/proc/%d/%cid_map", pid
,
2839 idtype
== ID_TYPE_UID
? 'u' : 'g');
2840 if (ret
< 0 || ret
>= MAXPATHLEN
)
2843 fd
= open(path
, O_WRONLY
);
2845 SYSERROR("Failed to open \"%s\"", path
);
2850 ret
= lxc_write_nointr(fd
, buf
, buf_size
);
2852 if (ret
!= buf_size
) {
2853 SYSERROR("Failed to write %cid mapping to \"%s\"",
2854 idtype
== ID_TYPE_UID
? 'u' : 'g', path
);
2861 /* Check whether a binary exist and has either CAP_SETUID, CAP_SETGID or both.
2863 * @return 1 if functional binary was found
2864 * @return 0 if binary exists but is lacking privilege
2865 * @return -ENOENT if binary does not exist
2866 * @return -EINVAL if cap to check is neither CAP_SETUID nor CAP_SETGID
2868 static int idmaptool_on_path_and_privileged(const char *binary
, cap_value_t cap
)
2875 if (cap
!= CAP_SETUID
&& cap
!= CAP_SETGID
)
2878 path
= on_path(binary
, NULL
);
2882 ret
= stat(path
, &st
);
2888 /* Check if the binary is setuid. */
2889 if (st
.st_mode
& S_ISUID
) {
2890 DEBUG("The binary \"%s\" does have the setuid bit set", path
);
2895 #if HAVE_LIBCAP && LIBCAP_SUPPORTS_FILE_CAPABILITIES
2896 /* Check if it has the CAP_SETUID capability. */
2897 if ((cap
& CAP_SETUID
) &&
2898 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_EFFECTIVE
) &&
2899 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_PERMITTED
)) {
2900 DEBUG("The binary \"%s\" has CAP_SETUID in its CAP_EFFECTIVE "
2901 "and CAP_PERMITTED sets", path
);
2906 /* Check if it has the CAP_SETGID capability. */
2907 if ((cap
& CAP_SETGID
) &&
2908 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_EFFECTIVE
) &&
2909 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_PERMITTED
)) {
2910 DEBUG("The binary \"%s\" has CAP_SETGID in its CAP_EFFECTIVE "
2911 "and CAP_PERMITTED sets", path
);
2916 /* If we cannot check for file capabilities we need to give the benefit
2917 * of the doubt. Otherwise we might fail even though all the necessary
2918 * file capabilities are set.
2920 DEBUG("Cannot check for file capabilites as full capability support is "
2921 "missing. Manual intervention needed");
2930 int lxc_map_ids_exec_wrapper(void *args
)
2932 execl("/bin/sh", "sh", "-c", (char *)args
, (char *)NULL
);
2936 int lxc_map_ids(struct lxc_list
*idmap
, pid_t pid
)
2941 char cmd_output
[MAXPATHLEN
];
2943 struct lxc_list
*iterator
;
2945 /* strlen("new@idmap") = 9
2949 * INTTYPE_TO_STRLEN(uint32_t)
2953 * We add some additional space to make sure that we really have
2954 * LXC_IDMAPLEN bytes available for our the {g,u]id mapping.
2956 int ret
= 0, gidmap
= 0, uidmap
= 0;
2957 char mapbuf
[9 + 1 + INTTYPE_TO_STRLEN(uint32_t) + 1 + LXC_IDMAPLEN
] = {0};
2958 bool had_entry
= false, use_shadow
= false;
2959 int hostuid
, hostgid
;
2961 hostuid
= geteuid();
2962 hostgid
= getegid();
2964 /* If new{g,u}idmap exists, that is, if shadow is handing out subuid
2965 * ranges, then insist that root also reserve ranges in subuid. This
2966 * will protected it by preventing another user from being handed the
2969 uidmap
= idmaptool_on_path_and_privileged("newuidmap", CAP_SETUID
);
2970 if (uidmap
== -ENOENT
)
2971 WARN("newuidmap binary is missing");
2973 WARN("newuidmap is lacking necessary privileges");
2975 gidmap
= idmaptool_on_path_and_privileged("newgidmap", CAP_SETGID
);
2976 if (gidmap
== -ENOENT
)
2977 WARN("newgidmap binary is missing");
2979 WARN("newgidmap is lacking necessary privileges");
2981 if (uidmap
> 0 && gidmap
> 0) {
2982 DEBUG("Functional newuidmap and newgidmap binary found");
2985 /* In case unprivileged users run application containers via
2986 * execute() or a start*() there are valid cases where they may
2987 * only want to map their own {g,u}id. Let's not block them from
2988 * doing so by requiring geteuid() == 0.
2990 DEBUG("No newuidmap and newgidmap binary found. Trying to "
2991 "write directly with euid %d", hostuid
);
2994 /* Check if we really need to use newuidmap and newgidmap.
2995 * If the user is only remapping his own {g,u}id, we don't need it.
2997 if (use_shadow
&& lxc_list_len(idmap
) == 2) {
2999 lxc_list_for_each(iterator
, idmap
) {
3000 map
= iterator
->elem
;
3001 if (map
->idtype
== ID_TYPE_UID
&& map
->range
== 1 &&
3002 map
->nsid
== hostuid
&& map
->hostid
== hostuid
)
3004 if (map
->idtype
== ID_TYPE_GID
&& map
->range
== 1 &&
3005 map
->nsid
== hostgid
&& map
->hostid
== hostgid
)
3012 for (type
= ID_TYPE_UID
, u_or_g
= 'u'; type
<= ID_TYPE_GID
;
3013 type
++, u_or_g
= 'g') {
3017 pos
+= sprintf(mapbuf
, "new%cidmap %d", u_or_g
, pid
);
3019 lxc_list_for_each(iterator
, idmap
) {
3020 map
= iterator
->elem
;
3021 if (map
->idtype
!= type
)
3026 left
= LXC_IDMAPLEN
- (pos
- mapbuf
);
3027 fill
= snprintf(pos
, left
, "%s%lu %lu %lu%s",
3028 use_shadow
? " " : "", map
->nsid
,
3029 map
->hostid
, map
->range
,
3030 use_shadow
? "" : "\n");
3031 if (fill
<= 0 || fill
>= left
) {
3032 /* The kernel only takes <= 4k for writes to
3033 * /proc/<pid>/{g,u}id_map
3035 SYSERROR("Too many %cid mappings defined", u_or_g
);
3044 /* Try to catch the ouput of new{g,u}idmap to make debugging
3048 ret
= run_command(cmd_output
, sizeof(cmd_output
),
3049 lxc_map_ids_exec_wrapper
,
3052 ERROR("new%cidmap failed to write mapping \"%s\": %s",
3053 u_or_g
, cmd_output
, mapbuf
);
3056 TRACE("new%cidmap wrote mapping \"%s\"", u_or_g
, mapbuf
);
3058 ret
= write_id_mapping(type
, pid
, mapbuf
, pos
- mapbuf
);
3060 ERROR("Failed to write mapping: %s", mapbuf
);
3063 TRACE("Wrote mapping \"%s\"", mapbuf
);
3066 memset(mapbuf
, 0, sizeof(mapbuf
));
3072 /* Return the host uid/gid to which the container root is mapped in val.
3073 * Return true if id was found, false otherwise.
3075 bool get_mapped_rootid(struct lxc_conf
*conf
, enum idtype idtype
,
3080 struct lxc_list
*it
;
3082 if (idtype
== ID_TYPE_UID
)
3083 nsid
= (conf
->root_nsuid_map
!= NULL
) ? 0 : conf
->init_uid
;
3085 nsid
= (conf
->root_nsgid_map
!= NULL
) ? 0 : conf
->init_gid
;
3087 lxc_list_for_each (it
, &conf
->id_map
) {
3089 if (map
->idtype
!= idtype
)
3091 if (map
->nsid
!= nsid
)
3100 int mapped_hostid(unsigned id
, struct lxc_conf
*conf
, enum idtype idtype
)
3103 struct lxc_list
*it
;
3105 lxc_list_for_each (it
, &conf
->id_map
) {
3107 if (map
->idtype
!= idtype
)
3110 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
)
3111 return (id
- map
->hostid
) + map
->nsid
;
3117 int find_unmapped_nsid(struct lxc_conf
*conf
, enum idtype idtype
)
3120 struct lxc_list
*it
;
3121 unsigned int freeid
= 0;
3124 lxc_list_for_each (it
, &conf
->id_map
) {
3126 if (map
->idtype
!= idtype
)
3129 if (freeid
>= map
->nsid
&& freeid
< map
->nsid
+ map
->range
) {
3130 freeid
= map
->nsid
+ map
->range
;
3138 int chown_mapped_root_exec_wrapper(void *args
)
3140 execvp("lxc-usernsexec", args
);
3144 /* chown_mapped_root: for an unprivileged user with uid/gid X to
3145 * chown a dir to subuid/subgid Y, he needs to run chown as root
3146 * in a userns where nsid 0 is mapped to hostuid/hostgid Y, and
3147 * nsid Y is mapped to hostuid/hostgid X. That way, the container
3148 * root is privileged with respect to hostuid/hostgid X, allowing
3149 * him to do the chown.
3151 int chown_mapped_root(const char *path
, struct lxc_conf
*conf
)
3153 uid_t rootuid
, rootgid
;
3155 int hostuid
, hostgid
, ret
;
3157 char map1
[100], map2
[100], map3
[100], map4
[100], map5
[100];
3159 const char *args1
[] = {"lxc-usernsexec",
3164 "--", "chown", ugid
, path
,
3166 const char *args2
[] = {"lxc-usernsexec",
3172 "--", "chown", ugid
, path
,
3174 char cmd_output
[MAXPATHLEN
];
3176 hostuid
= geteuid();
3177 hostgid
= getegid();
3179 if (!get_mapped_rootid(conf
, ID_TYPE_UID
, &val
)) {
3180 ERROR("No uid mapping for container root");
3183 rootuid
= (uid_t
)val
;
3185 if (!get_mapped_rootid(conf
, ID_TYPE_GID
, &val
)) {
3186 ERROR("No gid mapping for container root");
3189 rootgid
= (gid_t
)val
;
3192 if (chown(path
, rootuid
, rootgid
) < 0) {
3193 ERROR("Error chowning %s", path
);
3200 if (rootuid
== hostuid
) {
3202 INFO("Container root is our uid; no need to chown");
3206 /* save the current gid of "path" */
3207 if (stat(path
, &sb
) < 0) {
3208 ERROR("Error stat %s", path
);
3212 /* Update the path argument in case this was overlayfs. */
3213 args1
[sizeof(args1
) / sizeof(args1
[0]) - 2] = path
;
3214 args2
[sizeof(args2
) / sizeof(args2
[0]) - 2] = path
;
3217 * A file has to be group-owned by a gid mapped into the
3218 * container, or the container won't be privileged over it.
3220 DEBUG("trying to chown \"%s\" to %d", path
, hostgid
);
3221 if (sb
.st_uid
== hostuid
&&
3222 mapped_hostid(sb
.st_gid
, conf
, ID_TYPE_GID
) < 0 &&
3223 chown(path
, -1, hostgid
) < 0) {
3224 ERROR("Failed chgrping %s", path
);
3228 /* "u:0:rootuid:1" */
3229 ret
= snprintf(map1
, 100, "u:0:%d:1", rootuid
);
3230 if (ret
< 0 || ret
>= 100) {
3231 ERROR("Error uid printing map string");
3235 /* "u:hostuid:hostuid:1" */
3236 ret
= snprintf(map2
, 100, "u:%d:%d:1", hostuid
, hostuid
);
3237 if (ret
< 0 || ret
>= 100) {
3238 ERROR("Error uid printing map string");
3242 /* "g:0:rootgid:1" */
3243 ret
= snprintf(map3
, 100, "g:0:%d:1", rootgid
);
3244 if (ret
< 0 || ret
>= 100) {
3245 ERROR("Error gid printing map string");
3249 /* "g:pathgid:rootgid+pathgid:1" */
3250 ret
= snprintf(map4
, 100, "g:%d:%d:1", (gid_t
)sb
.st_gid
,
3251 rootgid
+ (gid_t
)sb
.st_gid
);
3252 if (ret
< 0 || ret
>= 100) {
3253 ERROR("Error gid printing map string");
3257 /* "g:hostgid:hostgid:1" */
3258 ret
= snprintf(map5
, 100, "g:%d:%d:1", hostgid
, hostgid
);
3259 if (ret
< 0 || ret
>= 100) {
3260 ERROR("Error gid printing map string");
3264 /* "0:pathgid" (chown) */
3265 ret
= snprintf(ugid
, 100, "0:%d", (gid_t
)sb
.st_gid
);
3266 if (ret
< 0 || ret
>= 100) {
3267 ERROR("Error owner printing format string for chown");
3271 if (hostgid
== sb
.st_gid
)
3272 ret
= run_command(cmd_output
, sizeof(cmd_output
),
3273 chown_mapped_root_exec_wrapper
,
3276 ret
= run_command(cmd_output
, sizeof(cmd_output
),
3277 chown_mapped_root_exec_wrapper
,
3280 ERROR("lxc-usernsexec failed: %s", cmd_output
);
3285 /* NOTE: Must not be called from inside the container namespace! */
3286 int lxc_create_tmp_proc_mount(struct lxc_conf
*conf
)
3290 mounted
= lxc_mount_proc_if_needed(conf
->rootfs
.path
? conf
->rootfs
.mount
: "");
3291 if (mounted
== -1) {
3292 SYSERROR("Failed to mount proc in the container");
3293 /* continue only if there is no rootfs */
3294 if (conf
->rootfs
.path
)
3296 } else if (mounted
== 1) {
3297 conf
->tmp_umount_proc
= true;
3303 void tmp_proc_unmount(struct lxc_conf
*lxc_conf
)
3305 if (!lxc_conf
->tmp_umount_proc
)
3308 (void)umount2("/proc", MNT_DETACH
);
3309 lxc_conf
->tmp_umount_proc
= false;
3312 /* Walk /proc/mounts and change any shared entries to slave. */
3313 void remount_all_slave(void)
3315 int memfd
, mntinfo_fd
, ret
;
3321 mntinfo_fd
= open("/proc/self/mountinfo", O_RDONLY
| O_CLOEXEC
);
3322 if (mntinfo_fd
< 0) {
3323 SYSERROR("Failed to open \"/proc/self/mountinfo\"");
3327 memfd
= memfd_create(".lxc_mountinfo", MFD_CLOEXEC
);
3329 char template[] = P_tmpdir
"/.lxc_mountinfo_XXXXXX";
3331 if (errno
!= ENOSYS
) {
3332 SYSERROR("Failed to create temporary in-memory file");
3337 memfd
= lxc_make_tmpfile(template, true);
3340 WARN("Failed to create temporary file");
3345 #define __LXC_SENDFILE_MAX 0x7ffff000 /* maximum number of bytes sendfile can handle */
3347 copied
= sendfile(memfd
, mntinfo_fd
, NULL
, __LXC_SENDFILE_MAX
);
3352 SYSERROR("Failed to copy \"/proc/self/mountinfo\"");
3359 /* After a successful fdopen() memfd will be closed when calling
3360 * fclose(f). Calling close(memfd) afterwards is undefined.
3362 ret
= lseek(memfd
, 0, SEEK_SET
);
3364 SYSERROR("Failed to reset file descriptor offset");
3369 f
= fdopen(memfd
, "r");
3371 SYSERROR("Failed to open copy of \"/proc/self/mountinfo\" to mark "
3372 "all shared. Continuing");
3377 while (getline(&line
, &len
, f
) != -1) {
3379 char *opts
, *target
;
3381 target
= get_field(line
, 4);
3385 opts
= get_field(target
, 2);
3389 null_endofword(opts
);
3390 if (!strstr(opts
, "shared"))
3393 null_endofword(target
);
3394 ret
= mount(NULL
, target
, NULL
, MS_SLAVE
, NULL
);
3396 SYSERROR("Failed to make \"%s\" MS_SLAVE", target
);
3397 ERROR("Continuing...");
3400 TRACE("Remounted \"%s\" as MS_SLAVE", target
);
3404 TRACE("Remounted all mount table entries as MS_SLAVE");
3407 static int lxc_execute_bind_init(struct lxc_handler
*handler
)
3411 char path
[PATH_MAX
], destpath
[PATH_MAX
];
3412 struct lxc_conf
*conf
= handler
->conf
;
3414 /* If init exists in the container, don't bind mount a static one */
3415 p
= choose_init(conf
->rootfs
.mount
);
3419 p
= strdup(old
+ strlen(conf
->rootfs
.mount
));
3424 INFO("Found existing init at \"%s\"", p
);
3428 ret
= snprintf(path
, PATH_MAX
, SBINDIR
"/init.lxc.static");
3429 if (ret
< 0 || ret
>= PATH_MAX
)
3432 if (!file_exists(path
)) {
3433 ERROR("The file \"%s\" does not exist on host", path
);
3437 ret
= snprintf(destpath
, PATH_MAX
, "%s" P_tmpdir
"%s", conf
->rootfs
.mount
, "/.lxc-init");
3438 if (ret
< 0 || ret
>= PATH_MAX
)
3441 if (!file_exists(destpath
)) {
3442 ret
= mknod(destpath
, S_IFREG
| 0000, 0);
3443 if (ret
< 0 && errno
!= EEXIST
) {
3444 SYSERROR("Failed to create dummy \"%s\" file as bind mount target", destpath
);
3449 ret
= safe_mount(path
, destpath
, "none", MS_BIND
, NULL
, conf
->rootfs
.mount
);
3451 SYSERROR("Failed to bind mount lxc.init.static into container");
3455 p
= strdup(destpath
+ strlen(conf
->rootfs
.mount
));
3459 INFO("Bind mounted lxc.init.static into container at \"%s\"", path
);
3461 ((struct execute_args
*)handler
->data
)->init_fd
= -1;
3462 ((struct execute_args
*)handler
->data
)->init_path
= p
;
3466 /* This does the work of remounting / if it is shared, calling the container
3467 * pre-mount hooks, and mounting the rootfs.
3469 int lxc_setup_rootfs_prepare_root(struct lxc_conf
*conf
, const char *name
,
3470 const char *lxcpath
)
3474 if (conf
->rootfs_setup
) {
3475 const char *path
= conf
->rootfs
.mount
;
3477 /* The rootfs was set up in another namespace. bind-mount it to
3478 * give us a mount in our own ns so we can pivot_root to it
3480 ret
= mount(path
, path
, "rootfs", MS_BIND
, NULL
);
3482 ERROR("Failed to bind mount container / onto itself");
3486 TRACE("Bind mounted container / onto itself");
3490 remount_all_slave();
3492 ret
= run_lxc_hooks(name
, "pre-mount", conf
, NULL
);
3494 ERROR("Failed to run pre-mount hooks");
3498 ret
= lxc_mount_rootfs(conf
);
3500 ERROR("Failed to setup rootfs for");
3504 conf
->rootfs_setup
= true;
3508 static bool verify_start_hooks(struct lxc_conf
*conf
)
3510 char path
[MAXPATHLEN
];
3511 struct lxc_list
*it
;
3513 lxc_list_for_each (it
, &conf
->hooks
[LXCHOOK_START
]) {
3516 char *hookname
= it
->elem
;
3518 ret
= snprintf(path
, MAXPATHLEN
, "%s%s",
3519 conf
->rootfs
.path
? conf
->rootfs
.mount
: "",
3521 if (ret
< 0 || ret
>= MAXPATHLEN
)
3524 ret
= stat(path
, &st
);
3526 SYSERROR("Start hook %s not found in container",
3537 static bool execveat_supported(void)
3539 #ifdef __NR_execveat
3541 * We use the syscall here, because it was introduced in kernel 3.19,
3542 * while glibc got support for using the syscall much later, in 2.27.
3543 * We don't want to use glibc because it falls back to /proc, and the
3544 * container may not have /proc mounted depending on its configuration.
3546 syscall(__NR_execveat
, -1, "", NULL
, NULL
, AT_EMPTY_PATH
);
3547 if (errno
== ENOSYS
)
3556 int lxc_setup(struct lxc_handler
*handler
)
3559 const char *lxcpath
= handler
->lxcpath
, *name
= handler
->name
;
3560 struct lxc_conf
*lxc_conf
= handler
->conf
;
3562 ret
= lxc_setup_rootfs_prepare_root(lxc_conf
, name
, lxcpath
);
3564 ERROR("Failed to setup rootfs");
3568 if (handler
->nsfd
[LXC_NS_UTS
] == -1) {
3569 ret
= setup_utsname(lxc_conf
->utsname
);
3571 ERROR("Failed to setup the utsname %s", name
);
3576 ret
= lxc_setup_network_in_child_namespaces(lxc_conf
, &lxc_conf
->network
);
3578 ERROR("Failed to setup network");
3582 ret
= lxc_network_send_name_and_ifindex_to_parent(handler
);
3584 ERROR("Failed to send network device names and ifindices to parent");
3588 if (lxc_conf
->autodev
> 0) {
3589 ret
= mount_autodev(name
, &lxc_conf
->rootfs
, lxcpath
);
3591 ERROR("Failed to mount \"/dev\"");
3596 /* Do automatic mounts (mainly /proc and /sys), but exclude those that
3597 * need to wait until other stuff has finished.
3599 ret
= lxc_mount_auto_mounts(lxc_conf
, lxc_conf
->auto_mounts
& ~LXC_AUTO_CGROUP_MASK
, handler
);
3601 ERROR("Failed to setup first automatic mounts");
3605 ret
= setup_mount(lxc_conf
, &lxc_conf
->rootfs
, lxc_conf
->fstab
, name
, lxcpath
);
3607 ERROR("Failed to setup mounts");
3611 /* Make sure any start hooks are in the container */
3612 if (!verify_start_hooks(lxc_conf
))
3615 if (lxc_conf
->is_execute
) {
3616 if (execveat_supported()) {
3618 char path
[PATH_MAX
];
3620 ret
= snprintf(path
, PATH_MAX
, SBINDIR
"/init.lxc.static");
3621 if (ret
< 0 || ret
>= PATH_MAX
) {
3622 ERROR("Path to init.lxc.static too long");
3626 fd
= open(path
, O_PATH
| O_CLOEXEC
);
3628 SYSERROR("Unable to open lxc.init.static");
3632 ((struct execute_args
*)handler
->data
)->init_fd
= fd
;
3633 ((struct execute_args
*)handler
->data
)->init_path
= NULL
;
3635 ret
= lxc_execute_bind_init(handler
);
3637 ERROR("Failed to bind-mount the lxc init system");
3643 /* Now mount only cgroups, if wanted. Before, /sys could not have been
3644 * mounted. It is guaranteed to be mounted now either through
3645 * automatically or via fstab entries.
3647 ret
= lxc_mount_auto_mounts(lxc_conf
, lxc_conf
->auto_mounts
& LXC_AUTO_CGROUP_MASK
, handler
);
3649 ERROR("Failed to setup remaining automatic mounts");
3653 ret
= run_lxc_hooks(name
, "mount", lxc_conf
, NULL
);
3655 ERROR("Failed to run mount hooks");
3659 if (lxc_conf
->autodev
> 0) {
3660 ret
= run_lxc_hooks(name
, "autodev", lxc_conf
, NULL
);
3662 ERROR("Failed to run autodev hooks");
3666 ret
= lxc_fill_autodev(&lxc_conf
->rootfs
);
3668 ERROR("Failed to populate \"/dev\"");
3673 if (!lxc_list_empty(&lxc_conf
->mount_list
)) {
3674 ret
= setup_mount_entries(lxc_conf
, &lxc_conf
->rootfs
,
3675 &lxc_conf
->mount_list
, name
, lxcpath
);
3677 ERROR("Failed to setup mount entries");
3682 ret
= lxc_setup_console(&lxc_conf
->rootfs
, &lxc_conf
->console
,
3683 lxc_conf
->ttys
.dir
);
3685 ERROR("Failed to setup console");
3689 ret
= lxc_setup_dev_symlinks(&lxc_conf
->rootfs
);
3691 ERROR("Failed to setup \"/dev\" symlinks");
3695 ret
= lxc_create_tmp_proc_mount(lxc_conf
);
3697 ERROR("Failed to \"/proc\" LSMs");
3701 ret
= lxc_setup_rootfs_switch_root(&lxc_conf
->rootfs
);
3703 ERROR("Failed to pivot root into rootfs");
3707 ret
= lxc_setup_devpts(lxc_conf
);
3709 ERROR("Failed to setup new devpts instance");
3713 ret
= lxc_create_ttys(handler
);
3717 ret
= setup_personality(lxc_conf
->personality
);
3719 ERROR("Failed to set personality");
3723 /* Set sysctl value to a path under /proc/sys as determined from the
3724 * key. For e.g. net.ipv4.ip_forward translated to
3725 * /proc/sys/net/ipv4/ip_forward.
3727 if (!lxc_list_empty(&lxc_conf
->sysctls
)) {
3728 ret
= setup_sysctl_parameters(&lxc_conf
->sysctls
);
3730 ERROR("Failed to setup sysctl parameters");
3735 if (!lxc_list_empty(&lxc_conf
->keepcaps
)) {
3736 if (!lxc_list_empty(&lxc_conf
->caps
)) {
3737 ERROR("Container requests lxc.cap.drop and "
3738 "lxc.cap.keep: either use lxc.cap.drop or "
3739 "lxc.cap.keep, not both");
3743 if (dropcaps_except(&lxc_conf
->keepcaps
)) {
3744 ERROR("Failed to keep capabilities");
3747 } else if (setup_caps(&lxc_conf
->caps
)) {
3748 ERROR("Failed to drop capabilities");
3752 NOTICE("The container \"%s\" is set up", name
);
3757 int run_lxc_hooks(const char *name
, char *hookname
, struct lxc_conf
*conf
,
3760 struct lxc_list
*it
;
3763 if (strcmp(hookname
, "pre-start") == 0)
3764 which
= LXCHOOK_PRESTART
;
3765 else if (strcmp(hookname
, "start-host") == 0)
3766 which
= LXCHOOK_START_HOST
;
3767 else if (strcmp(hookname
, "pre-mount") == 0)
3768 which
= LXCHOOK_PREMOUNT
;
3769 else if (strcmp(hookname
, "mount") == 0)
3770 which
= LXCHOOK_MOUNT
;
3771 else if (strcmp(hookname
, "autodev") == 0)
3772 which
= LXCHOOK_AUTODEV
;
3773 else if (strcmp(hookname
, "start") == 0)
3774 which
= LXCHOOK_START
;
3775 else if (strcmp(hookname
, "stop") == 0)
3776 which
= LXCHOOK_STOP
;
3777 else if (strcmp(hookname
, "post-stop") == 0)
3778 which
= LXCHOOK_POSTSTOP
;
3779 else if (strcmp(hookname
, "clone") == 0)
3780 which
= LXCHOOK_CLONE
;
3781 else if (strcmp(hookname
, "destroy") == 0)
3782 which
= LXCHOOK_DESTROY
;
3786 lxc_list_for_each (it
, &conf
->hooks
[which
]) {
3788 char *hook
= it
->elem
;
3790 ret
= run_script_argv(name
, conf
->hooks_version
, "lxc", hook
,
3799 int lxc_clear_config_caps(struct lxc_conf
*c
)
3801 struct lxc_list
*it
, *next
;
3803 lxc_list_for_each_safe (it
, &c
->caps
, next
) {
3812 static int lxc_free_idmap(struct lxc_list
*id_map
)
3814 struct lxc_list
*it
, *next
;
3816 lxc_list_for_each_safe (it
, id_map
, next
) {
3825 int lxc_clear_idmaps(struct lxc_conf
*c
)
3827 return lxc_free_idmap(&c
->id_map
);
3830 int lxc_clear_config_keepcaps(struct lxc_conf
*c
)
3832 struct lxc_list
*it
, *next
;
3834 lxc_list_for_each_safe (it
, &c
->keepcaps
, next
) {
3843 int lxc_clear_cgroups(struct lxc_conf
*c
, const char *key
, int version
)
3845 char *global_token
, *namespaced_token
;
3846 size_t namespaced_token_len
;
3847 struct lxc_list
*it
, *next
, *list
;
3848 const char *k
= key
;
3851 if (version
== CGROUP2_SUPER_MAGIC
) {
3852 global_token
= "lxc.cgroup2";
3853 namespaced_token
= "lxc.cgroup2.";
3854 namespaced_token_len
= sizeof("lxc.cgroup2.") - 1;
3856 } else if (version
== CGROUP_SUPER_MAGIC
) {
3857 global_token
= "lxc.cgroup";
3858 namespaced_token
= "lxc.cgroup.";
3859 namespaced_token_len
= sizeof("lxc.cgroup.") - 1;
3865 if (strcmp(key
, global_token
) == 0)
3867 else if (strncmp(key
, namespaced_token
, sizeof(namespaced_token
) - 1) == 0)
3868 k
+= namespaced_token_len
;
3872 lxc_list_for_each_safe (it
, list
, next
) {
3873 struct lxc_cgroup
*cg
= it
->elem
;
3875 if (!all
&& strcmp(cg
->subsystem
, k
) != 0)
3879 free(cg
->subsystem
);
3888 int lxc_clear_limits(struct lxc_conf
*c
, const char *key
)
3890 struct lxc_list
*it
, *next
;
3891 const char *k
= NULL
;
3894 if (strcmp(key
, "lxc.limit") == 0 || strcmp(key
, "lxc.prlimit") == 0)
3896 else if (strncmp(key
, "lxc.limit.", sizeof("lxc.limit.") - 1) == 0)
3897 k
= key
+ sizeof("lxc.limit.") - 1;
3898 else if (strncmp(key
, "lxc.prlimit.", sizeof("lxc.prlimit.") - 1) == 0)
3899 k
= key
+ sizeof("lxc.prlimit.") - 1;
3903 lxc_list_for_each_safe (it
, &c
->limits
, next
) {
3904 struct lxc_limit
*lim
= it
->elem
;
3906 if (!all
&& strcmp(lim
->resource
, k
) != 0)
3910 free(lim
->resource
);
3918 int lxc_clear_sysctls(struct lxc_conf
*c
, const char *key
)
3920 struct lxc_list
*it
, *next
;
3921 const char *k
= NULL
;
3924 if (strcmp(key
, "lxc.sysctl") == 0)
3926 else if (strncmp(key
, "lxc.sysctl.", sizeof("lxc.sysctl.") - 1) == 0)
3927 k
= key
+ sizeof("lxc.sysctl.") - 1;
3931 lxc_list_for_each_safe (it
, &c
->sysctls
, next
) {
3932 struct lxc_sysctl
*elem
= it
->elem
;
3934 if (!all
&& strcmp(elem
->key
, k
) != 0)
3947 int lxc_clear_procs(struct lxc_conf
*c
, const char *key
)
3949 struct lxc_list
*it
, *next
;
3950 const char *k
= NULL
;
3953 if (strcmp(key
, "lxc.proc") == 0)
3955 else if (strncmp(key
, "lxc.proc.", sizeof("lxc.proc.") - 1) == 0)
3956 k
= key
+ sizeof("lxc.proc.") - 1;
3960 lxc_list_for_each_safe (it
, &c
->procs
, next
) {
3961 struct lxc_proc
*proc
= it
->elem
;
3963 if (!all
&& strcmp(proc
->filename
, k
) != 0)
3967 free(proc
->filename
);
3976 int lxc_clear_groups(struct lxc_conf
*c
)
3978 struct lxc_list
*it
, *next
;
3980 lxc_list_for_each_safe (it
, &c
->groups
, next
) {
3989 int lxc_clear_environment(struct lxc_conf
*c
)
3991 struct lxc_list
*it
, *next
;
3993 lxc_list_for_each_safe (it
, &c
->environment
, next
) {
4002 int lxc_clear_mount_entries(struct lxc_conf
*c
)
4004 struct lxc_list
*it
, *next
;
4006 lxc_list_for_each_safe (it
, &c
->mount_list
, next
) {
4015 int lxc_clear_automounts(struct lxc_conf
*c
)
4021 int lxc_clear_hooks(struct lxc_conf
*c
, const char *key
)
4024 struct lxc_list
*it
, *next
;
4025 const char *k
= NULL
;
4026 bool all
= false, done
= false;
4028 if (strcmp(key
, "lxc.hook") == 0)
4030 else if (strncmp(key
, "lxc.hook.", sizeof("lxc.hook.") - 1) == 0)
4031 k
= key
+ sizeof("lxc.hook.") - 1;
4035 for (i
= 0; i
< NUM_LXC_HOOKS
; i
++) {
4036 if (all
|| strcmp(k
, lxchook_names
[i
]) == 0) {
4037 lxc_list_for_each_safe (it
, &c
->hooks
[i
], next
) {
4048 ERROR("Invalid hook key: %s", key
);
4055 static inline void lxc_clear_aliens(struct lxc_conf
*conf
)
4057 struct lxc_list
*it
, *next
;
4059 lxc_list_for_each_safe (it
, &conf
->aliens
, next
) {
4066 void lxc_clear_includes(struct lxc_conf
*conf
)
4068 struct lxc_list
*it
, *next
;
4070 lxc_list_for_each_safe (it
, &conf
->includes
, next
) {
4077 int lxc_clear_apparmor_raw(struct lxc_conf
*c
)
4079 struct lxc_list
*it
, *next
;
4081 lxc_list_for_each_safe (it
, &c
->lsm_aa_raw
, next
) {
4090 void lxc_conf_free(struct lxc_conf
*conf
)
4095 if (current_config
== conf
)
4096 current_config
= NULL
;
4097 lxc_terminal_conf_free(&conf
->console
);
4098 free(conf
->rootfs
.mount
);
4099 free(conf
->rootfs
.bdev_type
);
4100 free(conf
->rootfs
.options
);
4101 free(conf
->rootfs
.path
);
4102 free(conf
->logfile
);
4103 if (conf
->logfd
!= -1)
4105 free(conf
->utsname
);
4106 free(conf
->ttys
.dir
);
4107 free(conf
->ttys
.tty_names
);
4110 free(conf
->execute_cmd
);
4111 free(conf
->init_cmd
);
4112 free(conf
->init_cwd
);
4113 free(conf
->unexpanded_config
);
4115 lxc_free_networks(&conf
->network
);
4116 free(conf
->lsm_aa_profile
);
4117 free(conf
->lsm_aa_profile_computed
);
4118 free(conf
->lsm_se_context
);
4119 lxc_seccomp_free(conf
);
4120 lxc_clear_config_caps(conf
);
4121 lxc_clear_config_keepcaps(conf
);
4122 lxc_clear_cgroups(conf
, "lxc.cgroup", CGROUP_SUPER_MAGIC
);
4123 lxc_clear_cgroups(conf
, "lxc.cgroup2", CGROUP2_SUPER_MAGIC
);
4124 lxc_clear_hooks(conf
, "lxc.hook");
4125 lxc_clear_mount_entries(conf
);
4126 lxc_clear_idmaps(conf
);
4127 lxc_clear_groups(conf
);
4128 lxc_clear_includes(conf
);
4129 lxc_clear_aliens(conf
);
4130 lxc_clear_environment(conf
);
4131 lxc_clear_limits(conf
, "lxc.prlimit");
4132 lxc_clear_sysctls(conf
, "lxc.sysctl");
4133 lxc_clear_procs(conf
, "lxc.proc");
4134 lxc_clear_apparmor_raw(conf
);
4135 free(conf
->cgroup_meta
.dir
);
4136 free(conf
->cgroup_meta
.controllers
);
4137 free(conf
->shmount
.path_host
);
4138 free(conf
->shmount
.path_cont
);
4142 struct userns_fn_data
{
4144 const char *fn_name
;
4149 static int run_userns_fn(void *data
)
4153 struct userns_fn_data
*d
= data
;
4155 /* Close write end of the pipe. */
4158 /* Wait for parent to finish establishing a new mapping in the user
4159 * namespace we are executing in.
4161 ret
= lxc_read_nointr(d
->p
[0], &c
, 1);
4162 /* Close read end of the pipe. */
4168 TRACE("Calling function \"%s\"", d
->fn_name
);
4170 /* Call function to run. */
4171 return d
->fn(d
->arg
);
4174 static struct id_map
*mapped_nsid_add(struct lxc_conf
*conf
, unsigned id
,
4177 const struct id_map
*map
;
4178 struct id_map
*retmap
;
4180 map
= find_mapped_nsid_entry(conf
, id
, idtype
);
4184 retmap
= malloc(sizeof(*retmap
));
4188 memcpy(retmap
, map
, sizeof(*retmap
));
4192 static struct id_map
*find_mapped_hostid_entry(struct lxc_conf
*conf
,
4193 unsigned id
, enum idtype idtype
)
4196 struct lxc_list
*it
;
4197 struct id_map
*retmap
= NULL
;
4199 lxc_list_for_each (it
, &conf
->id_map
) {
4201 if (map
->idtype
!= idtype
)
4204 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
) {
4213 /* Allocate a new {g,u}id mapping for the given {g,u}id. Re-use an already
4214 * existing one or establish a new one.
4216 static struct id_map
*mapped_hostid_add(struct lxc_conf
*conf
, uid_t id
,
4220 struct id_map
*entry
= NULL
, *tmp
= NULL
;
4222 entry
= malloc(sizeof(*entry
));
4226 /* Reuse existing mapping. */
4227 tmp
= find_mapped_hostid_entry(conf
, id
, type
);
4229 return memcpy(entry
, tmp
, sizeof(*entry
));
4231 /* Find new mapping. */
4232 hostid_mapped
= find_unmapped_nsid(conf
, type
);
4233 if (hostid_mapped
< 0) {
4234 DEBUG("Failed to find free mapping for id %d", id
);
4239 entry
->idtype
= type
;
4240 entry
->nsid
= hostid_mapped
;
4241 entry
->hostid
= (unsigned long)id
;
4247 struct lxc_list
*get_minimal_idmap(struct lxc_conf
*conf
)
4250 uid_t nsuid
= (conf
->root_nsuid_map
!= NULL
) ? 0 : conf
->init_uid
;
4251 gid_t nsgid
= (conf
->root_nsgid_map
!= NULL
) ? 0 : conf
->init_gid
;
4252 struct lxc_list
*idmap
= NULL
, *tmplist
= NULL
;
4253 struct id_map
*container_root_uid
= NULL
, *container_root_gid
= NULL
,
4254 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
4256 /* Find container root mappings. */
4257 container_root_uid
= mapped_nsid_add(conf
, nsuid
, ID_TYPE_UID
);
4258 if (!container_root_uid
) {
4259 DEBUG("Failed to find mapping for namespace uid %d", 0);
4263 if (euid
>= container_root_uid
->hostid
&&
4264 euid
< (container_root_uid
->hostid
+ container_root_uid
->range
))
4265 host_uid_map
= container_root_uid
;
4267 container_root_gid
= mapped_nsid_add(conf
, nsgid
, ID_TYPE_GID
);
4268 if (!container_root_gid
) {
4269 DEBUG("Failed to find mapping for namespace gid %d", 0);
4273 if (egid
>= container_root_gid
->hostid
&&
4274 egid
< (container_root_gid
->hostid
+ container_root_gid
->range
))
4275 host_gid_map
= container_root_gid
;
4277 /* Check whether the {g,u}id of the user has a mapping. */
4279 host_uid_map
= mapped_hostid_add(conf
, euid
, ID_TYPE_UID
);
4280 if (!host_uid_map
) {
4281 DEBUG("Failed to find mapping for uid %d", euid
);
4286 host_gid_map
= mapped_hostid_add(conf
, egid
, ID_TYPE_GID
);
4287 if (!host_gid_map
) {
4288 DEBUG("Failed to find mapping for gid %d", egid
);
4292 /* Allocate new {g,u}id map list. */
4293 idmap
= malloc(sizeof(*idmap
));
4296 lxc_list_init(idmap
);
4298 /* Add container root to the map. */
4299 tmplist
= malloc(sizeof(*tmplist
));
4302 lxc_list_add_elem(tmplist
, container_root_uid
);
4303 lxc_list_add_tail(idmap
, tmplist
);
4305 if (host_uid_map
&& (host_uid_map
!= container_root_uid
)) {
4306 /* idmap will now keep track of that memory. */
4307 container_root_uid
= NULL
;
4309 /* Add container root to the map. */
4310 tmplist
= malloc(sizeof(*tmplist
));
4313 lxc_list_add_elem(tmplist
, host_uid_map
);
4314 lxc_list_add_tail(idmap
, tmplist
);
4316 /* idmap will now keep track of that memory. */
4317 container_root_uid
= NULL
;
4318 /* idmap will now keep track of that memory. */
4319 host_uid_map
= NULL
;
4321 tmplist
= malloc(sizeof(*tmplist
));
4324 lxc_list_add_elem(tmplist
, container_root_gid
);
4325 lxc_list_add_tail(idmap
, tmplist
);
4327 if (host_gid_map
&& (host_gid_map
!= container_root_gid
)) {
4328 /* idmap will now keep track of that memory. */
4329 container_root_gid
= NULL
;
4331 tmplist
= malloc(sizeof(*tmplist
));
4334 lxc_list_add_elem(tmplist
, host_gid_map
);
4335 lxc_list_add_tail(idmap
, tmplist
);
4337 /* idmap will now keep track of that memory. */
4338 container_root_gid
= NULL
;
4339 /* idmap will now keep track of that memory. */
4340 host_gid_map
= NULL
;
4342 TRACE("Allocated minimal idmapping");
4347 lxc_free_idmap(idmap
);
4350 if (container_root_uid
)
4351 free(container_root_uid
);
4352 if (container_root_gid
)
4353 free(container_root_gid
);
4354 if (host_uid_map
&& (host_uid_map
!= container_root_uid
))
4356 if (host_gid_map
&& (host_gid_map
!= container_root_gid
))
4362 /* Run a function in a new user namespace.
4363 * The caller's euid/egid will be mapped if it is not already.
4364 * Afaict, userns_exec_1() is only used to operate based on privileges for the
4365 * user's own {g,u}id on the host and for the container root's unmapped {g,u}id.
4366 * This means we require only to establish a mapping from:
4367 * - the container root {g,u}id as seen from the host > user's host {g,u}id
4368 * - the container root -> some sub{g,u}id
4369 * The former we add, if the user did not specifiy a mapping. The latter we
4370 * retrieve from the ontainer's configured {g,u}id mappings as it must have been
4371 * there to start the container in the first place.
4373 int userns_exec_1(struct lxc_conf
*conf
, int (*fn
)(void *), void *data
,
4374 const char *fn_name
)
4378 struct userns_fn_data d
;
4379 struct lxc_list
*idmap
;
4380 int ret
= -1, status
= -1;
4386 idmap
= get_minimal_idmap(conf
);
4390 ret
= pipe2(p
, O_CLOEXEC
);
4392 SYSERROR("Failed to create pipe");
4396 d
.fn_name
= fn_name
;
4401 /* Clone child in new user namespace. */
4402 pid
= lxc_raw_clone_cb(run_userns_fn
, &d
, CLONE_NEWUSER
);
4404 ERROR("Failed to clone process in new user namespace");
4411 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE
||
4412 conf
->loglevel
== LXC_LOG_LEVEL_TRACE
) {
4414 struct lxc_list
*it
;
4416 lxc_list_for_each (it
, idmap
) {
4418 TRACE("Establishing %cid mapping for \"%d\" in new "
4419 "user namespace: nsuid %lu - hostid %lu - range "
4421 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
,
4422 map
->nsid
, map
->hostid
, map
->range
);
4426 /* Set up {g,u}id mapping for user namespace of child process. */
4427 ret
= lxc_map_ids(idmap
, pid
);
4429 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid
);
4433 /* Tell child to proceed. */
4434 if (lxc_write_nointr(p
[1], &c
, 1) != 1) {
4435 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
4444 /* Wait for child to finish. */
4446 status
= wait_for_pid(pid
);
4454 int userns_exec_full(struct lxc_conf
*conf
, int (*fn
)(void *), void *data
,
4455 const char *fn_name
)
4461 struct lxc_list
*cur
;
4462 struct userns_fn_data d
;
4465 struct lxc_list
*idmap
= NULL
, *tmplist
= NULL
;
4466 struct id_map
*container_root_uid
= NULL
, *container_root_gid
= NULL
,
4467 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
4472 ret
= pipe2(p
, O_CLOEXEC
);
4474 SYSERROR("opening pipe");
4478 d
.fn_name
= fn_name
;
4483 /* Clone child in new user namespace. */
4484 pid
= lxc_clone(run_userns_fn
, &d
, CLONE_NEWUSER
);
4486 ERROR("Failed to clone process in new user namespace");
4496 /* Allocate new {g,u}id map list. */
4497 idmap
= malloc(sizeof(*idmap
));
4500 lxc_list_init(idmap
);
4502 /* Find container root. */
4503 lxc_list_for_each (cur
, &conf
->id_map
) {
4504 struct id_map
*tmpmap
;
4506 tmplist
= malloc(sizeof(*tmplist
));
4510 tmpmap
= malloc(sizeof(*tmpmap
));
4516 memset(tmpmap
, 0, sizeof(*tmpmap
));
4517 memcpy(tmpmap
, cur
->elem
, sizeof(*tmpmap
));
4518 tmplist
->elem
= tmpmap
;
4520 lxc_list_add_tail(idmap
, tmplist
);
4524 if (map
->idtype
== ID_TYPE_UID
)
4525 if (euid
>= map
->hostid
&& euid
< map
->hostid
+ map
->range
)
4528 if (map
->idtype
== ID_TYPE_GID
)
4529 if (egid
>= map
->hostid
&& egid
< map
->hostid
+ map
->range
)
4535 if (map
->idtype
== ID_TYPE_UID
)
4536 if (container_root_uid
== NULL
)
4537 container_root_uid
= map
;
4539 if (map
->idtype
== ID_TYPE_GID
)
4540 if (container_root_gid
== NULL
)
4541 container_root_gid
= map
;
4544 if (!container_root_uid
|| !container_root_gid
) {
4545 ERROR("No mapping for container root found");
4549 /* Check whether the {g,u}id of the user has a mapping. */
4551 host_uid_map
= mapped_hostid_add(conf
, euid
, ID_TYPE_UID
);
4553 host_uid_map
= container_root_uid
;
4556 host_gid_map
= mapped_hostid_add(conf
, egid
, ID_TYPE_GID
);
4558 host_gid_map
= container_root_gid
;
4560 if (!host_uid_map
) {
4561 DEBUG("Failed to find mapping for uid %d", euid
);
4565 if (!host_gid_map
) {
4566 DEBUG("Failed to find mapping for gid %d", egid
);
4570 if (host_uid_map
&& (host_uid_map
!= container_root_uid
)) {
4571 /* Add container root to the map. */
4572 tmplist
= malloc(sizeof(*tmplist
));
4575 lxc_list_add_elem(tmplist
, host_uid_map
);
4576 lxc_list_add_tail(idmap
, tmplist
);
4578 /* idmap will now keep track of that memory. */
4579 host_uid_map
= NULL
;
4581 if (host_gid_map
&& (host_gid_map
!= container_root_gid
)) {
4582 tmplist
= malloc(sizeof(*tmplist
));
4585 lxc_list_add_elem(tmplist
, host_gid_map
);
4586 lxc_list_add_tail(idmap
, tmplist
);
4588 /* idmap will now keep track of that memory. */
4589 host_gid_map
= NULL
;
4591 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE
||
4592 conf
->loglevel
== LXC_LOG_LEVEL_TRACE
) {
4593 lxc_list_for_each (cur
, idmap
) {
4595 TRACE("establishing %cid mapping for \"%d\" in new "
4596 "user namespace: nsuid %lu - hostid %lu - range "
4598 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
,
4599 map
->nsid
, map
->hostid
, map
->range
);
4603 /* Set up {g,u}id mapping for user namespace of child process. */
4604 ret
= lxc_map_ids(idmap
, pid
);
4606 ERROR("error setting up {g,u}id mappings for child process \"%d\"", pid
);
4610 /* Tell child to proceed. */
4611 if (lxc_write_nointr(p
[1], &c
, 1) != 1) {
4612 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
4621 /* Wait for child to finish. */
4623 ret
= wait_for_pid(pid
);
4626 lxc_free_idmap(idmap
);
4630 if (host_uid_map
&& (host_uid_map
!= container_root_uid
))
4632 if (host_gid_map
&& (host_gid_map
!= container_root_gid
))
4638 /* not thread-safe, do not use from api without first forking */
4639 static char *getuname(void)
4641 struct passwd pwent
;
4642 struct passwd
*pwentp
= NULL
;
4648 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
4652 buf
= malloc(bufsize
);
4656 ret
= getpwuid_r(geteuid(), &pwent
, buf
, bufsize
, &pwentp
);
4659 WARN("Could not find matched password record.");
4661 ERROR("Failed to get password record - %u", geteuid());
4666 username
= strdup(pwent
.pw_name
);
4672 /* not thread-safe, do not use from api without first forking */
4673 static char *getgname(void)
4676 struct group
*grentp
= NULL
;
4682 bufsize
= sysconf(_SC_GETGR_R_SIZE_MAX
);
4686 buf
= malloc(bufsize
);
4690 ret
= getgrgid_r(getegid(), &grent
, buf
, bufsize
, &grentp
);
4693 WARN("Could not find matched group record");
4695 ERROR("Failed to get group record - %u", getegid());
4700 grname
= strdup(grent
.gr_name
);
4706 /* not thread-safe, do not use from api without first forking */
4707 void suggest_default_idmap(void)
4709 char *uname
, *gname
;
4711 unsigned int uid
= 0, urange
= 0, gid
= 0, grange
= 0;
4725 f
= fopen(subuidfile
, "r");
4727 ERROR("Your system is not configured with subuids");
4733 while (getline(&line
, &len
, f
) != -1) {
4735 size_t no_newline
= 0;
4737 p
= strchr(line
, ':');
4745 if (strcmp(line
, uname
))
4748 p2
= strchr(p
, ':');
4755 no_newline
= strcspn(p2
, "\n");
4756 p2
[no_newline
] = '\0';
4758 if (lxc_safe_uint(p
, &uid
) < 0)
4759 WARN("Could not parse UID");
4760 if (lxc_safe_uint(p2
, &urange
) < 0)
4761 WARN("Could not parse UID range");
4765 f
= fopen(subgidfile
, "r");
4767 ERROR("Your system is not configured with subgids");
4773 while (getline(&line
, &len
, f
) != -1) {
4775 size_t no_newline
= 0;
4777 p
= strchr(line
, ':');
4785 if (strcmp(line
, uname
))
4788 p2
= strchr(p
, ':');
4795 no_newline
= strcspn(p2
, "\n");
4796 p2
[no_newline
] = '\0';
4798 if (lxc_safe_uint(p
, &gid
) < 0)
4799 WARN("Could not parse GID");
4800 if (lxc_safe_uint(p2
, &grange
) < 0)
4801 WARN("Could not parse GID range");
4807 if (!urange
|| !grange
) {
4808 ERROR("You do not have subuids or subgids allocated");
4809 ERROR("Unprivileged containers require subuids and subgids");
4815 ERROR("You must either run as root, or define uid mappings");
4816 ERROR("To pass uid mappings to lxc-create, you could create");
4817 ERROR("~/.config/lxc/default.conf:");
4818 ERROR("lxc.include = %s", LXC_DEFAULT_CONFIG
);
4819 ERROR("lxc.idmap = u 0 %u %u", uid
, urange
);
4820 ERROR("lxc.idmap = g 0 %u %u", gid
, grange
);
4826 static void free_cgroup_settings(struct lxc_list
*result
)
4828 struct lxc_list
*iterator
, *next
;
4830 lxc_list_for_each_safe (iterator
, result
, next
) {
4831 lxc_list_del(iterator
);
4837 /* Return the list of cgroup_settings sorted according to the following rules
4838 * 1. Put memory.limit_in_bytes before memory.memsw.limit_in_bytes
4840 struct lxc_list
*sort_cgroup_settings(struct lxc_list
*cgroup_settings
)
4842 struct lxc_list
*result
;
4843 struct lxc_cgroup
*cg
= NULL
;
4844 struct lxc_list
*it
= NULL
, *item
= NULL
, *memsw_limit
= NULL
;
4846 result
= malloc(sizeof(*result
));
4849 lxc_list_init(result
);
4851 /* Iterate over the cgroup settings and copy them to the output list. */
4852 lxc_list_for_each (it
, cgroup_settings
) {
4853 item
= malloc(sizeof(*item
));
4855 free_cgroup_settings(result
);
4859 item
->elem
= it
->elem
;
4861 if (strcmp(cg
->subsystem
, "memory.memsw.limit_in_bytes") == 0) {
4862 /* Store the memsw_limit location */
4864 } else if (strcmp(cg
->subsystem
, "memory.limit_in_bytes") == 0 &&
4865 memsw_limit
!= NULL
) {
4866 /* lxc.cgroup.memory.memsw.limit_in_bytes is found
4867 * before lxc.cgroup.memory.limit_in_bytes, swap these
4869 item
->elem
= memsw_limit
->elem
;
4870 memsw_limit
->elem
= it
->elem
;
4872 lxc_list_add_tail(result
, item
);